Skip to content

Techniques Module (softpotato.techniques)

The softpotato.techniques subpackage provides high-level electrochemical experimental protocols, excitation waveform generators, an automated simulation pipeline (simulate, simulate_sweep), a structured result container (TechniqueResult), a declarative Matplotlib plotting suite, and automated electrochemical diagnostics.


Theoretical Background

1. Potentiostatic vs. Galvanostatic Excitation & Event-Aware Integration

Every experimental technique in softpotato.techniques subclasses BaseTechnique, encapsulating a time-dependent excitation signal over \(t \in [0, t_{\max}]\) under either:

  • Potentiostatic control (mode="potentiostatic"): prescribes the electrode potential \(E(t)\) at the working electrode boundary, driving interfacial Nernstian, Butler–Volmer, or Tafel charge transfer.
  • Galvanostatic control (mode="galvanostatic"): prescribes the net Faradaic current \(I(t)\) (e.g. Chronopotentiometry), enforcing a Neumann interfacial flux \(J(t) = I(t) / (n F A)\) and recovering the electrode potential \(E(t)\) from the resulting surface concentrations.

Techniques with sharp step edges or switching vertices (CA, CV, DPV, SWV, SCV, CP, CustomWaveform) expose exact interior timestamps via event_times. simulate performs piecewise event-aware integration across each smooth sub-interval, preventing adaptive ODE solvers (Radau, BDF) from stepping over narrow pulses or switching vertices.

2. Sampled-Current Voltammetry (SCV)

SampledCurrentVoltammetry models a family of \(K\) independent constant-potential step experiments \(\{E_1, E_2, \dots, E_K\}\), each held for identical duration \(t_{\max}\) (with optional common quiet time \(t_{\text{quiet}}\) at \(E_{\text{quiet}}\)). Sampling the resulting chronoamperometric transients \(I_k(t)\) at one or more fixed sampling times \(\tau \in (0, t_{\max}]\) yields a sampled-current voltammogram \(I(\tau)\) vs. \(E_k\) free of charging-current interference at sufficiently long \(\tau\):

\[ I_k(\tau) = \text{Cottrell / Butler–Volmer response at potential } E_k \text{ evaluated at } t = \tau \]

3. Pulse Voltammetry (DPV & SWV)

  • Differential Pulse Voltammetry (DifferentialPulseVoltammetry): superimposes a constant-amplitude pulse \(\Delta E_p\) onto a staircase ramp of step height \(\Delta E_s\) and period \(t_{\text{period}}\). Current is sampled just before pulse application (\(I_{\text{pre}}\)) and at the end of the pulse (\(I_{\text{pulse}}\)), yielding the differential peak-shaped signal \(\Delta I = I_{\text{pulse}} - I_{\text{pre}}\) vs. \(E_{\text{base}}\).
  • Square Wave Voltammetry (SquareWaveVoltammetry): applies a symmetric square wave of amplitude \(E_{\text{sw}}\) and frequency \(f\) (\(T = 1/f\)) superimposed on a staircase ramp \(\Delta E_s\). Sampling at the end of each forward and reverse half-cycle produces \(I_{\text{forward}}\), \(I_{\text{reverse}}\), and the net signal \(I_{\text{net}} = I_{\text{forward}} - I_{\text{reverse}}\).

4. Rotating Disk Electrode (RDE) Hydrodynamics

RotatingDiskElectrode couples any potentiostatic waveform with convective-diffusion mass transport at angular velocity \(\omega\) (\(\text{rad}\,\text{s}^{-1}\)) or rotational speed \(\text{rpm}\) in an electrolyte of kinematic viscosity \(\nu\):

  • "nernst_layer": truncates the spatial domain at the steady-state Nernst diffusion layer thickness \(\delta_N = 1.61\, D^{1/3} \omega^{-1/2} \nu^{1/6}\) with bulk Dirichlet conditions at \(x = \delta_N\).
  • "levich_convection": solves the full 1D convective-diffusion PDE \(\partial c_i / \partial t = D_i \partial^2 c_i / \partial x^2 - v_x(x) \partial c_i / \partial x + R_i\) using the Cochran axial velocity profile \(v_x(x) = -0.510\, \omega^{3/2} \nu^{-1/2} x^2\) via RDEConvectionTerm.

API Overview

Waveforms & Experimental Techniques

Class Mode Key Parameters Description
BaseTechnique Both mode, duration, event_times, plot_specs Abstract base class for all electrochemical excitation protocols.
Chronoamperometry Potentiostatic E_step, duration, E_step1/E_step2, potentials/durations, E_quiet, t_quiet Single-, double-, and multi-step potential chronoamperometry.
LinearSweepVoltammetry Potentiostatic E_start, E_end, scan_rate, dE, n_points Unidirectional linear potential sweep \(E(t) = E_{\text{start}} \pm v t\).
CyclicVoltammetry Potentiostatic E_start, E_vertex1, E_vertex2, scan_rate, E_end, n_cycles Single- or multi-cycle triangular potential waveform with switching vertices.
SampledCurrentVoltammetry Potentiostatic potentials or (E_start, E_end, dE/step_height), duration, sample_times Family of independent constant-potential steps sampled at fixed \(\tau\).
DifferentialPulseVoltammetry Potentiostatic E_start, E_end, step_height, pulse_amplitude, pulse_width, pulse_period, sample_fraction Staircase + pulse waveform with sample_currents returning (E_base, i_pre, i_pulse, i_diff).
SquareWaveVoltammetry Potentiostatic E_start, E_end, step_height, amplitude, frequency, sample_fraction Staircase + square-wave waveform with sample_currents returning (E_step, i_forward, i_reverse, i_net).
Chronopotentiometry Galvanostatic current, duration, currents/durations, I_quiet, t_quiet Single- or multi-step constant-current protocol with potential recovery and transition time \(\tau\) detection.
RotatingDiskElectrode Potentiostatic waveform, omega/rpm, kinematic_viscosity, model Hydrodynamic RDE wrapper ('nernst_layer' or 'levich_convection').
RDESweep / simulate_rde_sweep Potentiostatic omegas/rpms, waveform or (E_start, E_end, scan_rate), model Multi-rotation-rate RDE sweep builder and runner returning RDESweepResult.
CustomWaveform Both segments, mode, n_points Composite excitation chaining ConstantSegment, LinearRampSegment, SinusoidalSegment, and CallableSegment.

Simulation Pipeline & Result Container

Symbol Key Parameters / Attributes Description
simulate technique, mechanism, geometry, grid, solver, t_eval, kinetics End-to-end simulation orchestrator: builds physics-informed mesh, assembles BCs, integrates piecewise across event_times, and returns TechniqueResult.
simulate_sweep techniques, mechanism, values, geometry, solver Runs parameter sweeps (sequence, mapping, or factory callable + values) via simulate.
TechniqueResult time, potential, current, charge, solver_result, cycles, E_step/i_net, E_base/i_diff, transition_time, sample_currents(), plot(), plot_summary() Structured result container with dict-like species access (result["Ox"]), technique-specific views, and plotting facade.

Declarative Plotting Interfaces

Every plotting function accepts an optional Matplotlib ax, returns (fig, ax) (or (fig, axes) for plot_summary), uses SI units and IUPAC current polarity (anodic positive, cathodic negative), and never calls plt.show().

Function / Helper Plot Kind Key Description
PlotSpec / resolve_plot_kind PLOT_ALIASES Declarative plot metadata and alias resolver mapping verbose names (e.g. 'current_vs_time') to canonical keys ('i_vs_t').
plot_result kind=None (uses result.default_plot) Central technique-aware dispatcher (also exposed as result.plot(kind=...)).
plot_summary Multi-panel (1x3 or 2x2) Renders default technique plot alongside 'i_vs_t', 'E_vs_t', and 'c_vs_x' (also result.plot_summary()).
plot_sweep Any supported kind Overlays Sequence[TechniqueResult], Mapping[Any, TechniqueResult], or RDESweepResult on a single axes.
plot_voltammogram 'voltammogram' \(I\) vs. \(E\) voltammogram with optional CV cycle selection and peaks overlay.
plot_current_vs_time 'i_vs_t' \(I(t)\) chronoamperogram (supports 2D SampledCurrentVoltammetry step families via step=).
plot_potential_vs_time 'E_vs_t' \(E(t)\) waveform or chronopotentiogram with optional transition-time \(\tau\) marker.
plot_concentration_profile 'c_vs_x' Spatial concentration profile \(c_i(x, t)\) at one or more timestamps t and species.
plot_charge_vs_time 'Q_vs_t' Cumulative charge \(Q(t)\) chronocoulogram.
plot_scv 'scv' Sampled-current voltammogram \(I(\tau)\) vs. \(E_{\text{step}}\) for one or more sample_times.
plot_dpv 'dpv' Differential pulse voltammogram (\(\Delta I\) and optional i_pre, i_pulse components).
plot_swv 'swv' Square-wave voltammogram (\(I_{\text{net}}\) and optional i_forward, i_reverse components).
plot_peaks Diagnostic Voltammogram with detected anodic/cathodic peak markers and annotations.
plot_randles_sevcik Diagnostic \(I_p\) vs. \(v^{1/2}\) Randles–Ševčík regression and fitted line.
plot_cottrell Diagnostic \(I\) vs. \(t^{-1/2}\) Cottrell regression and fitted line.
plot_levich Diagnostic \(I_L\) vs. \(\omega^{1/2}\) Levich regression and fitted line.
plot_koutecky_levich Diagnostic \(1/I\) vs. \(\omega^{-1/2}\) Koutecký–Levich regression and fitted line.
plot_tafel Diagnostic $\log_{10}

Post-Processing & Diagnostics

Function / Dataclass Inputs Output Description
find_peaks TechniqueResult or (E, i) CVDiagnostics or list[PeakInfo] Parabolic sub-grid peak detection ($E_{pa}, I_{pa}, E_{pc}, I_{pc}, \Delta E_p,
analyze_randles_sevcik Multi-scan-rate results or (v, I_p) RandlesSevcikFitResult Extracts diffusivity \(D\) from \(I_p\) vs. \(v^{1/2}\) regression.
analyze_nicholson TechniqueResult or (E, i) NicholsonDiagnostics Extracts \(\Delta E_p\), \(\Psi\), and standard rate constant \(k^0\) via Nicholson's method.
analyze_levich RDESweepResult or results LevichFitResult Extracts diffusivity \(D\) and Levich constant \(B\) from \(I_L\) vs. \(\omega^{1/2}\).
analyze_koutecky_levich RDESweepResult or results KouteckyLevichFitResult Separates kinetic current \(I_k\) (\(k^0\)) and mass-transport slope \(B\) (\(D\)).
analyze_tafel TechniqueResult or (\eta, i) TafelFitResult Extracts exchange current \(I_0\), transfer coefficient \(\alpha\), and Tafel slope \(b\).
analyze_cottrell TechniqueResult or (t, i) CottrellFitResult Extracts diffusivity \(D\) from \(I\) vs. \(t^{-1/2}\) Cottrell regression.
analyze_sand TechniqueResult or (t, signal) SandDiagnostics Detects transition time \(\tau\), computes \(I\tau^{1/2}\), and estimates \(D\).

User Guide & Examples

1. Cyclic Voltammetry Sweep, Plotting & Diagnostics

from softpotato.reactions import ButlerVolmer, Species
from softpotato.techniques import (
    CyclicVoltammetry,
    analyze_nicholson,
    analyze_randles_sevcik,
    find_peaks,
    plot_randles_sevcik,
    plot_sweep,
    simulate,
    simulate_sweep,
)

ox = Species(
    "Ox",
    diffusivity=1e-9,
    bulk_concentration=1.0,
    standard_potential=0.0,
    n_electrons=1,
)
red = Species(
    "Red",
    diffusivity=1e-9,
    bulk_concentration=0.0,
    standard_potential=0.0,
    n_electrons=-1,
)
kinetics = ButlerVolmer(k0=1e-4, alpha=0.5, E0=0.0, n=1)

# Single CV simulation + declarative plotting
cv = CyclicVoltammetry(E_start=0.4, E_vertex1=-0.4, E_vertex2=0.4, scan_rate=0.1)
res = simulate(cv, [ox, red], kinetics=kinetics)
fig, ax = res.plot()  # Default plot ('voltammogram')
fig_sum, axes = res.plot_summary()  # 2x2 summary (voltammogram, i_vs_t, E_vs_t, c_vs_x)

# Multi-scan-rate sweep & diagnostics
results = simulate_sweep(
    lambda v: CyclicVoltammetry(
        E_start=0.4, E_vertex1=-0.4, E_vertex2=0.4, scan_rate=v
    ),
    [ox, red],
    values=[0.05, 0.1, 0.2, 0.5],
    kinetics=kinetics,
)
plot_sweep(results, legend_title="Scan Rate")
rs_fit = analyze_randles_sevcik(results, n=1, area=1e-4, c_bulk=1.0)
plot_randles_sevcik(results, rs_fit)
nich = analyze_nicholson(res, D=1e-9)

2. Sampled-Current Voltammetry (SCV)

from softpotato.reactions import NernstianEquilibrium, Species
from softpotato.techniques import SampledCurrentVoltammetry, plot_scv, simulate

ox = Species(
    "Ox",
    diffusivity=1e-9,
    bulk_concentration=1.0,
    standard_potential=0.0,
    n_electrons=1,
)
red = Species(
    "Red",
    diffusivity=1e-9,
    bulk_concentration=0.0,
    standard_potential=0.0,
    n_electrons=-1,
)

scv = SampledCurrentVoltammetry(
    E_start=0.3,
    E_end=-0.3,
    dE=0.05,
    duration=2.0,
    sample_times=[0.2, 0.5, 1.0, 2.0],
)
res_scv = simulate(scv, [ox, red], kinetics=NernstianEquilibrium(E0=0.0, n=1))

# Extract sampled voltammograms directly or plot with plot_scv / res_scv.plot('scv')
e_steps, i_sampled = res_scv.sample_currents()
fig, ax = plot_scv(res_scv)

3. Interactive Tutorials

For complete, runnable notebooks with plots and analytical validation, see:


Module Contents

techniques

Electrochemical experimental techniques and excitation waveform generators.

BaseTechnique

Bases: ABC

Abstract base class for electrochemical experimental techniques.

Encapsulates a time-dependent excitation protocol \(E(t)\) (potentiostatic) or \(I(t)\) (galvanostatic) over \(t \in [0, t_{\max}]\), together with exact interior discontinuity/vertex timestamps (event_times) so adaptive ODE integrators can accurately resolve step edges and switching vertices.

Every BaseTechnique instance is directly callable (technique(t)), supporting both scalar floats (for solver boundary callables) and NumPy arrays (for vectorized post-processing and plotting).

Attributes:

Name Type Description
mode {'potentiostatic', 'galvanostatic'}

Control mode of the excitation waveform (default 'potentiostatic').

duration float

Total experiment duration \(t_{\max} > 0\) in seconds.

event_times tuple[float, ...]

Sorted strictly interior discontinuity or switching timestamps in \((0, t_{\max})\).

Source code in src/softpotato/techniques/base.py
class BaseTechnique(ABC):
    r"""Abstract base class for electrochemical experimental techniques.

    Encapsulates a time-dependent excitation protocol :math:`E(t)` (potentiostatic)
    or :math:`I(t)` (galvanostatic) over :math:`t \in [0, t_{\max}]`, together with
    exact interior discontinuity/vertex timestamps (:attr:`event_times`) so adaptive
    ODE integrators can accurately resolve step edges and switching vertices.

    Every ``BaseTechnique`` instance is directly callable (``technique(t)``),
    supporting both scalar floats (for solver boundary callables) and NumPy arrays
    (for vectorized post-processing and plotting).

    Attributes
    ----------
    mode : {'potentiostatic', 'galvanostatic'}
        Control mode of the excitation waveform (default ``'potentiostatic'``).
    duration : float
        Total experiment duration :math:`t_{\max} > 0` in seconds.
    event_times : tuple[float, ...]
        Sorted strictly interior discontinuity or switching timestamps in
        :math:`(0, t_{\max})`.
    """

    _mode: ControlMode = "potentiostatic"

    @property
    def mode(self) -> ControlMode:
        """Control mode: ``'potentiostatic'`` or ``'galvanostatic'``."""
        return self._mode

    @property
    @abstractmethod
    def duration(self) -> float:
        """Total experiment duration in seconds (:math:`t_{\\max} > 0`)."""
        raise NotImplementedError

    @property
    def event_times(self) -> tuple[float, ...]:
        """Sorted interior discontinuity/vertex timestamps in ``(0, duration)``."""
        return ()

    def _technique_plots(self) -> tuple[PlotSpec, ...]:
        """Return technique-specific :class:`PlotSpec` entries (default plot first)."""
        return ()

    @property
    def plot_specs(self) -> dict[str, PlotSpec]:
        """Ordered mapping of canonical plot kind to :class:`PlotSpec`.

        Includes technique-specific plots first (with the primary/default plot
        listed first), followed by universal plots (``'i_vs_t'``, ``'E_vs_t'``,
        ``'c_vs_x'``) without duplicates.
        """
        specs: dict[str, PlotSpec] = {}
        for spec in self._technique_plots():
            specs.setdefault(spec.kind, spec)

        universal = _UNIVERSAL_PLOT_SPECS
        if self.mode == "galvanostatic":
            universal = (
                _UNIVERSAL_PLOT_SPECS[1],
                _UNIVERSAL_PLOT_SPECS[0],
                _UNIVERSAL_PLOT_SPECS[2],
            )
        for spec in universal:
            specs.setdefault(spec.kind, spec)
        return specs

    @property
    def available_plots(self) -> tuple[str, ...]:
        """Ordered tuple of canonical plot kinds supported by this technique."""
        return tuple(self.plot_specs.keys())

    @property
    def default_plot(self) -> str:
        """Canonical plot kind used by default when plotting results of this technique."""
        return self.available_plots[0]

    @overload
    def excitation(self, t: float) -> float: ...

    @overload
    def excitation(self, t: np.ndarray) -> np.ndarray: ...

    @overload
    def excitation(self, t: float | ArrayLike) -> float | np.ndarray: ...

    @abstractmethod
    def excitation(self, t: float | ArrayLike) -> float | np.ndarray:
        """Evaluate the excitation signal at time ``t``.

        Parameters
        ----------
        t : float or array-like
            Time(s) in seconds at which to evaluate the waveform.

        Returns
        -------
        float or np.ndarray
            Excitation value(s) (potential in V for potentiostatic mode, or
            current in A for galvanostatic mode). Returns a Python ``float``
            for scalar inputs and a ``np.ndarray`` matching the input shape
            for array-like inputs.
        """
        raise NotImplementedError

    @overload
    def __call__(self, t: float) -> float: ...

    @overload
    def __call__(self, t: np.ndarray) -> np.ndarray: ...

    @overload
    def __call__(self, t: float | ArrayLike) -> float | np.ndarray: ...

    def __call__(self, t: float | ArrayLike) -> float | np.ndarray:
        """Callable alias for :meth:`excitation`."""
        return self.excitation(t)

    @overload
    def potential(self, t: float) -> float: ...

    @overload
    def potential(self, t: np.ndarray) -> np.ndarray: ...

    @overload
    def potential(self, t: float | ArrayLike) -> float | np.ndarray: ...

    def potential(self, t: float | ArrayLike) -> float | np.ndarray:
        """Evaluate applied electrode potential :math:`E(t)` in Volts.

        Only valid for ``mode='potentiostatic'`` techniques.

        Parameters
        ----------
        t : float or array-like
            Time(s) in seconds.

        Returns
        -------
        float or np.ndarray
            Applied potential :math:`E(t)` in Volts.

        Raises
        ------
        ValueError
            If the technique is not potentiostatic.
        """
        if self.mode != "potentiostatic":
            raise ValueError(
                "potential() is only available for potentiostatic techniques, "
                f"got mode={self.mode!r}."
            )
        return self.excitation(t)

    @overload
    def current(self, t: float) -> float: ...

    @overload
    def current(self, t: np.ndarray) -> np.ndarray: ...

    @overload
    def current(self, t: float | ArrayLike) -> float | np.ndarray: ...

    def current(self, t: float | ArrayLike) -> float | np.ndarray:
        """Evaluate applied current :math:`I(t)` in Amperes.

        Only valid for ``mode='galvanostatic'`` techniques.

        Parameters
        ----------
        t : float or array-like
            Time(s) in seconds.

        Returns
        -------
        float or np.ndarray
            Applied current :math:`I(t)` in Amperes.

        Raises
        ------
        ValueError
            If the technique is not galvanostatic.
        """
        if self.mode != "galvanostatic":
            raise ValueError(
                "current() is only available for galvanostatic techniques, "
                f"got mode={self.mode!r}."
            )
        return self.excitation(t)

    def _default_time_grid_points(self) -> int:
        """Default number of grid points when ``n_points`` and ``dt`` are omitted."""
        return _DEFAULT_TIME_GRID_POINTS

    def _extra_grid_times(self) -> tuple[float, ...]:
        """Additional critical timestamps to guarantee in :meth:`time_grid`."""
        return self.event_times

    def time_grid(
        self,
        n_points: int | None = None,
        dt: float | None = None,
    ) -> np.ndarray:
        """Generate evaluation timestamps covering ``[0, duration]`` and all events.

        Parameters
        ----------
        n_points : int, optional
            Number of base uniformly spaced timestamps (must be ``>= 2``).
            Mutually exclusive with ``dt``.
        dt : float, optional
            Base uniform time step in seconds (must be ``> 0``).
            Mutually exclusive with ``n_points``.

        Returns
        -------
        np.ndarray
            Strictly increasing 1D array of timestamps starting at ``0.0``,
            ending at :attr:`duration`, and guaranteed to contain every
            timestamp in :attr:`event_times`.

        Raises
        ------
        ValueError
            If both ``n_points`` and ``dt`` are provided, or if values are invalid.
        """
        if n_points is not None and dt is not None:
            raise ValueError("Specify at most one of 'n_points' or 'dt'.")

        if n_points is not None:
            n = _validate_positive_int(n_points, "n_points", minimum=2)
            base = np.linspace(0.0, self.duration, n, dtype=float)
        elif dt is not None:
            dt_val = _validate_positive_finite(dt, "dt")
            n_steps = math.floor(self.duration / dt_val)
            base = np.arange(n_steps + 1, dtype=float) * dt_val
        else:
            n = self._default_time_grid_points()
            base = np.linspace(0.0, self.duration, n, dtype=float)

        return _merge_time_grid(base, self.duration, self._extra_grid_times())

    def simulate(
        self,
        mechanism: Mechanism | SpeciesCollection | Sequence[Species] | Species,
        geometry: Geometry | str = "planar",
        grid: np.ndarray | Mesh1D | None = None,
        solver: BaseSolver | str = "scipy_ivp",
        t_eval: np.ndarray | Sequence[float] | None = None,
        solver_kwargs: Mapping[str, Any] | None = None,
        **kwargs: Any,
    ) -> TechniqueResult:
        """Simulate this technique with ``mechanism`` via :func:`~softpotato.techniques.simulate`.

        Convenience shorthand equivalent to
        ``simulate(self, mechanism, geometry=geometry, grid=grid, solver=solver, t_eval=t_eval, solver_kwargs=solver_kwargs, **kwargs)``.
        """
        from .pipeline import simulate as _simulate

        return _simulate(
            self,
            mechanism,
            geometry=geometry,
            grid=grid,
            solver=solver,
            t_eval=t_eval,
            solver_kwargs=solver_kwargs,
            **kwargs,
        )

mode property

mode: ControlMode

Control mode: 'potentiostatic' or 'galvanostatic'.

duration abstractmethod property

duration: float

Total experiment duration in seconds (\(t_{\max} > 0\)).

event_times property

event_times: tuple[float, ...]

Sorted interior discontinuity/vertex timestamps in (0, duration).

plot_specs property

plot_specs: dict[str, PlotSpec]

Ordered mapping of canonical plot kind to PlotSpec.

Includes technique-specific plots first (with the primary/default plot listed first), followed by universal plots ('i_vs_t', 'E_vs_t', 'c_vs_x') without duplicates.

available_plots property

available_plots: tuple[str, ...]

Ordered tuple of canonical plot kinds supported by this technique.

default_plot property

default_plot: str

Canonical plot kind used by default when plotting results of this technique.

excitation abstractmethod

excitation(t: float) -> float
excitation(t: ndarray) -> np.ndarray
excitation(t: float | ArrayLike) -> float | np.ndarray
excitation(t: float | ArrayLike) -> float | np.ndarray

Evaluate the excitation signal at time t.

Parameters:

Name Type Description Default
t float or array - like

Time(s) in seconds at which to evaluate the waveform.

required

Returns:

Type Description
float or ndarray

Excitation value(s) (potential in V for potentiostatic mode, or current in A for galvanostatic mode). Returns a Python float for scalar inputs and a np.ndarray matching the input shape for array-like inputs.

Source code in src/softpotato/techniques/base.py
@abstractmethod
def excitation(self, t: float | ArrayLike) -> float | np.ndarray:
    """Evaluate the excitation signal at time ``t``.

    Parameters
    ----------
    t : float or array-like
        Time(s) in seconds at which to evaluate the waveform.

    Returns
    -------
    float or np.ndarray
        Excitation value(s) (potential in V for potentiostatic mode, or
        current in A for galvanostatic mode). Returns a Python ``float``
        for scalar inputs and a ``np.ndarray`` matching the input shape
        for array-like inputs.
    """
    raise NotImplementedError

__call__

__call__(t: float) -> float
__call__(t: ndarray) -> np.ndarray
__call__(t: float | ArrayLike) -> float | np.ndarray
__call__(t: float | ArrayLike) -> float | np.ndarray

Callable alias for excitation.

Source code in src/softpotato/techniques/base.py
def __call__(self, t: float | ArrayLike) -> float | np.ndarray:
    """Callable alias for :meth:`excitation`."""
    return self.excitation(t)

potential

potential(t: float) -> float
potential(t: ndarray) -> np.ndarray
potential(t: float | ArrayLike) -> float | np.ndarray
potential(t: float | ArrayLike) -> float | np.ndarray

Evaluate applied electrode potential \(E(t)\) in Volts.

Only valid for mode='potentiostatic' techniques.

Parameters:

Name Type Description Default
t float or array - like

Time(s) in seconds.

required

Returns:

Type Description
float or ndarray

Applied potential \(E(t)\) in Volts.

Raises:

Type Description
ValueError

If the technique is not potentiostatic.

Source code in src/softpotato/techniques/base.py
def potential(self, t: float | ArrayLike) -> float | np.ndarray:
    """Evaluate applied electrode potential :math:`E(t)` in Volts.

    Only valid for ``mode='potentiostatic'`` techniques.

    Parameters
    ----------
    t : float or array-like
        Time(s) in seconds.

    Returns
    -------
    float or np.ndarray
        Applied potential :math:`E(t)` in Volts.

    Raises
    ------
    ValueError
        If the technique is not potentiostatic.
    """
    if self.mode != "potentiostatic":
        raise ValueError(
            "potential() is only available for potentiostatic techniques, "
            f"got mode={self.mode!r}."
        )
    return self.excitation(t)

current

current(t: float) -> float
current(t: ndarray) -> np.ndarray
current(t: float | ArrayLike) -> float | np.ndarray
current(t: float | ArrayLike) -> float | np.ndarray

Evaluate applied current \(I(t)\) in Amperes.

Only valid for mode='galvanostatic' techniques.

Parameters:

Name Type Description Default
t float or array - like

Time(s) in seconds.

required

Returns:

Type Description
float or ndarray

Applied current \(I(t)\) in Amperes.

Raises:

Type Description
ValueError

If the technique is not galvanostatic.

Source code in src/softpotato/techniques/base.py
def current(self, t: float | ArrayLike) -> float | np.ndarray:
    """Evaluate applied current :math:`I(t)` in Amperes.

    Only valid for ``mode='galvanostatic'`` techniques.

    Parameters
    ----------
    t : float or array-like
        Time(s) in seconds.

    Returns
    -------
    float or np.ndarray
        Applied current :math:`I(t)` in Amperes.

    Raises
    ------
    ValueError
        If the technique is not galvanostatic.
    """
    if self.mode != "galvanostatic":
        raise ValueError(
            "current() is only available for galvanostatic techniques, "
            f"got mode={self.mode!r}."
        )
    return self.excitation(t)

time_grid

time_grid(n_points: int | None = None, dt: float | None = None) -> np.ndarray

Generate evaluation timestamps covering [0, duration] and all events.

Parameters:

Name Type Description Default
n_points int

Number of base uniformly spaced timestamps (must be >= 2). Mutually exclusive with dt.

None
dt float

Base uniform time step in seconds (must be > 0). Mutually exclusive with n_points.

None

Returns:

Type Description
ndarray

Strictly increasing 1D array of timestamps starting at 0.0, ending at duration, and guaranteed to contain every timestamp in event_times.

Raises:

Type Description
ValueError

If both n_points and dt are provided, or if values are invalid.

Source code in src/softpotato/techniques/base.py
def time_grid(
    self,
    n_points: int | None = None,
    dt: float | None = None,
) -> np.ndarray:
    """Generate evaluation timestamps covering ``[0, duration]`` and all events.

    Parameters
    ----------
    n_points : int, optional
        Number of base uniformly spaced timestamps (must be ``>= 2``).
        Mutually exclusive with ``dt``.
    dt : float, optional
        Base uniform time step in seconds (must be ``> 0``).
        Mutually exclusive with ``n_points``.

    Returns
    -------
    np.ndarray
        Strictly increasing 1D array of timestamps starting at ``0.0``,
        ending at :attr:`duration`, and guaranteed to contain every
        timestamp in :attr:`event_times`.

    Raises
    ------
    ValueError
        If both ``n_points`` and ``dt`` are provided, or if values are invalid.
    """
    if n_points is not None and dt is not None:
        raise ValueError("Specify at most one of 'n_points' or 'dt'.")

    if n_points is not None:
        n = _validate_positive_int(n_points, "n_points", minimum=2)
        base = np.linspace(0.0, self.duration, n, dtype=float)
    elif dt is not None:
        dt_val = _validate_positive_finite(dt, "dt")
        n_steps = math.floor(self.duration / dt_val)
        base = np.arange(n_steps + 1, dtype=float) * dt_val
    else:
        n = self._default_time_grid_points()
        base = np.linspace(0.0, self.duration, n, dtype=float)

    return _merge_time_grid(base, self.duration, self._extra_grid_times())

simulate

simulate(mechanism: Mechanism | SpeciesCollection | Sequence[Species] | Species, geometry: Geometry | str = 'planar', grid: ndarray | Mesh1D | None = None, solver: BaseSolver | str = 'scipy_ivp', t_eval: ndarray | Sequence[float] | None = None, solver_kwargs: Mapping[str, Any] | None = None, **kwargs: Any) -> TechniqueResult

Simulate this technique with mechanism via simulate.

Convenience shorthand equivalent to simulate(self, mechanism, geometry=geometry, grid=grid, solver=solver, t_eval=t_eval, solver_kwargs=solver_kwargs, **kwargs).

Source code in src/softpotato/techniques/base.py
def simulate(
    self,
    mechanism: Mechanism | SpeciesCollection | Sequence[Species] | Species,
    geometry: Geometry | str = "planar",
    grid: np.ndarray | Mesh1D | None = None,
    solver: BaseSolver | str = "scipy_ivp",
    t_eval: np.ndarray | Sequence[float] | None = None,
    solver_kwargs: Mapping[str, Any] | None = None,
    **kwargs: Any,
) -> TechniqueResult:
    """Simulate this technique with ``mechanism`` via :func:`~softpotato.techniques.simulate`.

    Convenience shorthand equivalent to
    ``simulate(self, mechanism, geometry=geometry, grid=grid, solver=solver, t_eval=t_eval, solver_kwargs=solver_kwargs, **kwargs)``.
    """
    from .pipeline import simulate as _simulate

    return _simulate(
        self,
        mechanism,
        geometry=geometry,
        grid=grid,
        solver=solver,
        t_eval=t_eval,
        solver_kwargs=solver_kwargs,
        **kwargs,
    )

PlotSpec dataclass

Declarative specification for a plot supported by an electrochemical technique.

Attributes:

Name Type Description
kind str

Canonical concise plot key (e.g., 'voltammogram', 'i_vs_t', 'E_vs_t', 'c_vs_x').

title str

Default plot title.

x_label str

Default horizontal axis label including units.

y_label str

Default vertical axis label including units.

description str, default ''

Short human-readable description of the plot.

Source code in src/softpotato/techniques/base.py
@dataclass(frozen=True)
class PlotSpec:
    """Declarative specification for a plot supported by an electrochemical technique.

    Attributes
    ----------
    kind : str
        Canonical concise plot key (e.g., ``'voltammogram'``, ``'i_vs_t'``,
        ``'E_vs_t'``, ``'c_vs_x'``).
    title : str
        Default plot title.
    x_label : str
        Default horizontal axis label including units.
    y_label : str
        Default vertical axis label including units.
    description : str, default ''
        Short human-readable description of the plot.
    """

    kind: str
    title: str
    x_label: str
    y_label: str
    description: str = ""

Chronoamperometry

Bases: BaseTechnique

Potentiostatic step-potential waveform generator (Chronoamperometry).

Supports three construction modes, each optionally preceded by a resting (quiet) potential hold (E_quiet, t_quiet):

  1. Single potential step: Chronoamperometry(E_step=..., duration=...)
  2. Double potential step: Chronoamperometry(E_step1=..., E_step2=..., t_step1=..., t_step2=...)
  3. Arbitrary multi-step sequence: Chronoamperometry(potentials=[...], durations=[...])

At step transitions \(t = t_k\), the waveform is right-continuous: \(E(t) = E_k\) for \(t \in [t_k, t_{k+1})\), and \(E(t_{\max}) = E_{\text{last}}\).

Parameters:

Name Type Description Default
E_step float

Single-step applied potential in Volts. Must be paired with duration.

None
duration float

Single-step duration in seconds (\(> 0\)). Must be paired with E_step.

None
E_step1 float

First step potential in Volts for double-step chronoamperometry.

None
E_step2 float

Second (reversal) step potential in Volts for double-step chronoamperometry.

None
t_step1 float

First step duration in seconds (\(> 0\)).

None
t_step2 float

Second step duration in seconds (\(> 0\)).

None
potentials Sequence[float]

Ordered sequence of step potentials in Volts for multi-step experiments.

None
durations Sequence[float]

Ordered sequence of step durations in seconds (\(> 0\)), matching the length of potentials.

None
E_quiet float

Optional initial quiet/resting potential in Volts applied before the first step when t_quiet > 0.

None
t_quiet float

Optional initial quiet/resting duration in seconds (\(\ge 0\)). If t_quiet > 0, E_quiet must be provided.

0.0

Examples:

Single-step Cottrell experiment:

>>> from softpotato.techniques import Chronoamperometry
>>> ca = Chronoamperometry(E_step=-0.5, duration=5.0)
>>> ca.duration
5.0
>>> ca(2.5)
-0.5

Double-step chronoamperometry:

>>> dca = Chronoamperometry(E_step1=-0.5, E_step2=0.5, t_step1=2.0, t_step2=3.0)
>>> dca.event_times
(2.0,)
>>> dca(1.9), dca(2.0), dca(5.0)
(-0.5, 0.5, 0.5)
Source code in src/softpotato/techniques/chronoamperometry.py
class Chronoamperometry(BaseTechnique):
    r"""Potentiostatic step-potential waveform generator (Chronoamperometry).

    Supports three construction modes, each optionally preceded by a resting
    (quiet) potential hold ``(E_quiet, t_quiet)``:

    1. **Single potential step**: ``Chronoamperometry(E_step=..., duration=...)``
    2. **Double potential step**:
       ``Chronoamperometry(E_step1=..., E_step2=..., t_step1=..., t_step2=...)``
    3. **Arbitrary multi-step sequence**:
       ``Chronoamperometry(potentials=[...], durations=[...])``

    At step transitions :math:`t = t_k`, the waveform is right-continuous:
    :math:`E(t) = E_k` for :math:`t \in [t_k, t_{k+1})`, and
    :math:`E(t_{\max}) = E_{\text{last}}`.

    Parameters
    ----------
    E_step : float, optional
        Single-step applied potential in Volts. Must be paired with ``duration``.
    duration : float, optional
        Single-step duration in seconds (:math:`> 0`). Must be paired with ``E_step``.
    E_step1 : float, optional
        First step potential in Volts for double-step chronoamperometry.
    E_step2 : float, optional
        Second (reversal) step potential in Volts for double-step chronoamperometry.
    t_step1 : float, optional
        First step duration in seconds (:math:`> 0`).
    t_step2 : float, optional
        Second step duration in seconds (:math:`> 0`).
    potentials : Sequence[float], optional
        Ordered sequence of step potentials in Volts for multi-step experiments.
    durations : Sequence[float], optional
        Ordered sequence of step durations in seconds (:math:`> 0`), matching
        the length of ``potentials``.
    E_quiet : float, optional
        Optional initial quiet/resting potential in Volts applied before the
        first step when ``t_quiet > 0``.
    t_quiet : float, default 0.0
        Optional initial quiet/resting duration in seconds (:math:`\ge 0`).
        If ``t_quiet > 0``, ``E_quiet`` must be provided.

    Examples
    --------
    Single-step Cottrell experiment:

    >>> from softpotato.techniques import Chronoamperometry
    >>> ca = Chronoamperometry(E_step=-0.5, duration=5.0)
    >>> ca.duration
    5.0
    >>> ca(2.5)
    -0.5

    Double-step chronoamperometry:

    >>> dca = Chronoamperometry(E_step1=-0.5, E_step2=0.5, t_step1=2.0, t_step2=3.0)
    >>> dca.event_times
    (2.0,)
    >>> dca(1.9), dca(2.0), dca(5.0)
    (-0.5, 0.5, 0.5)
    """

    def __init__(
        self,
        E_step: float | None = None,
        duration: float | None = None,
        *,
        E_step1: float | None = None,
        E_step2: float | None = None,
        t_step1: float | None = None,
        t_step2: float | None = None,
        potentials: Sequence[float] | None = None,
        durations: Sequence[float] | None = None,
        E_quiet: float | None = None,
        t_quiet: float = 0.0,
    ) -> None:
        self._mode = "potentiostatic"

        single_any = E_step is not None or duration is not None
        double_any = any(x is not None for x in (E_step1, E_step2, t_step1, t_step2))
        multi_any = potentials is not None or durations is not None

        n_modes = int(single_any) + int(double_any) + int(multi_any)
        if n_modes == 0:
            raise ValueError(
                "Must specify one of: single-step (E_step, duration), "
                "double-step (E_step1, E_step2, t_step1, t_step2), or "
                "multi-step (potentials, durations)."
            )
        if n_modes > 1:
            raise ValueError(
                "Cannot mix single-step, double-step, and multi-step parameters."
            )

        step_potentials: list[float] = []
        step_durations: list[float] = []

        t_quiet_val = _validate_non_negative_finite(t_quiet, "t_quiet")
        e_quiet_val: float | None = (
            _validate_finite_real(E_quiet, "E_quiet") if E_quiet is not None else None
        )
        if t_quiet_val > 0.0:
            if e_quiet_val is None:
                raise ValueError("E_quiet must be provided when t_quiet > 0.")
            step_potentials.append(e_quiet_val)
            step_durations.append(t_quiet_val)

        if single_any:
            if E_step is None or duration is None:
                raise ValueError(
                    "Single-step mode requires both 'E_step' and 'duration'."
                )
            step_potentials.append(_validate_finite_real(E_step, "E_step"))
            step_durations.append(_validate_positive_finite(duration, "duration"))
        elif double_any:
            if any(x is None for x in (E_step1, E_step2, t_step1, t_step2)):
                raise ValueError(
                    "Double-step mode requires all of 'E_step1', 'E_step2', "
                    "'t_step1', and 't_step2'."
                )
            step_potentials.append(_validate_finite_real(E_step1, "E_step1"))
            step_potentials.append(_validate_finite_real(E_step2, "E_step2"))
            step_durations.append(_validate_positive_finite(t_step1, "t_step1"))
            step_durations.append(_validate_positive_finite(t_step2, "t_step2"))
        else:
            if potentials is None or durations is None:
                raise ValueError(
                    "Multi-step mode requires both 'potentials' and 'durations'."
                )
            if isinstance(potentials, (str, bytes)) or isinstance(
                durations, (str, bytes)
            ):
                raise TypeError(
                    "'potentials' and 'durations' must be numeric sequences."
                )
            pot_seq = list(potentials)
            dur_seq = list(durations)
            if len(pot_seq) == 0 or len(dur_seq) == 0:
                raise ValueError("'potentials' and 'durations' must not be empty.")
            if len(pot_seq) != len(dur_seq):
                raise ValueError(
                    f"'potentials' (len={len(pot_seq)}) and 'durations' "
                    f"(len={len(dur_seq)}) must have the same length."
                )
            for idx, (e_val, d_val) in enumerate(zip(pot_seq, dur_seq)):
                step_potentials.append(
                    _validate_finite_real(e_val, f"potentials[{idx}]")
                )
                step_durations.append(
                    _validate_positive_finite(d_val, f"durations[{idx}]")
                )

        self._E_quiet = e_quiet_val
        self._t_quiet = t_quiet_val
        self._potentials = tuple(step_potentials)
        self._durations = tuple(step_durations)

        starts: list[float] = []
        cursor = 0.0
        for d in self._durations:
            starts.append(cursor)
            cursor += d

        self._starts = np.asarray(starts, dtype=float)
        self._values = np.asarray(self._potentials, dtype=float)
        self._duration = float(cursor)
        self._event_times = _deduplicate_interior_events(starts[1:], self._duration)

    @property
    def potentials(self) -> tuple[float, ...]:
        """Ordered tuple of step potentials in Volts (including quiet hold if active)."""
        return self._potentials

    @property
    def durations(self) -> tuple[float, ...]:
        """Ordered tuple of step durations in seconds (including quiet hold if active)."""
        return self._durations

    @property
    def E_quiet(self) -> float | None:
        """Initial quiet/resting potential in Volts, or ``None``."""
        return self._E_quiet

    @property
    def t_quiet(self) -> float:
        """Initial quiet/resting duration in seconds."""
        return self._t_quiet

    @property
    def n_steps(self) -> int:
        """Total number of constant-potential segments."""
        return len(self._potentials)

    @property
    def step_times(self) -> tuple[float, ...]:
        """Start timestamps of each potential step."""
        return tuple(float(x) for x in self._starts)

    @property
    def duration(self) -> float:
        """Total experiment duration in seconds."""
        return self._duration

    @property
    def event_times(self) -> tuple[float, ...]:
        """Sorted interior step transition timestamps in ``(0, duration)``."""
        return self._event_times

    @overload
    def excitation(self, t: float) -> float: ...

    @overload
    def excitation(self, t: np.ndarray) -> np.ndarray: ...

    @overload
    def excitation(self, t: float | ArrayLike) -> float | np.ndarray: ...

    def excitation(self, t: float | ArrayLike) -> float | np.ndarray:
        normalized, is_scalar = _normalize_time_input(t)
        n_steps = len(self._values)

        if is_scalar:
            assert isinstance(normalized, float)
            if normalized <= 0.0:
                return float(self._values[0])
            if normalized >= self._duration:
                return float(self._values[-1])
            idx = int(np.searchsorted(self._starts, normalized, side="right")) - 1
            idx = min(max(idx, 0), n_steps - 1)
            return float(self._values[idx])

        assert isinstance(normalized, np.ndarray)
        orig_shape = normalized.shape
        flat = normalized.ravel()
        if flat.size == 0:
            return np.empty(orig_shape, dtype=float)

        clamped = np.clip(flat, 0.0, self._duration)
        indices = np.searchsorted(self._starts, clamped, side="right") - 1
        indices = np.clip(indices, 0, n_steps - 1)
        indices = np.where(clamped >= self._duration, n_steps - 1, indices)
        return self._values[indices].reshape(orig_shape)

    def _technique_plots(self) -> tuple[PlotSpec, ...]:
        return (
            PlotSpec(
                kind="i_vs_t",
                title="Chronoamperogram",
                x_label="$t$ / s",
                y_label="$I$ / A",
                description="Faradaic current transient following potential step(s).",
            ),
            PlotSpec(
                kind="Q_vs_t",
                title="Chronocoulogram",
                x_label="$t$ / s",
                y_label="$Q$ / C",
                description="Cumulative Faradaic charge Q(t) vs. time.",
            ),
        )

    def __repr__(self) -> str:
        return (
            f"Chronoamperometry(potentials={self._potentials!r}, "
            f"durations={self._durations!r})"
        )

potentials property

potentials: tuple[float, ...]

Ordered tuple of step potentials in Volts (including quiet hold if active).

durations property

durations: tuple[float, ...]

Ordered tuple of step durations in seconds (including quiet hold if active).

E_quiet property

E_quiet: float | None

Initial quiet/resting potential in Volts, or None.

t_quiet property

t_quiet: float

Initial quiet/resting duration in seconds.

n_steps property

n_steps: int

Total number of constant-potential segments.

step_times property

step_times: tuple[float, ...]

Start timestamps of each potential step.

duration property

duration: float

Total experiment duration in seconds.

event_times property

event_times: tuple[float, ...]

Sorted interior step transition timestamps in (0, duration).

Chronopotentiometry

Bases: BaseTechnique

Galvanostatic step-current waveform generator (Chronopotentiometry).

Supports two construction modes, each optionally preceded by an initial resting/quiet current hold (I_quiet, t_quiet):

  1. Single constant current step: Chronopotentiometry(current=..., duration=...)
  2. Multi-step current sequence (e.g., current-reversal chronopotentiometry): Chronopotentiometry(currents=[...], durations=[...])

Uses IUPAC polarity conventions: negative current (\(I < 0\)) is cathodic (reduction) and positive current (\(I > 0\)) is anodic (oxidation).

At step transitions \(t = t_k\), the waveform is right-continuous: \(I(t) = I_k\) for \(t \in [t_k, t_{k+1})\), and \(I(t_{\max}) = I_{\text{last}}\).

Parameters:

Name Type Description Default
current float

Constant applied current \(I\) in Amperes. Must be paired with duration.

None
duration float

Single-step duration in seconds (\(> 0\)). Must be paired with current.

None
currents Sequence[float]

Ordered sequence of applied currents in Amperes for multi-step experiments (such as current-reversal chronopotentiometry).

None
durations Sequence[float]

Ordered sequence of step durations in seconds (\(> 0\)), matching the length of currents.

None
I_quiet float

Optional initial quiet/resting current in Amperes applied before the first step when t_quiet > 0.

None
t_quiet float

Optional initial quiet/resting duration in seconds (\(\ge 0\)). If t_quiet > 0, I_quiet must be provided.

0.0

Examples:

Constant-current cathodic chronopotentiometry:

>>> from softpotato.techniques import Chronopotentiometry
>>> cp = Chronopotentiometry(current=-1e-4, duration=5.0)
>>> cp.mode
'galvanostatic'
>>> cp(2.5)
-0.0001

Current-reversal chronopotentiometry:

>>> rcp = Chronopotentiometry(currents=[-1e-4, 1e-4], durations=[2.0, 3.0])
>>> rcp.event_times
(2.0,)
>>> rcp(1.5), rcp(2.0)
(-0.0001, 0.0001)
Source code in src/softpotato/techniques/chronopotentiometry.py
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
class Chronopotentiometry(BaseTechnique):
    r"""Galvanostatic step-current waveform generator (Chronopotentiometry).

    Supports two construction modes, each optionally preceded by an initial
    resting/quiet current hold ``(I_quiet, t_quiet)``:

    1. **Single constant current step**:
       ``Chronopotentiometry(current=..., duration=...)``
    2. **Multi-step current sequence** (e.g., current-reversal chronopotentiometry):
       ``Chronopotentiometry(currents=[...], durations=[...])``

    Uses IUPAC polarity conventions: negative current (:math:`I < 0`) is cathodic
    (reduction) and positive current (:math:`I > 0`) is anodic (oxidation).

    At step transitions :math:`t = t_k`, the waveform is right-continuous:
    :math:`I(t) = I_k` for :math:`t \in [t_k, t_{k+1})`, and
    :math:`I(t_{\max}) = I_{\text{last}}`.

    Parameters
    ----------
    current : float, optional
        Constant applied current :math:`I` in Amperes. Must be paired with
        ``duration``.
    duration : float, optional
        Single-step duration in seconds (:math:`> 0`). Must be paired with
        ``current``.
    currents : Sequence[float], optional
        Ordered sequence of applied currents in Amperes for multi-step
        experiments (such as current-reversal chronopotentiometry).
    durations : Sequence[float], optional
        Ordered sequence of step durations in seconds (:math:`> 0`), matching
        the length of ``currents``.
    I_quiet : float, optional
        Optional initial quiet/resting current in Amperes applied before the
        first step when ``t_quiet > 0``.
    t_quiet : float, default 0.0
        Optional initial quiet/resting duration in seconds (:math:`\ge 0`).
        If ``t_quiet > 0``, ``I_quiet`` must be provided.

    Examples
    --------
    Constant-current cathodic chronopotentiometry:

    >>> from softpotato.techniques import Chronopotentiometry
    >>> cp = Chronopotentiometry(current=-1e-4, duration=5.0)
    >>> cp.mode
    'galvanostatic'
    >>> cp(2.5)
    -0.0001

    Current-reversal chronopotentiometry:

    >>> rcp = Chronopotentiometry(currents=[-1e-4, 1e-4], durations=[2.0, 3.0])
    >>> rcp.event_times
    (2.0,)
    >>> rcp(1.5), rcp(2.0)
    (-0.0001, 0.0001)
    """

    def __init__(
        self,
        current: float | None = None,
        duration: float | None = None,
        *,
        currents: Sequence[float] | None = None,
        durations: Sequence[float] | None = None,
        I_quiet: float | None = None,
        t_quiet: float = 0.0,
    ) -> None:
        self._mode = "galvanostatic"

        single_any = current is not None or duration is not None
        multi_any = currents is not None or durations is not None

        n_modes = int(single_any) + int(multi_any)
        if n_modes == 0:
            raise ValueError(
                "Must specify either single-step (current, duration) or "
                "multi-step (currents, durations)."
            )
        if n_modes > 1:
            raise ValueError("Cannot mix single-step and multi-step parameters.")

        step_currents: list[float] = []
        step_durations: list[float] = []

        t_quiet_val = _validate_non_negative_finite(t_quiet, "t_quiet")
        i_quiet_val: float | None = (
            _validate_finite_real(I_quiet, "I_quiet") if I_quiet is not None else None
        )
        if t_quiet_val > 0.0:
            if i_quiet_val is None:
                raise ValueError("I_quiet must be provided when t_quiet > 0.")
            step_currents.append(i_quiet_val)
            step_durations.append(t_quiet_val)

        if single_any:
            if current is None or duration is None:
                raise ValueError(
                    "Single-step mode requires both 'current' and 'duration'."
                )
            step_currents.append(_validate_finite_real(current, "current"))
            step_durations.append(_validate_positive_finite(duration, "duration"))
        else:
            if currents is None or durations is None:
                raise ValueError(
                    "Multi-step mode requires both 'currents' and 'durations'."
                )
            if isinstance(currents, (str, bytes)) or isinstance(
                durations, (str, bytes)
            ):
                raise TypeError("'currents' and 'durations' must be numeric sequences.")
            cur_seq = list(currents)
            dur_seq = list(durations)
            if len(cur_seq) == 0 or len(dur_seq) == 0:
                raise ValueError("'currents' and 'durations' must not be empty.")
            if len(cur_seq) != len(dur_seq):
                raise ValueError(
                    f"'currents' (len={len(cur_seq)}) and 'durations' "
                    f"(len={len(dur_seq)}) must have the same length."
                )
            for idx, (i_val, d_val) in enumerate(zip(cur_seq, dur_seq)):
                step_currents.append(_validate_finite_real(i_val, f"currents[{idx}]"))
                step_durations.append(
                    _validate_positive_finite(d_val, f"durations[{idx}]")
                )

        self._I_quiet = i_quiet_val
        self._t_quiet = t_quiet_val
        self._currents = tuple(step_currents)
        self._durations = tuple(step_durations)

        starts: list[float] = []
        cursor = 0.0
        for d in self._durations:
            starts.append(cursor)
            cursor += d

        self._starts = np.asarray(starts, dtype=float)
        self._values = np.asarray(self._currents, dtype=float)
        self._duration = float(cursor)
        self._event_times = _deduplicate_interior_events(starts[1:], self._duration)

    @property
    def currents(self) -> tuple[float, ...]:
        """Ordered tuple of step currents in Amperes (including quiet hold if active)."""
        return self._currents

    @property
    def durations(self) -> tuple[float, ...]:
        """Ordered tuple of step durations in seconds (including quiet hold if active)."""
        return self._durations

    @property
    def I_quiet(self) -> float | None:
        """Initial quiet/resting current in Amperes, or ``None``."""
        return self._I_quiet

    @property
    def t_quiet(self) -> float:
        """Initial quiet/resting duration in seconds."""
        return self._t_quiet

    @property
    def n_steps(self) -> int:
        """Total number of constant-current segments."""
        return len(self._currents)

    @property
    def step_times(self) -> tuple[float, ...]:
        """Start timestamps of each current step."""
        return tuple(float(x) for x in self._starts)

    @property
    def duration(self) -> float:
        """Total experiment duration in seconds."""
        return self._duration

    @property
    def event_times(self) -> tuple[float, ...]:
        """Sorted interior current step transition timestamps in ``(0, duration)``."""
        return self._event_times

    @overload
    def excitation(self, t: float) -> float: ...

    @overload
    def excitation(self, t: np.ndarray) -> np.ndarray: ...

    @overload
    def excitation(self, t: float | ArrayLike) -> float | np.ndarray: ...

    def excitation(self, t: float | ArrayLike) -> float | np.ndarray:
        normalized, is_scalar = _normalize_time_input(t)
        n_steps = len(self._values)

        if is_scalar:
            assert isinstance(normalized, float)
            if normalized <= 0.0:
                return float(self._values[0])
            if normalized >= self._duration:
                return float(self._values[-1])
            idx = int(np.searchsorted(self._starts, normalized, side="right")) - 1
            idx = min(max(idx, 0), n_steps - 1)
            return float(self._values[idx])

        assert isinstance(normalized, np.ndarray)
        orig_shape = normalized.shape
        flat = normalized.ravel()
        if flat.size == 0:
            return np.empty(orig_shape, dtype=float)

        clamped = np.clip(flat, 0.0, self._duration)
        indices = np.searchsorted(self._starts, clamped, side="right") - 1
        indices = np.clip(indices, 0, n_steps - 1)
        indices = np.where(clamped >= self._duration, n_steps - 1, indices)
        return self._values[indices].reshape(orig_shape)

    @overload
    def interfacial_flux(
        self,
        t: float,
        n: float,
        area: float,
        *,
        F: float = FARADAY,
    ) -> float: ...

    @overload
    def interfacial_flux(
        self,
        t: np.ndarray,
        n: float,
        area: float,
        *,
        F: float = FARADAY,
    ) -> np.ndarray: ...

    @overload
    def interfacial_flux(
        self,
        t: float | ArrayLike,
        n: float,
        area: float,
        *,
        F: float = FARADAY,
    ) -> float | np.ndarray: ...

    def interfacial_flux(
        self,
        t: float | ArrayLike,
        n: float,
        area: float,
        *,
        F: float = FARADAY,
    ) -> float | np.ndarray:
        r"""Compute interfacial molar flux :math:`J(t) = \frac{I(t)}{n F A}`.

        Follows IUPAC polarity conventions: cathodic reduction currents
        (:math:`I < 0`) yield negative flux (:math:`J < 0`, species consumed at
        the left electrode boundary), and anodic oxidation currents (:math:`I > 0`)
        yield positive flux (:math:`J > 0`).

        For direct Neumann boundary condition assignment at the left boundary
        (:math:`x = x_0`) where :math:`J_{\text{left}} = -D \frac{\partial c}{\partial x}`:

        - Oxidized species (consumed on reduction):
          :math:`\left.\frac{\partial c_{\text{Ox}}}{\partial x}\right|_{x_0} = -\frac{J(t)}{D_{\text{Ox}}}`
        - Reduced species (generated on reduction):
          :math:`\left.\frac{\partial c_{\text{Red}}}{\partial x}\right|_{x_0} = +\frac{J(t)}{D_{\text{Red}}}`

        Parameters
        ----------
        t : float or array-like
            Time(s) in seconds.
        n : float
            Number of electrons transferred per reaction (:math:`n > 0`).
        area : float
            Active electrode surface area :math:`A > 0` in :math:`\text{m}^2`
            or :math:`\text{cm}^2`.
        F : float, default FARADAY
            Faraday constant in :math:`\text{C}/\text{mol}` (:math:`F > 0`).

        Returns
        -------
        float or np.ndarray
            Interfacial molar flux :math:`J(t)` in :math:`\text{mol}/(\text{m}^2\cdot\text{s})`
            or :math:`\text{mol}/(\text{cm}^2\cdot\text{s})`.
        """
        n_val = _validate_positive_finite(n, "n")
        area_val = _validate_positive_finite(area, "area")
        f_val = _validate_positive_finite(F, "F")
        denom = n_val * f_val * area_val
        i_val = self.excitation(t)
        if isinstance(i_val, float):
            return i_val / denom
        return i_val / denom

    def recover_potential(
        self,
        c_ox: float | ArrayLike,
        c_red: float | ArrayLike,
        *,
        E0: float = 0.0,
        n: float = 1.0,
        T: float = STANDARD_TEMPERATURE,
        R: float = GAS_CONSTANT,
        F: float = FARADAY,
        kinetics: HeterogeneousKinetics | None = None,
        t: float | ArrayLike | None = None,
        current: float | ArrayLike | None = None,
        area: float | None = None,
    ) -> float | np.ndarray:
        r"""Recover electrode surface potential :math:`E(t)` from surface concentrations.

        - **Reversible (Nernstian) recovery** (``kinetics=None``):

          .. math::

              E(t) = E^{0\prime} + \frac{R T}{n F} \ln\left(\frac{c_{\text{Ox}}(0, t)}{c_{\text{Red}}(0, t)}\right)

        - **Finite-rate (Butler–Volmer / heterogeneous kinetics) recovery**
          (``kinetics`` provided): solves
          :math:`j_{\text{kinetics}}(E, c_{\text{Ox}}, c_{\text{Red}}) = I(t) / A`
          for :math:`E(t)` via safeguarded root-finding (:func:`scipy.optimize.brentq`).

        Parameters
        ----------
        c_ox : float or array-like
            Surface concentration of oxidized species :math:`c_{\text{Ox}}(0, t)`.
        c_red : float or array-like
            Surface concentration of reduced species :math:`c_{\text{Red}}(0, t)`.
        E0 : float, default 0.0
            Formal potential :math:`E^{0\prime}` in Volts (used when ``kinetics=None``).
        n : float, default 1.0
            Number of electrons transferred (:math:`n > 0`, used when ``kinetics=None``).
        T : float, default STANDARD_TEMPERATURE
            Temperature in Kelvin (:math:`T > 0`, used when ``kinetics=None``).
        R : float, default GAS_CONSTANT
            Molar gas constant (:math:`R > 0`, used when ``kinetics=None``).
        F : float, default FARADAY
            Faraday constant (:math:`F > 0`, used when ``kinetics=None``).
        kinetics : HeterogeneousKinetics, optional
            Optional heterogeneous kinetics model (e.g., :class:`ButlerVolmer`)
            for Butler–Volmer potential inversion. Requires ``area`` and either
            ``t`` or ``current``.
        t : float or array-like, optional
            Time(s) in seconds used to evaluate ``self.current(t)`` when
            ``kinetics`` is provided and ``current`` is omitted.
        current : float or array-like, optional
            Explicit applied current(s) in Amperes when ``kinetics`` is provided.
            Mutually exclusive with ``t``.
        area : float, optional
            Electrode surface area :math:`A > 0` (required when ``kinetics`` is
            provided).

        Returns
        -------
        float or np.ndarray
            Recovered electrode potential :math:`E(t)` in Volts. Returns ``np.nan``
            at points where inversion is undefined (e.g. depleted concentrations
            with non-zero opposing flux).
        """
        is_scalar = np.isscalar(c_ox) and np.isscalar(c_red)
        ox_arr, red_arr = np.broadcast_arrays(
            np.asarray(c_ox, dtype=float),
            np.asarray(c_red, dtype=float),
        )

        if kinetics is None:
            e0_val = _validate_finite_real(E0, "E0")
            n_val = _validate_positive_finite(n, "n")
            t_val = _validate_positive_finite(T, "T")
            r_val = _validate_positive_finite(R, "R")
            f_val = _validate_positive_finite(F, "F")
            vt = (r_val * t_val) / (n_val * f_val)

            with np.errstate(divide="ignore", invalid="ignore"):
                pot = np.where(
                    (ox_arr > 0.0) & (red_arr > 0.0),
                    e0_val + vt * np.log(ox_arr / red_arr),
                    np.where(
                        (ox_arr <= 0.0) & (red_arr > 0.0),
                        -np.inf,
                        np.where((ox_arr > 0.0) & (red_arr <= 0.0), np.inf, np.nan),
                    ),
                )
            if is_scalar:
                return float(pot.item())
            return np.asarray(pot, dtype=float)

        # Butler-Volmer / HeterogeneousKinetics inversion
        if area is None:
            raise ValueError("'area' must be provided when 'kinetics' is specified.")
        area_val = _validate_positive_finite(area, "area")

        if t is not None and current is not None:
            raise ValueError("Specify at most one of 't' or 'current'.")
        if current is not None:
            i_raw = np.asarray(current, dtype=float)
            is_scalar = is_scalar and np.isscalar(current)
        elif t is not None:
            i_raw = np.asarray(self.excitation(t), dtype=float)
            is_scalar = is_scalar and np.isscalar(t)
        elif self.n_steps == 1:
            i_raw = np.asarray(self._currents[0], dtype=float)
        else:
            raise ValueError(
                "Multi-step Chronopotentiometry requires 't' or 'current' when "
                "'kinetics' is provided."
            )

        ox_b, red_b, i_b = np.broadcast_arrays(ox_arr, red_arr, i_raw)
        j_target = i_b / area_val

        out = np.full(ox_b.shape, np.nan, dtype=float)
        flat_ox = ox_b.ravel()
        flat_red = red_b.ravel()
        flat_j = j_target.ravel()
        flat_out = out.ravel()

        e0_ref = float(kinetics.E0)
        for idx in range(flat_ox.size):
            co = float(flat_ox[idx])
            cr = float(flat_red[idx])
            jt = float(flat_j[idx])
            if not (math.isfinite(co) and math.isfinite(cr) and math.isfinite(jt)):
                continue
            if co < 0.0 or cr < 0.0:
                continue
            if co == 0.0 and cr == 0.0:
                continue
            if jt < 0.0 and co == 0.0:
                continue
            if jt > 0.0 and cr == 0.0:
                continue

            def _residual(
                E_val: float,
                _co: float = co,
                _cr: float = cr,
                _jt: float = jt,
            ) -> float:
                return float(kinetics.current_density(E_val, _co, _cr)) - _jt

            # Bracket around E0 (current_density is monotonically increasing in E)
            lo = e0_ref - 0.5
            hi = e0_ref + 0.5
            f_lo = _residual(lo)
            f_hi = _residual(hi)
            width = 0.5
            for _ in range(12):
                if math.isfinite(f_lo) and math.isfinite(f_hi) and f_lo * f_hi <= 0.0:
                    break
                width *= 2.0
                if not math.isfinite(f_lo) or f_lo > 0.0:
                    lo = e0_ref - width
                    f_lo = _residual(lo)
                if not math.isfinite(f_hi) or f_hi < 0.0:
                    hi = e0_ref + width
                    f_hi = _residual(hi)

            if math.isfinite(f_lo) and math.isfinite(f_hi) and f_lo * f_hi <= 0.0:
                flat_out[idx] = float(brentq(_residual, lo, hi, xtol=1e-12, rtol=1e-12))

        if is_scalar:
            return float(out.item())
        return out

    @staticmethod
    def detect_transition_time(
        t: ArrayLike,
        c_surface: ArrayLike,
        *,
        threshold: float = 1e-3,
        relative: bool = True,
    ) -> float | None:
        r"""Detect the chronopotentiometric transition time :math:`\tau`.

        Finds the earliest timestamp :math:`\tau` at which the electroactive
        reactant surface concentration :math:`c(0, t)` depletes to or below the
        specified threshold, using linear interpolation between adjacent samples.

        Parameters
        ----------
        t : array-like
            Strictly increasing 1D time array in seconds.
        c_surface : array-like
            1D surface concentration array :math:`c(0, t)` matching ``t``.
        threshold : float, default 1e-3
            Depletion threshold (:math:`\ge 0`). When ``relative=True``, interpreted
            as a fraction of the initial surface concentration ``c_surface[0]``
            (i.e. ``c_thresh = threshold * c_surface[0]``); otherwise an absolute
            concentration threshold.
        relative : bool, default True
            Whether ``threshold`` is relative to ``c_surface[0]``.

        Returns
        -------
        float or None
            Interpolated transition time :math:`\tau` in seconds, or ``None`` if
            surface concentration never drops to or below the threshold.
        """
        t_arr = np.asarray(t, dtype=float)
        c_arr = np.asarray(c_surface, dtype=float)
        if t_arr.ndim != 1 or c_arr.ndim != 1:
            raise ValueError("'t' and 'c_surface' must be 1D arrays.")
        if t_arr.size < 2 or t_arr.shape != c_arr.shape:
            raise ValueError("'t' and 'c_surface' must have the same length (>= 2).")
        if not np.all(np.isfinite(t_arr)) or not np.all(np.isfinite(c_arr)):
            raise ValueError("All values in 't' and 'c_surface' must be finite.")
        if np.any(np.diff(t_arr) <= 0.0):
            raise ValueError("'t' must be strictly increasing.")

        thresh_val = _validate_non_negative_finite(threshold, "threshold")
        if relative:
            if c_arr[0] <= 0.0:
                raise ValueError(
                    "Initial surface concentration c_surface[0] must be positive "
                    "when relative=True."
                )
            cutoff = thresh_val * float(c_arr[0])
        else:
            cutoff = thresh_val

        below = np.flatnonzero(c_arr <= cutoff)
        if below.size == 0:
            return None

        idx = int(below[0])
        if idx == 0:
            return float(t_arr[0])

        c0 = float(c_arr[idx - 1])
        c1 = float(c_arr[idx])
        t0 = float(t_arr[idx - 1])
        t1 = float(t_arr[idx])
        if c0 == c1:
            return t1
        frac = (c0 - cutoff) / (c0 - c1)
        return float(t0 + frac * (t1 - t0))

    def _technique_plots(self) -> tuple[PlotSpec, ...]:
        return (
            PlotSpec(
                kind="E_vs_t",
                title="Chronopotentiogram",
                x_label="$t$ / s",
                y_label="$E$ / V",
                description="Electrode potential response E(t) under controlled current.",
            ),
        )

    def __repr__(self) -> str:
        return (
            f"Chronopotentiometry(currents={self._currents!r}, "
            f"durations={self._durations!r})"
        )

currents property

currents: tuple[float, ...]

Ordered tuple of step currents in Amperes (including quiet hold if active).

durations property

durations: tuple[float, ...]

Ordered tuple of step durations in seconds (including quiet hold if active).

I_quiet property

I_quiet: float | None

Initial quiet/resting current in Amperes, or None.

t_quiet property

t_quiet: float

Initial quiet/resting duration in seconds.

n_steps property

n_steps: int

Total number of constant-current segments.

step_times property

step_times: tuple[float, ...]

Start timestamps of each current step.

duration property

duration: float

Total experiment duration in seconds.

event_times property

event_times: tuple[float, ...]

Sorted interior current step transition timestamps in (0, duration).

interfacial_flux

interfacial_flux(t: float, n: float, area: float, *, F: float = FARADAY) -> float
interfacial_flux(t: ndarray, n: float, area: float, *, F: float = FARADAY) -> np.ndarray
interfacial_flux(t: float | ArrayLike, n: float, area: float, *, F: float = FARADAY) -> float | np.ndarray
interfacial_flux(t: float | ArrayLike, n: float, area: float, *, F: float = FARADAY) -> float | np.ndarray

Compute interfacial molar flux \(J(t) = \frac{I(t)}{n F A}\).

Follows IUPAC polarity conventions: cathodic reduction currents (\(I < 0\)) yield negative flux (\(J < 0\), species consumed at the left electrode boundary), and anodic oxidation currents (\(I > 0\)) yield positive flux (\(J > 0\)).

For direct Neumann boundary condition assignment at the left boundary (\(x = x_0\)) where \(J_{\text{left}} = -D \frac{\partial c}{\partial x}\):

  • Oxidized species (consumed on reduction): \(\left.\frac{\partial c_{\text{Ox}}}{\partial x}\right|_{x_0} = -\frac{J(t)}{D_{\text{Ox}}}\)
  • Reduced species (generated on reduction): \(\left.\frac{\partial c_{\text{Red}}}{\partial x}\right|_{x_0} = +\frac{J(t)}{D_{\text{Red}}}\)

Parameters:

Name Type Description Default
t float or array - like

Time(s) in seconds.

required
n float

Number of electrons transferred per reaction (\(n > 0\)).

required
area float

Active electrode surface area \(A > 0\) in \(\text{m}^2\) or \(\text{cm}^2\).

required
F float

Faraday constant in \(\text{C}/\text{mol}\) (\(F > 0\)).

FARADAY

Returns:

Type Description
float or ndarray

Interfacial molar flux \(J(t)\) in \(\text{mol}/(\text{m}^2\cdot\text{s})\) or \(\text{mol}/(\text{cm}^2\cdot\text{s})\).

Source code in src/softpotato/techniques/chronopotentiometry.py
def interfacial_flux(
    self,
    t: float | ArrayLike,
    n: float,
    area: float,
    *,
    F: float = FARADAY,
) -> float | np.ndarray:
    r"""Compute interfacial molar flux :math:`J(t) = \frac{I(t)}{n F A}`.

    Follows IUPAC polarity conventions: cathodic reduction currents
    (:math:`I < 0`) yield negative flux (:math:`J < 0`, species consumed at
    the left electrode boundary), and anodic oxidation currents (:math:`I > 0`)
    yield positive flux (:math:`J > 0`).

    For direct Neumann boundary condition assignment at the left boundary
    (:math:`x = x_0`) where :math:`J_{\text{left}} = -D \frac{\partial c}{\partial x}`:

    - Oxidized species (consumed on reduction):
      :math:`\left.\frac{\partial c_{\text{Ox}}}{\partial x}\right|_{x_0} = -\frac{J(t)}{D_{\text{Ox}}}`
    - Reduced species (generated on reduction):
      :math:`\left.\frac{\partial c_{\text{Red}}}{\partial x}\right|_{x_0} = +\frac{J(t)}{D_{\text{Red}}}`

    Parameters
    ----------
    t : float or array-like
        Time(s) in seconds.
    n : float
        Number of electrons transferred per reaction (:math:`n > 0`).
    area : float
        Active electrode surface area :math:`A > 0` in :math:`\text{m}^2`
        or :math:`\text{cm}^2`.
    F : float, default FARADAY
        Faraday constant in :math:`\text{C}/\text{mol}` (:math:`F > 0`).

    Returns
    -------
    float or np.ndarray
        Interfacial molar flux :math:`J(t)` in :math:`\text{mol}/(\text{m}^2\cdot\text{s})`
        or :math:`\text{mol}/(\text{cm}^2\cdot\text{s})`.
    """
    n_val = _validate_positive_finite(n, "n")
    area_val = _validate_positive_finite(area, "area")
    f_val = _validate_positive_finite(F, "F")
    denom = n_val * f_val * area_val
    i_val = self.excitation(t)
    if isinstance(i_val, float):
        return i_val / denom
    return i_val / denom

recover_potential

recover_potential(c_ox: float | ArrayLike, c_red: float | ArrayLike, *, E0: float = 0.0, n: float = 1.0, T: float = STANDARD_TEMPERATURE, R: float = GAS_CONSTANT, F: float = FARADAY, kinetics: HeterogeneousKinetics | None = None, t: float | ArrayLike | None = None, current: float | ArrayLike | None = None, area: float | None = None) -> float | np.ndarray

Recover electrode surface potential \(E(t)\) from surface concentrations.

  • Reversible (Nernstian) recovery (kinetics=None):

    \[ E(t) = E^{0\prime} + \frac{R T}{n F} \ln\left(\frac{c_{\text{Ox}}(0, t)}{c_{\text{Red}}(0, t)}\right) \]
  • Finite-rate (Butler–Volmer / heterogeneous kinetics) recovery (kinetics provided): solves \(j_{\text{kinetics}}(E, c_{\text{Ox}}, c_{\text{Red}}) = I(t) / A\) for \(E(t)\) via safeguarded root-finding (scipy.optimize.brentq).

Parameters:

Name Type Description Default
c_ox float or array - like

Surface concentration of oxidized species \(c_{\text{Ox}}(0, t)\).

required
c_red float or array - like

Surface concentration of reduced species \(c_{\text{Red}}(0, t)\).

required
E0 float

Formal potential \(E^{0\prime}\) in Volts (used when kinetics=None).

0.0
n float

Number of electrons transferred (\(n > 0\), used when kinetics=None).

1.0
T float

Temperature in Kelvin (\(T > 0\), used when kinetics=None).

STANDARD_TEMPERATURE
R float

Molar gas constant (\(R > 0\), used when kinetics=None).

GAS_CONSTANT
F float

Faraday constant (\(F > 0\), used when kinetics=None).

FARADAY
kinetics HeterogeneousKinetics

Optional heterogeneous kinetics model (e.g., ButlerVolmer) for Butler–Volmer potential inversion. Requires area and either t or current.

None
t float or array - like

Time(s) in seconds used to evaluate self.current(t) when kinetics is provided and current is omitted.

None
current float or array - like

Explicit applied current(s) in Amperes when kinetics is provided. Mutually exclusive with t.

None
area float

Electrode surface area \(A > 0\) (required when kinetics is provided).

None

Returns:

Type Description
float or ndarray

Recovered electrode potential \(E(t)\) in Volts. Returns np.nan at points where inversion is undefined (e.g. depleted concentrations with non-zero opposing flux).

Source code in src/softpotato/techniques/chronopotentiometry.py
def recover_potential(
    self,
    c_ox: float | ArrayLike,
    c_red: float | ArrayLike,
    *,
    E0: float = 0.0,
    n: float = 1.0,
    T: float = STANDARD_TEMPERATURE,
    R: float = GAS_CONSTANT,
    F: float = FARADAY,
    kinetics: HeterogeneousKinetics | None = None,
    t: float | ArrayLike | None = None,
    current: float | ArrayLike | None = None,
    area: float | None = None,
) -> float | np.ndarray:
    r"""Recover electrode surface potential :math:`E(t)` from surface concentrations.

    - **Reversible (Nernstian) recovery** (``kinetics=None``):

      .. math::

          E(t) = E^{0\prime} + \frac{R T}{n F} \ln\left(\frac{c_{\text{Ox}}(0, t)}{c_{\text{Red}}(0, t)}\right)

    - **Finite-rate (Butler–Volmer / heterogeneous kinetics) recovery**
      (``kinetics`` provided): solves
      :math:`j_{\text{kinetics}}(E, c_{\text{Ox}}, c_{\text{Red}}) = I(t) / A`
      for :math:`E(t)` via safeguarded root-finding (:func:`scipy.optimize.brentq`).

    Parameters
    ----------
    c_ox : float or array-like
        Surface concentration of oxidized species :math:`c_{\text{Ox}}(0, t)`.
    c_red : float or array-like
        Surface concentration of reduced species :math:`c_{\text{Red}}(0, t)`.
    E0 : float, default 0.0
        Formal potential :math:`E^{0\prime}` in Volts (used when ``kinetics=None``).
    n : float, default 1.0
        Number of electrons transferred (:math:`n > 0`, used when ``kinetics=None``).
    T : float, default STANDARD_TEMPERATURE
        Temperature in Kelvin (:math:`T > 0`, used when ``kinetics=None``).
    R : float, default GAS_CONSTANT
        Molar gas constant (:math:`R > 0`, used when ``kinetics=None``).
    F : float, default FARADAY
        Faraday constant (:math:`F > 0`, used when ``kinetics=None``).
    kinetics : HeterogeneousKinetics, optional
        Optional heterogeneous kinetics model (e.g., :class:`ButlerVolmer`)
        for Butler–Volmer potential inversion. Requires ``area`` and either
        ``t`` or ``current``.
    t : float or array-like, optional
        Time(s) in seconds used to evaluate ``self.current(t)`` when
        ``kinetics`` is provided and ``current`` is omitted.
    current : float or array-like, optional
        Explicit applied current(s) in Amperes when ``kinetics`` is provided.
        Mutually exclusive with ``t``.
    area : float, optional
        Electrode surface area :math:`A > 0` (required when ``kinetics`` is
        provided).

    Returns
    -------
    float or np.ndarray
        Recovered electrode potential :math:`E(t)` in Volts. Returns ``np.nan``
        at points where inversion is undefined (e.g. depleted concentrations
        with non-zero opposing flux).
    """
    is_scalar = np.isscalar(c_ox) and np.isscalar(c_red)
    ox_arr, red_arr = np.broadcast_arrays(
        np.asarray(c_ox, dtype=float),
        np.asarray(c_red, dtype=float),
    )

    if kinetics is None:
        e0_val = _validate_finite_real(E0, "E0")
        n_val = _validate_positive_finite(n, "n")
        t_val = _validate_positive_finite(T, "T")
        r_val = _validate_positive_finite(R, "R")
        f_val = _validate_positive_finite(F, "F")
        vt = (r_val * t_val) / (n_val * f_val)

        with np.errstate(divide="ignore", invalid="ignore"):
            pot = np.where(
                (ox_arr > 0.0) & (red_arr > 0.0),
                e0_val + vt * np.log(ox_arr / red_arr),
                np.where(
                    (ox_arr <= 0.0) & (red_arr > 0.0),
                    -np.inf,
                    np.where((ox_arr > 0.0) & (red_arr <= 0.0), np.inf, np.nan),
                ),
            )
        if is_scalar:
            return float(pot.item())
        return np.asarray(pot, dtype=float)

    # Butler-Volmer / HeterogeneousKinetics inversion
    if area is None:
        raise ValueError("'area' must be provided when 'kinetics' is specified.")
    area_val = _validate_positive_finite(area, "area")

    if t is not None and current is not None:
        raise ValueError("Specify at most one of 't' or 'current'.")
    if current is not None:
        i_raw = np.asarray(current, dtype=float)
        is_scalar = is_scalar and np.isscalar(current)
    elif t is not None:
        i_raw = np.asarray(self.excitation(t), dtype=float)
        is_scalar = is_scalar and np.isscalar(t)
    elif self.n_steps == 1:
        i_raw = np.asarray(self._currents[0], dtype=float)
    else:
        raise ValueError(
            "Multi-step Chronopotentiometry requires 't' or 'current' when "
            "'kinetics' is provided."
        )

    ox_b, red_b, i_b = np.broadcast_arrays(ox_arr, red_arr, i_raw)
    j_target = i_b / area_val

    out = np.full(ox_b.shape, np.nan, dtype=float)
    flat_ox = ox_b.ravel()
    flat_red = red_b.ravel()
    flat_j = j_target.ravel()
    flat_out = out.ravel()

    e0_ref = float(kinetics.E0)
    for idx in range(flat_ox.size):
        co = float(flat_ox[idx])
        cr = float(flat_red[idx])
        jt = float(flat_j[idx])
        if not (math.isfinite(co) and math.isfinite(cr) and math.isfinite(jt)):
            continue
        if co < 0.0 or cr < 0.0:
            continue
        if co == 0.0 and cr == 0.0:
            continue
        if jt < 0.0 and co == 0.0:
            continue
        if jt > 0.0 and cr == 0.0:
            continue

        def _residual(
            E_val: float,
            _co: float = co,
            _cr: float = cr,
            _jt: float = jt,
        ) -> float:
            return float(kinetics.current_density(E_val, _co, _cr)) - _jt

        # Bracket around E0 (current_density is monotonically increasing in E)
        lo = e0_ref - 0.5
        hi = e0_ref + 0.5
        f_lo = _residual(lo)
        f_hi = _residual(hi)
        width = 0.5
        for _ in range(12):
            if math.isfinite(f_lo) and math.isfinite(f_hi) and f_lo * f_hi <= 0.0:
                break
            width *= 2.0
            if not math.isfinite(f_lo) or f_lo > 0.0:
                lo = e0_ref - width
                f_lo = _residual(lo)
            if not math.isfinite(f_hi) or f_hi < 0.0:
                hi = e0_ref + width
                f_hi = _residual(hi)

        if math.isfinite(f_lo) and math.isfinite(f_hi) and f_lo * f_hi <= 0.0:
            flat_out[idx] = float(brentq(_residual, lo, hi, xtol=1e-12, rtol=1e-12))

    if is_scalar:
        return float(out.item())
    return out

detect_transition_time staticmethod

detect_transition_time(t: ArrayLike, c_surface: ArrayLike, *, threshold: float = 0.001, relative: bool = True) -> float | None

Detect the chronopotentiometric transition time \(\tau\).

Finds the earliest timestamp \(\tau\) at which the electroactive reactant surface concentration \(c(0, t)\) depletes to or below the specified threshold, using linear interpolation between adjacent samples.

Parameters:

Name Type Description Default
t array - like

Strictly increasing 1D time array in seconds.

required
c_surface array - like

1D surface concentration array \(c(0, t)\) matching t.

required
threshold float

Depletion threshold (\(\ge 0\)). When relative=True, interpreted as a fraction of the initial surface concentration c_surface[0] (i.e. c_thresh = threshold * c_surface[0]); otherwise an absolute concentration threshold.

1e-3
relative bool

Whether threshold is relative to c_surface[0].

True

Returns:

Type Description
float or None

Interpolated transition time \(\tau\) in seconds, or None if surface concentration never drops to or below the threshold.

Source code in src/softpotato/techniques/chronopotentiometry.py
@staticmethod
def detect_transition_time(
    t: ArrayLike,
    c_surface: ArrayLike,
    *,
    threshold: float = 1e-3,
    relative: bool = True,
) -> float | None:
    r"""Detect the chronopotentiometric transition time :math:`\tau`.

    Finds the earliest timestamp :math:`\tau` at which the electroactive
    reactant surface concentration :math:`c(0, t)` depletes to or below the
    specified threshold, using linear interpolation between adjacent samples.

    Parameters
    ----------
    t : array-like
        Strictly increasing 1D time array in seconds.
    c_surface : array-like
        1D surface concentration array :math:`c(0, t)` matching ``t``.
    threshold : float, default 1e-3
        Depletion threshold (:math:`\ge 0`). When ``relative=True``, interpreted
        as a fraction of the initial surface concentration ``c_surface[0]``
        (i.e. ``c_thresh = threshold * c_surface[0]``); otherwise an absolute
        concentration threshold.
    relative : bool, default True
        Whether ``threshold`` is relative to ``c_surface[0]``.

    Returns
    -------
    float or None
        Interpolated transition time :math:`\tau` in seconds, or ``None`` if
        surface concentration never drops to or below the threshold.
    """
    t_arr = np.asarray(t, dtype=float)
    c_arr = np.asarray(c_surface, dtype=float)
    if t_arr.ndim != 1 or c_arr.ndim != 1:
        raise ValueError("'t' and 'c_surface' must be 1D arrays.")
    if t_arr.size < 2 or t_arr.shape != c_arr.shape:
        raise ValueError("'t' and 'c_surface' must have the same length (>= 2).")
    if not np.all(np.isfinite(t_arr)) or not np.all(np.isfinite(c_arr)):
        raise ValueError("All values in 't' and 'c_surface' must be finite.")
    if np.any(np.diff(t_arr) <= 0.0):
        raise ValueError("'t' must be strictly increasing.")

    thresh_val = _validate_non_negative_finite(threshold, "threshold")
    if relative:
        if c_arr[0] <= 0.0:
            raise ValueError(
                "Initial surface concentration c_surface[0] must be positive "
                "when relative=True."
            )
        cutoff = thresh_val * float(c_arr[0])
    else:
        cutoff = thresh_val

    below = np.flatnonzero(c_arr <= cutoff)
    if below.size == 0:
        return None

    idx = int(below[0])
    if idx == 0:
        return float(t_arr[0])

    c0 = float(c_arr[idx - 1])
    c1 = float(c_arr[idx])
    t0 = float(t_arr[idx - 1])
    t1 = float(t_arr[idx])
    if c0 == c1:
        return t1
    frac = (c0 - cutoff) / (c0 - c1)
    return float(t0 + frac * (t1 - t0))

CVDiagnostics dataclass

Summary voltammetric peak diagnostics for a CV or LSV trace.

Attributes:

Name Type Description
anodic_peak PeakInfo or None

Dominant anodic (positive current) peak, or None if not detected.

cathodic_peak PeakInfo or None

Dominant cathodic (negative current) peak, or None if not detected.

delta_Ep float or None

Peak-to-peak separation \(\Delta E_p = |E_{pa} - E_{pc}|\) in Volts when both peaks are detected, otherwise None.

E_half float or None

Midpoint potential \(E_{1/2} = \frac{1}{2}(E_{pa} + E_{pc})\) in Volts when both peaks are detected, otherwise None.

peak_current_ratio float or None

Magnitude ratio \(|I_{pa} / I_{pc}|\) when both peaks are detected and \(I_{pc} \neq 0\), otherwise None.

Source code in src/softpotato/techniques/diagnostics.py
@dataclass(frozen=True)
class CVDiagnostics:
    r"""Summary voltammetric peak diagnostics for a CV or LSV trace.

    Attributes
    ----------
    anodic_peak : PeakInfo or None
        Dominant anodic (positive current) peak, or ``None`` if not detected.
    cathodic_peak : PeakInfo or None
        Dominant cathodic (negative current) peak, or ``None`` if not detected.
    delta_Ep : float or None
        Peak-to-peak separation :math:`\Delta E_p = |E_{pa} - E_{pc}|` in Volts
        when both peaks are detected, otherwise ``None``.
    E_half : float or None
        Midpoint potential :math:`E_{1/2} = \frac{1}{2}(E_{pa} + E_{pc})` in
        Volts when both peaks are detected, otherwise ``None``.
    peak_current_ratio : float or None
        Magnitude ratio :math:`|I_{pa} / I_{pc}|` when both peaks are detected
        and :math:`I_{pc} \neq 0`, otherwise ``None``.
    """

    anodic_peak: PeakInfo | None
    cathodic_peak: PeakInfo | None
    delta_Ep: float | None
    E_half: float | None
    peak_current_ratio: float | None

NicholsonDiagnostics dataclass

Combined Nicholson and Matsuda–Ayabe kinetic diagnostics for CV.

Attributes:

Name Type Description
delta_Ep float

Peak-to-peak potential separation \(\Delta E_p\) in Volts.

delta_Ep_mv float

Peak-to-peak potential separation \(\Delta E_p\) in millivolts.

psi float

Dimensionless Nicholson kinetic parameter \(\Psi\).

k0 float

Extracted standard heterogeneous rate constant \(k^0\) in units consistent with \(D\) (e.g., \(\text{m}/\text{s}\) or \(\text{cm}/\text{s}\)).

lambda_param float

Dimensionless Matsuda–Ayabe reversibility parameter \(\Lambda = \sqrt{\pi}\,\Psi\).

regime {'reversible', 'quasi-reversible', 'irreversible'}

Matsuda–Ayabe kinetic reversibility classification.

nicholson NicholsonResult

Underlying NicholsonResult.

matsuda_ayabe MatsudaAyabeResult

Underlying MatsudaAyabeResult.

peaks CVDiagnostics or None

Detected voltammetric peaks when analyzed from a TechniqueResult or (E, I) arrays, or None when a scalar delta_Ep was supplied.

Source code in src/softpotato/techniques/diagnostics.py
@dataclass(frozen=True)
class NicholsonDiagnostics:
    r"""Combined Nicholson and Matsuda–Ayabe kinetic diagnostics for CV.

    Attributes
    ----------
    delta_Ep : float
        Peak-to-peak potential separation :math:`\Delta E_p` in Volts.
    delta_Ep_mv : float
        Peak-to-peak potential separation :math:`\Delta E_p` in millivolts.
    psi : float
        Dimensionless Nicholson kinetic parameter :math:`\Psi`.
    k0 : float
        Extracted standard heterogeneous rate constant :math:`k^0` in units
        consistent with :math:`D` (e.g., :math:`\text{m}/\text{s}` or
        :math:`\text{cm}/\text{s}`).
    lambda_param : float
        Dimensionless Matsuda–Ayabe reversibility parameter
        :math:`\Lambda = \sqrt{\pi}\,\Psi`.
    regime : {'reversible', 'quasi-reversible', 'irreversible'}
        Matsuda–Ayabe kinetic reversibility classification.
    nicholson : NicholsonResult
        Underlying :class:`~softpotato.analytical.voltammetry.NicholsonResult`.
    matsuda_ayabe : MatsudaAyabeResult
        Underlying :class:`~softpotato.analytical.voltammetry.MatsudaAyabeResult`.
    peaks : CVDiagnostics or None
        Detected voltammetric peaks when analyzed from a :class:`TechniqueResult`
        or ``(E, I)`` arrays, or ``None`` when a scalar ``delta_Ep`` was supplied.
    """

    delta_Ep: float
    delta_Ep_mv: float
    psi: float
    k0: float
    lambda_param: float
    regime: Literal["reversible", "quasi-reversible", "irreversible"]
    nicholson: NicholsonResult
    matsuda_ayabe: MatsudaAyabeResult
    peaks: CVDiagnostics | None = None

PeakInfo dataclass

Metadata for a single detected voltammetric current peak.

Attributes:

Name Type Description
E_peak float

Peak potential \(E_p\) in Volts (parabolically refined when enabled).

I_peak float

Peak current \(I_p\) in Amperes under IUPAC polarity conventions (positive for anodic, negative for cathodic).

index int

Discrete sample index of the detected local extremum in the analyzed potential/current arrays.

E_half_peak float or None

Half-peak potential \(E_{p/2}\) in Volts on the rising (pre-peak) flank where \(I = I_p / 2\), or None if not crossed.

polarity {'anodic', 'cathodic'}

Peak polarity: 'anodic' (\(I_p > 0\)) or 'cathodic' (\(I_p < 0\)).

Source code in src/softpotato/techniques/diagnostics.py
@dataclass(frozen=True)
class PeakInfo:
    r"""Metadata for a single detected voltammetric current peak.

    Attributes
    ----------
    E_peak : float
        Peak potential :math:`E_p` in Volts (parabolically refined when enabled).
    I_peak : float
        Peak current :math:`I_p` in Amperes under IUPAC polarity conventions
        (positive for anodic, negative for cathodic).
    index : int
        Discrete sample index of the detected local extremum in the analyzed
        potential/current arrays.
    E_half_peak : float or None
        Half-peak potential :math:`E_{p/2}` in Volts on the rising (pre-peak)
        flank where :math:`I = I_p / 2`, or ``None`` if not crossed.
    polarity : {'anodic', 'cathodic'}
        Peak polarity: ``'anodic'`` (:math:`I_p > 0`) or ``'cathodic'``
        (:math:`I_p < 0`).
    """

    E_peak: float
    I_peak: float
    index: int
    E_half_peak: float | None
    polarity: PeakPolarity

SandDiagnostics dataclass

Diagnostic summary for galvanostatic chronopotentiometry (Sand analysis).

Attributes:

Name Type Description
tau float or None

Detected transition time \(\tau\) in seconds, or None if no depletion/inflection transition occurred.

tau_theoretical float or None

Theoretical Sand transition time from sand_transition_time when D is supplied, otherwise None.

relative_error float or None

Relative error \(|\tau - \tau_{\text{th}}| / \tau_{\text{th}}\) when both tau and tau_theoretical are available, else None.

sand_constant float or None

Experimental Sand product \(|I|\sqrt{\tau}\) in \(\text{A}\cdot\text{s}^{1/2}\) when tau is detected.

D_estimated float or None

Diffusion coefficient \(D = \frac{4 I^2 \tau}{\pi (n F A c^*)^2}\) estimated from the detected transition time.

current float

Applied galvanostatic current \(I\) in Amperes (signed IUPAC).

detection_method {'concentration', 'potential', 'none'}

Signal source used to detect \(\tau\).

Source code in src/softpotato/techniques/diagnostics.py
@dataclass(frozen=True)
class SandDiagnostics:
    r"""Diagnostic summary for galvanostatic chronopotentiometry (Sand analysis).

    Attributes
    ----------
    tau : float or None
        Detected transition time :math:`\tau` in seconds, or ``None`` if no
        depletion/inflection transition occurred.
    tau_theoretical : float or None
        Theoretical Sand transition time from
        :func:`~softpotato.analytical.step.sand_transition_time` when ``D`` is
        supplied, otherwise ``None``.
    relative_error : float or None
        Relative error :math:`|\tau - \tau_{\text{th}}| / \tau_{\text{th}}`
        when both ``tau`` and ``tau_theoretical`` are available, else ``None``.
    sand_constant : float or None
        Experimental Sand product :math:`|I|\sqrt{\tau}` in
        :math:`\text{A}\cdot\text{s}^{1/2}` when ``tau`` is detected.
    D_estimated : float or None
        Diffusion coefficient :math:`D = \frac{4 I^2 \tau}{\pi (n F A c^*)^2}`
        estimated from the detected transition time.
    current : float
        Applied galvanostatic current :math:`I` in Amperes (signed IUPAC).
    detection_method : {'concentration', 'potential', 'none'}
        Signal source used to detect :math:`\tau`.
    """

    tau: float | None
    tau_theoretical: float | None
    relative_error: float | None
    sand_constant: float | None
    D_estimated: float | None
    current: float
    detection_method: Literal["concentration", "potential", "none"]

DifferentialPulseVoltammetry

Bases: BaseTechnique

Differential Pulse Voltammetry (DPV) waveform generator.

Superimposes constant-amplitude potential pulses \(\Delta E_p\) of width \(t_p\) onto a linear staircase ramp from \(E_{\text{start}}\) to \(E_{\text{end}}\) with step increment \(\Delta E_s > 0\) and cycle period \(\tau > t_p\).

Within each cycle \(k \in \{0, \dots, N-1\}\) over \([k\tau, (k+1)\tau)\):

  • Base hold (\(t \in [k\tau, k\tau + \tau - t_p)\)): \(E(t) = E_{\text{base}, k}\)
  • Pulse hold (\(t \in [k\tau + \tau - t_p, (k+1)\tau)\)): \(E(t) = E_{\text{base}, k} + \Delta E_p\)

Currents are sampled near the end of each base hold (\(I_{\text{pre}}\)) and near the end of each pulse hold (\(I_{\text{pulse}}\)) via sample_currents, yielding \(\Delta I = I_{\text{pulse}} - I_{\text{pre}}\).

Parameters:

Name Type Description Default
E_start float

Initial staircase base potential in Volts.

required
E_end float

Final staircase base potential in Volts (must differ from E_start).

required
step_height float

Staircase potential step magnitude \(\Delta E_s > 0\) in Volts.

required
pulse_amplitude float

Pulse potential amplitude \(\Delta E_p \neq 0\) in Volts (positive for anodic pulses, negative for cathodic pulses).

required
pulse_width float

Pulse duration \(t_p > 0\) in seconds.

required
pulse_period float

Total cycle period \(\tau > t_p\) in seconds.

required
sample_fraction float

Fraction \(\in (0, 1]\) of the base/pulse segment duration near the end of each segment over which current is averaged in sample_currents.

0.1

Examples:

>>> from softpotato.techniques import DifferentialPulseVoltammetry
>>> dpv = DifferentialPulseVoltammetry(
...     E_start=0.2,
...     E_end=-0.2,
...     step_height=0.05,
...     pulse_amplitude=-0.025,
...     pulse_width=0.05,
...     pulse_period=0.5,
... )
>>> dpv.n_steps
9
>>> dpv.duration
4.5
Source code in src/softpotato/techniques/pulse.py
class DifferentialPulseVoltammetry(BaseTechnique):
    r"""Differential Pulse Voltammetry (DPV) waveform generator.

    Superimposes constant-amplitude potential pulses :math:`\Delta E_p` of width
    :math:`t_p` onto a linear staircase ramp from :math:`E_{\text{start}}` to
    :math:`E_{\text{end}}` with step increment :math:`\Delta E_s > 0` and cycle
    period :math:`\tau > t_p`.

    Within each cycle :math:`k \in \{0, \dots, N-1\}` over
    :math:`[k\tau, (k+1)\tau)`:

    - **Base hold** (:math:`t \in [k\tau, k\tau + \tau - t_p)`):
      :math:`E(t) = E_{\text{base}, k}`
    - **Pulse hold** (:math:`t \in [k\tau + \tau - t_p, (k+1)\tau)`):
      :math:`E(t) = E_{\text{base}, k} + \Delta E_p`

    Currents are sampled near the end of each base hold (:math:`I_{\text{pre}}`)
    and near the end of each pulse hold (:math:`I_{\text{pulse}}`) via
    :meth:`sample_currents`, yielding :math:`\Delta I = I_{\text{pulse}} - I_{\text{pre}}`.

    Parameters
    ----------
    E_start : float
        Initial staircase base potential in Volts.
    E_end : float
        Final staircase base potential in Volts (must differ from ``E_start``).
    step_height : float
        Staircase potential step magnitude :math:`\Delta E_s > 0` in Volts.
    pulse_amplitude : float
        Pulse potential amplitude :math:`\Delta E_p \neq 0` in Volts (positive
        for anodic pulses, negative for cathodic pulses).
    pulse_width : float
        Pulse duration :math:`t_p > 0` in seconds.
    pulse_period : float
        Total cycle period :math:`\tau > t_p` in seconds.
    sample_fraction : float, default 0.1
        Fraction :math:`\in (0, 1]` of the base/pulse segment duration near the
        end of each segment over which current is averaged in :meth:`sample_currents`.

    Examples
    --------
    >>> from softpotato.techniques import DifferentialPulseVoltammetry
    >>> dpv = DifferentialPulseVoltammetry(
    ...     E_start=0.2,
    ...     E_end=-0.2,
    ...     step_height=0.05,
    ...     pulse_amplitude=-0.025,
    ...     pulse_width=0.05,
    ...     pulse_period=0.5,
    ... )
    >>> dpv.n_steps
    9
    >>> dpv.duration
    4.5
    """

    def __init__(
        self,
        E_start: float,
        E_end: float,
        step_height: float,
        pulse_amplitude: float,
        pulse_width: float,
        pulse_period: float,
        *,
        sample_fraction: float = 0.1,
    ) -> None:
        self._mode = "potentiostatic"
        self._E_start = _validate_finite_real(E_start, "E_start")
        self._E_end = _validate_finite_real(E_end, "E_end")
        if self._E_start == self._E_end:
            raise ValueError("E_start and E_end must be distinct.")

        self._step_height = _validate_positive_finite(step_height, "step_height")
        self._pulse_amplitude = _validate_finite_real(
            pulse_amplitude, "pulse_amplitude"
        )
        if self._pulse_amplitude == 0.0:
            raise ValueError("pulse_amplitude must be non-zero.")

        self._pulse_width = _validate_positive_finite(pulse_width, "pulse_width")
        self._pulse_period = _validate_positive_finite(pulse_period, "pulse_period")
        if self._pulse_width >= self._pulse_period:
            raise ValueError(
                "pulse_period must be strictly greater than pulse_width "
                f"(got pulse_width={self._pulse_width!r}, pulse_period={self._pulse_period!r})."
            )
        self._sample_fraction = _validate_sample_fraction(sample_fraction)

        self._base_width = float(self._pulse_period - self._pulse_width)
        self._base_potentials, self._direction = _build_step_potentials(
            self._E_start, self._E_end, self._step_height
        )
        self._pulse_potentials = tuple(
            float(e + self._pulse_amplitude) for e in self._base_potentials
        )
        self._n_steps = len(self._base_potentials)
        self._duration = float(self._n_steps * self._pulse_period)

        # Build flat arrays for O(log N) right-continuous evaluation
        seg_starts: list[float] = []
        seg_values: list[float] = []
        for k in range(self._n_steps):
            t0 = k * self._pulse_period
            t_rise = (k + 1) * self._pulse_period - self._pulse_width
            seg_starts.append(t0)
            seg_values.append(self._base_potentials[k])
            seg_starts.append(t_rise)
            seg_values.append(self._pulse_potentials[k])

        self._starts = np.asarray(seg_starts, dtype=float)
        self._values = np.asarray(seg_values, dtype=float)
        self._event_times = _deduplicate_interior_events(seg_starts[1:], self._duration)

    @property
    def E_start(self) -> float:
        """Initial staircase base potential in Volts."""
        return self._E_start

    @property
    def E_end(self) -> float:
        """Final staircase base potential in Volts."""
        return self._E_end

    @property
    def step_height(self) -> float:
        """Staircase potential step magnitude :math:`\\Delta E_s` in Volts."""
        return self._step_height

    @property
    def pulse_amplitude(self) -> float:
        """Pulse potential amplitude :math:`\\Delta E_p` in Volts."""
        return self._pulse_amplitude

    @property
    def pulse_width(self) -> float:
        """Pulse duration :math:`t_p` in seconds."""
        return self._pulse_width

    @property
    def pulse_period(self) -> float:
        """Total cycle period :math:`\\tau` in seconds."""
        return self._pulse_period

    @property
    def base_width(self) -> float:
        """Pre-pulse base hold duration :math:`\\tau - t_p` in seconds."""
        return self._base_width

    @property
    def sample_fraction(self) -> float:
        """Sampling window fraction near the end of each base/pulse segment."""
        return self._sample_fraction

    @property
    def direction(self) -> int:
        """Scan direction: ``+1`` (anodic) or ``-1`` (cathodic)."""
        return self._direction

    @property
    def n_steps(self) -> int:
        """Number of staircase steps / pulses."""
        return self._n_steps

    @property
    def base_potentials(self) -> tuple[float, ...]:
        """Ordered tuple of staircase base potentials :math:`E_{\\text{base}, k}` in Volts."""
        return self._base_potentials

    @property
    def pulse_potentials(self) -> tuple[float, ...]:
        """Ordered tuple of pulse potentials :math:`E_{\\text{base}, k} + \\Delta E_p` in Volts."""
        return self._pulse_potentials

    @property
    def duration(self) -> float:
        """Total experiment duration :math:`N \\tau` in seconds."""
        return self._duration

    def _technique_plots(self) -> tuple[PlotSpec, ...]:
        return (
            PlotSpec(
                kind="dpv",
                title="Differential Pulse Voltammogram",
                x_label=r"$E_{\mathrm{base}}$ / V",
                y_label=r"$\Delta I$ / A",
                description="Differential pulse current (i_pulse - i_pre) vs. base potential.",
            ),
        )

    @property
    def event_times(self) -> tuple[float, ...]:
        """Sorted interior pulse rise and fall timestamps in ``(0, duration)``."""
        return self._event_times

    def _default_time_grid_points(self) -> int:
        return max(1001, 20 * self._n_steps + 1)

    @overload
    def excitation(self, t: float) -> float: ...

    @overload
    def excitation(self, t: np.ndarray) -> np.ndarray: ...

    @overload
    def excitation(self, t: float | ArrayLike) -> float | np.ndarray: ...

    def excitation(self, t: float | ArrayLike) -> float | np.ndarray:
        normalized, is_scalar = _normalize_time_input(t)
        n_seg = len(self._values)

        if is_scalar:
            assert isinstance(normalized, float)
            if normalized <= 0.0:
                return float(self._values[0])
            if normalized >= self._duration:
                return float(self._values[-1])
            idx = int(np.searchsorted(self._starts, normalized, side="right")) - 1
            idx = min(max(idx, 0), n_seg - 1)
            return float(self._values[idx])

        assert isinstance(normalized, np.ndarray)
        orig_shape = normalized.shape
        flat = normalized.ravel()
        if flat.size == 0:
            return np.empty(orig_shape, dtype=float)

        clamped = np.clip(flat, 0.0, self._duration)
        indices = np.searchsorted(self._starts, clamped, side="right") - 1
        indices = np.clip(indices, 0, n_seg - 1)
        indices = np.where(clamped >= self._duration, n_seg - 1, indices)
        return self._values[indices].reshape(orig_shape)

    def sample_currents(
        self,
        t: ArrayLike,
        i: ArrayLike,
    ) -> tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]:
        """Sample pre-pulse, pulse, and differential currents across all steps.

        Parameters
        ----------
        t : array-like
            Strictly increasing 1D time array in seconds.
        i : array-like
            1D Faradaic current array in Amperes matching ``t``.

        Returns
        -------
        E_base : np.ndarray
            Staircase base potentials of shape ``(n_steps,)``.
        i_pre : np.ndarray
            Currents sampled near the end of each base hold, shape ``(n_steps,)``.
        i_pulse : np.ndarray
            Currents sampled near the end of each pulse hold, shape ``(n_steps,)``.
        i_diff : np.ndarray
            Differential current ``i_pulse - i_pre``, shape ``(n_steps,)``.
        """
        t_arr, i_arr = _validate_time_current_pair(t, i)

        w_base = self._sample_fraction * self._base_width
        w_pulse = self._sample_fraction * self._pulse_width

        i_pre = np.empty(self._n_steps, dtype=float)
        i_pulse = np.empty(self._n_steps, dtype=float)

        for k in range(self._n_steps):
            t_rise = (k + 1) * self._pulse_period - self._pulse_width
            t_end = (k + 1) * self._pulse_period

            i_pre[k] = _sample_window_mean(
                t_arr, i_arr, t_rise - w_base, t_rise, include_end=False
            )
            i_pulse[k] = _sample_window_mean(
                t_arr,
                i_arr,
                t_end - w_pulse,
                t_end,
                include_end=(k == self._n_steps - 1),
            )

        E_base = np.asarray(self._base_potentials, dtype=float)
        i_diff = i_pulse - i_pre
        return E_base, i_pre, i_pulse, i_diff

    def __repr__(self) -> str:
        return (
            f"DifferentialPulseVoltammetry(E_start={self._E_start!r}, "
            f"E_end={self._E_end!r}, step_height={self._step_height!r}, "
            f"pulse_amplitude={self._pulse_amplitude!r}, "
            f"pulse_width={self._pulse_width!r}, pulse_period={self._pulse_period!r})"
        )

E_start property

E_start: float

Initial staircase base potential in Volts.

E_end property

E_end: float

Final staircase base potential in Volts.

step_height property

step_height: float

Staircase potential step magnitude \(\Delta E_s\) in Volts.

pulse_amplitude property

pulse_amplitude: float

Pulse potential amplitude \(\Delta E_p\) in Volts.

pulse_width property

pulse_width: float

Pulse duration \(t_p\) in seconds.

pulse_period property

pulse_period: float

Total cycle period \(\tau\) in seconds.

base_width property

base_width: float

Pre-pulse base hold duration \(\tau - t_p\) in seconds.

sample_fraction property

sample_fraction: float

Sampling window fraction near the end of each base/pulse segment.

direction property

direction: int

Scan direction: +1 (anodic) or -1 (cathodic).

n_steps property

n_steps: int

Number of staircase steps / pulses.

base_potentials property

base_potentials: tuple[float, ...]

Ordered tuple of staircase base potentials \(E_{\text{base}, k}\) in Volts.

pulse_potentials property

pulse_potentials: tuple[float, ...]

Ordered tuple of pulse potentials \(E_{\text{base}, k} + \Delta E_p\) in Volts.

duration property

duration: float

Total experiment duration \(N \tau\) in seconds.

event_times property

event_times: tuple[float, ...]

Sorted interior pulse rise and fall timestamps in (0, duration).

sample_currents

sample_currents(t: ArrayLike, i: ArrayLike) -> tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]

Sample pre-pulse, pulse, and differential currents across all steps.

Parameters:

Name Type Description Default
t array - like

Strictly increasing 1D time array in seconds.

required
i array - like

1D Faradaic current array in Amperes matching t.

required

Returns:

Name Type Description
E_base ndarray

Staircase base potentials of shape (n_steps,).

i_pre ndarray

Currents sampled near the end of each base hold, shape (n_steps,).

i_pulse ndarray

Currents sampled near the end of each pulse hold, shape (n_steps,).

i_diff ndarray

Differential current i_pulse - i_pre, shape (n_steps,).

Source code in src/softpotato/techniques/pulse.py
def sample_currents(
    self,
    t: ArrayLike,
    i: ArrayLike,
) -> tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]:
    """Sample pre-pulse, pulse, and differential currents across all steps.

    Parameters
    ----------
    t : array-like
        Strictly increasing 1D time array in seconds.
    i : array-like
        1D Faradaic current array in Amperes matching ``t``.

    Returns
    -------
    E_base : np.ndarray
        Staircase base potentials of shape ``(n_steps,)``.
    i_pre : np.ndarray
        Currents sampled near the end of each base hold, shape ``(n_steps,)``.
    i_pulse : np.ndarray
        Currents sampled near the end of each pulse hold, shape ``(n_steps,)``.
    i_diff : np.ndarray
        Differential current ``i_pulse - i_pre``, shape ``(n_steps,)``.
    """
    t_arr, i_arr = _validate_time_current_pair(t, i)

    w_base = self._sample_fraction * self._base_width
    w_pulse = self._sample_fraction * self._pulse_width

    i_pre = np.empty(self._n_steps, dtype=float)
    i_pulse = np.empty(self._n_steps, dtype=float)

    for k in range(self._n_steps):
        t_rise = (k + 1) * self._pulse_period - self._pulse_width
        t_end = (k + 1) * self._pulse_period

        i_pre[k] = _sample_window_mean(
            t_arr, i_arr, t_rise - w_base, t_rise, include_end=False
        )
        i_pulse[k] = _sample_window_mean(
            t_arr,
            i_arr,
            t_end - w_pulse,
            t_end,
            include_end=(k == self._n_steps - 1),
        )

    E_base = np.asarray(self._base_potentials, dtype=float)
    i_diff = i_pulse - i_pre
    return E_base, i_pre, i_pulse, i_diff

SampledCurrentVoltammetry

Bases: BaseTechnique

Sampled-Current Voltammetry (SCV) potential-step family generator.

Applies a series of independent constant-potential steps across a potential window, where every step shares the exact same total duration \(t_{\max}\) and evaluation time grid. Sampling the resulting current transients \(I_k(t)\) at one or more fixed sampling times \(\tau \in (0, t_{\max}]\) yields the sampled-current voltammogram \(I(\tau)\) vs. \(E_k\).

Supports two mutually exclusive ways to specify the step potentials:

  1. Explicit potentials: SampledCurrentVoltammetry(potentials=[...], duration=...) accepting a Python list, tuple, or 1D NumPy array of potentials.
  2. Potential window + step: SampledCurrentVoltammetry(E_start=..., E_end=..., dE=..., duration=...) (or step_height=... as an alias for dE).

Parameters:

Name Type Description Default
potentials Sequence[float] or ndarray

Explicit 1D sequence or NumPy array of step potentials in Volts. Mutually exclusive with (E_start, E_end, dE / step_height).

None
duration float

Constant-potential step duration in seconds (\(> 0\)) applied uniformly to every potential step. Required.

None
E_start float

Initial potential of the potential window in Volts.

None
E_end float

Final potential of the potential window in Volts (must differ from E_start).

None
dE float

Potential step increment \(\Delta E > 0\) in Volts used with E_start and E_end. Mutually exclusive with step_height.

None
step_height float

Alias for dE (\(\Delta E > 0\) in Volts). Mutually exclusive with dE.

None
E_quiet float

Optional initial quiet/resting potential in Volts applied before every step when t_quiet > 0.

None
t_quiet float

Optional initial quiet/resting duration in seconds (\(\ge 0\)) applied identically to every step. If t_quiet > 0, E_quiet must be provided.

0.0
sample_times float or Sequence[float] or ndarray

Optional default sampling time(s) \(\tau \in (0, t_{\max}]\) in seconds for sample_currents. Any configured sample_times are guaranteed to appear in time_grid.

None
n_points int

Optional default number of points (\(\ge 2\)) for time_grid.

None

Examples:

From an explicit list or NumPy array:

>>> import numpy as np
>>> from softpotato.techniques import SampledCurrentVoltammetry
>>> scv = SampledCurrentVoltammetry(potentials=[-0.4, -0.2, 0.0, 0.2], duration=5.0)
>>> scv.n_steps
4
>>> scv.duration
5.0

From a potential window and step increment:

>>> scv_win = SampledCurrentVoltammetry(
...     E_start=0.2, E_end=-0.2, dE=0.1, duration=2.0
... )
>>> len(scv_win)
5
>>> tuple(round(e, 4) for e in scv_win.potentials)
(0.2, 0.1, 0.0, -0.1, -0.2)
Source code in src/softpotato/techniques/pulse.py
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
class SampledCurrentVoltammetry(BaseTechnique):
    r"""Sampled-Current Voltammetry (SCV) potential-step family generator.

    Applies a series of independent constant-potential steps across a potential
    window, where every step shares the exact same total duration :math:`t_{\max}`
    and evaluation time grid. Sampling the resulting current transients
    :math:`I_k(t)` at one or more fixed sampling times :math:`\tau \in (0, t_{\max}]`
    yields the sampled-current voltammogram :math:`I(\tau)` vs. :math:`E_k`.

    Supports two mutually exclusive ways to specify the step potentials:

    1. **Explicit potentials**: ``SampledCurrentVoltammetry(potentials=[...], duration=...)``
       accepting a Python list, tuple, or 1D NumPy array of potentials.
    2. **Potential window + step**:
       ``SampledCurrentVoltammetry(E_start=..., E_end=..., dE=..., duration=...)``
       (or ``step_height=...`` as an alias for ``dE``).

    Parameters
    ----------
    potentials : Sequence[float] or np.ndarray, optional
        Explicit 1D sequence or NumPy array of step potentials in Volts.
        Mutually exclusive with ``(E_start, E_end, dE / step_height)``.
    duration : float, optional
        Constant-potential step duration in seconds (:math:`> 0`) applied
        uniformly to every potential step. Required.
    E_start : float, optional
        Initial potential of the potential window in Volts.
    E_end : float, optional
        Final potential of the potential window in Volts (must differ from
        ``E_start``).
    dE : float, optional
        Potential step increment :math:`\Delta E > 0` in Volts used with
        ``E_start`` and ``E_end``. Mutually exclusive with ``step_height``.
    step_height : float, optional
        Alias for ``dE`` (:math:`\Delta E > 0` in Volts). Mutually exclusive
        with ``dE``.
    E_quiet : float, optional
        Optional initial quiet/resting potential in Volts applied before every
        step when ``t_quiet > 0``.
    t_quiet : float, default 0.0
        Optional initial quiet/resting duration in seconds (:math:`\ge 0`)
        applied identically to every step. If ``t_quiet > 0``, ``E_quiet`` must
        be provided.
    sample_times : float or Sequence[float] or np.ndarray, optional
        Optional default sampling time(s) :math:`\tau \in (0, t_{\max}]` in
        seconds for :meth:`sample_currents`. Any configured ``sample_times`` are
        guaranteed to appear in :meth:`time_grid`.
    n_points : int, optional
        Optional default number of points (:math:`\ge 2`) for :meth:`time_grid`.

    Examples
    --------
    From an explicit list or NumPy array:

    >>> import numpy as np
    >>> from softpotato.techniques import SampledCurrentVoltammetry
    >>> scv = SampledCurrentVoltammetry(potentials=[-0.4, -0.2, 0.0, 0.2], duration=5.0)
    >>> scv.n_steps
    4
    >>> scv.duration
    5.0

    From a potential window and step increment:

    >>> scv_win = SampledCurrentVoltammetry(
    ...     E_start=0.2, E_end=-0.2, dE=0.1, duration=2.0
    ... )
    >>> len(scv_win)
    5
    >>> tuple(round(e, 4) for e in scv_win.potentials)
    (0.2, 0.1, 0.0, -0.1, -0.2)
    """

    def __init__(
        self,
        potentials: Sequence[float] | np.ndarray | None = None,
        duration: float | None = None,
        *,
        E_start: float | None = None,
        E_end: float | None = None,
        dE: float | None = None,
        step_height: float | None = None,
        E_quiet: float | None = None,
        t_quiet: float = 0.0,
        sample_times: float | Sequence[float] | np.ndarray | None = None,
        n_points: int | None = None,
    ) -> None:
        self._mode = "potentiostatic"

        if duration is None:
            raise ValueError("'duration' must be provided and strictly positive.")
        step_dur = _validate_positive_finite(duration, "duration")

        if dE is not None and step_height is not None:
            raise ValueError("Specify at most one of 'dE' or 'step_height'.")
        resolved_de = dE if dE is not None else step_height

        explicit_mode = potentials is not None
        window_mode = any(x is not None for x in (E_start, E_end, resolved_de))

        if not explicit_mode and not window_mode:
            raise ValueError(
                "Must specify either 'potentials' or ('E_start', 'E_end', 'dE'/'step_height')."
            )
        if explicit_mode and window_mode:
            raise ValueError(
                "Cannot mix 'potentials' with ('E_start', 'E_end', 'dE'/'step_height')."
            )

        if explicit_mode:
            if isinstance(potentials, (str, bytes)):
                raise TypeError("'potentials' must be a numeric sequence or 1D array.")
            if isinstance(potentials, np.ndarray):
                if potentials.ndim != 1:
                    raise ValueError(
                        f"'potentials' array must be 1D, got shape {potentials.shape}."
                    )
                raw_pots = potentials.tolist()
            elif isinstance(potentials, Sequence):
                raw_pots = list(potentials)
            else:
                raise TypeError(
                    "'potentials' must be a numeric sequence or 1D numpy.ndarray, "
                    f"got {type(potentials).__name__}."
                )
            if len(raw_pots) == 0:
                raise ValueError("'potentials' must not be empty.")
            resolved_potentials = tuple(
                _validate_finite_real(v, f"potentials[{idx}]")
                for idx, v in enumerate(raw_pots)
            )
            self._E_start = resolved_potentials[0]
            self._E_end = resolved_potentials[-1]
            self._dE: float | None = None
        else:
            if E_start is None or E_end is None or resolved_de is None:
                raise ValueError(
                    "Window mode requires all of 'E_start', 'E_end', and 'dE' (or 'step_height')."
                )
            e_start_val = _validate_finite_real(E_start, "E_start")
            e_end_val = _validate_finite_real(E_end, "E_end")
            if e_start_val == e_end_val:
                raise ValueError("E_start and E_end must be distinct.")
            de_val = _validate_positive_finite(
                resolved_de, "dE" if dE is not None else "step_height"
            )
            resolved_potentials, _ = _build_step_potentials(
                e_start_val, e_end_val, de_val
            )
            self._E_start = e_start_val
            self._E_end = e_end_val
            self._dE = de_val

        t_quiet_val = _validate_non_negative_finite(t_quiet, "t_quiet")
        e_quiet_val: float | None = (
            _validate_finite_real(E_quiet, "E_quiet") if E_quiet is not None else None
        )
        if t_quiet_val > 0.0 and e_quiet_val is None:
            raise ValueError("E_quiet must be provided when t_quiet > 0.")

        self._default_n_points = (
            _validate_positive_int(n_points, "n_points", minimum=2)
            if n_points is not None
            else 1001
        )

        self._potentials: tuple[float, ...] = resolved_potentials
        self._potentials_arr = np.asarray(resolved_potentials, dtype=float)
        self._step_duration = step_dur
        self._E_quiet = e_quiet_val
        self._t_quiet = t_quiet_val
        self._duration = float(t_quiet_val + step_dur)
        self._event_times = (
            _deduplicate_interior_events([t_quiet_val], self._duration)
            if t_quiet_val > 0.0
            else ()
        )

        # Validate optional default sample_times against [0, duration]
        if sample_times is not None:
            self._sample_times: tuple[float, ...] | None = self._normalize_sample_times(
                sample_times
            )[0]
        else:
            self._sample_times = None

        # Construct uniform Chronoamperometry objects for every potential step
        self._steps: tuple[Chronoamperometry, ...] = tuple(
            Chronoamperometry(
                E_step=e_val,
                duration=step_dur,
                E_quiet=e_quiet_val,
                t_quiet=t_quiet_val,
            )
            for e_val in self._potentials
        )

    def _normalize_sample_times(
        self,
        sample_times: float | Sequence[float] | np.ndarray,
    ) -> tuple[tuple[float, ...], bool]:
        """Validate scalar or 1D sequence of sampling times in ``(0, duration]``."""
        if np.isscalar(sample_times):
            tau = _validate_positive_finite(sample_times, "sample_times")
            if tau > self._duration:
                raise ValueError(
                    f"sample_times ({tau}) must be <= duration ({self._duration})."
                )
            return (tau,), True

        if isinstance(sample_times, (str, bytes)):
            raise TypeError("'sample_times' must be a real number or numeric sequence.")
        if isinstance(sample_times, np.ndarray):
            if sample_times.ndim != 1:
                raise ValueError(
                    f"'sample_times' array must be 1D, got shape {sample_times.shape}."
                )
            raw = sample_times.tolist()
        elif isinstance(sample_times, Sequence):
            raw = list(sample_times)
        else:
            raise TypeError(
                "'sample_times' must be a real number or numeric sequence, "
                f"got {type(sample_times).__name__}."
            )
        if len(raw) == 0:
            raise ValueError("'sample_times' must not be empty.")
        cleaned: list[float] = []
        for idx, val in enumerate(raw):
            tau = _validate_positive_finite(val, f"sample_times[{idx}]")
            if tau > self._duration:
                raise ValueError(
                    f"sample_times[{idx}] ({tau}) must be <= duration ({self._duration})."
                )
            cleaned.append(tau)
        return tuple(cleaned), False

    @property
    def potentials(self) -> tuple[float, ...]:
        """Ordered tuple of constant step potentials in Volts."""
        return self._potentials

    @property
    def n_steps(self) -> int:
        """Number of constant-potential steps in the potential window."""
        return len(self._potentials)

    @property
    def step_duration(self) -> float:
        """Duration of the constant-potential hold in seconds (same for all steps)."""
        return self._step_duration

    @property
    def duration(self) -> float:
        """Total duration ``t_quiet + step_duration`` in seconds (same for all steps)."""
        return self._duration

    def _technique_plots(self) -> tuple[PlotSpec, ...]:
        return (
            PlotSpec(
                kind="scv",
                title="Sampled-Current Voltammogram",
                x_label="$E$ / V",
                y_label=r"$I(\tau)$ / A",
                description="Current sampled at fixed time(s) tau vs. step potential.",
            ),
        )

    @property
    def E_start(self) -> float:
        """Initial potential of the window in Volts."""
        return self._E_start

    @property
    def E_end(self) -> float:
        """Final potential of the window in Volts."""
        return self._E_end

    @property
    def dE(self) -> float | None:
        """Potential step increment in Volts if constructed in window mode, else ``None``."""
        return self._dE

    @property
    def E_quiet(self) -> float | None:
        """Optional quiet/resting potential in Volts, or ``None``."""
        return self._E_quiet

    @property
    def t_quiet(self) -> float:
        """Optional quiet/resting duration in seconds."""
        return self._t_quiet

    @property
    def sample_times(self) -> tuple[float, ...] | None:
        """Default sampling times in seconds, or ``None``."""
        return self._sample_times

    @property
    def steps(self) -> tuple[Chronoamperometry, ...]:
        """Tuple of :class:`Chronoamperometry` objects, one per potential step."""
        return self._steps

    @property
    def event_times(self) -> tuple[float, ...]:
        """Sorted interior transition timestamps shared by all steps."""
        return self._event_times

    def __len__(self) -> int:
        return len(self._steps)

    @overload
    def __getitem__(self, index: int) -> Chronoamperometry: ...

    @overload
    def __getitem__(self, index: slice) -> tuple[Chronoamperometry, ...]: ...

    def __getitem__(
        self, index: int | slice
    ) -> Chronoamperometry | tuple[Chronoamperometry, ...]:
        return self._steps[index]

    def __iter__(self) -> Iterator[Chronoamperometry]:
        return iter(self._steps)

    def _default_time_grid_points(self) -> int:
        return self._default_n_points

    def _extra_grid_times(self) -> tuple[float, ...]:
        if self._sample_times is None:
            return self._event_times
        return self._event_times + self._sample_times

    def excitation(self, t: float | ArrayLike) -> np.ndarray:  # type: ignore[override]
        """Evaluate applied potentials across all steps at time(s) ``t``.

        Parameters
        ----------
        t : float or array-like
            Time(s) in seconds.

        Returns
        -------
        np.ndarray
            For scalar ``t``, a 1D array of shape ``(n_steps,)``.
            For array-like ``t`` of shape ``S``, an array of shape
            ``(n_steps, *S)`` where row ``k`` is step ``k``'s potential waveform.
        """
        normalized, is_scalar = _normalize_time_input(t)
        if is_scalar:
            assert isinstance(normalized, float)
            if self._t_quiet > 0.0 and normalized < self._t_quiet:
                assert self._E_quiet is not None
                return np.full(self.n_steps, self._E_quiet, dtype=float)
            return self._potentials_arr.copy()

        assert isinstance(normalized, np.ndarray)
        out_shape = (self.n_steps, *normalized.shape)
        if normalized.size == 0:
            return np.empty(out_shape, dtype=float)

        # Broadcast step potentials across the time shape
        pot_bc = self._potentials_arr.reshape((self.n_steps,) + (1,) * normalized.ndim)
        out = np.broadcast_to(pot_bc, out_shape).astype(float, copy=True)
        if self._t_quiet > 0.0:
            assert self._E_quiet is not None
            quiet_mask = normalized < self._t_quiet
            if np.any(quiet_mask):
                out[:, quiet_mask] = self._E_quiet
        return out

    def sample_currents(
        self,
        t: ArrayLike,
        currents: ArrayLike,
        sample_times: float | Sequence[float] | np.ndarray | None = None,
    ) -> tuple[np.ndarray, np.ndarray]:
        """Extract sampled-current voltammogram(s) from step current transients.

        Parameters
        ----------
        t : array-like
            Shared strictly increasing 1D time array of shape ``(n_times,)`` in seconds.
        currents : array-like
            2D array (or sequence of 1D arrays) of shape ``(n_steps, n_times)``
            containing the current transient :math:`I_k(t)` for each potential step.
        sample_times : float or Sequence[float] or np.ndarray, optional
            Sampling time(s) :math:`\\tau \\in (0, t_{\\max}]` in seconds.
            Defaults to :attr:`sample_times` if configured, otherwise ``self.duration``.

        Returns
        -------
        potentials : np.ndarray
            1D array of step potentials of shape ``(n_steps,)``.
        sampled_currents : np.ndarray
            1D array of shape ``(n_steps,)`` when a single scalar sampling time
            is requested (or defaulted to ``duration``), or 2D array of shape
            ``(n_sample_times, n_steps)`` when a sequence of sampling times is given.
        """
        t_arr = np.asarray(t, dtype=float)
        if t_arr.ndim != 1 or t_arr.size < 2:
            raise ValueError("'t' must be a 1D array with at least 2 timestamps.")
        if not np.all(np.isfinite(t_arr)) or np.any(np.diff(t_arr) <= 0.0):
            raise ValueError("'t' must be finite and strictly increasing.")

        i_arr = np.asarray(currents, dtype=float)
        if i_arr.ndim != 2 or i_arr.shape != (self.n_steps, t_arr.size):
            raise ValueError(
                f"'currents' must have shape ({self.n_steps}, {t_arr.size}), "
                f"got {i_arr.shape}."
            )
        if not np.all(np.isfinite(i_arr)):
            raise ValueError("All values in 'currents' must be finite.")

        if sample_times is None:
            if self._sample_times is not None:
                taus = self._sample_times
                scalar_tau = False
            else:
                taus = (self._duration,)
                scalar_tau = True
        else:
            taus, scalar_tau = self._normalize_sample_times(sample_times)

        tau_arr = np.asarray(taus, dtype=float)
        sampled = np.empty((tau_arr.size, self.n_steps), dtype=float)
        for k in range(self.n_steps):
            sampled[:, k] = np.interp(tau_arr, t_arr, i_arr[k])

        if scalar_tau:
            return self._potentials_arr.copy(), sampled[0]
        return self._potentials_arr.copy(), sampled

    def __repr__(self) -> str:
        return (
            f"SampledCurrentVoltammetry(n_steps={self.n_steps}, "
            f"E_start={self._E_start!r}, E_end={self._E_end!r}, "
            f"duration={self._duration!r})"
        )

potentials property

potentials: tuple[float, ...]

Ordered tuple of constant step potentials in Volts.

n_steps property

n_steps: int

Number of constant-potential steps in the potential window.

step_duration property

step_duration: float

Duration of the constant-potential hold in seconds (same for all steps).

duration property

duration: float

Total duration t_quiet + step_duration in seconds (same for all steps).

E_start property

E_start: float

Initial potential of the window in Volts.

E_end property

E_end: float

Final potential of the window in Volts.

dE property

dE: float | None

Potential step increment in Volts if constructed in window mode, else None.

E_quiet property

E_quiet: float | None

Optional quiet/resting potential in Volts, or None.

t_quiet property

t_quiet: float

Optional quiet/resting duration in seconds.

sample_times property

sample_times: tuple[float, ...] | None

Default sampling times in seconds, or None.

steps property

steps: tuple[Chronoamperometry, ...]

Tuple of Chronoamperometry objects, one per potential step.

event_times property

event_times: tuple[float, ...]

Sorted interior transition timestamps shared by all steps.

excitation

excitation(t: float | ArrayLike) -> np.ndarray

Evaluate applied potentials across all steps at time(s) t.

Parameters:

Name Type Description Default
t float or array - like

Time(s) in seconds.

required

Returns:

Type Description
ndarray

For scalar t, a 1D array of shape (n_steps,). For array-like t of shape S, an array of shape (n_steps, *S) where row k is step k's potential waveform.

Source code in src/softpotato/techniques/pulse.py
def excitation(self, t: float | ArrayLike) -> np.ndarray:  # type: ignore[override]
    """Evaluate applied potentials across all steps at time(s) ``t``.

    Parameters
    ----------
    t : float or array-like
        Time(s) in seconds.

    Returns
    -------
    np.ndarray
        For scalar ``t``, a 1D array of shape ``(n_steps,)``.
        For array-like ``t`` of shape ``S``, an array of shape
        ``(n_steps, *S)`` where row ``k`` is step ``k``'s potential waveform.
    """
    normalized, is_scalar = _normalize_time_input(t)
    if is_scalar:
        assert isinstance(normalized, float)
        if self._t_quiet > 0.0 and normalized < self._t_quiet:
            assert self._E_quiet is not None
            return np.full(self.n_steps, self._E_quiet, dtype=float)
        return self._potentials_arr.copy()

    assert isinstance(normalized, np.ndarray)
    out_shape = (self.n_steps, *normalized.shape)
    if normalized.size == 0:
        return np.empty(out_shape, dtype=float)

    # Broadcast step potentials across the time shape
    pot_bc = self._potentials_arr.reshape((self.n_steps,) + (1,) * normalized.ndim)
    out = np.broadcast_to(pot_bc, out_shape).astype(float, copy=True)
    if self._t_quiet > 0.0:
        assert self._E_quiet is not None
        quiet_mask = normalized < self._t_quiet
        if np.any(quiet_mask):
            out[:, quiet_mask] = self._E_quiet
    return out

sample_currents

sample_currents(t: ArrayLike, currents: ArrayLike, sample_times: float | Sequence[float] | ndarray | None = None) -> tuple[np.ndarray, np.ndarray]

Extract sampled-current voltammogram(s) from step current transients.

Parameters:

Name Type Description Default
t array - like

Shared strictly increasing 1D time array of shape (n_times,) in seconds.

required
currents array - like

2D array (or sequence of 1D arrays) of shape (n_steps, n_times) containing the current transient \(I_k(t)\) for each potential step.

required
sample_times float or Sequence[float] or ndarray

Sampling time(s) \(\tau \in (0, t_{\max}]\) in seconds. Defaults to sample_times if configured, otherwise self.duration.

None

Returns:

Name Type Description
potentials ndarray

1D array of step potentials of shape (n_steps,).

sampled_currents ndarray

1D array of shape (n_steps,) when a single scalar sampling time is requested (or defaulted to duration), or 2D array of shape (n_sample_times, n_steps) when a sequence of sampling times is given.

Source code in src/softpotato/techniques/pulse.py
def sample_currents(
    self,
    t: ArrayLike,
    currents: ArrayLike,
    sample_times: float | Sequence[float] | np.ndarray | None = None,
) -> tuple[np.ndarray, np.ndarray]:
    """Extract sampled-current voltammogram(s) from step current transients.

    Parameters
    ----------
    t : array-like
        Shared strictly increasing 1D time array of shape ``(n_times,)`` in seconds.
    currents : array-like
        2D array (or sequence of 1D arrays) of shape ``(n_steps, n_times)``
        containing the current transient :math:`I_k(t)` for each potential step.
    sample_times : float or Sequence[float] or np.ndarray, optional
        Sampling time(s) :math:`\\tau \\in (0, t_{\\max}]` in seconds.
        Defaults to :attr:`sample_times` if configured, otherwise ``self.duration``.

    Returns
    -------
    potentials : np.ndarray
        1D array of step potentials of shape ``(n_steps,)``.
    sampled_currents : np.ndarray
        1D array of shape ``(n_steps,)`` when a single scalar sampling time
        is requested (or defaulted to ``duration``), or 2D array of shape
        ``(n_sample_times, n_steps)`` when a sequence of sampling times is given.
    """
    t_arr = np.asarray(t, dtype=float)
    if t_arr.ndim != 1 or t_arr.size < 2:
        raise ValueError("'t' must be a 1D array with at least 2 timestamps.")
    if not np.all(np.isfinite(t_arr)) or np.any(np.diff(t_arr) <= 0.0):
        raise ValueError("'t' must be finite and strictly increasing.")

    i_arr = np.asarray(currents, dtype=float)
    if i_arr.ndim != 2 or i_arr.shape != (self.n_steps, t_arr.size):
        raise ValueError(
            f"'currents' must have shape ({self.n_steps}, {t_arr.size}), "
            f"got {i_arr.shape}."
        )
    if not np.all(np.isfinite(i_arr)):
        raise ValueError("All values in 'currents' must be finite.")

    if sample_times is None:
        if self._sample_times is not None:
            taus = self._sample_times
            scalar_tau = False
        else:
            taus = (self._duration,)
            scalar_tau = True
    else:
        taus, scalar_tau = self._normalize_sample_times(sample_times)

    tau_arr = np.asarray(taus, dtype=float)
    sampled = np.empty((tau_arr.size, self.n_steps), dtype=float)
    for k in range(self.n_steps):
        sampled[:, k] = np.interp(tau_arr, t_arr, i_arr[k])

    if scalar_tau:
        return self._potentials_arr.copy(), sampled[0]
    return self._potentials_arr.copy(), sampled

SquareWaveVoltammetry

Bases: BaseTechnique

Osteryoung Square-Wave Voltammetry (SWV) waveform generator.

Superimposes a symmetric square wave of amplitude \(E_{\text{sw}} > 0\) and frequency \(f > 0\) (period \(\tau = 1/f\), half-period \(t_p = 1/(2f)\)) onto a linear staircase ramp from \(E_{\text{start}}\) to \(E_{\text{end}}\) with step height \(\Delta E_s > 0\).

Within each cycle \(k \in \{0, \dots, N-1\}\) over \([k\tau, (k+1)\tau)\) with scan direction \(s = \operatorname{sgn}(E_{\text{end}} - E_{\text{start}}) \in \{+1, -1\}\):

  • Forward half-cycle (\(t \in [k\tau, k\tau + t_p)\)): \(E(t) = E_{\text{step}, k} + s \, E_{\text{sw}}\)
  • Reverse half-cycle (\(t \in [k\tau + t_p, (k+1)\tau)\)): \(E(t) = E_{\text{step}, k} - s \, E_{\text{sw}}\)

Currents are sampled near the end of each forward (\(I_f\)) and reverse (\(I_r\)) half-period via sample_currents, yielding the net square-wave current \(\Delta I = I_f - I_r\) under IUPAC polarity.

Parameters:

Name Type Description Default
E_start float

Initial staircase potential in Volts.

required
E_end float

Final staircase potential in Volts (must differ from E_start).

required
step_height float

Staircase potential step magnitude \(\Delta E_s > 0\) in Volts.

required
amplitude float

Square-wave pulse amplitude \(E_{\text{sw}} > 0\) in Volts.

required
frequency float

Square-wave frequency \(f > 0\) in Hz.

required
sample_fraction float

Fraction \(\in (0, 1]\) of each half-period near the end of the half-cycle over which current is averaged in sample_currents.

0.1

Examples:

>>> from softpotato.techniques import SquareWaveVoltammetry
>>> swv = SquareWaveVoltammetry(
...     E_start=0.2,
...     E_end=-0.2,
...     step_height=0.05,
...     amplitude=0.025,
...     frequency=10.0,
... )
>>> swv.n_steps
9
>>> swv.period
0.1
>>> swv.half_period
0.05
Source code in src/softpotato/techniques/pulse.py
class SquareWaveVoltammetry(BaseTechnique):
    r"""Osteryoung Square-Wave Voltammetry (SWV) waveform generator.

    Superimposes a symmetric square wave of amplitude :math:`E_{\text{sw}} > 0`
    and frequency :math:`f > 0` (period :math:`\tau = 1/f`, half-period
    :math:`t_p = 1/(2f)`) onto a linear staircase ramp from :math:`E_{\text{start}}`
    to :math:`E_{\text{end}}` with step height :math:`\Delta E_s > 0`.

    Within each cycle :math:`k \in \{0, \dots, N-1\}` over
    :math:`[k\tau, (k+1)\tau)` with scan direction
    :math:`s = \operatorname{sgn}(E_{\text{end}} - E_{\text{start}}) \in \{+1, -1\}`:

    - **Forward half-cycle** (:math:`t \in [k\tau, k\tau + t_p)`):
      :math:`E(t) = E_{\text{step}, k} + s \, E_{\text{sw}}`
    - **Reverse half-cycle** (:math:`t \in [k\tau + t_p, (k+1)\tau)`):
      :math:`E(t) = E_{\text{step}, k} - s \, E_{\text{sw}}`

    Currents are sampled near the end of each forward (:math:`I_f`) and reverse
    (:math:`I_r`) half-period via :meth:`sample_currents`, yielding the net
    square-wave current :math:`\Delta I = I_f - I_r` under IUPAC polarity.

    Parameters
    ----------
    E_start : float
        Initial staircase potential in Volts.
    E_end : float
        Final staircase potential in Volts (must differ from ``E_start``).
    step_height : float
        Staircase potential step magnitude :math:`\Delta E_s > 0` in Volts.
    amplitude : float
        Square-wave pulse amplitude :math:`E_{\text{sw}} > 0` in Volts.
    frequency : float
        Square-wave frequency :math:`f > 0` in Hz.
    sample_fraction : float, default 0.1
        Fraction :math:`\in (0, 1]` of each half-period near the end of the
        half-cycle over which current is averaged in :meth:`sample_currents`.

    Examples
    --------
    >>> from softpotato.techniques import SquareWaveVoltammetry
    >>> swv = SquareWaveVoltammetry(
    ...     E_start=0.2,
    ...     E_end=-0.2,
    ...     step_height=0.05,
    ...     amplitude=0.025,
    ...     frequency=10.0,
    ... )
    >>> swv.n_steps
    9
    >>> swv.period
    0.1
    >>> swv.half_period
    0.05
    """

    def __init__(
        self,
        E_start: float,
        E_end: float,
        step_height: float,
        amplitude: float,
        frequency: float,
        *,
        sample_fraction: float = 0.1,
    ) -> None:
        self._mode = "potentiostatic"
        self._E_start = _validate_finite_real(E_start, "E_start")
        self._E_end = _validate_finite_real(E_end, "E_end")
        if self._E_start == self._E_end:
            raise ValueError("E_start and E_end must be distinct.")

        self._step_height = _validate_positive_finite(step_height, "step_height")
        self._amplitude = _validate_positive_finite(amplitude, "amplitude")
        self._frequency = _validate_positive_finite(frequency, "frequency")
        self._sample_fraction = _validate_sample_fraction(sample_fraction)

        self._period = 1.0 / self._frequency
        self._half_period = 0.5 * self._period

        self._step_potentials, self._direction = _build_step_potentials(
            self._E_start, self._E_end, self._step_height
        )
        signed_amp = self._direction * self._amplitude
        self._forward_potentials = tuple(
            float(e + signed_amp) for e in self._step_potentials
        )
        self._reverse_potentials = tuple(
            float(e - signed_amp) for e in self._step_potentials
        )
        self._n_steps = len(self._step_potentials)
        self._duration = float(self._n_steps * self._period)

        seg_starts: list[float] = []
        seg_values: list[float] = []
        for k in range(self._n_steps):
            t_fwd = k / self._frequency
            t_rev = (2 * k + 1) / (2.0 * self._frequency)
            seg_starts.append(t_fwd)
            seg_values.append(self._forward_potentials[k])
            seg_starts.append(t_rev)
            seg_values.append(self._reverse_potentials[k])

        self._starts = np.asarray(seg_starts, dtype=float)
        self._values = np.asarray(seg_values, dtype=float)
        self._event_times = _deduplicate_interior_events(seg_starts[1:], self._duration)

    @property
    def E_start(self) -> float:
        """Initial staircase potential in Volts."""
        return self._E_start

    @property
    def E_end(self) -> float:
        """Final staircase potential in Volts."""
        return self._E_end

    @property
    def step_height(self) -> float:
        """Staircase potential step magnitude :math:`\\Delta E_s` in Volts."""
        return self._step_height

    @property
    def amplitude(self) -> float:
        """Square-wave pulse amplitude :math:`E_{\\text{sw}}` in Volts."""
        return self._amplitude

    @property
    def frequency(self) -> float:
        """Square-wave frequency :math:`f` in Hz."""
        return self._frequency

    @property
    def period(self) -> float:
        """Square-wave cycle period :math:`\\tau = 1 / f` in seconds."""
        return self._period

    @property
    def half_period(self) -> float:
        """Square-wave half-period :math:`t_p = 1 / (2 f)` in seconds."""
        return self._half_period

    @property
    def sample_fraction(self) -> float:
        """Sampling window fraction near the end of each half-cycle."""
        return self._sample_fraction

    @property
    def direction(self) -> int:
        """Scan direction: ``+1`` (anodic) or ``-1`` (cathodic)."""
        return self._direction

    @property
    def n_steps(self) -> int:
        """Number of staircase steps / square-wave cycles."""
        return self._n_steps

    @property
    def step_potentials(self) -> tuple[float, ...]:
        """Ordered tuple of staircase step potentials :math:`E_{\\text{step}, k}` in Volts."""
        return self._step_potentials

    @property
    def forward_potentials(self) -> tuple[float, ...]:
        """Ordered tuple of forward half-cycle potentials in Volts."""
        return self._forward_potentials

    @property
    def reverse_potentials(self) -> tuple[float, ...]:
        """Ordered tuple of reverse half-cycle potentials in Volts."""
        return self._reverse_potentials

    @property
    def duration(self) -> float:
        """Total experiment duration :math:`N / f` in seconds."""
        return self._duration

    @property
    def event_times(self) -> tuple[float, ...]:
        """Sorted interior half-period transition timestamps in ``(0, duration)``."""
        return self._event_times

    def _default_time_grid_points(self) -> int:
        return max(1001, 20 * self._n_steps + 1)

    @overload
    def excitation(self, t: float) -> float: ...

    @overload
    def excitation(self, t: np.ndarray) -> np.ndarray: ...

    @overload
    def excitation(self, t: float | ArrayLike) -> float | np.ndarray: ...

    def excitation(self, t: float | ArrayLike) -> float | np.ndarray:
        normalized, is_scalar = _normalize_time_input(t)
        n_seg = len(self._values)

        if is_scalar:
            assert isinstance(normalized, float)
            if normalized <= 0.0:
                return float(self._values[0])
            if normalized >= self._duration:
                return float(self._values[-1])
            idx = int(np.searchsorted(self._starts, normalized, side="right")) - 1
            idx = min(max(idx, 0), n_seg - 1)
            return float(self._values[idx])

        assert isinstance(normalized, np.ndarray)
        orig_shape = normalized.shape
        flat = normalized.ravel()
        if flat.size == 0:
            return np.empty(orig_shape, dtype=float)

        clamped = np.clip(flat, 0.0, self._duration)
        indices = np.searchsorted(self._starts, clamped, side="right") - 1
        indices = np.clip(indices, 0, n_seg - 1)
        indices = np.where(clamped >= self._duration, n_seg - 1, indices)
        return self._values[indices].reshape(orig_shape)

    def sample_currents(
        self,
        t: ArrayLike,
        i: ArrayLike,
    ) -> tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]:
        """Sample forward, reverse, and net currents across all square-wave cycles.

        Parameters
        ----------
        t : array-like
            Strictly increasing 1D time array in seconds.
        i : array-like
            1D Faradaic current array in Amperes matching ``t``.

        Returns
        -------
        E_step : np.ndarray
            Staircase potentials of shape ``(n_steps,)``.
        i_forward : np.ndarray
            Forward half-cycle currents of shape ``(n_steps,)``.
        i_reverse : np.ndarray
            Reverse half-cycle currents of shape ``(n_steps,)``.
        i_net : np.ndarray
            Net square-wave current ``i_forward - i_reverse``, shape ``(n_steps,)``.
        """
        t_arr, i_arr = _validate_time_current_pair(t, i)

        w_half = self._sample_fraction * self._half_period

        i_forward = np.empty(self._n_steps, dtype=float)
        i_reverse = np.empty(self._n_steps, dtype=float)

        for k in range(self._n_steps):
            t_fwd_end = (2 * k + 1) / (2.0 * self._frequency)
            t_rev_end = (k + 1) / self._frequency

            i_forward[k] = _sample_window_mean(
                t_arr, i_arr, t_fwd_end - w_half, t_fwd_end, include_end=False
            )
            i_reverse[k] = _sample_window_mean(
                t_arr,
                i_arr,
                t_rev_end - w_half,
                t_rev_end,
                include_end=(k == self._n_steps - 1),
            )

        E_step = np.asarray(self._step_potentials, dtype=float)
        i_net = i_forward - i_reverse
        return E_step, i_forward, i_reverse, i_net

    def _technique_plots(self) -> tuple[PlotSpec, ...]:
        return (
            PlotSpec(
                kind="swv",
                title="Square-Wave Voltammogram",
                x_label=r"$E_{\mathrm{step}}$ / V",
                y_label="$I$ / A",
                description="Net square-wave current (i_forward - i_reverse) vs. step potential.",
            ),
        )

    def __repr__(self) -> str:
        return (
            f"SquareWaveVoltammetry(E_start={self._E_start!r}, "
            f"E_end={self._E_end!r}, step_height={self._step_height!r}, "
            f"amplitude={self._amplitude!r}, frequency={self._frequency!r})"
        )

E_start property

E_start: float

Initial staircase potential in Volts.

E_end property

E_end: float

Final staircase potential in Volts.

step_height property

step_height: float

Staircase potential step magnitude \(\Delta E_s\) in Volts.

amplitude property

amplitude: float

Square-wave pulse amplitude \(E_{\text{sw}}\) in Volts.

frequency property

frequency: float

Square-wave frequency \(f\) in Hz.

period property

period: float

Square-wave cycle period \(\tau = 1 / f\) in seconds.

half_period property

half_period: float

Square-wave half-period \(t_p = 1 / (2 f)\) in seconds.

sample_fraction property

sample_fraction: float

Sampling window fraction near the end of each half-cycle.

direction property

direction: int

Scan direction: +1 (anodic) or -1 (cathodic).

n_steps property

n_steps: int

Number of staircase steps / square-wave cycles.

step_potentials property

step_potentials: tuple[float, ...]

Ordered tuple of staircase step potentials \(E_{\text{step}, k}\) in Volts.

forward_potentials property

forward_potentials: tuple[float, ...]

Ordered tuple of forward half-cycle potentials in Volts.

reverse_potentials property

reverse_potentials: tuple[float, ...]

Ordered tuple of reverse half-cycle potentials in Volts.

duration property

duration: float

Total experiment duration \(N / f\) in seconds.

event_times property

event_times: tuple[float, ...]

Sorted interior half-period transition timestamps in (0, duration).

sample_currents

sample_currents(t: ArrayLike, i: ArrayLike) -> tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]

Sample forward, reverse, and net currents across all square-wave cycles.

Parameters:

Name Type Description Default
t array - like

Strictly increasing 1D time array in seconds.

required
i array - like

1D Faradaic current array in Amperes matching t.

required

Returns:

Name Type Description
E_step ndarray

Staircase potentials of shape (n_steps,).

i_forward ndarray

Forward half-cycle currents of shape (n_steps,).

i_reverse ndarray

Reverse half-cycle currents of shape (n_steps,).

i_net ndarray

Net square-wave current i_forward - i_reverse, shape (n_steps,).

Source code in src/softpotato/techniques/pulse.py
def sample_currents(
    self,
    t: ArrayLike,
    i: ArrayLike,
) -> tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]:
    """Sample forward, reverse, and net currents across all square-wave cycles.

    Parameters
    ----------
    t : array-like
        Strictly increasing 1D time array in seconds.
    i : array-like
        1D Faradaic current array in Amperes matching ``t``.

    Returns
    -------
    E_step : np.ndarray
        Staircase potentials of shape ``(n_steps,)``.
    i_forward : np.ndarray
        Forward half-cycle currents of shape ``(n_steps,)``.
    i_reverse : np.ndarray
        Reverse half-cycle currents of shape ``(n_steps,)``.
    i_net : np.ndarray
        Net square-wave current ``i_forward - i_reverse``, shape ``(n_steps,)``.
    """
    t_arr, i_arr = _validate_time_current_pair(t, i)

    w_half = self._sample_fraction * self._half_period

    i_forward = np.empty(self._n_steps, dtype=float)
    i_reverse = np.empty(self._n_steps, dtype=float)

    for k in range(self._n_steps):
        t_fwd_end = (2 * k + 1) / (2.0 * self._frequency)
        t_rev_end = (k + 1) / self._frequency

        i_forward[k] = _sample_window_mean(
            t_arr, i_arr, t_fwd_end - w_half, t_fwd_end, include_end=False
        )
        i_reverse[k] = _sample_window_mean(
            t_arr,
            i_arr,
            t_rev_end - w_half,
            t_rev_end,
            include_end=(k == self._n_steps - 1),
        )

    E_step = np.asarray(self._step_potentials, dtype=float)
    i_net = i_forward - i_reverse
    return E_step, i_forward, i_reverse, i_net

RDEConvectionTerm

Axial convective transport operator \(-v_x(x) \partial c/\partial x\) for RDE.

Implements the reactions protocol expected by DiffusionProblem and ScipyIVPSolver, optionally composing with an existing homogeneous reaction network or callable while supplying an exact sparse analytical Jacobian when possible.

Parameters:

Name Type Description Default
omega float

Angular rotation velocity \(\omega > 0\) in \(\text{rad}/\text{s}\).

required
kinematic_viscosity float

Kinematic viscosity \(\nu > 0\) in \(\text{m}^2/\text{s}\).

required
diffusivity float or Mapping[str, float]

Scalar diffusion coefficient or per-species diffusivity mapping used for local Péclet number evaluation.

required
base_reactions Any

Optional homogeneous reaction term (ReactionNetwork, HomogeneousReaction, Mechanism, or callable) to superpose with axial convection.

None
Source code in src/softpotato/techniques/rde.py
class RDEConvectionTerm:
    r"""Axial convective transport operator :math:`-v_x(x) \partial c/\partial x` for RDE.

    Implements the ``reactions`` protocol expected by
    :class:`~softpotato.solver.DiffusionProblem` and
    :class:`~softpotato.solver.ScipyIVPSolver`, optionally composing with an
    existing homogeneous reaction network or callable while supplying an exact
    sparse analytical Jacobian when possible.

    Parameters
    ----------
    omega : float
        Angular rotation velocity :math:`\omega > 0` in :math:`\text{rad}/\text{s}`.
    kinematic_viscosity : float
        Kinematic viscosity :math:`\nu > 0` in :math:`\text{m}^2/\text{s}`.
    diffusivity : float or Mapping[str, float]
        Scalar diffusion coefficient or per-species diffusivity mapping used
        for local Péclet number evaluation.
    base_reactions : Any, optional
        Optional homogeneous reaction term (``ReactionNetwork``,
        ``HomogeneousReaction``, ``Mechanism``, or callable) to superpose with
        axial convection.
    """

    def __init__(
        self,
        omega: float,
        kinematic_viscosity: float,
        diffusivity: float | Mapping[str, float],
        *,
        base_reactions: Any = None,
    ) -> None:
        self._omega = _validate_positive_finite(omega, "omega")
        self._kinematic_viscosity = _validate_positive_finite(
            kinematic_viscosity, "kinematic_viscosity"
        )
        if isinstance(diffusivity, Mapping):
            self._diffusivity_map: dict[str, float] | None = {
                sp: _validate_positive_finite(d_val, f"diffusivity[{sp!r}]")
                for sp, d_val in diffusivity.items()
            }
            self._default_diffusivity: float | None = None
        else:
            self._diffusivity_map = None
            self._default_diffusivity = _validate_positive_finite(
                diffusivity, "diffusivity"
            )
        self._base_reactions = base_reactions
        self._matrix_cache: dict[tuple[str, int, float, float], sparse.csc_matrix] = {}

        # Expose analytical jacobian only when base_reactions is absent or provides one
        if base_reactions is None:
            self._can_provide_jacobian = True
        else:
            has_local = callable(getattr(base_reactions, "local_jacobian", None))
            has_jac = callable(getattr(base_reactions, "jacobian", None))
            self._can_provide_jacobian = has_local or has_jac

        if not self._can_provide_jacobian:
            # Shadow the class method on this instance so ScipyIVPSolver falls back
            # to numerical finite-difference Jacobian instead of an incomplete one.
            self.jacobian = None  # type: ignore[assignment,method-assign]

    def _get_diffusivity(self, species_name: str) -> float:
        if self._diffusivity_map is not None:
            if species_name in self._diffusivity_map:
                return self._diffusivity_map[species_name]
            return next(iter(self._diffusivity_map.values()))
        assert self._default_diffusivity is not None
        return self._default_diffusivity

    def _get_operator(self, species_name: str, grid: np.ndarray) -> sparse.csc_matrix:
        key = (species_name, len(grid), float(grid[0]), float(grid[-1]))
        op = self._matrix_cache.get(key)
        if op is None:
            d_val = self._get_diffusivity(species_name)
            op = _build_convection_matrix(
                grid, self._omega, self._kinematic_viscosity, d_val
            )
            self._matrix_cache[key] = op
        return op

    def __call__(
        self,
        c_dict: dict[str, np.ndarray],
        grid: np.ndarray,
        t: float,
    ) -> dict[str, np.ndarray]:
        """Evaluate convective rate (plus optional homogeneous reactions) for each species."""
        grid_arr = np.asarray(grid, dtype=float)
        out: dict[str, np.ndarray] = {}
        for sp, c_arr in c_dict.items():
            op = self._get_operator(sp, grid_arr)
            out[sp] = np.asarray(op @ c_arr, dtype=float)

        if self._base_reactions is not None:
            base_rates = self._base_reactions(c_dict, grid_arr, t)
            for sp, rate in base_rates.items():
                if sp in out:
                    out[sp] = out[sp] + np.asarray(rate, dtype=float)
                else:
                    out[sp] = np.asarray(rate, dtype=float)
        return out

    def jacobian(
        self,
        c_dict: dict[str, np.ndarray],
        grid: np.ndarray,
        t: float,
        species: Sequence[str] | None = None,
    ) -> sparse.csc_matrix:
        """Assemble full sparse Jacobian ``(S*N, S*N)`` for convection + reactions."""
        grid_arr = np.asarray(grid, dtype=float)
        species_names = list(species) if species is not None else list(c_dict.keys())
        n_pts = len(grid_arr)
        blocks = [self._get_operator(sp, grid_arr) for sp in species_names]
        j_conv = sparse.block_diag(blocks, format="csc")

        if self._base_reactions is None:
            return j_conv

        local_jac_fn = getattr(self._base_reactions, "local_jacobian", None)
        if callable(local_jac_fn):
            local_j = np.asarray(
                local_jac_fn(c_dict, grid_arr, t, species=species_names), dtype=float
            )
            if local_j.ndim == 2:
                local_j = np.broadcast_to(
                    local_j[:, :, np.newaxis], (*local_j.shape, n_pts)
                )
            rows: list[np.ndarray] = []
            cols: list[np.ndarray] = []
            data: list[np.ndarray] = []
            j_idx = np.arange(n_pts)
            for i in range(len(species_names)):
                for k in range(len(species_names)):
                    vals = local_j[i, k, :]
                    if np.any(vals != 0.0):
                        rows.append(i * n_pts + j_idx)
                        cols.append(k * n_pts + j_idx)
                        data.append(vals)
            if data:
                total = len(species_names) * n_pts
                j_base = sparse.coo_matrix(
                    (
                        np.concatenate(data),
                        (np.concatenate(rows), np.concatenate(cols)),
                    ),
                    shape=(total, total),
                ).tocsc()
                return (j_conv + j_base).tocsc()
            return j_conv

        rxn_jac_fn = getattr(self._base_reactions, "jacobian", None)
        if callable(rxn_jac_fn):
            try:
                raw_j = rxn_jac_fn(c_dict, grid_arr, t, species=species_names)
            except TypeError:
                raw_j = rxn_jac_fn(c_dict, grid_arr, t)

            if isinstance(raw_j, Mapping):
                total = len(species_names) * n_pts
                sp_index = {sp: idx for idx, sp in enumerate(species_names)}
                rows_d: list[np.ndarray] = []
                cols_d: list[np.ndarray] = []
                data_d: list[np.ndarray] = []
                j_idx = np.arange(n_pts)
                for (sp_i, sp_k), block in raw_j.items():
                    if sp_i not in sp_index or sp_k not in sp_index:
                        continue
                    arr = np.broadcast_to(np.asarray(block, dtype=float), (n_pts,))
                    if np.any(arr != 0.0):
                        rows_d.append(sp_index[sp_i] * n_pts + j_idx)
                        cols_d.append(sp_index[sp_k] * n_pts + j_idx)
                        data_d.append(arr)
                if data_d:
                    j_base = sparse.coo_matrix(
                        (
                            np.concatenate(data_d),
                            (np.concatenate(rows_d), np.concatenate(cols_d)),
                        ),
                        shape=(total, total),
                    ).tocsc()
                    return (j_conv + j_base).tocsc()
                return j_conv

            return (j_conv + sparse.csc_matrix(raw_j)).tocsc()

        return j_conv

jacobian

jacobian(c_dict: dict[str, ndarray], grid: ndarray, t: float, species: Sequence[str] | None = None) -> sparse.csc_matrix

Assemble full sparse Jacobian (S*N, S*N) for convection + reactions.

Source code in src/softpotato/techniques/rde.py
def jacobian(
    self,
    c_dict: dict[str, np.ndarray],
    grid: np.ndarray,
    t: float,
    species: Sequence[str] | None = None,
) -> sparse.csc_matrix:
    """Assemble full sparse Jacobian ``(S*N, S*N)`` for convection + reactions."""
    grid_arr = np.asarray(grid, dtype=float)
    species_names = list(species) if species is not None else list(c_dict.keys())
    n_pts = len(grid_arr)
    blocks = [self._get_operator(sp, grid_arr) for sp in species_names]
    j_conv = sparse.block_diag(blocks, format="csc")

    if self._base_reactions is None:
        return j_conv

    local_jac_fn = getattr(self._base_reactions, "local_jacobian", None)
    if callable(local_jac_fn):
        local_j = np.asarray(
            local_jac_fn(c_dict, grid_arr, t, species=species_names), dtype=float
        )
        if local_j.ndim == 2:
            local_j = np.broadcast_to(
                local_j[:, :, np.newaxis], (*local_j.shape, n_pts)
            )
        rows: list[np.ndarray] = []
        cols: list[np.ndarray] = []
        data: list[np.ndarray] = []
        j_idx = np.arange(n_pts)
        for i in range(len(species_names)):
            for k in range(len(species_names)):
                vals = local_j[i, k, :]
                if np.any(vals != 0.0):
                    rows.append(i * n_pts + j_idx)
                    cols.append(k * n_pts + j_idx)
                    data.append(vals)
        if data:
            total = len(species_names) * n_pts
            j_base = sparse.coo_matrix(
                (
                    np.concatenate(data),
                    (np.concatenate(rows), np.concatenate(cols)),
                ),
                shape=(total, total),
            ).tocsc()
            return (j_conv + j_base).tocsc()
        return j_conv

    rxn_jac_fn = getattr(self._base_reactions, "jacobian", None)
    if callable(rxn_jac_fn):
        try:
            raw_j = rxn_jac_fn(c_dict, grid_arr, t, species=species_names)
        except TypeError:
            raw_j = rxn_jac_fn(c_dict, grid_arr, t)

        if isinstance(raw_j, Mapping):
            total = len(species_names) * n_pts
            sp_index = {sp: idx for idx, sp in enumerate(species_names)}
            rows_d: list[np.ndarray] = []
            cols_d: list[np.ndarray] = []
            data_d: list[np.ndarray] = []
            j_idx = np.arange(n_pts)
            for (sp_i, sp_k), block in raw_j.items():
                if sp_i not in sp_index or sp_k not in sp_index:
                    continue
                arr = np.broadcast_to(np.asarray(block, dtype=float), (n_pts,))
                if np.any(arr != 0.0):
                    rows_d.append(sp_index[sp_i] * n_pts + j_idx)
                    cols_d.append(sp_index[sp_k] * n_pts + j_idx)
                    data_d.append(arr)
            if data_d:
                j_base = sparse.coo_matrix(
                    (
                        np.concatenate(data_d),
                        (np.concatenate(rows_d), np.concatenate(cols_d)),
                    ),
                    shape=(total, total),
                ).tocsc()
                return (j_conv + j_base).tocsc()
            return j_conv

        return (j_conv + sparse.csc_matrix(raw_j)).tocsc()

    return j_conv

__call__

__call__(c_dict: dict[str, ndarray], grid: ndarray, t: float) -> dict[str, np.ndarray]

Evaluate convective rate (plus optional homogeneous reactions) for each species.

Source code in src/softpotato/techniques/rde.py
def __call__(
    self,
    c_dict: dict[str, np.ndarray],
    grid: np.ndarray,
    t: float,
) -> dict[str, np.ndarray]:
    """Evaluate convective rate (plus optional homogeneous reactions) for each species."""
    grid_arr = np.asarray(grid, dtype=float)
    out: dict[str, np.ndarray] = {}
    for sp, c_arr in c_dict.items():
        op = self._get_operator(sp, grid_arr)
        out[sp] = np.asarray(op @ c_arr, dtype=float)

    if self._base_reactions is not None:
        base_rates = self._base_reactions(c_dict, grid_arr, t)
        for sp, rate in base_rates.items():
            if sp in out:
                out[sp] = out[sp] + np.asarray(rate, dtype=float)
            else:
                out[sp] = np.asarray(rate, dtype=float)
    return out

RDESweep

Multi-rotation-rate Rotating Disk Electrode (RDE) sweep configuration.

Generates an ordered collection of RotatingDiskElectrode instances sharing the same potential waveform, electrolyte viscosity, and hydrodynamic transport model across a series of rotation rates \(\{\omega_1, \dots, \omega_M\}\) for Levich and Koutecký–Levich analysis.

Parameters:

Name Type Description Default
waveform BaseTechnique

Shared potentiostatic excitation waveform. Mutually exclusive with direct LSV parameters (E_start, E_end, scan_rate).

None
omegas Sequence[float] or array - like

Sequence of positive angular rotation velocities in \(\text{rad}/\text{s}\). Mutually exclusive with rpms.

None
rpms Sequence[float] or array - like

Sequence of positive rotational speeds in RPM. Mutually exclusive with omegas.

None
kinematic_viscosity float

Electrolyte kinematic viscosity \(\nu > 0\) in \(\text{m}^2/\text{s}\).

1e-6
model ('nernst_layer', 'convective_diffusion')

Hydrodynamic mass-transport model.

'nernst_layer'
E_start optional

Direct LSV waveform parameters when waveform is omitted.

None
E_end optional

Direct LSV waveform parameters when waveform is omitted.

None
scan_rate optional

Direct LSV waveform parameters when waveform is omitted.

None
dE optional

Direct LSV waveform parameters when waveform is omitted.

None
n_points optional

Direct LSV waveform parameters when waveform is omitted.

None
domain_factor float

Domain multiplier \(k > 0\) applied to \(\delta_N\).

None

Examples:

>>> from softpotato.techniques import RDESweep
>>> sweep = RDESweep(
...     E_start=0.5, E_end=-0.5, scan_rate=0.05, rpms=[400, 900, 1600, 2500]
... )
>>> len(sweep)
4
Source code in src/softpotato/techniques/rde.py
class RDESweep:
    r"""Multi-rotation-rate Rotating Disk Electrode (RDE) sweep configuration.

    Generates an ordered collection of :class:`RotatingDiskElectrode`
    instances sharing the same potential waveform, electrolyte viscosity, and
    hydrodynamic transport model across a series of rotation rates
    :math:`\{\omega_1, \dots, \omega_M\}` for Levich and Koutecký–Levich
    analysis.

    Parameters
    ----------
    waveform : BaseTechnique, optional
        Shared potentiostatic excitation waveform. Mutually exclusive with
        direct LSV parameters (``E_start``, ``E_end``, ``scan_rate``).
    omegas : Sequence[float] or array-like, optional
        Sequence of positive angular rotation velocities in
        :math:`\text{rad}/\text{s}`. Mutually exclusive with ``rpms``.
    rpms : Sequence[float] or array-like, optional
        Sequence of positive rotational speeds in RPM. Mutually exclusive with
        ``omegas``.
    kinematic_viscosity : float, default 1e-6
        Electrolyte kinematic viscosity :math:`\nu > 0` in :math:`\text{m}^2/\text{s}`.
    model : {'nernst_layer', 'convective_diffusion'}, default 'nernst_layer'
        Hydrodynamic mass-transport model.
    E_start, E_end, scan_rate, dE, n_points : optional
        Direct LSV waveform parameters when ``waveform`` is omitted.
    domain_factor : float, optional
        Domain multiplier :math:`k > 0` applied to :math:`\delta_N`.

    Examples
    --------
    >>> from softpotato.techniques import RDESweep
    >>> sweep = RDESweep(
    ...     E_start=0.5, E_end=-0.5, scan_rate=0.05, rpms=[400, 900, 1600, 2500]
    ... )
    >>> len(sweep)
    4
    """

    def __init__(
        self,
        waveform: BaseTechnique | None = None,
        *,
        omegas: Sequence[float] | ArrayLike | None = None,
        rpms: Sequence[float] | ArrayLike | None = None,
        kinematic_viscosity: float = _DEFAULT_KINEMATIC_VISCOSITY,
        model: RDEModel = "nernst_layer",
        E_start: float | None = None,
        E_end: float | None = None,
        scan_rate: float | None = None,
        dE: float | None = None,
        n_points: int | None = None,
        domain_factor: float | None = None,
    ) -> None:
        self._waveform = _resolve_waveform(
            waveform,
            E_start=E_start,
            E_end=E_end,
            scan_rate=scan_rate,
            dE=dE,
            n_points=n_points,
        )
        self._omegas, self._rpms = _resolve_rotation_sequence(omegas, rpms)
        self._kinematic_viscosity = _validate_positive_finite(
            kinematic_viscosity, "kinematic_viscosity"
        )
        self._model: RDEModel = _resolve_rde_model(model)
        self._domain_factor = (
            None
            if domain_factor is None
            else _validate_positive_finite(domain_factor, "domain_factor")
        )
        self._techniques: tuple[RotatingDiskElectrode, ...] = tuple(
            RotatingDiskElectrode(
                self._waveform,
                omega=float(w),
                kinematic_viscosity=self._kinematic_viscosity,
                model=self._model,
                domain_factor=self._domain_factor,
            )
            for w in self._omegas
        )

    @property
    def waveform(self) -> BaseTechnique:
        """Shared potentiostatic excitation waveform."""
        return self._waveform

    @property
    def omegas(self) -> np.ndarray:
        r"""1D array of angular rotation velocities :math:`\omega` in :math:`\text{rad}/\text{s}`."""
        return self._omegas.copy()

    @property
    def rpms(self) -> np.ndarray:
        """1D array of rotational speeds in RPM."""
        return self._rpms.copy()

    @property
    def kinematic_viscosity(self) -> float:
        r"""Kinematic viscosity :math:`\nu` in :math:`\text{m}^2/\text{s}`."""
        return self._kinematic_viscosity

    @property
    def nu(self) -> float:
        """Alias for :attr:`kinematic_viscosity`."""
        return self._kinematic_viscosity

    @property
    def model(self) -> RDEModel:
        """Hydrodynamic mass-transport model."""
        return self._model

    @property
    def n_rates(self) -> int:
        """Number of rotation rates in the sweep."""
        return len(self._techniques)

    @property
    def techniques(self) -> tuple[RotatingDiskElectrode, ...]:
        """Tuple of configured :class:`RotatingDiskElectrode` instances."""
        return self._techniques

    def diffusion_layer_thicknesses(self, D: float) -> np.ndarray:
        r"""Compute Nernst diffusion layer thickness :math:`\delta_N(\omega)` for each rate."""
        return np.asarray(
            [tech.diffusion_layer_thickness(D) for tech in self._techniques],
            dtype=float,
        )

    def __len__(self) -> int:
        return len(self._techniques)

    def __iter__(self) -> Iterator[RotatingDiskElectrode]:
        return iter(self._techniques)

    @overload
    def __getitem__(self, index: int) -> RotatingDiskElectrode: ...

    @overload
    def __getitem__(self, index: slice) -> tuple[RotatingDiskElectrode, ...]: ...

    def __getitem__(
        self, index: int | slice
    ) -> RotatingDiskElectrode | tuple[RotatingDiskElectrode, ...]:
        return self._techniques[index]

    def simulate(
        self,
        *,
        D: float | None = None,
        diffusivity: Mapping[str, float] | None = None,
        c_bulk: float = 1.0,
        initial_conditions: Mapping[str, Any] | None = None,
        boundary_conditions: Mapping[str, tuple[BoundaryCondition, BoundaryCondition]]
        | None = None,
        kinetics: HeterogeneousKinetics | NernstianEquilibrium | None = None,
        species_name: str = "Ox",
        red_species_name: str = "Red",
        c_red_bulk: float = 0.0,
        n_electrons: int | Mapping[str, int] = 1,
        area: float = 1.0,
        reactions: Any = None,
        n_points: int = 80,
        grid_kind: str = "geometric",
        gamma: float = 1.06,
        beta: float = 3.0,
        domain_factor: float | None = None,
        solver: str = "scipy_ivp",
        t_eval: np.ndarray | None = None,
        solver_kwargs: Mapping[str, Any] | None = None,
    ) -> RDESweepResult:
        """Run the PDE simulation across all rotation rates in this sweep."""
        return simulate_rde_sweep(
            sweep=self,
            D=D,
            diffusivity=diffusivity,
            c_bulk=c_bulk,
            initial_conditions=initial_conditions,
            boundary_conditions=boundary_conditions,
            kinetics=kinetics,
            species_name=species_name,
            red_species_name=red_species_name,
            c_red_bulk=c_red_bulk,
            n_electrons=n_electrons,
            area=area,
            reactions=reactions,
            n_points=n_points,
            grid_kind=grid_kind,
            gamma=gamma,
            beta=beta,
            domain_factor=domain_factor,
            solver=solver,
            t_eval=t_eval,
            solver_kwargs=solver_kwargs,
        )

    def __repr__(self) -> str:
        return (
            f"RDESweep(waveform={self._waveform!r}, "
            f"n_rates={self.n_rates}, "
            f"kinematic_viscosity={self._kinematic_viscosity!r}, "
            f"model={self._model!r})"
        )

waveform property

waveform: BaseTechnique

Shared potentiostatic excitation waveform.

omegas property

omegas: ndarray

1D array of angular rotation velocities \(\omega\) in \(\text{rad}/\text{s}\).

rpms property

rpms: ndarray

1D array of rotational speeds in RPM.

kinematic_viscosity property

kinematic_viscosity: float

Kinematic viscosity \(\nu\) in \(\text{m}^2/\text{s}\).

nu property

nu: float

Alias for kinematic_viscosity.

model property

model: RDEModel

Hydrodynamic mass-transport model.

n_rates property

n_rates: int

Number of rotation rates in the sweep.

techniques property

techniques: tuple[RotatingDiskElectrode, ...]

Tuple of configured RotatingDiskElectrode instances.

diffusion_layer_thicknesses

diffusion_layer_thicknesses(D: float) -> np.ndarray

Compute Nernst diffusion layer thickness \(\delta_N(\omega)\) for each rate.

Source code in src/softpotato/techniques/rde.py
def diffusion_layer_thicknesses(self, D: float) -> np.ndarray:
    r"""Compute Nernst diffusion layer thickness :math:`\delta_N(\omega)` for each rate."""
    return np.asarray(
        [tech.diffusion_layer_thickness(D) for tech in self._techniques],
        dtype=float,
    )

simulate

simulate(*, D: float | None = None, diffusivity: Mapping[str, float] | None = None, c_bulk: float = 1.0, initial_conditions: Mapping[str, Any] | None = None, boundary_conditions: Mapping[str, tuple[BoundaryCondition, BoundaryCondition]] | None = None, kinetics: HeterogeneousKinetics | NernstianEquilibrium | None = None, species_name: str = 'Ox', red_species_name: str = 'Red', c_red_bulk: float = 0.0, n_electrons: int | Mapping[str, int] = 1, area: float = 1.0, reactions: Any = None, n_points: int = 80, grid_kind: str = 'geometric', gamma: float = 1.06, beta: float = 3.0, domain_factor: float | None = None, solver: str = 'scipy_ivp', t_eval: ndarray | None = None, solver_kwargs: Mapping[str, Any] | None = None) -> RDESweepResult

Run the PDE simulation across all rotation rates in this sweep.

Source code in src/softpotato/techniques/rde.py
def simulate(
    self,
    *,
    D: float | None = None,
    diffusivity: Mapping[str, float] | None = None,
    c_bulk: float = 1.0,
    initial_conditions: Mapping[str, Any] | None = None,
    boundary_conditions: Mapping[str, tuple[BoundaryCondition, BoundaryCondition]]
    | None = None,
    kinetics: HeterogeneousKinetics | NernstianEquilibrium | None = None,
    species_name: str = "Ox",
    red_species_name: str = "Red",
    c_red_bulk: float = 0.0,
    n_electrons: int | Mapping[str, int] = 1,
    area: float = 1.0,
    reactions: Any = None,
    n_points: int = 80,
    grid_kind: str = "geometric",
    gamma: float = 1.06,
    beta: float = 3.0,
    domain_factor: float | None = None,
    solver: str = "scipy_ivp",
    t_eval: np.ndarray | None = None,
    solver_kwargs: Mapping[str, Any] | None = None,
) -> RDESweepResult:
    """Run the PDE simulation across all rotation rates in this sweep."""
    return simulate_rde_sweep(
        sweep=self,
        D=D,
        diffusivity=diffusivity,
        c_bulk=c_bulk,
        initial_conditions=initial_conditions,
        boundary_conditions=boundary_conditions,
        kinetics=kinetics,
        species_name=species_name,
        red_species_name=red_species_name,
        c_red_bulk=c_red_bulk,
        n_electrons=n_electrons,
        area=area,
        reactions=reactions,
        n_points=n_points,
        grid_kind=grid_kind,
        gamma=gamma,
        beta=beta,
        domain_factor=domain_factor,
        solver=solver,
        t_eval=t_eval,
        solver_kwargs=solver_kwargs,
    )

RDESweepResult dataclass

Container for multi-rotation-rate RDE simulation sweep results.

Attributes:

Name Type Description
omegas ndarray

Angular rotation velocities \(\omega\) in \(\text{rad}/\text{s}\) of shape (M,).

rpms ndarray

Rotational speeds in RPM of shape (M,).

results tuple[SolverResult, ...]

Individual SolverResult objects for each rotation rate.

limiting_currents ndarray

Final-time (steady-state) Faradaic current of species at each rotation rate, of shape (M,) in Amperes.

techniques tuple[RotatingDiskElectrode, ...]

Configured RotatingDiskElectrode instance for each rotation rate.

species str

Primary species name used to populate limiting_currents.

Source code in src/softpotato/techniques/rde.py
@dataclass(frozen=True)
class RDESweepResult:
    """Container for multi-rotation-rate RDE simulation sweep results.

    Attributes
    ----------
    omegas : np.ndarray
        Angular rotation velocities :math:`\\omega` in :math:`\\text{rad}/\\text{s}`
        of shape ``(M,)``.
    rpms : np.ndarray
        Rotational speeds in RPM of shape ``(M,)``.
    results : tuple[SolverResult, ...]
        Individual :class:`~softpotato.solver.SolverResult` objects for each
        rotation rate.
    limiting_currents : np.ndarray
        Final-time (steady-state) Faradaic current of :attr:`species` at each
        rotation rate, of shape ``(M,)`` in Amperes.
    techniques : tuple[RotatingDiskElectrode, ...]
        Configured :class:`RotatingDiskElectrode` instance for each rotation rate.
    species : str
        Primary species name used to populate :attr:`limiting_currents`.
    """

    omegas: np.ndarray
    rpms: np.ndarray
    results: tuple[SolverResult, ...]
    limiting_currents: np.ndarray
    techniques: tuple[RotatingDiskElectrode, ...]
    species: str

    def __len__(self) -> int:
        return len(self.results)

RotatingDiskElectrode

Bases: BaseTechnique

Rotating Disk Electrode (RDE) hydrodynamic electrochemical technique.

Wraps an underlying potentiostatic excitation waveform (LinearSweepVoltammetry, CyclicVoltammetry, Chronoamperometry, or any potentiostatic BaseTechnique) and couples it with rotation-dependent hydrodynamic mass transport:

  • model="nernst_layer" (default): Nernst stagnant diffusion layer approximation on \(x \in [0, \delta_N]\) with bulk Dirichlet boundary condition at \(x = \delta_N\), where

    \[ \delta_N = 1.610 \, D^{1/3} \nu^{1/6} \omega^{-1/2} \]
  • model="convective_diffusion": Full Levich axial convective-diffusion PDE on \(x \in [0, k \delta_N]\) (default \(k = 3.0\)) including the von Kármán axial fluid velocity toward the disk:

    \[ v_x(x) = -0.51023 \, \omega^{3/2} \nu^{-1/2} x^2 \]

Parameters:

Name Type Description Default
waveform BaseTechnique

Underlying potentiostatic excitation waveform (e.g., LSV, CV, or CA). Mutually exclusive with direct LSV parameters (E_start, E_end, scan_rate).

None
omega float

Angular rotation velocity \(\omega > 0\) in \(\text{rad}/\text{s}\). Mutually exclusive with rpm.

None
rpm float

Rotational speed in revolutions per minute (\(\text{rpm} > 0\)), converted to \(\omega\) via rpm_to_rad_s. Mutually exclusive with omega.

None
kinematic_viscosity float

Electrolyte kinematic viscosity \(\nu > 0\) in \(\text{m}^2/\text{s}\) (default 1e-6 for water at 298 K).

1e-6
model ('nernst_layer', 'convective_diffusion')

Hydrodynamic mass-transport model.

'nernst_layer'
E_start float

Initial potential in Volts when constructing a default LSV waveform.

None
E_end float

Final potential in Volts when constructing a default LSV waveform.

None
scan_rate float

Scan rate magnitude in V/s when constructing a default LSV waveform.

None
dE float

Default potential step resolution in Volts for the default LSV waveform.

None
n_points int

Default number of time grid points for the default LSV waveform.

None
domain_factor float

Multiplier \(k > 0\) applied to \(\delta_N\) when constructing spatial grids via build_grid. Defaults to 1.0 for model="nernst_layer" and 3.0 for model="convective_diffusion".

None

Examples:

>>> from softpotato.techniques import RotatingDiskElectrode
>>> rde = RotatingDiskElectrode(
...     E_start=0.5, E_end=-0.5, scan_rate=0.05, rpm=1600
... )
>>> round(rde.omega, 2)
167.55
>>> round(rde.diffusion_layer_thickness(D=1e-9) * 1e6, 2)
12.44
Source code in src/softpotato/techniques/rde.py
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
class RotatingDiskElectrode(BaseTechnique):
    r"""Rotating Disk Electrode (RDE) hydrodynamic electrochemical technique.

    Wraps an underlying potentiostatic excitation waveform
    (:class:`~softpotato.techniques.LinearSweepVoltammetry`,
    :class:`~softpotato.techniques.CyclicVoltammetry`,
    :class:`~softpotato.techniques.Chronoamperometry`, or any potentiostatic
    :class:`~softpotato.techniques.BaseTechnique`) and couples it with
    rotation-dependent hydrodynamic mass transport:

    - ``model="nernst_layer"`` (default): Nernst stagnant diffusion layer
      approximation on :math:`x \in [0, \delta_N]` with bulk Dirichlet boundary
      condition at :math:`x = \delta_N`, where

      .. math::

          \delta_N = 1.610 \, D^{1/3} \nu^{1/6} \omega^{-1/2}

    - ``model="convective_diffusion"``: Full Levich axial convective-diffusion
      PDE on :math:`x \in [0, k \delta_N]` (default :math:`k = 3.0`) including
      the von Kármán axial fluid velocity toward the disk:

      .. math::

          v_x(x) = -0.51023 \, \omega^{3/2} \nu^{-1/2} x^2

    Parameters
    ----------
    waveform : BaseTechnique, optional
        Underlying potentiostatic excitation waveform (e.g., LSV, CV, or CA).
        Mutually exclusive with direct LSV parameters
        (``E_start``, ``E_end``, ``scan_rate``).
    omega : float, optional
        Angular rotation velocity :math:`\omega > 0` in :math:`\text{rad}/\text{s}`.
        Mutually exclusive with ``rpm``.
    rpm : float, optional
        Rotational speed in revolutions per minute (:math:`\text{rpm} > 0`),
        converted to :math:`\omega` via
        :func:`~softpotato.analytical.hydrodynamics.rpm_to_rad_s`.
        Mutually exclusive with ``omega``.
    kinematic_viscosity : float, default 1e-6
        Electrolyte kinematic viscosity :math:`\nu > 0` in :math:`\text{m}^2/\text{s}`
        (default ``1e-6`` for water at 298 K).
    model : {'nernst_layer', 'convective_diffusion'}, default 'nernst_layer'
        Hydrodynamic mass-transport model.
    E_start : float, optional
        Initial potential in Volts when constructing a default LSV waveform.
    E_end : float, optional
        Final potential in Volts when constructing a default LSV waveform.
    scan_rate : float, optional
        Scan rate magnitude in V/s when constructing a default LSV waveform.
    dE : float, optional
        Default potential step resolution in Volts for the default LSV waveform.
    n_points : int, optional
        Default number of time grid points for the default LSV waveform.
    domain_factor : float, optional
        Multiplier :math:`k > 0` applied to :math:`\delta_N` when constructing
        spatial grids via :meth:`build_grid`. Defaults to ``1.0`` for
        ``model="nernst_layer"`` and ``3.0`` for ``model="convective_diffusion"``.

    Examples
    --------
    >>> from softpotato.techniques import RotatingDiskElectrode
    >>> rde = RotatingDiskElectrode(
    ...     E_start=0.5, E_end=-0.5, scan_rate=0.05, rpm=1600
    ... )
    >>> round(rde.omega, 2)
    167.55
    >>> round(rde.diffusion_layer_thickness(D=1e-9) * 1e6, 2)
    12.44
    """

    def __init__(
        self,
        waveform: BaseTechnique | None = None,
        *,
        omega: float | None = None,
        rpm: float | None = None,
        kinematic_viscosity: float = _DEFAULT_KINEMATIC_VISCOSITY,
        model: RDEModel = "nernst_layer",
        E_start: float | None = None,
        E_end: float | None = None,
        scan_rate: float | None = None,
        dE: float | None = None,
        n_points: int | None = None,
        domain_factor: float | None = None,
    ) -> None:
        self._mode = "potentiostatic"
        self._waveform = _resolve_waveform(
            waveform,
            E_start=E_start,
            E_end=E_end,
            scan_rate=scan_rate,
            dE=dE,
            n_points=n_points,
        )
        self._omega, self._rpm = _resolve_scalar_rotation(omega, rpm)
        self._kinematic_viscosity = _validate_positive_finite(
            kinematic_viscosity, "kinematic_viscosity"
        )
        self._model: RDEModel = _resolve_rde_model(model)
        if domain_factor is None:
            self._domain_factor = (
                1.0
                if self._model == "nernst_layer"
                else _DEFAULT_CONVECTIVE_DOMAIN_FACTOR
            )
        else:
            self._domain_factor = _validate_positive_finite(
                domain_factor, "domain_factor"
            )

    @property
    def waveform(self) -> BaseTechnique:
        """Underlying potentiostatic excitation waveform."""
        return self._waveform

    @property
    def omega(self) -> float:
        r"""Angular rotation velocity :math:`\omega` in :math:`\text{rad}/\text{s}`."""
        return self._omega

    @property
    def rpm(self) -> float:
        """Rotational speed in revolutions per minute (RPM)."""
        return self._rpm

    @property
    def kinematic_viscosity(self) -> float:
        r"""Kinematic viscosity :math:`\nu` in :math:`\text{m}^2/\text{s}`."""
        return self._kinematic_viscosity

    @property
    def nu(self) -> float:
        r"""Alias for :attr:`kinematic_viscosity` (:math:`\nu`)."""
        return self._kinematic_viscosity

    @property
    def model(self) -> RDEModel:
        """Hydrodynamic mass-transport model (``'nernst_layer'`` or ``'convective_diffusion'``)."""
        return self._model

    @property
    def domain_factor(self) -> float:
        r"""Domain multiplier :math:`k` such that :math:`x_{\max} = k \delta_N`."""
        return self._domain_factor

    @property
    def duration(self) -> float:
        """Total experiment duration in seconds (delegated to :attr:`waveform`)."""
        return self._waveform.duration

    @property
    def event_times(self) -> tuple[float, ...]:
        """Sorted interior event timestamps (delegated to :attr:`waveform`)."""
        return self._waveform.event_times

    def _technique_plots(self) -> tuple[PlotSpec, ...]:
        base_specs = self._waveform._technique_plots()
        if not base_specs:
            return ()
        first = base_specs[0]
        rde_title = (
            first.title if first.title.startswith("RDE ") else f"RDE {first.title}"
        )
        updated_first = PlotSpec(
            kind=first.kind,
            title=rde_title,
            x_label=first.x_label,
            y_label=first.y_label,
            description=first.description,
        )
        return (updated_first, *base_specs[1:])

    @overload
    def excitation(self, t: float) -> float: ...

    @overload
    def excitation(self, t: np.ndarray) -> np.ndarray: ...

    @overload
    def excitation(self, t: float | ArrayLike) -> float | np.ndarray: ...

    def excitation(self, t: float | ArrayLike) -> float | np.ndarray:
        """Evaluate the underlying potential waveform :math:`E(t)` at time ``t``."""
        return self._waveform.excitation(t)

    def time_grid(
        self,
        n_points: int | None = None,
        dt: float | None = None,
        **kwargs: Any,
    ) -> np.ndarray:
        """Generate evaluation timestamps (delegated to :attr:`waveform`)."""
        if kwargs:
            return self._waveform.time_grid(n_points=n_points, dt=dt, **kwargs)
        return self._waveform.time_grid(n_points=n_points, dt=dt)

    def diffusion_layer_thickness(self, D: float) -> float:
        r"""Compute the Nernst stagnant diffusion layer thickness :math:`\delta_N`.

        Delegates to :func:`~softpotato.analytical.hydrodynamics.nernst_diffusion_layer`:

        .. math::

            \delta_N = 1.610 \, D^{1/3} \nu^{1/6} \omega^{-1/2}

        Parameters
        ----------
        D : float
            Diffusion coefficient :math:`D > 0` in consistent units with
            :attr:`kinematic_viscosity` (e.g., :math:`\text{m}^2/\text{s}`).

        Returns
        -------
        float
            Diffusion layer thickness :math:`\delta_N > 0`.
        """
        d_val = _validate_positive_finite(D, "D")
        return float(
            nernst_diffusion_layer(
                omega=self._omega,
                D=d_val,
                nu=self._kinematic_viscosity,
            )
        )

    @overload
    def axial_velocity(self, x: float) -> float: ...

    @overload
    def axial_velocity(self, x: np.ndarray) -> np.ndarray: ...

    @overload
    def axial_velocity(self, x: float | ArrayLike) -> float | np.ndarray: ...

    def axial_velocity(self, x: float | ArrayLike) -> float | np.ndarray:
        r"""Evaluate the von Kármán axial fluid velocity :math:`v_x(x)` toward the disk.

        .. math::

            v_x(x) = -0.51023 \, \omega^{3/2} \nu^{-1/2} x^2

        Parameters
        ----------
        x : float or array-like
            Axial distance(s) from the disk electrode surface (:math:`x \ge 0`).

        Returns
        -------
        float or np.ndarray
            Axial velocity :math:`v_x(x) \le 0` in :math:`\text{m}/\text{s}`
            (or consistent units).
        """
        coeff = (
            -_VON_KARMAN_A * (self._omega**1.5) * (self._kinematic_viscosity ** (-0.5))
        )
        if np.isscalar(x):
            x_val = _validate_finite_real(x, "x")
            if x_val < 0.0:
                raise ValueError(f"Axial coordinate x must be >= 0, got {x!r}.")
            return float(coeff * x_val * x_val)

        x_arr = np.asarray(x, dtype=float)
        if not np.all(np.isfinite(x_arr)) or np.any(x_arr < 0.0):
            raise ValueError("All axial coordinates in x must be finite and >= 0.")
        return coeff * (x_arr**2)

    def build_grid(
        self,
        D: float,
        n_points: int = 80,
        kind: str = "geometric",
        gamma: float = 1.06,
        *,
        beta: float = 3.0,
        domain_factor: float | None = None,
    ) -> Mesh1D:
        r"""Construct a 1D spatial mesh bounded by the hydrodynamic diffusion layer.

        For ``model="nernst_layer"``, the default domain is :math:`[0, \delta_N]`.
        For ``model="convective_diffusion"``, the default domain is
        :math:`[0, k \cdot \delta_N]` with :math:`k = 3.0`.

        Parameters
        ----------
        D : float
            Reference diffusion coefficient :math:`D > 0`.
        n_points : int, default 80
            Number of spatial grid nodes (:math:`\ge 3`).
        kind : {'geometric', 'exponential', 'uniform'}, default 'geometric'
            Mesh discretization family.
        gamma : float, default 1.06
            Geometric expansion ratio :math:`\gamma > 1` (used when
            ``kind="geometric"``).
        beta : float, default 3.0
            Exponential stretching factor :math:`\beta > 0` (used when
            ``kind="exponential"``).
        domain_factor : float, optional
            Override for :attr:`domain_factor` (:math:`k > 0`).

        Returns
        -------
        Mesh1D
            Constructed 1D spatial mesh spanning :math:`[0, k \delta_N]`.
        """
        n_pts = _validate_positive_int(n_points, "n_points", minimum=3)
        factor = (
            self._domain_factor
            if domain_factor is None
            else _validate_positive_finite(domain_factor, "domain_factor")
        )
        delta = self.diffusion_layer_thickness(D)
        x_max = factor * delta

        if not isinstance(kind, str):
            raise TypeError(f"kind must be a string, got {type(kind).__name__}.")
        kind_norm = kind.strip().lower()

        if kind_norm == "geometric":
            return GeometricExpandingMesh(0.0, x_max, n_points=n_pts, gamma=gamma)
        if kind_norm == "exponential":
            return ExponentialMesh(0.0, x_max, n_points=n_pts, beta=beta)
        if kind_norm == "uniform":
            return Uniform1DMesh(0.0, x_max, n_points=n_pts)

        raise ValueError(
            f"Unknown mesh kind {kind!r}. Must be one of "
            "('geometric', 'exponential', 'uniform')."
        )

    def convection_term(
        self,
        diffusivity: float | Mapping[str, float],
        *,
        reactions: Any = None,
    ) -> RDEConvectionTerm:
        """Create an :class:`RDEConvectionTerm` for ``DiffusionProblem(reactions=...)``."""
        return RDEConvectionTerm(
            omega=self._omega,
            kinematic_viscosity=self._kinematic_viscosity,
            diffusivity=diffusivity,
            base_reactions=reactions,
        )

    def levich_limiting_current(
        self,
        *,
        n: float = 1,
        D: float = 1e-9,
        c_bulk: float = 1.0,
        area: float = 1.0,
    ) -> float:
        r"""Compute the analytical Levich limiting current :math:`I_L` at this rotation rate.

        Delegates to :func:`~softpotato.analytical.hydrodynamics.levich`.
        """
        return float(
            levich(
                omega=self._omega,
                n=n,
                D=D,
                c_bulk=c_bulk,
                area=area,
                nu=self._kinematic_viscosity,
            )
        )

    def with_rotation(
        self,
        *,
        omega: float | None = None,
        rpm: float | None = None,
    ) -> RotatingDiskElectrode:
        """Return a copy of this RDE technique at a different rotation rate."""
        return RotatingDiskElectrode(
            self._waveform,
            omega=omega,
            rpm=rpm,
            kinematic_viscosity=self._kinematic_viscosity,
            model=self._model,
            domain_factor=self._domain_factor,
        )

    def build_problem(
        self,
        *,
        D: float | None = None,
        diffusivity: Mapping[str, float] | None = None,
        c_bulk: float = 1.0,
        initial_conditions: Mapping[str, Any] | None = None,
        boundary_conditions: Mapping[str, tuple[BoundaryCondition, BoundaryCondition]]
        | None = None,
        kinetics: HeterogeneousKinetics | NernstianEquilibrium | None = None,
        species_name: str = "Ox",
        red_species_name: str = "Red",
        c_red_bulk: float = 0.0,
        n_electrons: int | Mapping[str, int] = 1,
        area: float = 1.0,
        reactions: Any = None,
        n_points: int = 80,
        grid_kind: str = "geometric",
        gamma: float = 1.06,
        beta: float = 3.0,
        domain_factor: float | None = None,
    ) -> DiffusionProblem:
        """Build a configured :class:`~softpotato.solver.DiffusionProblem` for this RDE.

        Automatically sizes the spatial mesh to the hydrodynamic diffusion
        layer, attaches bulk Dirichlet outer boundary conditions, and injects
        the axial convective velocity operator when
        ``model="convective_diffusion"``.
        """
        if D is None and diffusivity is None:
            raise ValueError("Either 'D' or 'diffusivity' must be provided.")
        if D is not None and diffusivity is not None:
            raise ValueError("Specify either 'D' or 'diffusivity', not both.")

        area_val = _validate_positive_finite(area, "area")
        n_electrons_arg: int | dict[str, int] = (
            dict(n_electrons) if isinstance(n_electrons, Mapping) else n_electrons
        )

        if diffusivity is not None:
            diff_map = {
                sp: _validate_positive_finite(val, f"diffusivity[{sp!r}]")
                for sp, val in diffusivity.items()
            }
            if not diff_map:
                raise ValueError("'diffusivity' mapping must not be empty.")
            d_ref = max(diff_map.values())
        else:
            assert D is not None
            d_ref = _validate_positive_finite(D, "D")
            if kinetics is not None and boundary_conditions is None:
                diff_map = {species_name: d_ref, red_species_name: d_ref}
            else:
                diff_map = {species_name: d_ref}

        mesh = self.build_grid(
            D=d_ref,
            n_points=n_points,
            kind=grid_kind,
            gamma=gamma,
            beta=beta,
            domain_factor=domain_factor,
        )

        if boundary_conditions is None and isinstance(kinetics, HeterogeneousKinetics):
            from softpotato.reactions.mechanisms import ElectrochemicalStep, Mechanism
            from softpotato.reactions.species import Species

            d_ox = diff_map.get(species_name, d_ref)
            d_red = diff_map.get(red_species_name, d_ref)
            diff_map.setdefault(species_name, d_ox)
            diff_map.setdefault(red_species_name, d_red)

            ox_sp = Species(
                species_name,
                diffusivity=d_ox,
                bulk_concentration=c_bulk,
                n_electrons=int(kinetics.n),
            )
            red_sp = Species(
                red_species_name,
                diffusivity=d_red,
                bulk_concentration=c_red_bulk,
            )
            mech = Mechanism(
                species=[ox_sp, red_sp],
                electrochemical_steps=[ElectrochemicalStep(ox_sp, red_sp, kinetics)],
            )
            mech_problem = mech.create_problem(
                mesh,
                potential=self,
                geometry=PlanarGeometry(area=area_val),
                diffusivity=diff_map,
                initial_conditions=initial_conditions,
                n_electrons=n_electrons_arg,
                electrodes="left",
                bulk_bc="dirichlet",
            )
            bcs = mech_problem.boundary_conditions
            ics = mech_problem.initial_conditions
            interfacial_rxn = mech_problem.reactions
            if reactions is not None and interfacial_rxn is not None:
                # Compose user homogeneous reactions with interfacial kinetics
                user_rxn = reactions
                mech_rxn = interfacial_rxn

                def _composed_rxn(
                    c_dict: dict[str, np.ndarray],
                    x_arr: np.ndarray,
                    t_val: float,
                ) -> dict[str, np.ndarray]:
                    out_i = mech_rxn(c_dict, x_arr, t_val)
                    out_u = user_rxn(c_dict, x_arr, t_val)
                    return {sp: out_i[sp] + out_u[sp] for sp in out_i}

                base_rxn: Any = _composed_rxn
            elif reactions is not None:
                base_rxn = reactions
            else:
                base_rxn = interfacial_rxn

            effective_reactions = (
                self.convection_term(diff_map, reactions=base_rxn)
                if self._model == "convective_diffusion"
                else base_rxn
            )

            return DiffusionProblem(
                grid=mesh,
                diffusivity=diff_map,
                boundary_conditions=bcs,
                initial_conditions=ics,
                reactions=effective_reactions,
                species=mech.species,
                geometry=PlanarGeometry(area=area_val),
                n_electrons=n_electrons_arg,
                mechanism=mech,
            )

        if boundary_conditions is not None:
            bcs = dict(boundary_conditions)
        elif kinetics is not None:
            d_ox = diff_map.get(species_name, d_ref)
            d_red = diff_map.get(red_species_name, d_ref)
            bcs = create_electrochemical_bcs(
                kinetics=kinetics,
                potential=self,
                ox=species_name,
                red=red_species_name,
                D_ox=d_ox,
                D_red=d_red,
                c_ox_bulk=c_bulk,
                c_red_bulk=c_red_bulk,
                electrode_side="left",
                bulk_bc="dirichlet",
            )
            diff_map.setdefault(species_name, d_ox)
            diff_map.setdefault(red_species_name, d_red)
        else:
            # Default mass-transport-limited (zero surface concentration) Dirichlet BC
            bcs = {sp: (DirichletBC(0.0), DirichletBC(c_bulk)) for sp in diff_map}

        if initial_conditions is not None:
            ics = dict(initial_conditions)
        elif kinetics is not None and boundary_conditions is None:
            ics = {species_name: c_bulk, red_species_name: c_red_bulk}
        else:
            ics = {sp: c_bulk for sp in diff_map}

        effective_reactions = (
            self.convection_term(diff_map, reactions=reactions)
            if self._model == "convective_diffusion"
            else reactions
        )

        return DiffusionProblem(
            grid=mesh,
            diffusivity=diff_map,
            boundary_conditions=bcs,
            initial_conditions=ics,
            reactions=effective_reactions,
            geometry=PlanarGeometry(area=area_val),
            n_electrons=n_electrons_arg,
        )

    def __repr__(self) -> str:
        return (
            f"RotatingDiskElectrode(waveform={self._waveform!r}, "
            f"omega={self._omega!r}, "
            f"kinematic_viscosity={self._kinematic_viscosity!r}, "
            f"model={self._model!r})"
        )

waveform property

waveform: BaseTechnique

Underlying potentiostatic excitation waveform.

omega property

omega: float

Angular rotation velocity \(\omega\) in \(\text{rad}/\text{s}\).

rpm property

rpm: float

Rotational speed in revolutions per minute (RPM).

kinematic_viscosity property

kinematic_viscosity: float

Kinematic viscosity \(\nu\) in \(\text{m}^2/\text{s}\).

nu property

nu: float

Alias for kinematic_viscosity (\(\nu\)).

model property

model: RDEModel

Hydrodynamic mass-transport model ('nernst_layer' or 'convective_diffusion').

domain_factor property

domain_factor: float

Domain multiplier \(k\) such that \(x_{\max} = k \delta_N\).

duration property

duration: float

Total experiment duration in seconds (delegated to waveform).

event_times property

event_times: tuple[float, ...]

Sorted interior event timestamps (delegated to waveform).

excitation

excitation(t: float) -> float
excitation(t: ndarray) -> np.ndarray
excitation(t: float | ArrayLike) -> float | np.ndarray
excitation(t: float | ArrayLike) -> float | np.ndarray

Evaluate the underlying potential waveform \(E(t)\) at time t.

Source code in src/softpotato/techniques/rde.py
def excitation(self, t: float | ArrayLike) -> float | np.ndarray:
    """Evaluate the underlying potential waveform :math:`E(t)` at time ``t``."""
    return self._waveform.excitation(t)

time_grid

time_grid(n_points: int | None = None, dt: float | None = None, **kwargs: Any) -> np.ndarray

Generate evaluation timestamps (delegated to waveform).

Source code in src/softpotato/techniques/rde.py
def time_grid(
    self,
    n_points: int | None = None,
    dt: float | None = None,
    **kwargs: Any,
) -> np.ndarray:
    """Generate evaluation timestamps (delegated to :attr:`waveform`)."""
    if kwargs:
        return self._waveform.time_grid(n_points=n_points, dt=dt, **kwargs)
    return self._waveform.time_grid(n_points=n_points, dt=dt)

diffusion_layer_thickness

diffusion_layer_thickness(D: float) -> float

Compute the Nernst stagnant diffusion layer thickness \(\delta_N\).

Delegates to nernst_diffusion_layer:

\[ \delta_N = 1.610 \, D^{1/3} \nu^{1/6} \omega^{-1/2} \]

Parameters:

Name Type Description Default
D float

Diffusion coefficient \(D > 0\) in consistent units with kinematic_viscosity (e.g., \(\text{m}^2/\text{s}\)).

required

Returns:

Type Description
float

Diffusion layer thickness \(\delta_N > 0\).

Source code in src/softpotato/techniques/rde.py
def diffusion_layer_thickness(self, D: float) -> float:
    r"""Compute the Nernst stagnant diffusion layer thickness :math:`\delta_N`.

    Delegates to :func:`~softpotato.analytical.hydrodynamics.nernst_diffusion_layer`:

    .. math::

        \delta_N = 1.610 \, D^{1/3} \nu^{1/6} \omega^{-1/2}

    Parameters
    ----------
    D : float
        Diffusion coefficient :math:`D > 0` in consistent units with
        :attr:`kinematic_viscosity` (e.g., :math:`\text{m}^2/\text{s}`).

    Returns
    -------
    float
        Diffusion layer thickness :math:`\delta_N > 0`.
    """
    d_val = _validate_positive_finite(D, "D")
    return float(
        nernst_diffusion_layer(
            omega=self._omega,
            D=d_val,
            nu=self._kinematic_viscosity,
        )
    )

axial_velocity

axial_velocity(x: float) -> float
axial_velocity(x: ndarray) -> np.ndarray
axial_velocity(x: float | ArrayLike) -> float | np.ndarray
axial_velocity(x: float | ArrayLike) -> float | np.ndarray

Evaluate the von Kármán axial fluid velocity \(v_x(x)\) toward the disk.

\[ v_x(x) = -0.51023 \, \omega^{3/2} \nu^{-1/2} x^2 \]

Parameters:

Name Type Description Default
x float or array - like

Axial distance(s) from the disk electrode surface (\(x \ge 0\)).

required

Returns:

Type Description
float or ndarray

Axial velocity \(v_x(x) \le 0\) in \(\text{m}/\text{s}\) (or consistent units).

Source code in src/softpotato/techniques/rde.py
def axial_velocity(self, x: float | ArrayLike) -> float | np.ndarray:
    r"""Evaluate the von Kármán axial fluid velocity :math:`v_x(x)` toward the disk.

    .. math::

        v_x(x) = -0.51023 \, \omega^{3/2} \nu^{-1/2} x^2

    Parameters
    ----------
    x : float or array-like
        Axial distance(s) from the disk electrode surface (:math:`x \ge 0`).

    Returns
    -------
    float or np.ndarray
        Axial velocity :math:`v_x(x) \le 0` in :math:`\text{m}/\text{s}`
        (or consistent units).
    """
    coeff = (
        -_VON_KARMAN_A * (self._omega**1.5) * (self._kinematic_viscosity ** (-0.5))
    )
    if np.isscalar(x):
        x_val = _validate_finite_real(x, "x")
        if x_val < 0.0:
            raise ValueError(f"Axial coordinate x must be >= 0, got {x!r}.")
        return float(coeff * x_val * x_val)

    x_arr = np.asarray(x, dtype=float)
    if not np.all(np.isfinite(x_arr)) or np.any(x_arr < 0.0):
        raise ValueError("All axial coordinates in x must be finite and >= 0.")
    return coeff * (x_arr**2)

build_grid

build_grid(D: float, n_points: int = 80, kind: str = 'geometric', gamma: float = 1.06, *, beta: float = 3.0, domain_factor: float | None = None) -> Mesh1D

Construct a 1D spatial mesh bounded by the hydrodynamic diffusion layer.

For model="nernst_layer", the default domain is \([0, \delta_N]\). For model="convective_diffusion", the default domain is \([0, k \cdot \delta_N]\) with \(k = 3.0\).

Parameters:

Name Type Description Default
D float

Reference diffusion coefficient \(D > 0\).

required
n_points int

Number of spatial grid nodes (\(\ge 3\)).

80
kind ('geometric', 'exponential', 'uniform')

Mesh discretization family.

'geometric'
gamma float

Geometric expansion ratio \(\gamma > 1\) (used when kind="geometric").

1.06
beta float

Exponential stretching factor \(\beta > 0\) (used when kind="exponential").

3.0
domain_factor float

Override for domain_factor (\(k > 0\)).

None

Returns:

Type Description
Mesh1D

Constructed 1D spatial mesh spanning \([0, k \delta_N]\).

Source code in src/softpotato/techniques/rde.py
def build_grid(
    self,
    D: float,
    n_points: int = 80,
    kind: str = "geometric",
    gamma: float = 1.06,
    *,
    beta: float = 3.0,
    domain_factor: float | None = None,
) -> Mesh1D:
    r"""Construct a 1D spatial mesh bounded by the hydrodynamic diffusion layer.

    For ``model="nernst_layer"``, the default domain is :math:`[0, \delta_N]`.
    For ``model="convective_diffusion"``, the default domain is
    :math:`[0, k \cdot \delta_N]` with :math:`k = 3.0`.

    Parameters
    ----------
    D : float
        Reference diffusion coefficient :math:`D > 0`.
    n_points : int, default 80
        Number of spatial grid nodes (:math:`\ge 3`).
    kind : {'geometric', 'exponential', 'uniform'}, default 'geometric'
        Mesh discretization family.
    gamma : float, default 1.06
        Geometric expansion ratio :math:`\gamma > 1` (used when
        ``kind="geometric"``).
    beta : float, default 3.0
        Exponential stretching factor :math:`\beta > 0` (used when
        ``kind="exponential"``).
    domain_factor : float, optional
        Override for :attr:`domain_factor` (:math:`k > 0`).

    Returns
    -------
    Mesh1D
        Constructed 1D spatial mesh spanning :math:`[0, k \delta_N]`.
    """
    n_pts = _validate_positive_int(n_points, "n_points", minimum=3)
    factor = (
        self._domain_factor
        if domain_factor is None
        else _validate_positive_finite(domain_factor, "domain_factor")
    )
    delta = self.diffusion_layer_thickness(D)
    x_max = factor * delta

    if not isinstance(kind, str):
        raise TypeError(f"kind must be a string, got {type(kind).__name__}.")
    kind_norm = kind.strip().lower()

    if kind_norm == "geometric":
        return GeometricExpandingMesh(0.0, x_max, n_points=n_pts, gamma=gamma)
    if kind_norm == "exponential":
        return ExponentialMesh(0.0, x_max, n_points=n_pts, beta=beta)
    if kind_norm == "uniform":
        return Uniform1DMesh(0.0, x_max, n_points=n_pts)

    raise ValueError(
        f"Unknown mesh kind {kind!r}. Must be one of "
        "('geometric', 'exponential', 'uniform')."
    )

convection_term

convection_term(diffusivity: float | Mapping[str, float], *, reactions: Any = None) -> RDEConvectionTerm

Create an RDEConvectionTerm for DiffusionProblem(reactions=...).

Source code in src/softpotato/techniques/rde.py
def convection_term(
    self,
    diffusivity: float | Mapping[str, float],
    *,
    reactions: Any = None,
) -> RDEConvectionTerm:
    """Create an :class:`RDEConvectionTerm` for ``DiffusionProblem(reactions=...)``."""
    return RDEConvectionTerm(
        omega=self._omega,
        kinematic_viscosity=self._kinematic_viscosity,
        diffusivity=diffusivity,
        base_reactions=reactions,
    )

levich_limiting_current

levich_limiting_current(*, n: float = 1, D: float = 1e-09, c_bulk: float = 1.0, area: float = 1.0) -> float

Compute the analytical Levich limiting current \(I_L\) at this rotation rate.

Delegates to levich.

Source code in src/softpotato/techniques/rde.py
def levich_limiting_current(
    self,
    *,
    n: float = 1,
    D: float = 1e-9,
    c_bulk: float = 1.0,
    area: float = 1.0,
) -> float:
    r"""Compute the analytical Levich limiting current :math:`I_L` at this rotation rate.

    Delegates to :func:`~softpotato.analytical.hydrodynamics.levich`.
    """
    return float(
        levich(
            omega=self._omega,
            n=n,
            D=D,
            c_bulk=c_bulk,
            area=area,
            nu=self._kinematic_viscosity,
        )
    )

with_rotation

with_rotation(*, omega: float | None = None, rpm: float | None = None) -> RotatingDiskElectrode

Return a copy of this RDE technique at a different rotation rate.

Source code in src/softpotato/techniques/rde.py
def with_rotation(
    self,
    *,
    omega: float | None = None,
    rpm: float | None = None,
) -> RotatingDiskElectrode:
    """Return a copy of this RDE technique at a different rotation rate."""
    return RotatingDiskElectrode(
        self._waveform,
        omega=omega,
        rpm=rpm,
        kinematic_viscosity=self._kinematic_viscosity,
        model=self._model,
        domain_factor=self._domain_factor,
    )

build_problem

build_problem(*, D: float | None = None, diffusivity: Mapping[str, float] | None = None, c_bulk: float = 1.0, initial_conditions: Mapping[str, Any] | None = None, boundary_conditions: Mapping[str, tuple[BoundaryCondition, BoundaryCondition]] | None = None, kinetics: HeterogeneousKinetics | NernstianEquilibrium | None = None, species_name: str = 'Ox', red_species_name: str = 'Red', c_red_bulk: float = 0.0, n_electrons: int | Mapping[str, int] = 1, area: float = 1.0, reactions: Any = None, n_points: int = 80, grid_kind: str = 'geometric', gamma: float = 1.06, beta: float = 3.0, domain_factor: float | None = None) -> DiffusionProblem

Build a configured DiffusionProblem for this RDE.

Automatically sizes the spatial mesh to the hydrodynamic diffusion layer, attaches bulk Dirichlet outer boundary conditions, and injects the axial convective velocity operator when model="convective_diffusion".

Source code in src/softpotato/techniques/rde.py
def build_problem(
    self,
    *,
    D: float | None = None,
    diffusivity: Mapping[str, float] | None = None,
    c_bulk: float = 1.0,
    initial_conditions: Mapping[str, Any] | None = None,
    boundary_conditions: Mapping[str, tuple[BoundaryCondition, BoundaryCondition]]
    | None = None,
    kinetics: HeterogeneousKinetics | NernstianEquilibrium | None = None,
    species_name: str = "Ox",
    red_species_name: str = "Red",
    c_red_bulk: float = 0.0,
    n_electrons: int | Mapping[str, int] = 1,
    area: float = 1.0,
    reactions: Any = None,
    n_points: int = 80,
    grid_kind: str = "geometric",
    gamma: float = 1.06,
    beta: float = 3.0,
    domain_factor: float | None = None,
) -> DiffusionProblem:
    """Build a configured :class:`~softpotato.solver.DiffusionProblem` for this RDE.

    Automatically sizes the spatial mesh to the hydrodynamic diffusion
    layer, attaches bulk Dirichlet outer boundary conditions, and injects
    the axial convective velocity operator when
    ``model="convective_diffusion"``.
    """
    if D is None and diffusivity is None:
        raise ValueError("Either 'D' or 'diffusivity' must be provided.")
    if D is not None and diffusivity is not None:
        raise ValueError("Specify either 'D' or 'diffusivity', not both.")

    area_val = _validate_positive_finite(area, "area")
    n_electrons_arg: int | dict[str, int] = (
        dict(n_electrons) if isinstance(n_electrons, Mapping) else n_electrons
    )

    if diffusivity is not None:
        diff_map = {
            sp: _validate_positive_finite(val, f"diffusivity[{sp!r}]")
            for sp, val in diffusivity.items()
        }
        if not diff_map:
            raise ValueError("'diffusivity' mapping must not be empty.")
        d_ref = max(diff_map.values())
    else:
        assert D is not None
        d_ref = _validate_positive_finite(D, "D")
        if kinetics is not None and boundary_conditions is None:
            diff_map = {species_name: d_ref, red_species_name: d_ref}
        else:
            diff_map = {species_name: d_ref}

    mesh = self.build_grid(
        D=d_ref,
        n_points=n_points,
        kind=grid_kind,
        gamma=gamma,
        beta=beta,
        domain_factor=domain_factor,
    )

    if boundary_conditions is None and isinstance(kinetics, HeterogeneousKinetics):
        from softpotato.reactions.mechanisms import ElectrochemicalStep, Mechanism
        from softpotato.reactions.species import Species

        d_ox = diff_map.get(species_name, d_ref)
        d_red = diff_map.get(red_species_name, d_ref)
        diff_map.setdefault(species_name, d_ox)
        diff_map.setdefault(red_species_name, d_red)

        ox_sp = Species(
            species_name,
            diffusivity=d_ox,
            bulk_concentration=c_bulk,
            n_electrons=int(kinetics.n),
        )
        red_sp = Species(
            red_species_name,
            diffusivity=d_red,
            bulk_concentration=c_red_bulk,
        )
        mech = Mechanism(
            species=[ox_sp, red_sp],
            electrochemical_steps=[ElectrochemicalStep(ox_sp, red_sp, kinetics)],
        )
        mech_problem = mech.create_problem(
            mesh,
            potential=self,
            geometry=PlanarGeometry(area=area_val),
            diffusivity=diff_map,
            initial_conditions=initial_conditions,
            n_electrons=n_electrons_arg,
            electrodes="left",
            bulk_bc="dirichlet",
        )
        bcs = mech_problem.boundary_conditions
        ics = mech_problem.initial_conditions
        interfacial_rxn = mech_problem.reactions
        if reactions is not None and interfacial_rxn is not None:
            # Compose user homogeneous reactions with interfacial kinetics
            user_rxn = reactions
            mech_rxn = interfacial_rxn

            def _composed_rxn(
                c_dict: dict[str, np.ndarray],
                x_arr: np.ndarray,
                t_val: float,
            ) -> dict[str, np.ndarray]:
                out_i = mech_rxn(c_dict, x_arr, t_val)
                out_u = user_rxn(c_dict, x_arr, t_val)
                return {sp: out_i[sp] + out_u[sp] for sp in out_i}

            base_rxn: Any = _composed_rxn
        elif reactions is not None:
            base_rxn = reactions
        else:
            base_rxn = interfacial_rxn

        effective_reactions = (
            self.convection_term(diff_map, reactions=base_rxn)
            if self._model == "convective_diffusion"
            else base_rxn
        )

        return DiffusionProblem(
            grid=mesh,
            diffusivity=diff_map,
            boundary_conditions=bcs,
            initial_conditions=ics,
            reactions=effective_reactions,
            species=mech.species,
            geometry=PlanarGeometry(area=area_val),
            n_electrons=n_electrons_arg,
            mechanism=mech,
        )

    if boundary_conditions is not None:
        bcs = dict(boundary_conditions)
    elif kinetics is not None:
        d_ox = diff_map.get(species_name, d_ref)
        d_red = diff_map.get(red_species_name, d_ref)
        bcs = create_electrochemical_bcs(
            kinetics=kinetics,
            potential=self,
            ox=species_name,
            red=red_species_name,
            D_ox=d_ox,
            D_red=d_red,
            c_ox_bulk=c_bulk,
            c_red_bulk=c_red_bulk,
            electrode_side="left",
            bulk_bc="dirichlet",
        )
        diff_map.setdefault(species_name, d_ox)
        diff_map.setdefault(red_species_name, d_red)
    else:
        # Default mass-transport-limited (zero surface concentration) Dirichlet BC
        bcs = {sp: (DirichletBC(0.0), DirichletBC(c_bulk)) for sp in diff_map}

    if initial_conditions is not None:
        ics = dict(initial_conditions)
    elif kinetics is not None and boundary_conditions is None:
        ics = {species_name: c_bulk, red_species_name: c_red_bulk}
    else:
        ics = {sp: c_bulk for sp in diff_map}

    effective_reactions = (
        self.convection_term(diff_map, reactions=reactions)
        if self._model == "convective_diffusion"
        else reactions
    )

    return DiffusionProblem(
        grid=mesh,
        diffusivity=diff_map,
        boundary_conditions=bcs,
        initial_conditions=ics,
        reactions=effective_reactions,
        geometry=PlanarGeometry(area=area_val),
        n_electrons=n_electrons_arg,
    )

TechniqueResult dataclass

Structured container for the output of simulate.

Wraps the underlying SolverResult with electrochemical observables (time, potential, current, charge), dict-like species concentration profile access (result["Ox"]), and technique-specific convenience views (CV cycles, SWV E_step / i_forward / i_reverse / i_net, DPV E_base / i_pre / i_pulse / i_diff, and CP transition_time).

Attributes:

Name Type Description
technique BaseTechnique

The executed electrochemical technique specification.

solver_result SolverResult

Underlying full PDE solution containing species concentration profiles, interfacial fluxes, per-species currents, spatial grid, and solver status.

time ndarray

1D array of evaluation timestamps \(t\) in seconds.

potential ndarray

Electrode potential \(E(t)\) in Volts (applied waveform for potentiostatic techniques; recovered surface potential for galvanostatic chronopotentiometry when kinetics/redox metadata are available).

current ndarray

Net Faradaic current \(I(t)\) in Amperes under IUPAC polarity conventions (anodic positive, cathodic negative).

charge ndarray

Cumulative charge \(Q(t) = \int_0^t I(\tau)\,d\tau\) in Coulombs computed via trapezoidal integration. Automatically computed if omitted.

metadata dict[str, Any]

Auxiliary execution metadata (solver name, geometry, segment count, technique-specific quantities such as transition_time).

Source code in src/softpotato/techniques/result.py
@dataclass
class TechniqueResult:
    r"""Structured container for the output of :func:`~softpotato.techniques.simulate`.

    Wraps the underlying :class:`~softpotato.solver.SolverResult` with
    electrochemical observables (``time``, ``potential``, ``current``, ``charge``),
    dict-like species concentration profile access (``result["Ox"]``), and
    technique-specific convenience views (CV ``cycles``, SWV ``E_step`` /
    ``i_forward`` / ``i_reverse`` / ``i_net``, DPV ``E_base`` / ``i_pre`` /
    ``i_pulse`` / ``i_diff``, and CP ``transition_time``).

    Attributes
    ----------
    technique : BaseTechnique
        The executed electrochemical technique specification.
    solver_result : SolverResult
        Underlying full PDE solution containing species concentration profiles,
        interfacial fluxes, per-species currents, spatial grid, and solver status.
    time : np.ndarray
        1D array of evaluation timestamps :math:`t` in seconds.
    potential : np.ndarray
        Electrode potential :math:`E(t)` in Volts (applied waveform for
        potentiostatic techniques; recovered surface potential for galvanostatic
        chronopotentiometry when kinetics/redox metadata are available).
    current : np.ndarray
        Net Faradaic current :math:`I(t)` in Amperes under IUPAC polarity
        conventions (anodic positive, cathodic negative).
    charge : np.ndarray
        Cumulative charge :math:`Q(t) = \int_0^t I(\tau)\,d\tau` in Coulombs
        computed via trapezoidal integration. Automatically computed if omitted.
    metadata : dict[str, Any]
        Auxiliary execution metadata (solver name, geometry, segment count,
        technique-specific quantities such as ``transition_time``).
    """

    technique: BaseTechnique
    solver_result: SolverResult
    time: np.ndarray
    potential: np.ndarray
    current: np.ndarray
    charge: np.ndarray | None = None
    metadata: dict[str, Any] = field(default_factory=dict)

    _dpv_cache: tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray] | None = field(
        default=None, init=False, repr=False, compare=False
    )
    _swv_cache: tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray] | None = field(
        default=None, init=False, repr=False, compare=False
    )
    _cycles_cache: tuple[TechniqueResult, ...] | None = field(
        default=None, init=False, repr=False, compare=False
    )

    def __post_init__(self) -> None:
        self.time = np.asarray(self.time, dtype=float)
        self.potential = np.asarray(self.potential, dtype=float)
        self.current = np.asarray(self.current, dtype=float)
        if self.charge is None:
            self.charge = _compute_cumulative_charge(self.time, self.current)
        else:
            self.charge = np.asarray(self.charge, dtype=float)

    # ------------------------------------------------------------------
    # Delegation & dict-like species concentration access
    # ------------------------------------------------------------------

    @property
    def species(self) -> list[str]:
        """List of chemical species present in the solution."""
        return self.solver_result.species

    def __getitem__(self, species_name: str) -> np.ndarray:
        """Shorthand to access 2D concentration profile ``(N_t, N_x)`` for a species."""
        return self.solver_result[species_name]

    def __contains__(self, species_name: object) -> bool:
        return species_name in self.solver_result.concentrations

    @property
    def concentrations(self) -> dict[str, np.ndarray]:
        """Mapping from species name to 2D concentration profile ``(N_t, N_x)``."""
        return self.solver_result.concentrations

    @property
    def fluxes(self) -> dict[str, np.ndarray]:
        """Mapping from species name to left-boundary interfacial flux ``(N_t,)``."""
        return self.solver_result.fluxes

    @property
    def currents(self) -> dict[str, np.ndarray]:
        """Mapping from species name to per-species Faradaic current ``(N_t,)``."""
        return self.solver_result.currents

    @property
    def grid(self) -> np.ndarray:
        """1D spatial coordinate grid ``x`` from the underlying solver result."""
        return self.solver_result.x

    @property
    def x(self) -> np.ndarray:
        """Alias for :attr:`grid`."""
        return self.solver_result.x

    @property
    def t(self) -> np.ndarray:
        """Alias for :attr:`time`."""
        return self.time

    @property
    def E(self) -> np.ndarray:
        """Alias for :attr:`potential`."""
        return self.potential

    @property
    def i(self) -> np.ndarray:
        """Alias for :attr:`current`."""
        return self.current

    @property
    def Q(self) -> np.ndarray:
        """Alias for :attr:`charge`."""
        assert self.charge is not None
        return self.charge

    @property
    def success(self) -> bool:
        """Whether the underlying numerical integration succeeded."""
        return self.solver_result.success

    @property
    def message(self) -> str:
        """Status message from the underlying numerical solver."""
        return self.solver_result.message

    # ------------------------------------------------------------------
    # Cyclic Voltammetry convenience views
    # ------------------------------------------------------------------

    @property
    def cycles(self) -> tuple[TechniqueResult, ...]:
        """Per-cycle :class:`TechniqueResult` slices for :class:`CyclicVoltammetry`.

        Returns
        -------
        tuple[TechniqueResult, ...]
            One sliced :class:`TechniqueResult` per voltammetric cycle in
            :attr:`CyclicVoltammetry.cycle_time_ranges`.

        Raises
        ------
        TypeError
            If :attr:`technique` is not a :class:`CyclicVoltammetry` instance.
        """
        if not isinstance(self.technique, CyclicVoltammetry):
            raise TypeError(
                "cycles is only available for CyclicVoltammetry results, "
                f"got {type(self.technique).__name__}."
            )
        if self._cycles_cache is None:
            tol = 1e-12 * max(1.0, self.technique.duration)
            cycle_views: list[TechniqueResult] = []
            for idx, (t_start, t_end) in enumerate(self.technique.cycle_time_ranges):
                mask = (self.time >= t_start - tol) & (self.time <= t_end + tol)
                t_cyc = self.time[mask].copy()
                e_cyc = self.potential[mask].copy()
                i_cyc = self.current[mask].copy()
                sr_cyc = _slice_solver_result(self.solver_result, mask)
                cycle_views.append(
                    TechniqueResult(
                        technique=self.technique,
                        solver_result=sr_cyc,
                        time=t_cyc,
                        potential=e_cyc,
                        current=i_cyc,
                        metadata={
                            **self.metadata,
                            "cycle_index": idx,
                            "cycle_time_range": (t_start, t_end),
                        },
                    )
                )
            self._cycles_cache = tuple(cycle_views)
        return self._cycles_cache

    # ------------------------------------------------------------------
    # Square-Wave Voltammetry convenience views
    # ------------------------------------------------------------------

    def _get_swv_sampled(
        self,
    ) -> tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]:
        if not isinstance(self.technique, SquareWaveVoltammetry):
            raise TypeError(
                "SWV sampled views are only available for SquareWaveVoltammetry results, "
                f"got {type(self.technique).__name__}."
            )
        if self._swv_cache is None:
            self._swv_cache = self.technique.sample_currents(self.time, self.current)
        return self._swv_cache

    @property
    def E_step(self) -> np.ndarray:
        """Staircase step potentials for :class:`SquareWaveVoltammetry`."""
        return self._get_swv_sampled()[0]

    @property
    def i_forward(self) -> np.ndarray:
        """Forward half-cycle sampled currents for :class:`SquareWaveVoltammetry`."""
        return self._get_swv_sampled()[1]

    @property
    def i_reverse(self) -> np.ndarray:
        """Reverse half-cycle sampled currents for :class:`SquareWaveVoltammetry`."""
        return self._get_swv_sampled()[2]

    @property
    def i_net(self) -> np.ndarray:
        """Net square-wave current ``i_forward - i_reverse`` for :class:`SquareWaveVoltammetry`."""
        return self._get_swv_sampled()[3]

    # ------------------------------------------------------------------
    # Differential Pulse Voltammetry convenience views
    # ------------------------------------------------------------------

    def _get_dpv_sampled(
        self,
    ) -> tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]:
        if not isinstance(self.technique, DifferentialPulseVoltammetry):
            raise TypeError(
                "DPV sampled views are only available for DifferentialPulseVoltammetry results, "
                f"got {type(self.technique).__name__}."
            )
        if self._dpv_cache is None:
            self._dpv_cache = self.technique.sample_currents(self.time, self.current)
        return self._dpv_cache

    @property
    def E_base(self) -> np.ndarray:
        """Staircase base potentials for :class:`DifferentialPulseVoltammetry`."""
        return self._get_dpv_sampled()[0]

    @property
    def i_pre(self) -> np.ndarray:
        """Pre-pulse sampled currents for :class:`DifferentialPulseVoltammetry`."""
        return self._get_dpv_sampled()[1]

    @property
    def i_pulse(self) -> np.ndarray:
        """End-of-pulse sampled currents for :class:`DifferentialPulseVoltammetry`."""
        return self._get_dpv_sampled()[2]

    @property
    def i_diff(self) -> np.ndarray:
        """Differential current ``i_pulse - i_pre`` for :class:`DifferentialPulseVoltammetry`."""
        return self._get_dpv_sampled()[3]

    # ------------------------------------------------------------------
    # Chronopotentiometry convenience views
    # ------------------------------------------------------------------

    @property
    def transition_time(self) -> float | None:
        r"""Detected chronopotentiometric transition time :math:`\tau` in seconds, or ``None``.

        Raises
        ------
        TypeError
            If :attr:`technique` is not a :class:`Chronopotentiometry` instance.
        """
        if not isinstance(self.technique, Chronopotentiometry):
            raise TypeError(
                "transition_time is only available for Chronopotentiometry results, "
                f"got {type(self.technique).__name__}."
            )
        if "transition_time" in self.metadata:
            val = self.metadata["transition_time"]
            return None if val is None else float(val)
        return None

    # ------------------------------------------------------------------
    # Sampled-Current Voltammetry convenience views
    # ------------------------------------------------------------------

    def sample_currents(
        self,
        sample_times: float
        | list[float]
        | tuple[float, ...]
        | np.ndarray
        | None = None,
    ) -> tuple[np.ndarray, np.ndarray]:
        """Sample voltammogram(s) at ``sample_times`` for :class:`SampledCurrentVoltammetry`."""
        if not isinstance(self.technique, SampledCurrentVoltammetry):
            raise TypeError(
                "sample_currents() is only available for SampledCurrentVoltammetry results, "
                f"got {type(self.technique).__name__}."
            )
        return self.technique.sample_currents(
            self.time, self.current, sample_times=sample_times
        )

    # ------------------------------------------------------------------
    # Plotting facade
    # ------------------------------------------------------------------

    @property
    def plot_specs(self) -> dict[str, PlotSpec]:
        """Ordered mapping of canonical plot kind to :class:`PlotSpec`."""
        return self.technique.plot_specs

    @property
    def available_plots(self) -> tuple[str, ...]:
        """Ordered tuple of canonical plot kinds supported for this result."""
        return self.technique.available_plots

    @property
    def default_plot(self) -> str:
        """Canonical plot kind used by default when calling :meth:`plot`."""
        return self.technique.default_plot

    def plot(
        self,
        kind: str | None = None,
        *,
        ax: Axes | None = None,
        **kwargs: Any,
    ) -> tuple[Figure, Axes]:
        """Plot this simulation result using the declarative plotting suite.

        Delegates to :func:`~softpotato.techniques.plotting.plot_result`.

        Parameters
        ----------
        kind : str, optional
            Concise plot key (e.g., ``'voltammogram'``, ``'i_vs_t'``,
            ``'E_vs_t'``, ``'c_vs_x'``) or verbose alias (e.g.,
            ``'current_vs_time'``, ``'potential_vs_time'``,
            ``'concentration_profile'``). Defaults to :attr:`default_plot`.
        ax : matplotlib.axes.Axes, optional
            Existing Axes to draw onto. A new figure and axes are created
            when omitted.
        **kwargs : Any
            Additional keyword arguments forwarded to the plot renderer.

        Returns
        -------
        tuple[matplotlib.figure.Figure, matplotlib.axes.Axes]
            Figure and Axes containing the rendered plot.
        """
        from .plotting import plot_result

        return plot_result(self, kind=kind, ax=ax, **kwargs)

    def plot_summary(
        self,
        *,
        t: float | Sequence[float] | None = None,
        species: str | Sequence[str] | None = None,
        figsize: tuple[float, float] | None = None,
        **kwargs: Any,
    ) -> tuple[Figure, np.ndarray]:
        """Render a multi-panel overview figure for this simulation result.

        Delegates to :func:`~softpotato.techniques.plotting.plot_summary`.
        """
        from .plotting import plot_summary as _plot_summary

        return _plot_summary(
            self,
            t=t,
            species=species,
            figsize=figsize,
            **kwargs,
        )

species property

species: list[str]

List of chemical species present in the solution.

concentrations property

concentrations: dict[str, ndarray]

Mapping from species name to 2D concentration profile (N_t, N_x).

fluxes property

fluxes: dict[str, ndarray]

Mapping from species name to left-boundary interfacial flux (N_t,).

currents property

currents: dict[str, ndarray]

Mapping from species name to per-species Faradaic current (N_t,).

grid property

grid: ndarray

1D spatial coordinate grid x from the underlying solver result.

x property

x: ndarray

Alias for grid.

t property

t: ndarray

Alias for time.

E property

E: ndarray

Alias for potential.

i property

i: ndarray

Alias for current.

Q property

Q: ndarray

Alias for charge.

success property

success: bool

Whether the underlying numerical integration succeeded.

message property

message: str

Status message from the underlying numerical solver.

cycles property

cycles: tuple[TechniqueResult, ...]

Per-cycle TechniqueResult slices for CyclicVoltammetry.

Returns:

Type Description
tuple[TechniqueResult, ...]

One sliced TechniqueResult per voltammetric cycle in CyclicVoltammetry.cycle_time_ranges.

Raises:

Type Description
TypeError

If technique is not a CyclicVoltammetry instance.

E_step property

E_step: ndarray

Staircase step potentials for SquareWaveVoltammetry.

i_forward property

i_forward: ndarray

Forward half-cycle sampled currents for SquareWaveVoltammetry.

i_reverse property

i_reverse: ndarray

Reverse half-cycle sampled currents for SquareWaveVoltammetry.

i_net property

i_net: ndarray

Net square-wave current i_forward - i_reverse for SquareWaveVoltammetry.

E_base property

E_base: ndarray

Staircase base potentials for DifferentialPulseVoltammetry.

i_pre property

i_pre: ndarray

Pre-pulse sampled currents for DifferentialPulseVoltammetry.

i_pulse property

i_pulse: ndarray

End-of-pulse sampled currents for DifferentialPulseVoltammetry.

i_diff property

i_diff: ndarray

Differential current i_pulse - i_pre for DifferentialPulseVoltammetry.

transition_time property

transition_time: float | None

Detected chronopotentiometric transition time \(\tau\) in seconds, or None.

Raises:

Type Description
TypeError

If technique is not a Chronopotentiometry instance.

plot_specs property

plot_specs: dict[str, PlotSpec]

Ordered mapping of canonical plot kind to PlotSpec.

available_plots property

available_plots: tuple[str, ...]

Ordered tuple of canonical plot kinds supported for this result.

default_plot property

default_plot: str

Canonical plot kind used by default when calling plot.

__getitem__

__getitem__(species_name: str) -> np.ndarray

Shorthand to access 2D concentration profile (N_t, N_x) for a species.

Source code in src/softpotato/techniques/result.py
def __getitem__(self, species_name: str) -> np.ndarray:
    """Shorthand to access 2D concentration profile ``(N_t, N_x)`` for a species."""
    return self.solver_result[species_name]

sample_currents

sample_currents(sample_times: float | list[float] | tuple[float, ...] | ndarray | None = None) -> tuple[np.ndarray, np.ndarray]

Sample voltammogram(s) at sample_times for SampledCurrentVoltammetry.

Source code in src/softpotato/techniques/result.py
def sample_currents(
    self,
    sample_times: float
    | list[float]
    | tuple[float, ...]
    | np.ndarray
    | None = None,
) -> tuple[np.ndarray, np.ndarray]:
    """Sample voltammogram(s) at ``sample_times`` for :class:`SampledCurrentVoltammetry`."""
    if not isinstance(self.technique, SampledCurrentVoltammetry):
        raise TypeError(
            "sample_currents() is only available for SampledCurrentVoltammetry results, "
            f"got {type(self.technique).__name__}."
        )
    return self.technique.sample_currents(
        self.time, self.current, sample_times=sample_times
    )

plot

plot(kind: str | None = None, *, ax: Axes | None = None, **kwargs: Any) -> tuple[Figure, Axes]

Plot this simulation result using the declarative plotting suite.

Delegates to plot_result.

Parameters:

Name Type Description Default
kind str

Concise plot key (e.g., 'voltammogram', 'i_vs_t', 'E_vs_t', 'c_vs_x') or verbose alias (e.g., 'current_vs_time', 'potential_vs_time', 'concentration_profile'). Defaults to default_plot.

None
ax Axes

Existing Axes to draw onto. A new figure and axes are created when omitted.

None
**kwargs Any

Additional keyword arguments forwarded to the plot renderer.

{}

Returns:

Type Description
tuple[Figure, Axes]

Figure and Axes containing the rendered plot.

Source code in src/softpotato/techniques/result.py
def plot(
    self,
    kind: str | None = None,
    *,
    ax: Axes | None = None,
    **kwargs: Any,
) -> tuple[Figure, Axes]:
    """Plot this simulation result using the declarative plotting suite.

    Delegates to :func:`~softpotato.techniques.plotting.plot_result`.

    Parameters
    ----------
    kind : str, optional
        Concise plot key (e.g., ``'voltammogram'``, ``'i_vs_t'``,
        ``'E_vs_t'``, ``'c_vs_x'``) or verbose alias (e.g.,
        ``'current_vs_time'``, ``'potential_vs_time'``,
        ``'concentration_profile'``). Defaults to :attr:`default_plot`.
    ax : matplotlib.axes.Axes, optional
        Existing Axes to draw onto. A new figure and axes are created
        when omitted.
    **kwargs : Any
        Additional keyword arguments forwarded to the plot renderer.

    Returns
    -------
    tuple[matplotlib.figure.Figure, matplotlib.axes.Axes]
        Figure and Axes containing the rendered plot.
    """
    from .plotting import plot_result

    return plot_result(self, kind=kind, ax=ax, **kwargs)

plot_summary

plot_summary(*, t: float | Sequence[float] | None = None, species: str | Sequence[str] | None = None, figsize: tuple[float, float] | None = None, **kwargs: Any) -> tuple[Figure, np.ndarray]

Render a multi-panel overview figure for this simulation result.

Delegates to plot_summary.

Source code in src/softpotato/techniques/result.py
def plot_summary(
    self,
    *,
    t: float | Sequence[float] | None = None,
    species: str | Sequence[str] | None = None,
    figsize: tuple[float, float] | None = None,
    **kwargs: Any,
) -> tuple[Figure, np.ndarray]:
    """Render a multi-panel overview figure for this simulation result.

    Delegates to :func:`~softpotato.techniques.plotting.plot_summary`.
    """
    from .plotting import plot_summary as _plot_summary

    return _plot_summary(
        self,
        t=t,
        species=species,
        figsize=figsize,
        **kwargs,
    )

CyclicVoltammetry

Bases: BaseTechnique

Multi-cycle triangular potential waveform generator (Cyclic Voltammetry).

Each cycle sweeps linearly along the vertex sequence:

  • \(E_{\text{start}} \to E_{\text{vertex1}} \to E_{\text{vertex2}} \to E_{\text{start}}\) for intermediate cycles (with the final leg omitted when \(E_{\text{vertex2}} = E_{\text{start}}\)), and
  • \(E_{\text{start}} \to E_{\text{vertex1}} \to E_{\text{vertex2}} \to E_{\text{end}}\) for the final cycle (where E_end defaults to E_start, and the final leg is omitted when \(E_{\text{end}} = E_{\text{vertex2}}\)).

Exact switching vertex timestamps (where \(dE/dt\) reverses sign) are recorded in event_times, and per-cycle time intervals are exposed via cycle_time_ranges.

Parameters:

Name Type Description Default
E_start float

Initial potential \(E_{\text{start}}\) in Volts.

required
E_vertex1 float

First switching vertex potential \(E_{\lambda 1}\) in Volts (must differ from E_start).

required
E_vertex2 float

Second switching vertex potential \(E_{\lambda 2}\) in Volts (must differ from E_vertex1). Set equal to E_start for a standard two-vertex triangular wave.

required
scan_rate float

Scan rate magnitude \(v > 0\) in V/s.

required
E_end float

Final potential at the end of the last cycle in Volts. Defaults to E_start.

None
n_cycles int

Number of complete voltammetric cycles (\(\ge 1\)).

1
dE float

Default potential step resolution \(\Delta E > 0\) in Volts for time_grid. Mutually exclusive with n_points.

None
n_points int

Default number of points (\(\ge 2\)) for time_grid. Mutually exclusive with dE.

None

Examples:

>>> from softpotato.techniques import CyclicVoltammetry
>>> cv = CyclicVoltammetry(
...     E_start=0.5, E_vertex1=-0.5, E_vertex2=0.5, scan_rate=0.5, n_cycles=2
... )
>>> cv.duration
8.0
>>> cv.event_times
(2.0, 4.0, 6.0)
>>> cv.cycle_time_ranges
((0.0, 4.0), (4.0, 8.0))
Source code in src/softpotato/techniques/voltammetry.py
class CyclicVoltammetry(BaseTechnique):
    r"""Multi-cycle triangular potential waveform generator (Cyclic Voltammetry).

    Each cycle sweeps linearly along the vertex sequence:

    - :math:`E_{\text{start}} \to E_{\text{vertex1}} \to E_{\text{vertex2}} \to E_{\text{start}}`
      for intermediate cycles (with the final leg omitted when
      :math:`E_{\text{vertex2}} = E_{\text{start}}`), and
    - :math:`E_{\text{start}} \to E_{\text{vertex1}} \to E_{\text{vertex2}} \to E_{\text{end}}`
      for the final cycle (where ``E_end`` defaults to ``E_start``, and the final
      leg is omitted when :math:`E_{\text{end}} = E_{\text{vertex2}}`).

    Exact switching vertex timestamps (where :math:`dE/dt` reverses sign) are
    recorded in :attr:`event_times`, and per-cycle time intervals are exposed via
    :attr:`cycle_time_ranges`.

    Parameters
    ----------
    E_start : float
        Initial potential :math:`E_{\text{start}}` in Volts.
    E_vertex1 : float
        First switching vertex potential :math:`E_{\lambda 1}` in Volts
        (must differ from ``E_start``).
    E_vertex2 : float
        Second switching vertex potential :math:`E_{\lambda 2}` in Volts
        (must differ from ``E_vertex1``). Set equal to ``E_start`` for a
        standard two-vertex triangular wave.
    scan_rate : float
        Scan rate magnitude :math:`v > 0` in V/s.
    E_end : float, optional
        Final potential at the end of the last cycle in Volts. Defaults to
        ``E_start``.
    n_cycles : int, default 1
        Number of complete voltammetric cycles (:math:`\ge 1`).
    dE : float, optional
        Default potential step resolution :math:`\Delta E > 0` in Volts for
        :meth:`time_grid`. Mutually exclusive with ``n_points``.
    n_points : int, optional
        Default number of points (:math:`\ge 2`) for :meth:`time_grid`.
        Mutually exclusive with ``dE``.

    Examples
    --------
    >>> from softpotato.techniques import CyclicVoltammetry
    >>> cv = CyclicVoltammetry(
    ...     E_start=0.5, E_vertex1=-0.5, E_vertex2=0.5, scan_rate=0.5, n_cycles=2
    ... )
    >>> cv.duration
    8.0
    >>> cv.event_times
    (2.0, 4.0, 6.0)
    >>> cv.cycle_time_ranges
    ((0.0, 4.0), (4.0, 8.0))
    """

    def __init__(
        self,
        E_start: float,
        E_vertex1: float,
        E_vertex2: float,
        scan_rate: float,
        *,
        E_end: float | None = None,
        n_cycles: int = 1,
        dE: float | None = None,
        n_points: int | None = None,
    ) -> None:
        self._mode = "potentiostatic"
        self._E_start = _validate_finite_real(E_start, "E_start")
        self._E_vertex1 = _validate_finite_real(E_vertex1, "E_vertex1")
        self._E_vertex2 = _validate_finite_real(E_vertex2, "E_vertex2")
        self._E_end = (
            self._E_start if E_end is None else _validate_finite_real(E_end, "E_end")
        )

        if self._E_vertex1 == self._E_start:
            raise ValueError("E_vertex1 must differ from E_start.")
        if self._E_vertex2 == self._E_vertex1:
            raise ValueError("E_vertex2 must differ from E_vertex1.")

        self._scan_rate = _validate_positive_finite(scan_rate, "scan_rate")
        self._n_cycles = _validate_positive_int(n_cycles, "n_cycles", minimum=1)

        if dE is not None and n_points is not None:
            raise ValueError("Specify at most one of 'dE' or 'n_points'.")
        self._dE = _validate_positive_finite(dE, "dE") if dE is not None else None
        self._n_points = (
            _validate_positive_int(n_points, "n_points", minimum=2)
            if n_points is not None
            else None
        )

        # Build piecewise-linear legs across all cycles
        leg_starts: list[float] = []
        leg_e0: list[float] = []
        leg_e1: list[float] = []
        leg_durations: list[float] = []
        leg_slopes: list[float] = []
        cycle_ranges: list[tuple[float, float]] = []

        cursor = 0.0
        for cycle_idx in range(self._n_cycles):
            cycle_start = cursor
            cycle_end_target = (
                self._E_end if cycle_idx == self._n_cycles - 1 else self._E_start
            )
            waypoints = [self._E_start, self._E_vertex1, self._E_vertex2]
            if cycle_end_target != self._E_vertex2:
                waypoints.append(cycle_end_target)

            for e_from, e_to in itertools.pairwise(waypoints):
                dur = abs(e_to - e_from) / self._scan_rate
                slope = self._scan_rate if e_to > e_from else -self._scan_rate
                leg_starts.append(cursor)
                leg_e0.append(e_from)
                leg_e1.append(e_to)
                leg_durations.append(dur)
                leg_slopes.append(slope)
                cursor += dur

            cycle_ranges.append((cycle_start, cursor))

        self._leg_starts = np.asarray(leg_starts, dtype=float)
        self._leg_e0 = np.asarray(leg_e0, dtype=float)
        self._leg_e1 = np.asarray(leg_e1, dtype=float)
        self._leg_durations = np.asarray(leg_durations, dtype=float)
        self._leg_slopes = np.asarray(leg_slopes, dtype=float)
        self._duration = float(cursor)
        self._cycle_time_ranges: tuple[tuple[float, float], ...] = tuple(cycle_ranges)

        # Switching vertices are interior transitions where dE/dt reverses sign
        switching_times: list[float] = []
        for idx in range(1, len(leg_starts)):
            if leg_slopes[idx - 1] * leg_slopes[idx] < 0.0:
                switching_times.append(leg_starts[idx])
        self._event_times = _deduplicate_interior_events(
            switching_times, self._duration
        )

    @property
    def E_start(self) -> float:
        """Initial potential in Volts."""
        return self._E_start

    @property
    def E_vertex1(self) -> float:
        """First switching vertex potential in Volts."""
        return self._E_vertex1

    @property
    def E_vertex2(self) -> float:
        """Second switching vertex potential in Volts."""
        return self._E_vertex2

    @property
    def E_end(self) -> float:
        """Final potential at the end of the last cycle in Volts."""
        return self._E_end

    @property
    def scan_rate(self) -> float:
        """Scan rate magnitude :math:`v` in V/s."""
        return self._scan_rate

    @property
    def n_cycles(self) -> int:
        """Number of voltammetric cycles."""
        return self._n_cycles

    @property
    def dE(self) -> float | None:
        """Default potential step resolution in Volts, or ``None``."""
        return self._dE

    @property
    def n_points(self) -> int | None:
        """Default number of time grid points, or ``None``."""
        return self._n_points

    @property
    def duration(self) -> float:
        """Total multi-cycle experiment duration in seconds."""
        return self._duration

    @property
    def event_times(self) -> tuple[float, ...]:
        """Sorted switching vertex timestamps where scan direction reverses."""
        return self._event_times

    @property
    def cycle_time_ranges(self) -> tuple[tuple[float, float], ...]:
        """Per-cycle ``(t_start, t_end)`` intervals for slicing multi-cycle results."""
        return self._cycle_time_ranges

    def _extra_grid_times(self) -> tuple[float, ...]:
        cycle_bounds = tuple(
            t for start, end in self._cycle_time_ranges for t in (start, end)
        )
        return self._event_times + cycle_bounds

    @overload
    def excitation(self, t: float) -> float: ...

    @overload
    def excitation(self, t: np.ndarray) -> np.ndarray: ...

    @overload
    def excitation(self, t: float | ArrayLike) -> float | np.ndarray: ...

    def excitation(self, t: float | ArrayLike) -> float | np.ndarray:
        normalized, is_scalar = _normalize_time_input(t)
        n_legs = len(self._leg_starts)

        if is_scalar:
            assert isinstance(normalized, float)
            if normalized <= 0.0:
                return float(self._leg_e0[0])
            if normalized >= self._duration:
                return float(self._leg_e1[-1])
            idx = int(np.searchsorted(self._leg_starts, normalized, side="right")) - 1
            idx = min(max(idx, 0), n_legs - 1)
            dt_local = normalized - float(self._leg_starts[idx])
            if dt_local <= 0.0:
                return float(self._leg_e0[idx])
            if dt_local >= float(self._leg_durations[idx]):
                return float(self._leg_e1[idx])
            return float(self._leg_e0[idx] + self._leg_slopes[idx] * dt_local)

        assert isinstance(normalized, np.ndarray)
        orig_shape = normalized.shape
        flat = normalized.ravel()
        if flat.size == 0:
            return np.empty(orig_shape, dtype=float)

        clamped = np.clip(flat, 0.0, self._duration)
        indices = np.searchsorted(self._leg_starts, clamped, side="right") - 1
        indices = np.clip(indices, 0, n_legs - 1)
        at_end = clamped >= self._duration
        indices = np.where(at_end, n_legs - 1, indices)

        dt_local = clamped - self._leg_starts[indices]
        e0 = self._leg_e0[indices]
        e1 = self._leg_e1[indices]
        durs = self._leg_durations[indices]
        slopes = self._leg_slopes[indices]

        values = e0 + slopes * dt_local
        values = np.where(dt_local <= 0.0, e0, values)
        values = np.where((dt_local >= durs) | at_end, e1, values)
        return values.reshape(orig_shape)

    def time_grid(
        self,
        n_points: int | None = None,
        dt: float | None = None,
        dE: float | None = None,
    ) -> np.ndarray:
        """Generate evaluation timestamps including all switching vertices and cycle bounds.

        Parameters
        ----------
        n_points : int, optional
            Number of uniformly spaced base timestamps (``>= 2``).
        dt : float, optional
            Uniform time step in seconds (``> 0``).
        dE : float, optional
            Uniform potential step in Volts (``> 0``), converted to
            ``dt = dE / scan_rate``.

        Returns
        -------
        np.ndarray
            Strictly increasing 1D array of timestamps in ``[0, duration]``.
        """
        n_specified = sum(x is not None for x in (n_points, dt, dE))
        if n_specified > 1:
            raise ValueError("Specify at most one of 'n_points', 'dt', or 'dE'.")

        if dE is not None:
            dE_val = _validate_positive_finite(dE, "dE")
            return super().time_grid(dt=dE_val / self._scan_rate)
        if n_points is not None or dt is not None:
            return super().time_grid(n_points=n_points, dt=dt)

        if self._n_points is not None:
            return super().time_grid(n_points=self._n_points)
        if self._dE is not None:
            return super().time_grid(dt=self._dE / self._scan_rate)
        return super().time_grid()

    def _technique_plots(self) -> tuple[PlotSpec, ...]:
        return (
            PlotSpec(
                kind="voltammogram",
                title="Cyclic Voltammogram",
                x_label="$E$ / V",
                y_label="$I$ / A",
                description="Faradaic current vs. applied potential across voltammetric cycle(s).",
            ),
        )

    def __repr__(self) -> str:
        return (
            f"CyclicVoltammetry(E_start={self._E_start!r}, "
            f"E_vertex1={self._E_vertex1!r}, E_vertex2={self._E_vertex2!r}, "
            f"E_end={self._E_end!r}, scan_rate={self._scan_rate!r}, "
            f"n_cycles={self._n_cycles!r})"
        )

E_start property

E_start: float

Initial potential in Volts.

E_vertex1 property

E_vertex1: float

First switching vertex potential in Volts.

E_vertex2 property

E_vertex2: float

Second switching vertex potential in Volts.

E_end property

E_end: float

Final potential at the end of the last cycle in Volts.

scan_rate property

scan_rate: float

Scan rate magnitude \(v\) in V/s.

n_cycles property

n_cycles: int

Number of voltammetric cycles.

dE property

dE: float | None

Default potential step resolution in Volts, or None.

n_points property

n_points: int | None

Default number of time grid points, or None.

duration property

duration: float

Total multi-cycle experiment duration in seconds.

event_times property

event_times: tuple[float, ...]

Sorted switching vertex timestamps where scan direction reverses.

cycle_time_ranges property

cycle_time_ranges: tuple[tuple[float, float], ...]

Per-cycle (t_start, t_end) intervals for slicing multi-cycle results.

time_grid

time_grid(n_points: int | None = None, dt: float | None = None, dE: float | None = None) -> np.ndarray

Generate evaluation timestamps including all switching vertices and cycle bounds.

Parameters:

Name Type Description Default
n_points int

Number of uniformly spaced base timestamps (>= 2).

None
dt float

Uniform time step in seconds (> 0).

None
dE float

Uniform potential step in Volts (> 0), converted to dt = dE / scan_rate.

None

Returns:

Type Description
ndarray

Strictly increasing 1D array of timestamps in [0, duration].

Source code in src/softpotato/techniques/voltammetry.py
def time_grid(
    self,
    n_points: int | None = None,
    dt: float | None = None,
    dE: float | None = None,
) -> np.ndarray:
    """Generate evaluation timestamps including all switching vertices and cycle bounds.

    Parameters
    ----------
    n_points : int, optional
        Number of uniformly spaced base timestamps (``>= 2``).
    dt : float, optional
        Uniform time step in seconds (``> 0``).
    dE : float, optional
        Uniform potential step in Volts (``> 0``), converted to
        ``dt = dE / scan_rate``.

    Returns
    -------
    np.ndarray
        Strictly increasing 1D array of timestamps in ``[0, duration]``.
    """
    n_specified = sum(x is not None for x in (n_points, dt, dE))
    if n_specified > 1:
        raise ValueError("Specify at most one of 'n_points', 'dt', or 'dE'.")

    if dE is not None:
        dE_val = _validate_positive_finite(dE, "dE")
        return super().time_grid(dt=dE_val / self._scan_rate)
    if n_points is not None or dt is not None:
        return super().time_grid(n_points=n_points, dt=dt)

    if self._n_points is not None:
        return super().time_grid(n_points=self._n_points)
    if self._dE is not None:
        return super().time_grid(dt=self._dE / self._scan_rate)
    return super().time_grid()

LinearSweepVoltammetry

Bases: BaseTechnique

Unidirectional linear potential sweep waveform (LSV).

Sweeps electrode potential linearly from \(E_{\text{start}}\) to \(E_{\text{end}}\) at scan rate \(v > 0\) (V/s):

\[ E(t) = E_{\text{start}} + \operatorname{sgn}(E_{\text{end}} - E_{\text{start}}) \cdot v \cdot t \]

for \(t \in [0, |E_{\text{end}} - E_{\text{start}}| / v]\).

Parameters:

Name Type Description Default
E_start float

Initial potential \(E_{\text{start}}\) in Volts.

required
E_end float

Final potential \(E_{\text{end}}\) in Volts (must differ from E_start).

required
scan_rate float

Scan rate magnitude \(v > 0\) in V/s.

required
dE float

Default potential step resolution \(\Delta E > 0\) in Volts used by time_grid when no resolution arguments are passed. Mutually exclusive with n_points.

None
n_points int

Default number of points (\(\ge 2\)) used by time_grid when no resolution arguments are passed. Mutually exclusive with dE.

None

Examples:

>>> from softpotato.techniques import LinearSweepVoltammetry
>>> lsv = LinearSweepVoltammetry(E_start=0.5, E_end=-0.5, scan_rate=0.1)
>>> lsv.duration
10.0
>>> lsv(5.0)
0.0
Source code in src/softpotato/techniques/voltammetry.py
class LinearSweepVoltammetry(BaseTechnique):
    r"""Unidirectional linear potential sweep waveform (LSV).

    Sweeps electrode potential linearly from :math:`E_{\text{start}}` to
    :math:`E_{\text{end}}` at scan rate :math:`v > 0` (V/s):

    .. math::

        E(t) = E_{\text{start}} + \operatorname{sgn}(E_{\text{end}} - E_{\text{start}}) \cdot v \cdot t

    for :math:`t \in [0, |E_{\text{end}} - E_{\text{start}}| / v]`.

    Parameters
    ----------
    E_start : float
        Initial potential :math:`E_{\text{start}}` in Volts.
    E_end : float
        Final potential :math:`E_{\text{end}}` in Volts (must differ from ``E_start``).
    scan_rate : float
        Scan rate magnitude :math:`v > 0` in V/s.
    dE : float, optional
        Default potential step resolution :math:`\Delta E > 0` in Volts used by
        :meth:`time_grid` when no resolution arguments are passed. Mutually
        exclusive with ``n_points``.
    n_points : int, optional
        Default number of points (:math:`\ge 2`) used by :meth:`time_grid` when
        no resolution arguments are passed. Mutually exclusive with ``dE``.

    Examples
    --------
    >>> from softpotato.techniques import LinearSweepVoltammetry
    >>> lsv = LinearSweepVoltammetry(E_start=0.5, E_end=-0.5, scan_rate=0.1)
    >>> lsv.duration
    10.0
    >>> lsv(5.0)
    0.0
    """

    def __init__(
        self,
        E_start: float,
        E_end: float,
        scan_rate: float,
        *,
        dE: float | None = None,
        n_points: int | None = None,
    ) -> None:
        self._mode = "potentiostatic"
        self._E_start = _validate_finite_real(E_start, "E_start")
        self._E_end = _validate_finite_real(E_end, "E_end")
        if self._E_start == self._E_end:
            raise ValueError("E_start and E_end must be distinct.")

        self._scan_rate = _validate_positive_finite(scan_rate, "scan_rate")

        if dE is not None and n_points is not None:
            raise ValueError("Specify at most one of 'dE' or 'n_points'.")
        self._dE = _validate_positive_finite(dE, "dE") if dE is not None else None
        self._n_points = (
            _validate_positive_int(n_points, "n_points", minimum=2)
            if n_points is not None
            else None
        )

        self._direction = 1 if self._E_end > self._E_start else -1
        self._duration = abs(self._E_end - self._E_start) / self._scan_rate

    @property
    def E_start(self) -> float:
        """Initial electrode potential in Volts."""
        return self._E_start

    @property
    def E_end(self) -> float:
        """Final electrode potential in Volts."""
        return self._E_end

    @property
    def scan_rate(self) -> float:
        """Scan rate magnitude :math:`v` in V/s."""
        return self._scan_rate

    @property
    def direction(self) -> int:
        """Sweep direction: ``+1`` (anodic/positive) or ``-1`` (cathodic/negative)."""
        return self._direction

    @property
    def dE(self) -> float | None:
        """Default potential step resolution in Volts, or ``None``."""
        return self._dE

    @property
    def n_points(self) -> int | None:
        """Default number of time grid points, or ``None``."""
        return self._n_points

    @property
    def duration(self) -> float:
        """Total sweep duration :math:`|E_{\\text{end}} - E_{\\text{start}}| / v` in seconds."""
        return self._duration

    @overload
    def excitation(self, t: float) -> float: ...

    @overload
    def excitation(self, t: np.ndarray) -> np.ndarray: ...

    @overload
    def excitation(self, t: float | ArrayLike) -> float | np.ndarray: ...

    def excitation(self, t: float | ArrayLike) -> float | np.ndarray:
        normalized, is_scalar = _normalize_time_input(t)
        slope = self._direction * self._scan_rate

        if is_scalar:
            assert isinstance(normalized, float)
            if normalized <= 0.0:
                return self._E_start
            if normalized >= self._duration:
                return self._E_end
            return self._E_start + slope * normalized

        assert isinstance(normalized, np.ndarray)
        clamped = np.clip(normalized, 0.0, self._duration)
        values = self._E_start + slope * clamped
        values = np.where(clamped <= 0.0, self._E_start, values)
        values = np.where(clamped >= self._duration, self._E_end, values)
        return values

    def time_grid(
        self,
        n_points: int | None = None,
        dt: float | None = None,
        dE: float | None = None,
    ) -> np.ndarray:
        """Generate evaluation timestamps for the linear sweep.

        Parameters
        ----------
        n_points : int, optional
            Number of uniformly spaced timestamps (``>= 2``).
        dt : float, optional
            Uniform time step in seconds (``> 0``).
        dE : float, optional
            Uniform potential step in Volts (``> 0``), converted to
            ``dt = dE / scan_rate``.

        Returns
        -------
        np.ndarray
            Strictly increasing 1D array of timestamps in ``[0, duration]``.
        """
        n_specified = sum(x is not None for x in (n_points, dt, dE))
        if n_specified > 1:
            raise ValueError("Specify at most one of 'n_points', 'dt', or 'dE'.")

        if dE is not None:
            dE_val = _validate_positive_finite(dE, "dE")
            return super().time_grid(dt=dE_val / self._scan_rate)
        if n_points is not None or dt is not None:
            return super().time_grid(n_points=n_points, dt=dt)

        if self._n_points is not None:
            return super().time_grid(n_points=self._n_points)
        if self._dE is not None:
            return super().time_grid(dt=self._dE / self._scan_rate)
        return super().time_grid()

    def _technique_plots(self) -> tuple[PlotSpec, ...]:
        return (
            PlotSpec(
                kind="voltammogram",
                title="Linear Sweep Voltammogram",
                x_label="$E$ / V",
                y_label="$I$ / A",
                description="Faradaic current vs. applied potential during linear sweep.",
            ),
        )

    def __repr__(self) -> str:
        return (
            f"LinearSweepVoltammetry(E_start={self._E_start!r}, "
            f"E_end={self._E_end!r}, scan_rate={self._scan_rate!r})"
        )

E_start property

E_start: float

Initial electrode potential in Volts.

E_end property

E_end: float

Final electrode potential in Volts.

scan_rate property

scan_rate: float

Scan rate magnitude \(v\) in V/s.

direction property

direction: int

Sweep direction: +1 (anodic/positive) or -1 (cathodic/negative).

dE property

dE: float | None

Default potential step resolution in Volts, or None.

n_points property

n_points: int | None

Default number of time grid points, or None.

duration property

duration: float

Total sweep duration \(|E_{\text{end}} - E_{\text{start}}| / v\) in seconds.

time_grid

time_grid(n_points: int | None = None, dt: float | None = None, dE: float | None = None) -> np.ndarray

Generate evaluation timestamps for the linear sweep.

Parameters:

Name Type Description Default
n_points int

Number of uniformly spaced timestamps (>= 2).

None
dt float

Uniform time step in seconds (> 0).

None
dE float

Uniform potential step in Volts (> 0), converted to dt = dE / scan_rate.

None

Returns:

Type Description
ndarray

Strictly increasing 1D array of timestamps in [0, duration].

Source code in src/softpotato/techniques/voltammetry.py
def time_grid(
    self,
    n_points: int | None = None,
    dt: float | None = None,
    dE: float | None = None,
) -> np.ndarray:
    """Generate evaluation timestamps for the linear sweep.

    Parameters
    ----------
    n_points : int, optional
        Number of uniformly spaced timestamps (``>= 2``).
    dt : float, optional
        Uniform time step in seconds (``> 0``).
    dE : float, optional
        Uniform potential step in Volts (``> 0``), converted to
        ``dt = dE / scan_rate``.

    Returns
    -------
    np.ndarray
        Strictly increasing 1D array of timestamps in ``[0, duration]``.
    """
    n_specified = sum(x is not None for x in (n_points, dt, dE))
    if n_specified > 1:
        raise ValueError("Specify at most one of 'n_points', 'dt', or 'dE'.")

    if dE is not None:
        dE_val = _validate_positive_finite(dE, "dE")
        return super().time_grid(dt=dE_val / self._scan_rate)
    if n_points is not None or dt is not None:
        return super().time_grid(n_points=n_points, dt=dt)

    if self._n_points is not None:
        return super().time_grid(n_points=self._n_points)
    if self._dE is not None:
        return super().time_grid(dt=self._dE / self._scan_rate)
    return super().time_grid()

CallableSegment

Bases: WaveformSegment

Arbitrary user-defined callable segment \(y(\tau) = f(\tau)\).

Supports both vectorized NumPy callables and scalar-only Python callables (automatically falling back to element-wise evaluation for arrays if a scalar-only callable is provided).

Parameters:

Name Type Description Default
func Callable[[float | ndarray], float | ndarray]

Function evaluated on local segment time \(\tau \in [0, \Delta t]\).

required
duration float

Segment duration in seconds (\(\Delta t > 0\)).

required
event_times Sequence[float]

Optional interior discontinuity timestamps in local time (0, duration).

()
Source code in src/softpotato/techniques/waveforms.py
class CallableSegment(WaveformSegment):
    r"""Arbitrary user-defined callable segment :math:`y(\tau) = f(\tau)`.

    Supports both vectorized NumPy callables and scalar-only Python callables
    (automatically falling back to element-wise evaluation for arrays if a
    scalar-only callable is provided).

    Parameters
    ----------
    func : Callable[[float | np.ndarray], float | np.ndarray]
        Function evaluated on local segment time :math:`\tau \in [0, \Delta t]`.
    duration : float
        Segment duration in seconds (:math:`\Delta t > 0`).
    event_times : Sequence[float], optional
        Optional interior discontinuity timestamps in local time ``(0, duration)``.
    """

    def __init__(
        self,
        func: Callable[[float | np.ndarray], float | np.ndarray],
        duration: float,
        *,
        event_times: Sequence[float] = (),
    ) -> None:
        if not callable(func):
            raise TypeError(f"func must be callable, got {type(func).__name__}.")
        super().__init__(duration)
        self._func = func
        validated_events = [
            _validate_finite_real(t_ev, "event_times entry") for t_ev in event_times
        ]
        self._event_times = _deduplicate_interior_events(
            validated_events, self._duration
        )

    @property
    def func(self) -> Callable[[float | np.ndarray], float | np.ndarray]:
        """Underlying segment callable."""
        return self._func

    @property
    def event_times(self) -> tuple[float, ...]:
        """Sorted interior local event timestamps in ``(0, duration)``."""
        return self._event_times

    @overload
    def evaluate(self, t_local: float) -> float: ...

    @overload
    def evaluate(self, t_local: np.ndarray) -> np.ndarray: ...

    @overload
    def evaluate(self, t_local: float | ArrayLike) -> float | np.ndarray: ...

    def evaluate(self, t_local: float | ArrayLike) -> float | np.ndarray:
        normalized, is_scalar = _normalize_time_input(t_local)
        if is_scalar:
            assert isinstance(normalized, float)
            tau = min(max(normalized, 0.0), self._duration)
            val = float(self._func(tau))
            if not math.isfinite(val):
                raise ValueError(
                    f"CallableSegment returned non-finite value {val!r} at t={tau}."
                )
            return val

        assert isinstance(normalized, np.ndarray)
        tau_arr = np.clip(normalized, 0.0, self._duration)
        if tau_arr.size == 0:
            return np.empty(tau_arr.shape, dtype=float)

        try:
            raw = self._func(tau_arr)
            result = np.asarray(raw, dtype=float)
            if result.shape != tau_arr.shape:
                result = np.broadcast_to(result, tau_arr.shape).astype(float, copy=True)
        except (TypeError, ValueError):
            flat = [float(self._func(float(ti))) for ti in tau_arr.ravel()]
            result = np.asarray(flat, dtype=float).reshape(tau_arr.shape)

        if not np.all(np.isfinite(result)):
            raise ValueError("CallableSegment returned non-finite values.")
        return result

    def __repr__(self) -> str:
        func_name = getattr(self._func, "__name__", repr(self._func))
        return f"CallableSegment(func={func_name}, duration={self._duration!r})"

func property

func: Callable[[float | ndarray], float | ndarray]

Underlying segment callable.

event_times property

event_times: tuple[float, ...]

Sorted interior local event timestamps in (0, duration).

ConstantSegment

Bases: WaveformSegment

Constant-value hold segment \(y(\tau) = y_0\) for \(\tau \in [0, \Delta t]\).

Parameters:

Name Type Description Default
value float

Constant excitation level (potential in V or current in A).

required
duration float

Hold duration in seconds (\(\Delta t > 0\)).

required
Source code in src/softpotato/techniques/waveforms.py
class ConstantSegment(WaveformSegment):
    r"""Constant-value hold segment :math:`y(\tau) = y_0` for :math:`\tau \in [0, \Delta t]`.

    Parameters
    ----------
    value : float
        Constant excitation level (potential in V or current in A).
    duration : float
        Hold duration in seconds (:math:`\Delta t > 0`).
    """

    def __init__(self, value: float, duration: float) -> None:
        super().__init__(duration)
        self._value = _validate_finite_real(value, "value")

    @property
    def value(self) -> float:
        """Constant excitation level."""
        return self._value

    @overload
    def evaluate(self, t_local: float) -> float: ...

    @overload
    def evaluate(self, t_local: np.ndarray) -> np.ndarray: ...

    @overload
    def evaluate(self, t_local: float | ArrayLike) -> float | np.ndarray: ...

    def evaluate(self, t_local: float | ArrayLike) -> float | np.ndarray:
        normalized, is_scalar = _normalize_time_input(t_local)
        if is_scalar:
            return self._value
        assert isinstance(normalized, np.ndarray)
        return np.full(normalized.shape, self._value, dtype=float)

    def __repr__(self) -> str:
        return f"ConstantSegment(value={self._value!r}, duration={self._duration!r})"

value property

value: float

Constant excitation level.

CustomWaveform

Bases: BaseTechnique

Composite electrochemical waveform chaining arbitrary WaveformSegment objects.

Aggregates total duration and interior event_times across all chained segments automatically. At interior segment boundaries, evaluation is right-continuous (t in [t_k, t_{k+1}) evaluates segment k), while the final endpoint t == duration evaluates the last segment at its end time.

Parameters:

Name Type Description Default
segments Sequence[WaveformSegment]

Non-empty ordered sequence of WaveformSegment instances.

required
mode ('potentiostatic', 'galvanostatic')

Control mode of the composite excitation signal.

'potentiostatic'
n_points int

Default number of points for time_grid when neither n_points nor dt is passed (default 1001).

None

Examples:

>>> from softpotato.techniques import (
...     ConstantSegment,
...     CustomWaveform,
...     LinearRampSegment,
... )
>>> wf = CustomWaveform([
...     ConstantSegment(0.0, duration=1.0),
...     LinearRampSegment(0.0, -0.5, duration=2.0),
...     ConstantSegment(-0.5, duration=1.0),
... ])
>>> wf.duration
4.0
>>> wf.event_times
(1.0, 3.0)
>>> wf(2.0)
-0.25
Source code in src/softpotato/techniques/waveforms.py
class CustomWaveform(BaseTechnique):
    """Composite electrochemical waveform chaining arbitrary :class:`WaveformSegment` objects.

    Aggregates total :attr:`duration` and interior :attr:`event_times` across all
    chained segments automatically. At interior segment boundaries, evaluation is
    right-continuous (``t in [t_k, t_{k+1})`` evaluates segment ``k``), while the
    final endpoint ``t == duration`` evaluates the last segment at its end time.

    Parameters
    ----------
    segments : Sequence[WaveformSegment]
        Non-empty ordered sequence of :class:`WaveformSegment` instances.
    mode : {'potentiostatic', 'galvanostatic'}, default 'potentiostatic'
        Control mode of the composite excitation signal.
    n_points : int, optional
        Default number of points for :meth:`time_grid` when neither ``n_points``
        nor ``dt`` is passed (default 1001).

    Examples
    --------
    >>> from softpotato.techniques import (
    ...     ConstantSegment,
    ...     CustomWaveform,
    ...     LinearRampSegment,
    ... )
    >>> wf = CustomWaveform([
    ...     ConstantSegment(0.0, duration=1.0),
    ...     LinearRampSegment(0.0, -0.5, duration=2.0),
    ...     ConstantSegment(-0.5, duration=1.0),
    ... ])
    >>> wf.duration
    4.0
    >>> wf.event_times
    (1.0, 3.0)
    >>> wf(2.0)
    -0.25
    """

    def __init__(
        self,
        segments: Sequence[WaveformSegment],
        *,
        mode: ControlMode = "potentiostatic",
        n_points: int | None = None,
    ) -> None:
        if isinstance(segments, (str, bytes)) or not isinstance(segments, Sequence):
            raise TypeError(
                f"segments must be a sequence of WaveformSegment, got {type(segments).__name__}."
            )
        if len(segments) == 0:
            raise ValueError("segments must not be empty.")

        seg_list: list[WaveformSegment] = []
        for idx, seg in enumerate(segments):
            if not isinstance(seg, WaveformSegment):
                raise TypeError(
                    f"segments[{idx}] must be a WaveformSegment instance, "
                    f"got {type(seg).__name__}."
                )
            seg_list.append(seg)

        self._mode = _validate_mode(mode)
        self._default_n_points = (
            _validate_positive_int(n_points, "n_points", minimum=2)
            if n_points is not None
            else 1001
        )
        self._segments: tuple[WaveformSegment, ...] = tuple(seg_list)

        starts: list[float] = []
        events: list[float] = []
        cursor = 0.0
        for idx, seg in enumerate(self._segments):
            starts.append(cursor)
            if idx > 0:
                events.append(cursor)
            for local_ev in seg.event_times:
                events.append(cursor + local_ev)
            cursor += seg.duration

        self._starts = np.asarray(starts, dtype=float)
        self._duration = float(cursor)
        self._event_times = _deduplicate_interior_events(events, self._duration)

    @property
    def segments(self) -> tuple[WaveformSegment, ...]:
        """Ordered tuple of constituent :class:`WaveformSegment` objects."""
        return self._segments

    @property
    def segment_boundaries(self) -> tuple[float, ...]:
        """Timestamps of all segment boundaries including ``0.0`` and :attr:`duration`."""
        return tuple(float(x) for x in self._starts) + (self._duration,)

    @property
    def duration(self) -> float:
        """Total composite waveform duration in seconds."""
        return self._duration

    @property
    def event_times(self) -> tuple[float, ...]:
        """Sorted interior segment boundaries and segment-internal event times."""
        return self._event_times

    def _default_time_grid_points(self) -> int:
        return self._default_n_points

    @overload
    def excitation(self, t: float) -> float: ...

    @overload
    def excitation(self, t: np.ndarray) -> np.ndarray: ...

    @overload
    def excitation(self, t: float | ArrayLike) -> float | np.ndarray: ...

    def excitation(self, t: float | ArrayLike) -> float | np.ndarray:
        normalized, is_scalar = _normalize_time_input(t)
        n_seg = len(self._segments)

        if is_scalar:
            assert isinstance(normalized, float)
            if normalized <= 0.0:
                return float(self._segments[0].evaluate(0.0))
            if normalized >= self._duration:
                last = self._segments[-1]
                return float(last.evaluate(last.duration))
            idx = int(np.searchsorted(self._starts, normalized, side="right")) - 1
            idx = min(max(idx, 0), n_seg - 1)
            seg = self._segments[idx]
            t_local = min(max(normalized - float(self._starts[idx]), 0.0), seg.duration)
            return float(seg.evaluate(t_local))

        assert isinstance(normalized, np.ndarray)
        orig_shape = normalized.shape
        flat = normalized.ravel()
        if flat.size == 0:
            return np.empty(orig_shape, dtype=float)

        clamped = np.clip(flat, 0.0, self._duration)
        indices = np.searchsorted(self._starts, clamped, side="right") - 1
        indices = np.clip(indices, 0, n_seg - 1)
        # Ensure exact final endpoint evaluates at the end of the last segment
        at_end = clamped >= self._duration
        indices = np.where(at_end, n_seg - 1, indices)

        out = np.empty(flat.shape, dtype=float)
        for seg_idx, seg in enumerate(self._segments):
            mask = indices == seg_idx
            if not np.any(mask):
                continue
            t_local_arr = np.clip(
                clamped[mask] - self._starts[seg_idx], 0.0, seg.duration
            )
            if seg_idx == n_seg - 1:
                t_local_arr = np.where(at_end[mask], seg.duration, t_local_arr)
            out[mask] = seg.evaluate(t_local_arr)

        return out.reshape(orig_shape)

    def __repr__(self) -> str:
        return (
            f"CustomWaveform(n_segments={len(self._segments)}, "
            f"duration={self._duration!r}, mode={self._mode!r})"
        )

segments property

segments: tuple[WaveformSegment, ...]

Ordered tuple of constituent WaveformSegment objects.

segment_boundaries property

segment_boundaries: tuple[float, ...]

Timestamps of all segment boundaries including 0.0 and duration.

duration property

duration: float

Total composite waveform duration in seconds.

event_times property

event_times: tuple[float, ...]

Sorted interior segment boundaries and segment-internal event times.

LinearRampSegment

Bases: WaveformSegment

Linear ramp segment from start to end over duration.

\[ y(\tau) = y_{\text{start}} + \frac{y_{\text{end}} - y_{\text{start}}}{\Delta t} \, \tau \]

Parameters:

Name Type Description Default
start float

Starting excitation value at \(\tau = 0\).

required
end float

Ending excitation value at \(\tau = \Delta t\).

required
duration float

Ramp duration in seconds (\(\Delta t > 0\)). Mutually exclusive with rate.

None
rate float

Positive ramp rate magnitude \(|dy/dt| > 0\). When given, duration is computed as \(|y_{\text{end}} - y_{\text{start}}| / \text{rate}\). Requires start != end.

None
Source code in src/softpotato/techniques/waveforms.py
class LinearRampSegment(WaveformSegment):
    r"""Linear ramp segment from ``start`` to ``end`` over ``duration``.

    .. math::

        y(\tau) = y_{\text{start}} + \frac{y_{\text{end}} - y_{\text{start}}}{\Delta t} \, \tau

    Parameters
    ----------
    start : float
        Starting excitation value at :math:`\tau = 0`.
    end : float
        Ending excitation value at :math:`\tau = \Delta t`.
    duration : float, optional
        Ramp duration in seconds (:math:`\Delta t > 0`). Mutually exclusive
        with ``rate``.
    rate : float, optional
        Positive ramp rate magnitude :math:`|dy/dt| > 0`. When given, duration
        is computed as :math:`|y_{\text{end}} - y_{\text{start}}| / \text{rate}`.
        Requires ``start != end``.
    """

    def __init__(
        self,
        start: float,
        end: float,
        duration: float | None = None,
        *,
        rate: float | None = None,
    ) -> None:
        self._start = _validate_finite_real(start, "start")
        self._end = _validate_finite_real(end, "end")

        if duration is not None and rate is not None:
            raise ValueError("Specify either 'duration' or 'rate', not both.")
        if duration is None and rate is None:
            raise ValueError("Must specify either 'duration' or 'rate'.")

        if rate is not None:
            rate_val = _validate_positive_finite(rate, "rate")
            span = abs(self._end - self._start)
            if span == 0.0:
                raise ValueError("Cannot infer duration from 'rate' when start == end.")
            resolved_duration = span / rate_val
        else:
            resolved_duration = _validate_positive_finite(duration, "duration")

        super().__init__(resolved_duration)
        self._slope = (self._end - self._start) / self._duration

    @property
    def start(self) -> float:
        """Starting value at ``t_local = 0``."""
        return self._start

    @property
    def end(self) -> float:
        """Ending value at ``t_local = duration``."""
        return self._end

    @property
    def slope(self) -> float:
        """Signed ramp rate ``(end - start) / duration``."""
        return self._slope

    @property
    def rate(self) -> float:
        """Unsigned ramp rate magnitude ``abs(slope)``."""
        return abs(self._slope)

    @overload
    def evaluate(self, t_local: float) -> float: ...

    @overload
    def evaluate(self, t_local: np.ndarray) -> np.ndarray: ...

    @overload
    def evaluate(self, t_local: float | ArrayLike) -> float | np.ndarray: ...

    def evaluate(self, t_local: float | ArrayLike) -> float | np.ndarray:
        normalized, is_scalar = _normalize_time_input(t_local)
        if is_scalar:
            assert isinstance(normalized, float)
            if normalized <= 0.0:
                return self._start
            if normalized >= self._duration:
                return self._end
            return self._start + self._slope * normalized

        assert isinstance(normalized, np.ndarray)
        clamped = np.clip(normalized, 0.0, self._duration)
        values = self._start + self._slope * clamped
        values = np.where(clamped <= 0.0, self._start, values)
        values = np.where(clamped >= self._duration, self._end, values)
        return values

    def __repr__(self) -> str:
        return (
            f"LinearRampSegment(start={self._start!r}, end={self._end!r}, "
            f"duration={self._duration!r})"
        )

start property

start: float

Starting value at t_local = 0.

end property

end: float

Ending value at t_local = duration.

slope property

slope: float

Signed ramp rate (end - start) / duration.

rate property

rate: float

Unsigned ramp rate magnitude abs(slope).

SinusoidalSegment

Bases: WaveformSegment

Sinusoidal excitation segment over \(\tau \in [0, \Delta t]\).

\[ y(\tau) = y_0 + A \sin(2 \pi f \tau + \phi) \]

Parameters:

Name Type Description Default
offset float

DC offset level \(y_0\).

required
amplitude float

Peak oscillation amplitude \(A\) (must be finite; typically >= 0).

required
frequency float

Oscillation frequency \(f > 0\) in Hz.

required
duration float

Segment duration in seconds (\(\Delta t > 0\)).

required
phase float

Initial phase angle \(\phi\) in radians.

0.0
Source code in src/softpotato/techniques/waveforms.py
class SinusoidalSegment(WaveformSegment):
    r"""Sinusoidal excitation segment over :math:`\tau \in [0, \Delta t]`.

    .. math::

        y(\tau) = y_0 + A \sin(2 \pi f \tau + \phi)

    Parameters
    ----------
    offset : float
        DC offset level :math:`y_0`.
    amplitude : float
        Peak oscillation amplitude :math:`A` (must be finite; typically ``>= 0``).
    frequency : float
        Oscillation frequency :math:`f > 0` in Hz.
    duration : float
        Segment duration in seconds (:math:`\Delta t > 0`).
    phase : float, default 0.0
        Initial phase angle :math:`\phi` in radians.
    """

    def __init__(
        self,
        offset: float,
        amplitude: float,
        frequency: float,
        duration: float,
        phase: float = 0.0,
    ) -> None:
        super().__init__(duration)
        self._offset = _validate_finite_real(offset, "offset")
        self._amplitude = _validate_finite_real(amplitude, "amplitude")
        self._frequency = _validate_positive_finite(frequency, "frequency")
        self._phase = _validate_finite_real(phase, "phase")

    @property
    def offset(self) -> float:
        """DC offset level."""
        return self._offset

    @property
    def amplitude(self) -> float:
        """Oscillation amplitude."""
        return self._amplitude

    @property
    def frequency(self) -> float:
        """Oscillation frequency in Hz."""
        return self._frequency

    @property
    def phase(self) -> float:
        """Initial phase in radians."""
        return self._phase

    @overload
    def evaluate(self, t_local: float) -> float: ...

    @overload
    def evaluate(self, t_local: np.ndarray) -> np.ndarray: ...

    @overload
    def evaluate(self, t_local: float | ArrayLike) -> float | np.ndarray: ...

    def evaluate(self, t_local: float | ArrayLike) -> float | np.ndarray:
        normalized, is_scalar = _normalize_time_input(t_local)
        omega = 2.0 * math.pi * self._frequency
        if is_scalar:
            assert isinstance(normalized, float)
            tau = min(max(normalized, 0.0), self._duration)
            return self._offset + self._amplitude * math.sin(omega * tau + self._phase)

        assert isinstance(normalized, np.ndarray)
        tau_arr = np.clip(normalized, 0.0, self._duration)
        return self._offset + self._amplitude * np.sin(omega * tau_arr + self._phase)

    def __repr__(self) -> str:
        return (
            f"SinusoidalSegment(offset={self._offset!r}, amplitude={self._amplitude!r}, "
            f"frequency={self._frequency!r}, duration={self._duration!r}, "
            f"phase={self._phase!r})"
        )

offset property

offset: float

DC offset level.

amplitude property

amplitude: float

Oscillation amplitude.

frequency property

frequency: float

Oscillation frequency in Hz.

phase property

phase: float

Initial phase in radians.

WaveformSegment

Bases: ABC

Abstract base class for a single time-localized waveform segment.

A segment is defined over local time \(\tau \in [0, \Delta t]\) with strictly positive duration \(\Delta t > 0\). Segments can be chained sequentially inside CustomWaveform.

Source code in src/softpotato/techniques/waveforms.py
class WaveformSegment(ABC):
    r"""Abstract base class for a single time-localized waveform segment.

    A segment is defined over local time :math:`\tau \in [0, \Delta t]` with
    strictly positive duration :math:`\Delta t > 0`. Segments can be chained
    sequentially inside :class:`CustomWaveform`.
    """

    def __init__(self, duration: float) -> None:
        self._duration = _validate_positive_finite(duration, "duration")

    @property
    def duration(self) -> float:
        """Segment duration in seconds (:math:`\\Delta t > 0`)."""
        return self._duration

    @property
    def event_times(self) -> tuple[float, ...]:
        """Optional interior event timestamps in local time ``(0, duration)``."""
        return ()

    @property
    def start_value(self) -> float:
        """Excitation value at the start of the segment (:math:`\\tau = 0`)."""
        return float(self.evaluate(0.0))

    @property
    def end_value(self) -> float:
        """Excitation value at the end of the segment (:math:`\\tau = \\Delta t`)."""
        return float(self.evaluate(self._duration))

    @overload
    def evaluate(self, t_local: float) -> float: ...

    @overload
    def evaluate(self, t_local: np.ndarray) -> np.ndarray: ...

    @overload
    def evaluate(self, t_local: float | ArrayLike) -> float | np.ndarray: ...

    @abstractmethod
    def evaluate(self, t_local: float | ArrayLike) -> float | np.ndarray:
        """Evaluate the segment at local time(s) ``t_local`` in ``[0, duration]``."""
        raise NotImplementedError

    @overload
    def __call__(self, t_local: float) -> float: ...

    @overload
    def __call__(self, t_local: np.ndarray) -> np.ndarray: ...

    @overload
    def __call__(self, t_local: float | ArrayLike) -> float | np.ndarray: ...

    def __call__(self, t_local: float | ArrayLike) -> float | np.ndarray:
        """Callable alias for :meth:`evaluate`."""
        return self.evaluate(t_local)

duration property

duration: float

Segment duration in seconds (\(\Delta t > 0\)).

event_times property

event_times: tuple[float, ...]

Optional interior event timestamps in local time (0, duration).

start_value property

start_value: float

Excitation value at the start of the segment (\(\tau = 0\)).

end_value property

end_value: float

Excitation value at the end of the segment (\(\tau = \Delta t\)).

evaluate abstractmethod

evaluate(t_local: float) -> float
evaluate(t_local: ndarray) -> np.ndarray
evaluate(t_local: float | ArrayLike) -> float | np.ndarray
evaluate(t_local: float | ArrayLike) -> float | np.ndarray

Evaluate the segment at local time(s) t_local in [0, duration].

Source code in src/softpotato/techniques/waveforms.py
@abstractmethod
def evaluate(self, t_local: float | ArrayLike) -> float | np.ndarray:
    """Evaluate the segment at local time(s) ``t_local`` in ``[0, duration]``."""
    raise NotImplementedError

__call__

__call__(t_local: float) -> float
__call__(t_local: ndarray) -> np.ndarray
__call__(t_local: float | ArrayLike) -> float | np.ndarray
__call__(t_local: float | ArrayLike) -> float | np.ndarray

Callable alias for evaluate.

Source code in src/softpotato/techniques/waveforms.py
def __call__(self, t_local: float | ArrayLike) -> float | np.ndarray:
    """Callable alias for :meth:`evaluate`."""
    return self.evaluate(t_local)

resolve_plot_kind

resolve_plot_kind(kind: str) -> str

Resolve a concise plot key or verbose alias to its canonical plot kind.

Parameters:

Name Type Description Default
kind str

Concise plot key (e.g., 'i_vs_t', 'E_vs_t', 'c_vs_x', 'voltammogram') or verbose alias (e.g., 'current_vs_time', 'potential_vs_time', 'concentration_profile').

required

Returns:

Type Description
str

Canonical plot key if recognized, otherwise the stripped input string.

Source code in src/softpotato/techniques/base.py
def resolve_plot_kind(kind: str) -> str:
    """Resolve a concise plot key or verbose alias to its canonical plot kind.

    Parameters
    ----------
    kind : str
        Concise plot key (e.g., ``'i_vs_t'``, ``'E_vs_t'``, ``'c_vs_x'``,
        ``'voltammogram'``) or verbose alias (e.g., ``'current_vs_time'``,
        ``'potential_vs_time'``, ``'concentration_profile'``).

    Returns
    -------
    str
        Canonical plot key if recognized, otherwise the stripped input string.
    """
    if not isinstance(kind, str):
        raise TypeError(f"Plot kind must be a string, got {type(kind).__name__}.")
    cleaned = kind.strip()
    lowered = cleaned.lower()
    if lowered in _CANONICAL_PLOT_KINDS:
        return _CANONICAL_PLOT_KINDS[lowered]
    if lowered in PLOT_ALIASES:
        return PLOT_ALIASES[lowered]
    return cleaned

analyze_cottrell

analyze_cottrell(result: TechniqueResult | ArrayLike, current: ArrayLike | None = None, *, n: float, area: float, c_bulk: float, t_min: float | None = None, t_max: float | None = None, method: Literal['linear', 'nonlinear'] = 'linear', fit_background: bool = False, confidence_level: float = 0.95) -> CottrellFitResult

Perform Cottrell analysis (\(I\) vs. \(t^{-1/2}\)) on a CA transient.

Filters the transient to strictly positive times within [t_min, t_max] and delegates to fit_cottrell to recover the diffusion coefficient \(D\).

Parameters:

Name Type Description Default
result TechniqueResult or array - like

A chronoamperometric TechniqueResult or a 1D time array \(t\) in seconds (paired with current).

required
current array - like

1D Faradaic current array \(I\) in Amperes when result is a time array.

None
n float

Number of electrons transferred (\(n > 0\)).

required
area float

Electrode surface area \(A > 0\) in \(\text{m}^2\) or \(\text{cm}^2\).

required
c_bulk float

Bulk reactant concentration \(c^* > 0\) in matching volume units.

required
t_min float

Lower time cutoff in seconds (inclusive, strictly positive).

None
t_max float

Upper time cutoff in seconds (inclusive).

None
method ('linear', 'nonlinear')

Regression method forwarded to fit_cottrell.

'linear'
fit_background bool

Whether to fit a constant background current offset \(I_{\text{bg}}\).

False
confidence_level float

Confidence level for Student's \(t\) parameter intervals.

0.95

Returns:

Type Description
CottrellFitResult

Extracted diffusion coefficient \(D\), standard error, slope, background current, and goodness-of-fit statistics.

Source code in src/softpotato/techniques/diagnostics.py
def analyze_cottrell(
    result: TechniqueResult | ArrayLike,
    current: ArrayLike | None = None,
    *,
    n: float,
    area: float,
    c_bulk: float,
    t_min: float | None = None,
    t_max: float | None = None,
    method: Literal["linear", "nonlinear"] = "linear",
    fit_background: bool = False,
    confidence_level: float = 0.95,
) -> CottrellFitResult:
    r"""Perform Cottrell analysis (:math:`I` vs. :math:`t^{-1/2}`) on a CA transient.

    Filters the transient to strictly positive times within ``[t_min, t_max]``
    and delegates to :func:`~softpotato.analytical.fitting.fit_cottrell` to
    recover the diffusion coefficient :math:`D`.

    Parameters
    ----------
    result : TechniqueResult or array-like
        A chronoamperometric :class:`~softpotato.techniques.TechniqueResult` or
        a 1D time array :math:`t` in seconds (paired with ``current``).
    current : array-like, optional
        1D Faradaic current array :math:`I` in Amperes when ``result`` is a time
        array.
    n : float
        Number of electrons transferred (:math:`n > 0`).
    area : float
        Electrode surface area :math:`A > 0` in :math:`\text{m}^2` or
        :math:`\text{cm}^2`.
    c_bulk : float
        Bulk reactant concentration :math:`c^* > 0` in matching volume units.
    t_min : float, optional
        Lower time cutoff in seconds (inclusive, strictly positive).
    t_max : float, optional
        Upper time cutoff in seconds (inclusive).
    method : {'linear', 'nonlinear'}, default 'linear'
        Regression method forwarded to :func:`fit_cottrell`.
    fit_background : bool, default False
        Whether to fit a constant background current offset :math:`I_{\text{bg}}`.
    confidence_level : float, default 0.95
        Confidence level for Student's :math:`t` parameter intervals.

    Returns
    -------
    CottrellFitResult
        Extracted diffusion coefficient :math:`D`, standard error, slope,
        background current, and goodness-of-fit statistics.
    """
    t_offset = 0.0
    if isinstance(result, TechniqueResult):
        if current is not None:
            raise ValueError(
                "Do not pass 'current' when the first argument is a TechniqueResult."
            )
        t_arr, i_arr = _validate_1d_pair(
            result.time, result.current, "time", "current", min_points=2
        )
        if (
            isinstance(result.technique, Chronoamperometry)
            and result.technique.t_quiet > 0.0
        ):
            t_offset = result.technique.t_quiet
    else:
        if current is None:
            raise ValueError(
                "'current' must be provided when the first argument is a time array."
            )
        t_arr, i_arr = _validate_1d_pair(result, current, "t", "current", min_points=2)

    if t_min is not None:
        t_min_val = _validate_finite_real(t_min, "t_min")
    else:
        t_min_val = None
    if t_max is not None:
        t_max_val = _validate_finite_real(t_max, "t_max")
    else:
        t_max_val = None
    if t_min_val is not None and t_max_val is not None and t_min_val >= t_max_val:
        raise ValueError(
            f"t_min ({t_min_val!r}) must be strictly less than t_max ({t_max_val!r})."
        )

    t_eff = t_arr - t_offset
    mask = t_eff > 0.0
    if t_min_val is not None:
        mask &= t_arr >= t_min_val
    if t_max_val is not None:
        mask &= t_arr <= t_max_val

    t_sub = t_eff[mask]
    i_sub = i_arr[mask]
    if t_sub.size < 2:
        raise ValueError(
            f"Cottrell analysis requires at least 2 valid points with t > 0 in the "
            f"selected window; got {t_sub.size}."
        )

    return fit_cottrell(
        time=t_sub,
        current=i_sub,
        method=method,
        n=n,
        area=area,
        c_bulk=c_bulk,
        fit_background=fit_background,
        confidence_level=confidence_level,
    )

analyze_koutecky_levich

analyze_koutecky_levich(results: RDESweepResult | Sequence[TechniqueResult] | Mapping[Any, TechniqueResult] | ArrayLike, currents: ArrayLike | None = None, *, potential: float | None = None, n: float, area: float, c_bulk: float, kinematic_viscosity: float | None = None, method: Literal['linear', 'nonlinear'] = 'linear', confidence_level: float = 0.95) -> KouteckyLevichFitResult

Perform Koutecký–Levich regression (\(|I|^{-1}\) vs. \(\omega^{-1/2}\)).

Evaluates \(I(E, \omega)\) at the chosen electrode potential across a series of RDE sweeps (or accepts raw (omegas, currents) arrays) and delegates to fit_koutecky_levich to separate kinetic current \(I_K\) and mass-transport Levich constant \(B\). Handles both anodic (\(I > 0\)) and cathodic (\(I < 0\)) IUPAC currents cleanly.

Parameters:

Name Type Description Default
results RDESweepResult, Sequence[TechniqueResult], Mapping, or array-like

Multi-rotation-rate RDE simulation results or 1D array of angular rotation velocities \(\omega\) in rad/s (paired with currents).

required
currents array - like

1D array of Faradaic currents \(I\) in Amperes at each rotation rate when results is a raw array of angular velocities.

None
potential float

Electrode potential \(E\) in Volts at which to evaluate \(I(E, \omega)\) across RDE sweeps. Required when results is an RDESweepResult or collection of TechniqueResult.

None
n float

Number of electrons transferred (\(n > 0\)).

required
area float

Disk electrode surface area \(A > 0\) in \(\text{m}^2\) or \(\text{cm}^2\).

required
c_bulk float

Bulk reactant concentration \(c^* > 0\) in matching volume units.

required
kinematic_viscosity float

Electrolyte kinematic viscosity \(\nu > 0\). Inferred from RDE technique metadata when available, defaulting to 1e-6.

None
method ('linear', 'nonlinear')

Regression method forwarded to fit_koutecky_levich.

'linear'
confidence_level float

Confidence level for Student's \(t\) parameter intervals.

0.95

Returns:

Type Description
KouteckyLevichFitResult

Extracted kinetic current \(I_K\), apparent rate constant \(k(E)\), Levich constant \(B\), diffusion coefficient \(D\), and goodness-of-fit statistics.

Source code in src/softpotato/techniques/diagnostics.py
def analyze_koutecky_levich(
    results: RDESweepResult
    | Sequence[TechniqueResult]
    | Mapping[Any, TechniqueResult]
    | ArrayLike,
    currents: ArrayLike | None = None,
    *,
    potential: float | None = None,
    n: float,
    area: float,
    c_bulk: float,
    kinematic_viscosity: float | None = None,
    method: Literal["linear", "nonlinear"] = "linear",
    confidence_level: float = 0.95,
) -> KouteckyLevichFitResult:
    r"""Perform Koutecký–Levich regression (:math:`|I|^{-1}` vs. :math:`\omega^{-1/2}`).

    Evaluates :math:`I(E, \omega)` at the chosen electrode ``potential`` across a
    series of RDE sweeps (or accepts raw ``(omegas, currents)`` arrays) and
    delegates to :func:`~softpotato.analytical.fitting.fit_koutecky_levich` to
    separate kinetic current :math:`I_K` and mass-transport Levich constant
    :math:`B`. Handles both anodic (:math:`I > 0`) and cathodic (:math:`I < 0`)
    IUPAC currents cleanly.

    Parameters
    ----------
    results : RDESweepResult, Sequence[TechniqueResult], Mapping, or array-like
        Multi-rotation-rate RDE simulation results or 1D array of angular
        rotation velocities :math:`\omega` in rad/s (paired with ``currents``).
    currents : array-like, optional
        1D array of Faradaic currents :math:`I` in Amperes at each rotation rate
        when ``results`` is a raw array of angular velocities.
    potential : float, optional
        Electrode potential :math:`E` in Volts at which to evaluate
        :math:`I(E, \omega)` across RDE sweeps. Required when ``results`` is an
        :class:`RDESweepResult` or collection of :class:`TechniqueResult`.
    n : float
        Number of electrons transferred (:math:`n > 0`).
    area : float
        Disk electrode surface area :math:`A > 0` in :math:`\text{m}^2` or
        :math:`\text{cm}^2`.
    c_bulk : float
        Bulk reactant concentration :math:`c^* > 0` in matching volume units.
    kinematic_viscosity : float, optional
        Electrolyte kinematic viscosity :math:`\nu > 0`. Inferred from RDE
        technique metadata when available, defaulting to ``1e-6``.
    method : {'linear', 'nonlinear'}, default 'linear'
        Regression method forwarded to :func:`fit_koutecky_levich`.
    confidence_level : float, default 0.95
        Confidence level for Student's :math:`t` parameter intervals.

    Returns
    -------
    KouteckyLevichFitResult
        Extracted kinetic current :math:`I_K`, apparent rate constant
        :math:`k(E)`, Levich constant :math:`B`, diffusion coefficient :math:`D`,
        and goodness-of-fit statistics.
    """
    if currents is not None:
        w_arr, i_arr = _validate_1d_pair(
            results,  # type: ignore[arg-type]
            currents,
            "omegas",
            "currents",
            min_points=2,
        )
        nu_val = _resolve_kinematic_viscosity(kinematic_viscosity)
    else:
        if potential is None:
            raise ValueError(
                "'potential' must be provided when analyzing RDE simulation results."
            )
        w_arr, i_arr, techs = _extract_rde_series(
            results,  # type: ignore[arg-type]
            potential=potential,
        )
        nu_val = _resolve_kinematic_viscosity(kinematic_viscosity, techs)

    if np.any(i_arr == 0.0):
        raise ValueError("All currents in Koutecký–Levich analysis must be non-zero.")
    if not (np.all(i_arr > 0.0) or np.all(i_arr < 0.0)):
        raise ValueError(
            "All currents in Koutecký–Levich analysis must share the same polarity "
            "(all anodic > 0 or all cathodic < 0)."
        )

    return fit_koutecky_levich(
        current=np.abs(i_arr),
        omega=w_arr,
        method=method,
        n=n,
        area=area,
        c_bulk=c_bulk,
        nu=nu_val,
        confidence_level=confidence_level,
    )

analyze_levich

analyze_levich(results: RDESweepResult | Sequence[TechniqueResult] | Mapping[Any, TechniqueResult] | ArrayLike, limiting_currents: ArrayLike | None = None, *, n: float, area: float, c_bulk: float, kinematic_viscosity: float | None = None, limiting_potential: float | None = None, method: Literal['linear', 'nonlinear'] = 'linear', fit_intercept: bool = False, confidence_level: float = 0.95) -> LevichFitResult

Perform Levich regression (\(I_L\) vs. \(\omega^{1/2}\)) on RDE sweeps.

Accepts an RDESweepResult, a sequence or mapping of RDE TechniqueResult objects, or raw (omegas, limiting_currents) arrays, and delegates to fit_levich.

Parameters:

Name Type Description Default
results RDESweepResult, Sequence[TechniqueResult], Mapping, or array-like

Multi-rotation-rate RDE simulation results or 1D array of angular rotation velocities \(\omega\) in rad/s (paired with limiting_currents).

required
limiting_currents array - like

1D array of limiting currents \(I_L\) in Amperes when results is a raw array of angular velocities.

None
n float

Number of electrons transferred (\(n > 0\)).

required
area float

Disk electrode surface area \(A > 0\) in \(\text{m}^2\) or \(\text{cm}^2\).

required
c_bulk float

Bulk reactant concentration \(c^* > 0\) in matching volume units.

required
kinematic_viscosity float

Electrolyte kinematic viscosity \(\nu > 0\) in \(\text{m}^2/\text{s}\) or \(\text{cm}^2/\text{s}\). If omitted, inferred from the RDE technique metadata when available, defaulting to 1e-6 \(\text{m}^2/\text{s}\).

None
limiting_potential float

Optional electrode potential (in Volts) at which to sample \(I_L\) from each RDE sweep. When None, uses the steady-state terminal current of each sweep.

None
method ('linear', 'nonlinear')

Regression method forwarded to fit_levich.

'linear'
fit_intercept bool

Whether to include a non-zero current offset intercept.

False
confidence_level float

Confidence level for Student's \(t\) parameter intervals.

0.95

Returns:

Type Description
LevichFitResult

Extracted Levich constant \(B\), diffusion coefficient \(D\), standard errors, and goodness-of-fit statistics.

Source code in src/softpotato/techniques/diagnostics.py
def analyze_levich(
    results: RDESweepResult
    | Sequence[TechniqueResult]
    | Mapping[Any, TechniqueResult]
    | ArrayLike,
    limiting_currents: ArrayLike | None = None,
    *,
    n: float,
    area: float,
    c_bulk: float,
    kinematic_viscosity: float | None = None,
    limiting_potential: float | None = None,
    method: Literal["linear", "nonlinear"] = "linear",
    fit_intercept: bool = False,
    confidence_level: float = 0.95,
) -> LevichFitResult:
    r"""Perform Levich regression (:math:`I_L` vs. :math:`\omega^{1/2}`) on RDE sweeps.

    Accepts an :class:`~softpotato.techniques.RDESweepResult`, a sequence or
    mapping of RDE :class:`~softpotato.techniques.TechniqueResult` objects, or
    raw ``(omegas, limiting_currents)`` arrays, and delegates to
    :func:`~softpotato.analytical.fitting.fit_levich`.

    Parameters
    ----------
    results : RDESweepResult, Sequence[TechniqueResult], Mapping, or array-like
        Multi-rotation-rate RDE simulation results or 1D array of angular
        rotation velocities :math:`\omega` in rad/s (paired with
        ``limiting_currents``).
    limiting_currents : array-like, optional
        1D array of limiting currents :math:`I_L` in Amperes when ``results`` is
        a raw array of angular velocities.
    n : float
        Number of electrons transferred (:math:`n > 0`).
    area : float
        Disk electrode surface area :math:`A > 0` in :math:`\text{m}^2` or
        :math:`\text{cm}^2`.
    c_bulk : float
        Bulk reactant concentration :math:`c^* > 0` in matching volume units.
    kinematic_viscosity : float, optional
        Electrolyte kinematic viscosity :math:`\nu > 0` in
        :math:`\text{m}^2/\text{s}` or :math:`\text{cm}^2/\text{s}`. If omitted,
        inferred from the RDE technique metadata when available, defaulting to
        ``1e-6`` :math:`\text{m}^2/\text{s}`.
    limiting_potential : float, optional
        Optional electrode potential (in Volts) at which to sample :math:`I_L`
        from each RDE sweep. When ``None``, uses the steady-state terminal
        current of each sweep.
    method : {'linear', 'nonlinear'}, default 'linear'
        Regression method forwarded to :func:`fit_levich`.
    fit_intercept : bool, default False
        Whether to include a non-zero current offset intercept.
    confidence_level : float, default 0.95
        Confidence level for Student's :math:`t` parameter intervals.

    Returns
    -------
    LevichFitResult
        Extracted Levich constant :math:`B`, diffusion coefficient :math:`D`,
        standard errors, and goodness-of-fit statistics.
    """
    if limiting_currents is not None:
        w_arr, il_arr = _validate_1d_pair(
            results,  # type: ignore[arg-type]
            limiting_currents,
            "omegas",
            "limiting_currents",
            min_points=2,
        )
        nu_val = _resolve_kinematic_viscosity(kinematic_viscosity)
    else:
        w_arr, il_arr, techs = _extract_rde_series(
            results,  # type: ignore[arg-type]
            potential=limiting_potential,
        )
        nu_val = _resolve_kinematic_viscosity(kinematic_viscosity, techs)

    return fit_levich(
        current=il_arr,
        omega=w_arr,
        method=method,
        n=n,
        area=area,
        c_bulk=c_bulk,
        nu=nu_val,
        fit_intercept=fit_intercept,
        confidence_level=confidence_level,
    )

analyze_nicholson

analyze_nicholson(result: TechniqueResult | ArrayLike | float, current: ArrayLike | None = None, *, D: float, scan_rate: float | None = None, n: float = 1, temperature: float = STANDARD_TEMPERATURE, alpha: float = 0.5, cycle: int | None = -1, parabolic: bool = True, method: Literal['swaddle', 'lavagnini', 'table'] = 'swaddle') -> NicholsonDiagnostics

Extract heterogeneous rate constant \(k^0\) via Nicholson analysis.

Detects the anodic and cathodic peaks of a CV trace, computes \(\Delta E_p = |E_{pa} - E_{pc}|\), evaluates the Nicholson kinetic parameter \(\Psi\) and standard rate constant \(k^0\) via nicholson_psi, and classifies the kinetic regime via matsuda_ayabe.

Parameters:

Name Type Description Default
result TechniqueResult, array-like, or float

A CV TechniqueResult, a 1D potential array (paired with current), or a scalar peak-to-peak separation \(\Delta E_p\) in Volts.

required
current array - like

1D Faradaic current array in Amperes when result is a potential array.

None
D float

Diffusion coefficient (\(D > 0\)).

required
scan_rate float

Potential scan rate \(v > 0\) in V/s. Inferred automatically from result.technique.scan_rate when result is a CV TechniqueResult.

None
n float

Number of electrons transferred (\(n > 0\)).

1
temperature float

Absolute temperature \(T > 0\) in Kelvin.

298.15
alpha float

Charge-transfer coefficient \(0 < \alpha < 1\) forwarded to matsuda_ayabe.

0.5
cycle int or None

CV cycle index to inspect when result is a TechniqueResult.

-1
parabolic bool

Whether to use 3-point parabolic interpolation for peak refinement.

True
method ('swaddle', 'lavagnini', 'table')

Nicholson working curve approximation passed to nicholson_psi.

'swaddle'

Returns:

Type Description
NicholsonDiagnostics

Container with \(\Delta E_p\), \(\Psi\), \(k^0\), \(\Lambda\), Matsuda–Ayabe regime classification, and detected peaks.

Source code in src/softpotato/techniques/diagnostics.py
def analyze_nicholson(
    result: TechniqueResult | ArrayLike | float,
    current: ArrayLike | None = None,
    *,
    D: float,
    scan_rate: float | None = None,
    n: float = 1,
    temperature: float = STANDARD_TEMPERATURE,
    alpha: float = 0.5,
    cycle: int | None = -1,
    parabolic: bool = True,
    method: Literal["swaddle", "lavagnini", "table"] = "swaddle",
) -> NicholsonDiagnostics:
    r"""Extract heterogeneous rate constant :math:`k^0` via Nicholson analysis.

    Detects the anodic and cathodic peaks of a CV trace, computes
    :math:`\Delta E_p = |E_{pa} - E_{pc}|`, evaluates the Nicholson kinetic
    parameter :math:`\Psi` and standard rate constant :math:`k^0` via
    :func:`~softpotato.analytical.voltammetry.nicholson_psi`, and classifies the
    kinetic regime via :func:`~softpotato.analytical.voltammetry.matsuda_ayabe`.

    Parameters
    ----------
    result : TechniqueResult, array-like, or float
        A CV :class:`~softpotato.techniques.TechniqueResult`, a 1D potential
        array (paired with ``current``), or a scalar peak-to-peak separation
        :math:`\Delta E_p` in Volts.
    current : array-like, optional
        1D Faradaic current array in Amperes when ``result`` is a potential array.
    D : float
        Diffusion coefficient (:math:`D > 0`).
    scan_rate : float, optional
        Potential scan rate :math:`v > 0` in V/s. Inferred automatically from
        ``result.technique.scan_rate`` when ``result`` is a CV
        :class:`TechniqueResult`.
    n : float, default 1
        Number of electrons transferred (:math:`n > 0`).
    temperature : float, default 298.15
        Absolute temperature :math:`T > 0` in Kelvin.
    alpha : float, default 0.5
        Charge-transfer coefficient :math:`0 < \alpha < 1` forwarded to
        :func:`~softpotato.analytical.voltammetry.matsuda_ayabe`.
    cycle : int or None, default -1
        CV cycle index to inspect when ``result`` is a :class:`TechniqueResult`.
    parabolic : bool, default True
        Whether to use 3-point parabolic interpolation for peak refinement.
    method : {'swaddle', 'lavagnini', 'table'}, default 'swaddle'
        Nicholson working curve approximation passed to :func:`nicholson_psi`.

    Returns
    -------
    NicholsonDiagnostics
        Container with :math:`\Delta E_p`, :math:`\Psi`, :math:`k^0`,
        :math:`\Lambda`, Matsuda–Ayabe regime classification, and detected peaks.
    """
    peaks: CVDiagnostics | None = None
    if isinstance(result, TechniqueResult):
        if current is not None:
            raise ValueError(
                "Do not pass 'current' when the first argument is a TechniqueResult."
            )
        if scan_rate is None:
            inferred_v = getattr(result.technique, "scan_rate", None)
            if inferred_v is None:
                raise ValueError(
                    "Could not infer 'scan_rate' from technique "
                    f"{type(result.technique).__name__}; pass 'scan_rate' explicitly."
                )
            v_val = _validate_positive_finite(inferred_v, "scan_rate")
        else:
            v_val = _validate_positive_finite(scan_rate, "scan_rate")

        peaks = find_peaks(result, cycle=cycle, parabolic=parabolic)
        if peaks.delta_Ep is None:
            raise ValueError(
                "Nicholson analysis requires both an anodic and a cathodic peak; "
                f"detected anodic={peaks.anodic_peak is not None}, "
                f"cathodic={peaks.cathodic_peak is not None}."
            )
        delta_ep = peaks.delta_Ep
    elif current is not None:
        if scan_rate is None:
            raise ValueError(
                "'scan_rate' must be provided when analyzing raw (E, I) arrays."
            )
        v_val = _validate_positive_finite(scan_rate, "scan_rate")
        peaks = find_peaks(result, current, parabolic=parabolic)
        if peaks.delta_Ep is None:
            raise ValueError(
                "Nicholson analysis requires both an anodic and a cathodic peak."
            )
        delta_ep = peaks.delta_Ep
    elif isinstance(result, (int, float, np.number)) and not isinstance(result, bool):
        if scan_rate is None:
            raise ValueError(
                "'scan_rate' must be provided when passing scalar 'delta_Ep'."
            )
        v_val = _validate_positive_finite(scan_rate, "scan_rate")
        delta_ep = _validate_positive_finite(float(result), "delta_Ep")
    else:
        raise TypeError(
            "result must be a TechniqueResult, a potential array paired with 'current', "
            f"or a scalar delta_Ep in Volts, got {type(result).__name__}."
        )

    nich_res = nicholson_psi(
        delta_ep=delta_ep,
        v=v_val,
        D=D,
        n=n,
        T=temperature,
        in_volts=True,
        method=method,
    )
    assert isinstance(nich_res, NicholsonResult) and nich_res.k0 is not None

    ma_res = matsuda_ayabe(
        k0=nich_res.k0,
        v=v_val,
        D=D,
        n=n,
        alpha=alpha,
        T=temperature,
    )

    return NicholsonDiagnostics(
        delta_Ep=nich_res.delta_ep,
        delta_Ep_mv=nich_res.delta_ep_mv,
        psi=nich_res.psi,
        k0=nich_res.k0,
        lambda_param=ma_res.lambda_param,
        regime=ma_res.classification,
        nicholson=nich_res,
        matsuda_ayabe=ma_res,
        peaks=peaks,
    )

analyze_randles_sevcik

analyze_randles_sevcik(results: Sequence[TechniqueResult] | Mapping[Any, TechniqueResult] | ArrayLike, peak_currents: ArrayLike | None = None, *, n: float, area: float, c_bulk: float, temperature: float = STANDARD_TEMPERATURE, polarity: PeakPolarity = 'cathodic', cycle: int | None = -1, parabolic: bool = True, method: Literal['linear', 'nonlinear'] = 'linear', model: Literal['reversible', 'irreversible'] = 'reversible', alpha: float = 0.5, n_alpha: float = 1, fit_intercept: bool = True, confidence_level: float = 0.95) -> RandlesSevcikFitResult

Perform multi-scan-rate Randles–Ševčík regression to extract diffusivity \(D\).

Extracts peak currents \(I_p\) and scan rates \(v\) from a series of CV or LSV TechniqueResult objects (or accepts raw (scan_rates, peak_currents) arrays directly) and delegates to fit_randles_sevcik.

Parameters:

Name Type Description Default
results Sequence[TechniqueResult], Mapping[Any, TechniqueResult], or array-like

Collection of CV/LSV simulation results (e.g., from simulate_sweep) or a 1D array of scan rates \(v\) in V/s when peak_currents is supplied.

required
peak_currents array - like

1D array of peak currents \(I_p\) in Amperes when results is a raw array of scan rates.

None
n float

Number of electrons transferred (\(n > 0\)).

required
area float

Electrode surface area \(A > 0\) in \(\text{m}^2\) or \(\text{cm}^2\).

required
c_bulk float

Bulk reactant concentration \(c^* > 0\) in matching volume units.

required
temperature float

Absolute temperature \(T > 0\) in Kelvin.

298.15
polarity ('cathodic', 'anodic')

Peak polarity to extract from each voltammogram.

'cathodic'
cycle int or None

CV cycle index to inspect (ignored for LSV or raw arrays).

-1
parabolic bool

Whether to use parabolic sub-sample peak refinement.

True
method ('linear', 'nonlinear')

Regression method passed to fit_randles_sevcik.

'linear'
model ('reversible', 'irreversible')

Reversibility model passed to fit_randles_sevcik.

'reversible'
alpha float

Charge-transfer coefficient for irreversible model.

0.5
n_alpha float

Electrons transferred up to the rate-determining step (irreversible model).

1
fit_intercept bool

Whether to fit a non-zero current intercept.

True
confidence_level float

Confidence level for Student's \(t\) parameter intervals.

0.95

Returns:

Type Description
RandlesSevcikFitResult

Fitted diffusion coefficient \(D\), slope, intercept, standard errors, and goodness-of-fit metrics.

Source code in src/softpotato/techniques/diagnostics.py
def analyze_randles_sevcik(
    results: Sequence[TechniqueResult] | Mapping[Any, TechniqueResult] | ArrayLike,
    peak_currents: ArrayLike | None = None,
    *,
    n: float,
    area: float,
    c_bulk: float,
    temperature: float = STANDARD_TEMPERATURE,
    polarity: PeakPolarity = "cathodic",
    cycle: int | None = -1,
    parabolic: bool = True,
    method: Literal["linear", "nonlinear"] = "linear",
    model: Literal["reversible", "irreversible"] = "reversible",
    alpha: float = 0.5,
    n_alpha: float = 1,
    fit_intercept: bool = True,
    confidence_level: float = 0.95,
) -> RandlesSevcikFitResult:
    r"""Perform multi-scan-rate Randles–Ševčík regression to extract diffusivity :math:`D`.

    Extracts peak currents :math:`I_p` and scan rates :math:`v` from a series of
    CV or LSV :class:`~softpotato.techniques.TechniqueResult` objects (or accepts
    raw ``(scan_rates, peak_currents)`` arrays directly) and delegates to
    :func:`~softpotato.analytical.fitting.fit_randles_sevcik`.

    Parameters
    ----------
    results : Sequence[TechniqueResult], Mapping[Any, TechniqueResult], or array-like
        Collection of CV/LSV simulation results (e.g., from
        :func:`~softpotato.techniques.simulate_sweep`) or a 1D array of scan
        rates :math:`v` in V/s when ``peak_currents`` is supplied.
    peak_currents : array-like, optional
        1D array of peak currents :math:`I_p` in Amperes when ``results`` is a
        raw array of scan rates.
    n : float
        Number of electrons transferred (:math:`n > 0`).
    area : float
        Electrode surface area :math:`A > 0` in :math:`\text{m}^2` or
        :math:`\text{cm}^2`.
    c_bulk : float
        Bulk reactant concentration :math:`c^* > 0` in matching volume units.
    temperature : float, default 298.15
        Absolute temperature :math:`T > 0` in Kelvin.
    polarity : {'cathodic', 'anodic'}, default 'cathodic'
        Peak polarity to extract from each voltammogram.
    cycle : int or None, default -1
        CV cycle index to inspect (ignored for LSV or raw arrays).
    parabolic : bool, default True
        Whether to use parabolic sub-sample peak refinement.
    method : {'linear', 'nonlinear'}, default 'linear'
        Regression method passed to :func:`fit_randles_sevcik`.
    model : {'reversible', 'irreversible'}, default 'reversible'
        Reversibility model passed to :func:`fit_randles_sevcik`.
    alpha : float, default 0.5
        Charge-transfer coefficient for irreversible model.
    n_alpha : float, default 1
        Electrons transferred up to the rate-determining step (irreversible model).
    fit_intercept : bool, default True
        Whether to fit a non-zero current intercept.
    confidence_level : float, default 0.95
        Confidence level for Student's :math:`t` parameter intervals.

    Returns
    -------
    RandlesSevcikFitResult
        Fitted diffusion coefficient :math:`D`, slope, intercept, standard
        errors, and goodness-of-fit metrics.
    """
    if polarity not in ("cathodic", "anodic"):
        raise ValueError(f"polarity must be 'cathodic' or 'anodic', got {polarity!r}.")

    if peak_currents is not None:
        v_arr, ip_arr = _validate_1d_pair(
            results,  # type: ignore[arg-type]
            peak_currents,
            "scan_rates",
            "peak_currents",
            min_points=2,
        )
    else:
        items: list[tuple[Any, Any]]
        if isinstance(results, Mapping):
            if len(results) == 0:
                raise ValueError("'results' mapping must not be empty.")
            items = list(results.items())
        elif isinstance(results, Sequence) and not isinstance(results, (str, bytes)):
            if len(results) == 0:
                raise ValueError("'results' sequence must not be empty.")
            items = [(None, r) for r in results]
        else:
            raise TypeError(
                "results must be a sequence/mapping of TechniqueResult objects "
                "or a scan-rate array paired with 'peak_currents'."
            )

        v_list: list[float] = []
        ip_list: list[float] = []
        for idx, (key, res) in enumerate(items):
            if not isinstance(res, TechniqueResult):
                raise TypeError(
                    f"Expected TechniqueResult at index {idx}, got {type(res).__name__}."
                )
            v_val = getattr(res.technique, "scan_rate", None)
            if v_val is None:
                if isinstance(key, (int, float, np.number)) and not isinstance(
                    key, bool
                ):
                    v_val = float(key)
                else:
                    raise ValueError(
                        f"Could not infer 'scan_rate' from technique "
                        f"{type(res.technique).__name__} at index {idx}."
                    )
            v_list.append(_validate_positive_finite(v_val, "scan_rate"))

            diag = find_peaks(res, cycle=cycle, parabolic=parabolic, polarity=polarity)
            peak = diag.cathodic_peak if polarity == "cathodic" else diag.anodic_peak
            if peak is None:
                raise ValueError(
                    f"No {polarity} peak detected in result at index {idx} "
                    f"(scan_rate={v_val!r} V/s)."
                )
            ip_list.append(peak.I_peak)

        v_arr = np.asarray(v_list, dtype=float)
        ip_arr = np.asarray(ip_list, dtype=float)

    return fit_randles_sevcik(
        scan_rate=v_arr,
        peak_current=ip_arr,
        method=method,
        model=model,
        n=n,
        area=area,
        c_bulk=c_bulk,
        alpha=alpha,
        n_alpha=n_alpha,
        T=temperature,
        fit_intercept=fit_intercept,
        confidence_level=confidence_level,
    )

analyze_sand

analyze_sand(result: TechniqueResult | ArrayLike, signal: ArrayLike | None = None, *, n: float, area: float, c_bulk: float, threshold: float = 0.001, D: float | None = None, current: float | None = None, species: str | None = None, signal_kind: Literal['auto', 'concentration', 'potential'] = 'auto', relative: bool = True, F: float = FARADAY) -> SandDiagnostics

Detect chronopotentiometric transition time \(\tau\) and run Sand analysis.

Detects the transition time \(\tau\) from reactant surface concentration depletion (via detect_transition_time) or from the potential inflection point \(\max |dE/dt|\), computes the experimental Sand product \(|I|\sqrt{\tau}\) and estimated diffusion coefficient \(D\), and optionally compares against sand_transition_time.

Parameters:

Name Type Description Default
result TechniqueResult or array - like

A chronopotentiometric TechniqueResult or a 1D time array \(t\) in seconds (paired with signal).

required
signal array - like

1D surface concentration \(c(0, t)\) or electrode potential \(E(t)\) array when result is a raw time array.

None
n float

Number of electrons transferred (\(n > 0\)).

required
area float

Electrode surface area \(A > 0\) in \(\text{m}^2\) or \(\text{cm}^2\).

required
c_bulk float

Bulk reactant concentration \(c^* > 0\) in matching volume units.

required
threshold float

Surface concentration depletion threshold forwarded to Chronopotentiometry.detect_transition_time.

1e-3
D float

Known diffusion coefficient (\(D > 0\)) for computing theoretical Sand transition time \(\tau_{\text{th}}\) and relative error.

None
current float

Applied constant current \(I \neq 0\) in Amperes. Inferred automatically from result when a TechniqueResult is passed; required when raw arrays are passed.

None
species str

Reactant species name to inspect in result.concentrations. Defaults to result.metadata['reactant_species'] or the first species with positive initial surface concentration.

None
signal_kind ('auto', 'concentration', 'potential')

Signal source used for transition time detection.

'auto'
relative bool

Whether threshold is relative to initial surface concentration.

True
F float

Faraday constant in \(\text{C}/\text{mol}\).

FARADAY

Returns:

Type Description
SandDiagnostics

Detected \(\tau\), theoretical \(\tau\) (if D supplied), relative error, Sand constant \(|I|\sqrt{\tau}\), estimated \(D\), applied current, and detection method.

Source code in src/softpotato/techniques/diagnostics.py
def analyze_sand(
    result: TechniqueResult | ArrayLike,
    signal: ArrayLike | None = None,
    *,
    n: float,
    area: float,
    c_bulk: float,
    threshold: float = 1e-3,
    D: float | None = None,
    current: float | None = None,
    species: str | None = None,
    signal_kind: Literal["auto", "concentration", "potential"] = "auto",
    relative: bool = True,
    F: float = FARADAY,
) -> SandDiagnostics:
    r"""Detect chronopotentiometric transition time :math:`\tau` and run Sand analysis.

    Detects the transition time :math:`\tau` from reactant surface concentration
    depletion (via :meth:`~softpotato.techniques.Chronopotentiometry.detect_transition_time`)
    or from the potential inflection point :math:`\max |dE/dt|`, computes the
    experimental Sand product :math:`|I|\sqrt{\tau}` and estimated diffusion
    coefficient :math:`D`, and optionally compares against
    :func:`~softpotato.analytical.step.sand_transition_time`.

    Parameters
    ----------
    result : TechniqueResult or array-like
        A chronopotentiometric :class:`~softpotato.techniques.TechniqueResult`
        or a 1D time array :math:`t` in seconds (paired with ``signal``).
    signal : array-like, optional
        1D surface concentration :math:`c(0, t)` or electrode potential
        :math:`E(t)` array when ``result`` is a raw time array.
    n : float
        Number of electrons transferred (:math:`n > 0`).
    area : float
        Electrode surface area :math:`A > 0` in :math:`\text{m}^2` or
        :math:`\text{cm}^2`.
    c_bulk : float
        Bulk reactant concentration :math:`c^* > 0` in matching volume units.
    threshold : float, default 1e-3
        Surface concentration depletion threshold forwarded to
        :meth:`Chronopotentiometry.detect_transition_time`.
    D : float, optional
        Known diffusion coefficient (:math:`D > 0`) for computing theoretical
        Sand transition time :math:`\tau_{\text{th}}` and relative error.
    current : float, optional
        Applied constant current :math:`I \neq 0` in Amperes. Inferred
        automatically from ``result`` when a :class:`TechniqueResult` is passed;
        required when raw arrays are passed.
    species : str, optional
        Reactant species name to inspect in ``result.concentrations``. Defaults
        to ``result.metadata['reactant_species']`` or the first species with
        positive initial surface concentration.
    signal_kind : {'auto', 'concentration', 'potential'}, default 'auto'
        Signal source used for transition time detection.
    relative : bool, default True
        Whether ``threshold`` is relative to initial surface concentration.
    F : float, default FARADAY
        Faraday constant in :math:`\text{C}/\text{mol}`.

    Returns
    -------
    SandDiagnostics
        Detected :math:`\tau`, theoretical :math:`\tau` (if ``D`` supplied),
        relative error, Sand constant :math:`|I|\sqrt{\tau}`, estimated
        :math:`D`, applied current, and detection method.
    """
    n_val = _validate_positive_finite(n, "n")
    area_val = _validate_positive_finite(area, "area")
    c_bulk_val = _validate_positive_finite(c_bulk, "c_bulk")
    f_val = _validate_positive_finite(F, "F")
    if D is not None:
        d_val: float | None = _validate_positive_finite(D, "D")
    else:
        d_val = None

    if signal_kind not in ("auto", "concentration", "potential"):
        raise ValueError(
            "signal_kind must be 'auto', 'concentration', or 'potential', "
            f"got {signal_kind!r}."
        )

    tau: float | None = None
    detection_method: Literal["concentration", "potential", "none"] = "none"

    if isinstance(result, TechniqueResult):
        if signal is not None:
            raise ValueError(
                "Do not pass 'signal' when the first argument is a TechniqueResult."
            )
        t_arr = np.asarray(result.time, dtype=float)
        if current is not None:
            i_val = _validate_finite_real(current, "current")
        elif isinstance(result.technique, Chronopotentiometry):
            nonzero_i = [v for v in result.technique.currents if v != 0.0]
            if not nonzero_i:
                raise ValueError(
                    "Applied current cannot be zero in Sand chronopotentiometry analysis."
                )
            i_val = float(nonzero_i[0])
        else:
            nz = result.current[result.current != 0.0]
            if nz.size == 0:
                raise ValueError(
                    "Applied current cannot be zero in Sand chronopotentiometry analysis."
                )
            i_val = float(nz[0])

        if i_val == 0.0:
            raise ValueError("Applied current I cannot be zero in the Sand equation.")

        # 1. Surface concentration depletion detection
        if signal_kind in ("auto", "concentration"):
            sp_name = species or result.metadata.get("reactant_species")
            if sp_name is None:
                for cand in result.species:
                    if float(result.concentrations[cand][0, 0]) > 0.0:
                        sp_name = cand
                        break
            if sp_name is not None and sp_name in result.concentrations:
                c_surf = np.asarray(result.concentrations[sp_name][:, 0], dtype=float)
                if not relative or c_surf[0] > 0.0:
                    tau = Chronopotentiometry.detect_transition_time(
                        t_arr, c_surf, threshold=threshold, relative=relative
                    )
                    if tau is not None:
                        detection_method = "concentration"

        # 2. Fallback or explicit potential inflection detection
        if tau is None and signal_kind in ("auto", "potential"):
            pot_arr = np.asarray(result.potential, dtype=float)
            tau = _detect_potential_inflection(t_arr, pot_arr)
            if tau is not None:
                detection_method = "potential"
    else:
        if signal is None:
            raise ValueError(
                "'signal' must be provided when the first argument is a time array."
            )
        if current is None:
            raise ValueError(
                "'current' must be provided when analyzing raw (t, signal) arrays."
            )
        i_val = _validate_finite_real(current, "current")
        if i_val == 0.0:
            raise ValueError("Applied current I cannot be zero in the Sand equation.")

        if signal_kind == "potential":
            t_arr, pot_arr = _validate_1d_pair(
                result, signal, "t", "potential", min_points=2, require_finite=False
            )
            if not np.all(np.isfinite(t_arr)) or np.any(np.diff(t_arr) <= 0.0):
                raise ValueError("'t' must be finite and strictly increasing.")
            tau = _detect_potential_inflection(t_arr, pot_arr)
            if tau is not None:
                detection_method = "potential"
        else:
            t_arr, c_surf = _validate_1d_pair(
                result, signal, "t", "c_surface", min_points=2
            )
            tau = Chronopotentiometry.detect_transition_time(
                t_arr, c_surf, threshold=threshold, relative=relative
            )
            if tau is not None:
                detection_method = "concentration"

    tau_th = (
        sand_transition_time(
            I=i_val, n=n_val, D=d_val, c_bulk=c_bulk_val, area=area_val, F=f_val
        )
        if d_val is not None
        else None
    )

    if tau is not None and tau > 0.0:
        sand_const: float | None = float(abs(i_val) * math.sqrt(tau))
        denom = math.pi * ((n_val * f_val * area_val * c_bulk_val) ** 2)
        d_est: float | None = float(4.0 * (i_val**2) * tau / denom)
        rel_err: float | None = (
            float(abs(tau - tau_th) / tau_th) if tau_th is not None else None
        )
    else:
        sand_const = None
        d_est = None
        rel_err = None

    return SandDiagnostics(
        tau=tau,
        tau_theoretical=tau_th,
        relative_error=rel_err,
        sand_constant=sand_const,
        D_estimated=d_est,
        current=i_val,
        detection_method=detection_method,
    )

analyze_tafel

analyze_tafel(result: TechniqueResult | ArrayLike, current: ArrayLike | None = None, *, E0: float, overpotential_window: tuple[float, float] | None = None, branch: PeakPolarity = 'cathodic', temperature: float = STANDARD_TEMPERATURE, n: float = 1, area: float | None = None, c_bulk: float | None = None, cycle: int | None = -1, confidence_level: float = 0.95) -> TafelFitResult

Extract Tafel slope, transfer coefficient, and exchange current.

Computes overpotential \(\eta = E - E^{0\prime}\) and delegates to fit_tafel on the selected kinetic branch ('cathodic' for \(\eta < 0\), 'anodic' for \(\eta > 0\)).

Parameters:

Name Type Description Default
result TechniqueResult or array - like

A voltammetric TechniqueResult or a 1D electrode potential array \(E\) in Volts (paired with current).

required
current array - like

1D Faradaic current array \(I\) in Amperes when result is a potential array.

None
E0 float

Formal / equilibrium potential \(E^{0\prime}\) in Volts used to compute \(\eta = E - E^{0\prime}\).

required
overpotential_window tuple of (float, float)

Signed overpotential interval (eta_min, eta_max) in Volts over which to fit (e.g., (-0.20, -0.06) for the cathodic branch or (0.06, 0.20) for the anodic branch).

None
branch ('cathodic', 'anodic')

Kinetic polarization branch to fit.

'cathodic'
temperature float

Absolute temperature \(T > 0\) in Kelvin.

298.15
n float

Number of electrons transferred (\(n > 0\)).

1
area float

Electrode surface area \(A > 0\) (if provided alongside c_bulk, extracts \(k^0\)).

None
c_bulk float

Bulk concentration \(c^* > 0\) (if provided alongside area, extracts \(k^0\)).

None
cycle int or None

CV cycle index to inspect when result is a CV TechniqueResult.

-1
confidence_level float

Confidence level for Student's \(t\) parameter intervals.

0.95

Returns:

Type Description
TafelFitResult

Extracted exchange current \(I_0\), Tafel slope \(b\) (in V/dec and mV/dec), charge-transfer coefficient \(\alpha\), optional \(k^0\), and goodness-of-fit statistics.

Source code in src/softpotato/techniques/diagnostics.py
def analyze_tafel(
    result: TechniqueResult | ArrayLike,
    current: ArrayLike | None = None,
    *,
    E0: float,
    overpotential_window: tuple[float, float] | None = None,
    branch: PeakPolarity = "cathodic",
    temperature: float = STANDARD_TEMPERATURE,
    n: float = 1,
    area: float | None = None,
    c_bulk: float | None = None,
    cycle: int | None = -1,
    confidence_level: float = 0.95,
) -> TafelFitResult:
    r"""Extract Tafel slope, transfer coefficient, and exchange current.

    Computes overpotential :math:`\eta = E - E^{0\prime}` and delegates to
    :func:`~softpotato.analytical.fitting.fit_tafel` on the selected kinetic
    branch (``'cathodic'`` for :math:`\eta < 0`, ``'anodic'`` for :math:`\eta > 0`).

    Parameters
    ----------
    result : TechniqueResult or array-like
        A voltammetric :class:`~softpotato.techniques.TechniqueResult` or a 1D
        electrode potential array :math:`E` in Volts (paired with ``current``).
    current : array-like, optional
        1D Faradaic current array :math:`I` in Amperes when ``result`` is a
        potential array.
    E0 : float
        Formal / equilibrium potential :math:`E^{0\prime}` in Volts used to
        compute :math:`\eta = E - E^{0\prime}`.
    overpotential_window : tuple of (float, float), optional
        Signed overpotential interval ``(eta_min, eta_max)`` in Volts over which
        to fit (e.g., ``(-0.20, -0.06)`` for the cathodic branch or
        ``(0.06, 0.20)`` for the anodic branch).
    branch : {'cathodic', 'anodic'}, default 'cathodic'
        Kinetic polarization branch to fit.
    temperature : float, default 298.15
        Absolute temperature :math:`T > 0` in Kelvin.
    n : float, default 1
        Number of electrons transferred (:math:`n > 0`).
    area : float, optional
        Electrode surface area :math:`A > 0` (if provided alongside ``c_bulk``,
        extracts :math:`k^0`).
    c_bulk : float, optional
        Bulk concentration :math:`c^* > 0` (if provided alongside ``area``,
        extracts :math:`k^0`).
    cycle : int or None, default -1
        CV cycle index to inspect when ``result`` is a CV
        :class:`TechniqueResult`.
    confidence_level : float, default 0.95
        Confidence level for Student's :math:`t` parameter intervals.

    Returns
    -------
    TafelFitResult
        Extracted exchange current :math:`I_0`, Tafel slope :math:`b` (in V/dec
        and mV/dec), charge-transfer coefficient :math:`\alpha`, optional
        :math:`k^0`, and goodness-of-fit statistics.
    """
    e0_val = _validate_finite_real(E0, "E0")
    e_arr, i_arr = _extract_potential_current(result, current, cycle=cycle)

    # For CV TechniqueResult, isolate the forward leg so reverse-scan diffusion
    # depletion does not contaminate the Tafel regression at overlapping potentials.
    if isinstance(result, TechniqueResult) and isinstance(
        result.technique, CyclicVoltammetry
    ):
        de = np.diff(e_arr)
        nonzero = np.flatnonzero(de != 0.0)
        if nonzero.size > 0:
            first_sign = 1.0 if de[nonzero[0]] > 0.0 else -1.0
            reversals = np.flatnonzero(de * first_sign < 0.0)
            if reversals.size > 0:
                end_idx = int(reversals[0]) + 1
                e_arr = e_arr[:end_idx]
                i_arr = i_arr[:end_idx]

    eta = e_arr - e0_val
    return fit_tafel(
        overpotential=eta,
        current=i_arr,
        branch=branch,
        fit_range=overpotential_window,
        area=area,
        c_bulk=c_bulk,
        n=n,
        T=temperature,
        confidence_level=confidence_level,
    )

find_peaks

find_peaks(result_or_E: TechniqueResult | ArrayLike, current: ArrayLike | None = None, *, cycle: int | None = -1, parabolic: bool = True, prominence: float | None = None, min_current: float = 0.0, distance: int | None = None, polarity: Literal['both', 'anodic', 'cathodic'] = 'both', return_all: Literal[False] = False) -> CVDiagnostics
find_peaks(result_or_E: TechniqueResult | ArrayLike, current: ArrayLike | None = None, *, cycle: int | None = -1, parabolic: bool = True, prominence: float | None = None, min_current: float = 0.0, distance: int | None = None, polarity: Literal['both', 'anodic', 'cathodic'] = 'both', return_all: Literal[True]) -> list[PeakInfo]
find_peaks(result_or_E: TechniqueResult | ArrayLike, current: ArrayLike | None = None, *, cycle: int | None = -1, parabolic: bool = True, prominence: float | None = None, min_current: float = 0.0, distance: int | None = None, polarity: Literal['both', 'anodic', 'cathodic'] = 'both', return_all: bool = False) -> CVDiagnostics | list[PeakInfo]

Detect anodic and cathodic voltammetric peaks under IUPAC polarity conventions.

Identifies interior local maxima (\(I > 0\), anodic) and local minima (\(I < 0\), cathodic) in a voltammogram, optionally refining peak potential \(E_p\) and peak current \(I_p\) via 3-point parabolic interpolation and computing the rising-flank half-peak potential \(E_{p/2}\).

Parameters:

Name Type Description Default
result_or_E TechniqueResult or array - like

Either a TechniqueResult (CV, LSV, SWV, DPV, etc.) or a 1D array of electrode potentials \(E\) in Volts.

required
current array - like

1D array of Faradaic currents \(I\) in Amperes (required when result_or_E is a raw potential array; must be None when a TechniqueResult is passed).

None
cycle int or None

Cycle index to analyze when result_or_E is a CyclicVoltammetry result (-1 selects the last cycle; None analyzes the full multi-cycle trace).

-1
parabolic bool

If True, refine \(E_p\) and \(I_p\) using 3-point quadratic interpolation around the discrete grid extremum.

True
prominence float

Minimum peak prominence (in Amperes) forwarded to scipy.signal.find_peaks.

None
min_current float

Minimum absolute current threshold (\(|I_p| > \text{min\_current}\)) for a peak to be accepted.

0.0
distance int

Minimum sample separation between adjacent peaks of the same polarity.

None
polarity ('both', 'anodic', 'cathodic')

Which peak polarities to search for.

'both'
return_all bool

If False (default), returns a CVDiagnostics summary containing the dominant anodic and cathodic peaks plus \(\Delta E_p\), \(E_{1/2}\), and \(|I_{pa}/I_{pc}|\). If True, returns a list of all detected PeakInfo objects ordered by sample index.

False

Returns:

Type Description
CVDiagnostics or list[PeakInfo]

Voltammetric peak diagnostics summary or full list of detected peaks.

Source code in src/softpotato/techniques/diagnostics.py
def find_peaks(
    result_or_E: TechniqueResult | ArrayLike,
    current: ArrayLike | None = None,
    *,
    cycle: int | None = -1,
    parabolic: bool = True,
    prominence: float | None = None,
    min_current: float = 0.0,
    distance: int | None = None,
    polarity: Literal["both", "anodic", "cathodic"] = "both",
    return_all: bool = False,
) -> CVDiagnostics | list[PeakInfo]:
    r"""Detect anodic and cathodic voltammetric peaks under IUPAC polarity conventions.

    Identifies interior local maxima (:math:`I > 0`, anodic) and local minima
    (:math:`I < 0`, cathodic) in a voltammogram, optionally refining peak
    potential :math:`E_p` and peak current :math:`I_p` via 3-point parabolic
    interpolation and computing the rising-flank half-peak potential
    :math:`E_{p/2}`.

    Parameters
    ----------
    result_or_E : TechniqueResult or array-like
        Either a :class:`~softpotato.techniques.TechniqueResult` (CV, LSV, SWV,
        DPV, etc.) or a 1D array of electrode potentials :math:`E` in Volts.
    current : array-like, optional
        1D array of Faradaic currents :math:`I` in Amperes (required when
        ``result_or_E`` is a raw potential array; must be ``None`` when a
        :class:`TechniqueResult` is passed).
    cycle : int or None, default -1
        Cycle index to analyze when ``result_or_E`` is a
        :class:`~softpotato.techniques.CyclicVoltammetry` result (``-1`` selects
        the last cycle; ``None`` analyzes the full multi-cycle trace).
    parabolic : bool, default True
        If ``True``, refine :math:`E_p` and :math:`I_p` using 3-point quadratic
        interpolation around the discrete grid extremum.
    prominence : float, optional
        Minimum peak prominence (in Amperes) forwarded to
        :func:`scipy.signal.find_peaks`.
    min_current : float, default 0.0
        Minimum absolute current threshold (:math:`|I_p| > \text{min\_current}`)
        for a peak to be accepted.
    distance : int, optional
        Minimum sample separation between adjacent peaks of the same polarity.
    polarity : {'both', 'anodic', 'cathodic'}, default 'both'
        Which peak polarities to search for.
    return_all : bool, default False
        If ``False`` (default), returns a :class:`CVDiagnostics` summary
        containing the dominant anodic and cathodic peaks plus
        :math:`\Delta E_p`, :math:`E_{1/2}`, and :math:`|I_{pa}/I_{pc}|`.
        If ``True``, returns a list of all detected :class:`PeakInfo` objects
        ordered by sample index.

    Returns
    -------
    CVDiagnostics or list[PeakInfo]
        Voltammetric peak diagnostics summary or full list of detected peaks.
    """
    if polarity not in ("both", "anodic", "cathodic"):
        raise ValueError(
            f"polarity must be 'both', 'anodic', or 'cathodic', got {polarity!r}."
        )
    if min_current < 0.0 or not math.isfinite(min_current):
        raise ValueError(
            f"min_current must be finite and non-negative, got {min_current!r}."
        )

    e_arr, i_arr = _extract_potential_current(result_or_E, current, cycle=cycle)

    peak_kwargs: dict[str, Any] = {}
    if prominence is not None:
        peak_kwargs["prominence"] = _validate_positive_finite(prominence, "prominence")
    if distance is not None:
        peak_kwargs["distance"] = distance

    anodic_peaks: list[PeakInfo] = []
    cathodic_peaks: list[PeakInfo] = []

    if e_arr.size >= 3:
        if polarity in ("both", "anodic"):
            an_indices, _ = _scipy_find_peaks(i_arr, height=min_current, **peak_kwargs)
            for raw_idx in an_indices:
                idx = int(raw_idx)
                if float(i_arr[idx]) <= min_current:
                    continue
                if parabolic:
                    e_p, i_p = _parabolic_refine(e_arr, i_arr, idx, "anodic")
                else:
                    e_p, i_p = float(e_arr[idx]), float(i_arr[idx])
                e_half_p = _find_half_peak_potential(e_arr, i_arr, idx, i_p, "anodic")
                anodic_peaks.append(
                    PeakInfo(
                        E_peak=e_p,
                        I_peak=i_p,
                        index=idx,
                        E_half_peak=e_half_p,
                        polarity="anodic",
                    )
                )

        if polarity in ("both", "cathodic"):
            cat_indices, _ = _scipy_find_peaks(
                -i_arr, height=min_current, **peak_kwargs
            )
            for raw_idx in cat_indices:
                idx = int(raw_idx)
                if float(-i_arr[idx]) <= min_current:
                    continue
                if parabolic:
                    e_p, i_p = _parabolic_refine(e_arr, i_arr, idx, "cathodic")
                else:
                    e_p, i_p = float(e_arr[idx]), float(i_arr[idx])
                e_half_p = _find_half_peak_potential(e_arr, i_arr, idx, i_p, "cathodic")
                cathodic_peaks.append(
                    PeakInfo(
                        E_peak=e_p,
                        I_peak=i_p,
                        index=idx,
                        E_half_peak=e_half_p,
                        polarity="cathodic",
                    )
                )

    if return_all:
        all_peaks = anodic_peaks + cathodic_peaks
        all_peaks.sort(key=lambda p: p.index)
        return all_peaks

    best_anodic = max(anodic_peaks, key=lambda p: p.I_peak) if anodic_peaks else None
    best_cathodic = (
        min(cathodic_peaks, key=lambda p: p.I_peak) if cathodic_peaks else None
    )

    if best_anodic is not None and best_cathodic is not None:
        delta_ep: float | None = float(abs(best_anodic.E_peak - best_cathodic.E_peak))
        e_half: float | None = float(0.5 * (best_anodic.E_peak + best_cathodic.E_peak))
        ratio: float | None = (
            float(abs(best_anodic.I_peak / best_cathodic.I_peak))
            if best_cathodic.I_peak != 0.0
            else None
        )
    else:
        delta_ep = None
        e_half = None
        ratio = None

    return CVDiagnostics(
        anodic_peak=best_anodic,
        cathodic_peak=best_cathodic,
        delta_Ep=delta_ep,
        E_half=e_half,
        peak_current_ratio=ratio,
    )

simulate

simulate(technique: BaseTechnique, mechanism: MechanismInput, geometry: Geometry | str = 'planar', grid: ndarray | Mesh1D | None = None, solver: BaseSolver | str = 'scipy_ivp', t_eval: ndarray | Sequence[float] | None = None, solver_kwargs: Mapping[str, Any] | None = None, *, mesh_kwargs: Mapping[str, Any] | None = None, bc_kwargs: Mapping[str, Any] | None = None, bc_overrides: Mapping[str, tuple[BoundaryCondition, BoundaryCondition]] | None = None, electrodes: Literal['left', 'right', 'both'] = 'left', bulk_bc: Literal['dirichlet', 'neumann'] = 'dirichlet', n_electrons: int | Mapping[str, int] | None = None, kinetics: HeterogeneousKinetics | NernstianEquilibrium | None = None) -> TechniqueResult

Run a complete electrochemical technique simulation in a single call.

Orchestrates physics-informed spatial meshing, boundary condition assembly (both potentiostatic and galvanostatic), event-aware piecewise numerical integration across waveform discontinuities/switching vertices, and Faradaic current / cumulative charge extraction.

Parameters:

Name Type Description Default
technique BaseTechnique

Electrochemical excitation waveform (e.g., Chronoamperometry, LinearSweepVoltammetry, CyclicVoltammetry, DifferentialPulseVoltammetry, SquareWaveVoltammetry, SampledCurrentVoltammetry, Chronopotentiometry, or CustomWaveform).

required
mechanism Mechanism, SpeciesCollection, Sequence[Species], or Species

Chemical/electrochemical reaction mechanism or species specification. When a SpeciesCollection or sequence of Species is passed directly, a Mechanism is constructed automatically (using kinetics if given, or Nernstian equilibrium for a redox pair in potentiostatic mode).

required
geometry Geometry or str

Coordinate geometry instance or registered alias ('planar', 'spherical', 'cylindrical').

`'planar'`
grid ndarray or Mesh1D

1D spatial grid or mesh. When None, automatically constructs a physics-informed mesh via create_diffusion_mesh respecting curvilinear r0 and hydrodynamic Nernst layer thickness.

None
solver BaseSolver or str

Numerical diffusion solver instance or registered alias ('scipy_ivp', 'crank_nicolson', 'implicit', 'explicit').

`'scipy_ivp'`
t_eval ndarray or Sequence[float]

Strictly increasing 1D evaluation timestamps in [0, technique.duration]. Defaults to technique.time_grid().

None
solver_kwargs Mapping[str, Any]

Optional keyword arguments passed to the solver (e.g. method='Radau', rtol=1e-6, atol=1e-8, dt=...).

None
mesh_kwargs Mapping[str, Any]

Optional keyword arguments forwarded to create_diffusion_mesh when grid=None.

None
bc_kwargs Mapping[str, Any]

Optional keyword arguments forwarded to Mechanism.create_problem when constructing potentiostatic boundary conditions.

None
bc_overrides Mapping[str, tuple[BoundaryCondition, BoundaryCondition]]

Optional per-species boundary condition overrides.

None
electrodes ('left', 'right', 'both')

Active electrode boundary for Faradaic current evaluation.

'left'
bulk_bc ('dirichlet', 'neumann')

Boundary condition type applied at the bulk (non-electrode) boundary.

'dirichlet'
n_electrons int or Mapping[str, int]

Optional electron transfer count overrides.

None
kinetics HeterogeneousKinetics or NernstianEquilibrium

Optional interfacial kinetics used when mechanism is supplied as a SpeciesCollection or sequence of Species.

None

Returns:

Type Description
TechniqueResult

Structured simulation result containing time, potential, current, charge, solver_result, species profiles, and technique-specific views.

Source code in src/softpotato/techniques/pipeline.py
def simulate(
    technique: BaseTechnique,
    mechanism: MechanismInput,
    geometry: Geometry | str = "planar",
    grid: np.ndarray | Mesh1D | None = None,
    solver: BaseSolver | str = "scipy_ivp",
    t_eval: np.ndarray | Sequence[float] | None = None,
    solver_kwargs: Mapping[str, Any] | None = None,
    *,
    mesh_kwargs: Mapping[str, Any] | None = None,
    bc_kwargs: Mapping[str, Any] | None = None,
    bc_overrides: Mapping[str, tuple[BoundaryCondition, BoundaryCondition]]
    | None = None,
    electrodes: Literal["left", "right", "both"] = "left",
    bulk_bc: Literal["dirichlet", "neumann"] = "dirichlet",
    n_electrons: int | Mapping[str, int] | None = None,
    kinetics: HeterogeneousKinetics | NernstianEquilibrium | None = None,
) -> TechniqueResult:
    r"""Run a complete electrochemical technique simulation in a single call.

    Orchestrates physics-informed spatial meshing, boundary condition assembly
    (both potentiostatic and galvanostatic), event-aware piecewise numerical
    integration across waveform discontinuities/switching vertices, and
    Faradaic current / cumulative charge extraction.

    Parameters
    ----------
    technique : BaseTechnique
        Electrochemical excitation waveform (e.g., :class:`Chronoamperometry`,
        :class:`LinearSweepVoltammetry`, :class:`CyclicVoltammetry`,
        :class:`DifferentialPulseVoltammetry`, :class:`SquareWaveVoltammetry`,
        :class:`SampledCurrentVoltammetry`, :class:`Chronopotentiometry`, or
        :class:`CustomWaveform`).
    mechanism : Mechanism, SpeciesCollection, Sequence[Species], or Species
        Chemical/electrochemical reaction mechanism or species specification.
        When a :class:`SpeciesCollection` or sequence of :class:`Species` is
        passed directly, a :class:`Mechanism` is constructed automatically
        (using ``kinetics`` if given, or Nernstian equilibrium for a redox pair
        in potentiostatic mode).
    geometry : Geometry or str, default ``'planar'``
        Coordinate geometry instance or registered alias (``'planar'``,
        ``'spherical'``, ``'cylindrical'``).
    grid : np.ndarray or Mesh1D, optional
        1D spatial grid or mesh. When ``None``, automatically constructs a
        physics-informed mesh via :func:`~softpotato.grid.create_diffusion_mesh`
        respecting curvilinear ``r0`` and hydrodynamic Nernst layer thickness.
    solver : BaseSolver or str, default ``'scipy_ivp'``
        Numerical diffusion solver instance or registered alias (``'scipy_ivp'``,
        ``'crank_nicolson'``, ``'implicit'``, ``'explicit'``).
    t_eval : np.ndarray or Sequence[float], optional
        Strictly increasing 1D evaluation timestamps in ``[0, technique.duration]``.
        Defaults to ``technique.time_grid()``.
    solver_kwargs : Mapping[str, Any], optional
        Optional keyword arguments passed to the solver (e.g. ``method='Radau'``,
        ``rtol=1e-6``, ``atol=1e-8``, ``dt=...``).
    mesh_kwargs : Mapping[str, Any], optional
        Optional keyword arguments forwarded to :func:`~softpotato.grid.create_diffusion_mesh`
        when ``grid=None``.
    bc_kwargs : Mapping[str, Any], optional
        Optional keyword arguments forwarded to :meth:`Mechanism.create_problem`
        when constructing potentiostatic boundary conditions.
    bc_overrides : Mapping[str, tuple[BoundaryCondition, BoundaryCondition]], optional
        Optional per-species boundary condition overrides.
    electrodes : {'left', 'right', 'both'}, default ``'left'``
        Active electrode boundary for Faradaic current evaluation.
    bulk_bc : {'dirichlet', 'neumann'}, default ``'dirichlet'``
        Boundary condition type applied at the bulk (non-electrode) boundary.
    n_electrons : int or Mapping[str, int], optional
        Optional electron transfer count overrides.
    kinetics : HeterogeneousKinetics or NernstianEquilibrium, optional
        Optional interfacial kinetics used when ``mechanism`` is supplied as
        a :class:`SpeciesCollection` or sequence of :class:`Species`.

    Returns
    -------
    TechniqueResult
        Structured simulation result containing ``time``, ``potential``,
        ``current``, ``charge``, ``solver_result``, species profiles, and
        technique-specific views.
    """
    if not isinstance(technique, BaseTechnique):
        raise TypeError(
            f"technique must be a BaseTechnique instance, got {type(technique).__name__}."
        )

    resolved_mech = _resolve_mechanism(
        mechanism, mode=technique.mode, kinetics=kinetics
    )
    resolved_geom = _resolve_geometry(geometry)
    resolved_solver, run_kwargs = _resolve_solver(solver, solver_kwargs)
    resolved_t_eval = _validate_t_eval(t_eval, technique)
    resolved_grid: np.ndarray | Mesh1D = (
        grid
        if grid is not None
        else _build_auto_grid(technique, resolved_mech, resolved_geom, mesh_kwargs)
    )
    mesh_obj = resolved_grid if isinstance(resolved_grid, Mesh1D) else None

    # Special handling for SampledCurrentVoltammetry (family of CA steps)
    if isinstance(technique, SampledCurrentVoltammetry):
        step_results: list[TechniqueResult] = []
        for step_ca in technique.steps:
            step_res = simulate(
                technique=step_ca,
                mechanism=resolved_mech,
                geometry=resolved_geom,
                grid=resolved_grid,
                solver=resolved_solver,
                t_eval=resolved_t_eval,
                solver_kwargs=run_kwargs if run_kwargs else None,
                bc_kwargs=bc_kwargs,
                bc_overrides=bc_overrides,
                electrodes=electrodes,
                bulk_bc=bulk_bc,
                n_electrons=n_electrons,
            )
            step_results.append(step_res)

        pot_2d = np.asarray(technique.excitation(resolved_t_eval), dtype=float)
        curr_2d = np.vstack([r.current for r in step_results])
        last_sr = step_results[-1].solver_result
        agg_sr = SolverResult(
            t=last_sr.t,
            x=last_sr.x,
            concentrations=last_sr.concentrations,
            fluxes=last_sr.fluxes,
            right_fluxes=last_sr.right_fluxes,
            currents=last_sr.currents,
            left_currents=last_sr.left_currents,
            right_currents=last_sr.right_currents,
            success=all(r.success for r in step_results),
            message=(
                "All SCV steps completed successfully."
                if all(r.success for r in step_results)
                else next(r.message for r in step_results if not r.success)
            ),
            raw_output=[r.solver_result.raw_output for r in step_results],
            mesh=mesh_obj,
        )
        return TechniqueResult(
            technique=technique,
            solver_result=agg_sr,
            time=resolved_t_eval,
            potential=pot_2d,
            current=curr_2d,
            metadata={
                "solver": type(resolved_solver).__name__,
                "geometry": resolved_geom.name,
                "n_steps": technique.n_steps,
                "step_results": tuple(step_results),
            },
        )

    # Partition [0, t_end] at strictly interior event_times
    t_end_target = float(resolved_t_eval[-1])
    tol = 1e-12 * max(1.0, technique.duration)
    interior_events = [
        float(ev)
        for ev in technique.event_times
        if tol < float(ev) < t_end_target - tol
    ]
    boundaries = [0.0, *interior_events, t_end_target]
    n_segments = len(boundaries) - 1

    problem_ne = _infer_problem_n_electrons(resolved_mech, n_electrons)
    extra_bc_kwargs = dict(bc_kwargs) if bc_kwargs is not None else {}

    prev_c: dict[str, np.ndarray] | None = None
    stitched_segments: list[tuple[SolverResult, np.ndarray]] = []
    galv_info: (
        tuple[
            str,
            str | None,
            float,
            Literal["left", "right"],
            float,
            ElectrochemicalStep | None,
        ]
        | None
    ) = None

    for seg_idx in range(n_segments):
        seg_start = boundaries[seg_idx]
        seg_end = boundaries[seg_idx + 1]
        is_last = seg_idx == n_segments - 1

        seg_callable = _make_segment_callable(
            technique, seg_start, seg_end, is_last=is_last
        )

        # Select requested evaluation points falling inside this segment
        if seg_idx == 0:
            mask = (resolved_t_eval >= seg_start - tol) & (
                resolved_t_eval <= seg_end + tol
            )
        else:
            mask = (resolved_t_eval > seg_start + tol) & (
                resolved_t_eval <= seg_end + tol
            )
        req_times = resolved_t_eval[mask]

        # Build solver t_eval for this segment (must span [seg_start, seg_end] with >= 2 pts)
        seg_points = [seg_start, *req_times.tolist(), seg_end]
        seg_t_eval_list: list[float] = []
        for pt in sorted(seg_points):
            clamped_pt = min(max(pt, seg_start), seg_end)
            if not seg_t_eval_list or (clamped_pt - seg_t_eval_list[-1]) > tol:
                seg_t_eval_list.append(clamped_pt)
        if seg_t_eval_list[-1] != seg_end:
            seg_t_eval_list[-1] = seg_end
        if len(seg_t_eval_list) < 2:
            seg_t_eval_list = [seg_start, seg_end]
        seg_t_eval = np.asarray(seg_t_eval_list, dtype=float)

        # Build DiffusionProblem for this segment
        if technique.mode == "galvanostatic":
            (
                galv_bcs,
                ox_name,
                red_name,
                n_val,
                side,
                area,
                step_obj,
            ) = _build_galvanostatic_bcs(
                seg_callable,
                resolved_mech,
                resolved_geom,
                resolved_grid,
                electrodes=electrodes,
                bulk_bc=bulk_bc,
                bc_overrides=bc_overrides,
            )
            galv_info = (ox_name, red_name, n_val, side, area, step_obj)
            problem = resolved_mech.create_problem(
                resolved_grid,
                boundary_conditions=galv_bcs,
                geometry=resolved_geom,
                initial_conditions=prev_c,
                n_electrons=problem_ne,
                electrodes=electrodes,
            )
        else:
            problem = resolved_mech.create_problem(
                resolved_grid,
                potential=seg_callable,
                geometry=resolved_geom,
                initial_conditions=prev_c,
                n_electrons=problem_ne,
                electrodes=electrodes,
                bulk_bc=bulk_bc,
                bc_overrides=bc_overrides,
                **extra_bc_kwargs,
            )

        seg_res = resolved_solver.solve(
            problem,
            t_span=(seg_start, seg_end),
            t_eval=seg_t_eval,
            **run_kwargs,
        )

        if not seg_res.success:
            empty_arr = np.full(resolved_t_eval.size, np.nan, dtype=float)
            return TechniqueResult(
                technique=technique,
                solver_result=seg_res,
                time=resolved_t_eval,
                potential=empty_arr.copy(),
                current=empty_arr.copy(),
                charge=empty_arr.copy(),
                metadata={
                    "solver": type(resolved_solver).__name__,
                    "geometry": resolved_geom.name,
                    "n_segments": n_segments,
                    "failed_segment": seg_idx,
                },
            )

        # Carry terminal concentration profile into the next segment
        prev_c = {
            sp: seg_res.concentrations[sp][-1].copy()
            for sp in resolved_mech.species_names
        }

        if req_times.size > 0:
            # Map each requested timestamp to its index in seg_res.t
            idx = np.searchsorted(seg_res.t, req_times)
            idx = np.clip(idx, 0, seg_res.t.size - 1)
            # Pick nearest neighbor in case of floating-point rounding
            left_idx = np.clip(idx - 1, 0, seg_res.t.size - 1)
            use_left = np.abs(seg_res.t[left_idx] - req_times) < np.abs(
                seg_res.t[idx] - req_times
            )
            chosen_idx = np.where(use_left, left_idx, idx)
            stitched_segments.append((seg_res, chosen_idx))

    combined_sr = _stitch_solver_results(stitched_segments, mesh_obj)
    # Preserve exact requested time stamps
    combined_sr.t = resolved_t_eval.copy()

    metadata: dict[str, Any] = {
        "solver": type(resolved_solver).__name__,
        "geometry": resolved_geom.name,
        "n_segments": n_segments,
    }

    if technique.mode == "galvanostatic":
        assert galv_info is not None
        ox_name, red_name, n_val, side, area, step_obj = galv_info
        current_arr = np.asarray(technique.current(resolved_t_eval), dtype=float)
        potential_arr = _recover_galvanostatic_potential(
            technique,
            combined_sr,
            resolved_mech,
            current_arr,
            ox_name=ox_name,
            red_name=red_name,
            n_val=n_val,
            side=side,
            area=area,
            step=step_obj,
        )
        if isinstance(technique, Chronopotentiometry):
            idx_surf = 0 if side == "left" else -1
            first_nonzero = next(
                (i_val for i_val in technique.currents if i_val != 0.0), 0.0
            )
            reactant_name = (
                red_name if (first_nonzero > 0.0 and red_name is not None) else ox_name
            )
            c_reactant = combined_sr.concentrations[reactant_name][:, idx_surf]
            tau = (
                Chronopotentiometry.detect_transition_time(resolved_t_eval, c_reactant)
                if c_reactant[0] > 0.0
                else None
            )
            metadata["transition_time"] = tau
            metadata["reactant_species"] = reactant_name
    else:
        potential_arr = np.asarray(technique.potential(resolved_t_eval), dtype=float)
        current_arr = _extract_net_faradaic_current(
            combined_sr, resolved_mech, resolved_geom, electrodes
        )

    return TechniqueResult(
        technique=technique,
        solver_result=combined_sr,
        time=resolved_t_eval,
        potential=potential_arr,
        current=current_arr,
        metadata=metadata,
    )

simulate_sweep

simulate_sweep(techniques: Sequence[BaseTechnique], mechanism: MechanismInput, *, values: None = None, geometry: Geometry | str = 'planar', grid: ndarray | Mesh1D | None = None, solver: BaseSolver | str = 'scipy_ivp', t_eval: ndarray | Sequence[float] | None = None, solver_kwargs: Mapping[str, Any] | None = None, **kwargs: Any) -> list[TechniqueResult]
simulate_sweep(techniques: Mapping[Any, BaseTechnique], mechanism: MechanismInput, *, values: None = None, geometry: Geometry | str = 'planar', grid: ndarray | Mesh1D | None = None, solver: BaseSolver | str = 'scipy_ivp', t_eval: ndarray | Sequence[float] | None = None, solver_kwargs: Mapping[str, Any] | None = None, **kwargs: Any) -> dict[Any, TechniqueResult]
simulate_sweep(techniques: Callable[[Any], BaseTechnique], mechanism: MechanismInput, *, values: Sequence[Any], geometry: Geometry | str = 'planar', grid: ndarray | Mesh1D | None = None, solver: BaseSolver | str = 'scipy_ivp', t_eval: ndarray | Sequence[float] | None = None, solver_kwargs: Mapping[str, Any] | None = None, **kwargs: Any) -> dict[Any, TechniqueResult]
simulate_sweep(techniques: Sequence[BaseTechnique] | Mapping[Any, BaseTechnique] | Callable[[Any], BaseTechnique], mechanism: MechanismInput, *, values: Sequence[Any] | None = None, geometry: Geometry | str = 'planar', grid: ndarray | Mesh1D | None = None, solver: BaseSolver | str = 'scipy_ivp', t_eval: ndarray | Sequence[float] | None = None, solver_kwargs: Mapping[str, Any] | None = None, **kwargs: Any) -> list[TechniqueResult] | dict[Any, TechniqueResult]

Run a parameter sweep (e.g., scan-rate or rotation-rate series) via simulate.

Supports three input modes:

  1. Sequence of techniques: simulate_sweep([cv1, cv2, ...], mechanism) returns list[TechniqueResult].
  2. Mapping of parameter labels to techniques: simulate_sweep({0.05: cv1, 0.1: cv2}, mechanism) returns dict[Any, TechniqueResult].
  3. Factory callable + parameter values: simulate_sweep(lambda v: CyclicVoltammetry(..., scan_rate=v), mechanism, values=[0.05, 0.1, 0.5]) returns dict[Any, TechniqueResult] keyed by each value in values.

Parameters:

Name Type Description Default
techniques Sequence[BaseTechnique], Mapping[Any, BaseTechnique], or Callable

Collection of techniques to simulate or a factory callable mapping each parameter value in values to a BaseTechnique.

required
mechanism Mechanism, SpeciesCollection, Sequence[Species], or Species

Chemical/electrochemical mechanism passed to simulate.

required
values Sequence[Any]

Parameter values to sweep when techniques is a factory callable.

None
geometry Geometry or str

Coordinate geometry forwarded to simulate.

`'planar'`
grid ndarray or Mesh1D

Optional fixed spatial grid forwarded to simulate. Leave None so each technique auto-sizes its diffusion mesh to its own duration.

None
solver BaseSolver or str

Numerical solver forwarded to simulate.

`'scipy_ivp'`
t_eval ndarray or Sequence[float]

Optional fixed evaluation timestamps forwarded to simulate.

None
solver_kwargs Mapping[str, Any]

Optional solver options forwarded to simulate.

None
**kwargs Any

Additional keyword arguments forwarded to simulate.

{}

Returns:

Type Description
list[TechniqueResult] or dict[Any, TechniqueResult]

Ordered list or mapping of simulation results ready for diagnostics.

Source code in src/softpotato/techniques/pipeline.py
def simulate_sweep(
    techniques: Sequence[BaseTechnique]
    | Mapping[Any, BaseTechnique]
    | Callable[[Any], BaseTechnique],
    mechanism: MechanismInput,
    *,
    values: Sequence[Any] | None = None,
    geometry: Geometry | str = "planar",
    grid: np.ndarray | Mesh1D | None = None,
    solver: BaseSolver | str = "scipy_ivp",
    t_eval: np.ndarray | Sequence[float] | None = None,
    solver_kwargs: Mapping[str, Any] | None = None,
    **kwargs: Any,
) -> list[TechniqueResult] | dict[Any, TechniqueResult]:
    """Run a parameter sweep (e.g., scan-rate or rotation-rate series) via :func:`simulate`.

    Supports three input modes:

    1. **Sequence of techniques**: ``simulate_sweep([cv1, cv2, ...], mechanism)``
       returns ``list[TechniqueResult]``.
    2. **Mapping of parameter labels to techniques**:
       ``simulate_sweep({0.05: cv1, 0.1: cv2}, mechanism)`` returns
       ``dict[Any, TechniqueResult]``.
    3. **Factory callable + parameter values**:
       ``simulate_sweep(lambda v: CyclicVoltammetry(..., scan_rate=v), mechanism, values=[0.05, 0.1, 0.5])``
       returns ``dict[Any, TechniqueResult]`` keyed by each value in ``values``.

    Parameters
    ----------
    techniques : Sequence[BaseTechnique], Mapping[Any, BaseTechnique], or Callable
        Collection of techniques to simulate or a factory callable mapping each
        parameter value in ``values`` to a :class:`BaseTechnique`.
    mechanism : Mechanism, SpeciesCollection, Sequence[Species], or Species
        Chemical/electrochemical mechanism passed to :func:`simulate`.
    values : Sequence[Any], optional
        Parameter values to sweep when ``techniques`` is a factory callable.
    geometry : Geometry or str, default ``'planar'``
        Coordinate geometry forwarded to :func:`simulate`.
    grid : np.ndarray or Mesh1D, optional
        Optional fixed spatial grid forwarded to :func:`simulate`. Leave ``None``
        so each technique auto-sizes its diffusion mesh to its own duration.
    solver : BaseSolver or str, default ``'scipy_ivp'``
        Numerical solver forwarded to :func:`simulate`.
    t_eval : np.ndarray or Sequence[float], optional
        Optional fixed evaluation timestamps forwarded to :func:`simulate`.
    solver_kwargs : Mapping[str, Any], optional
        Optional solver options forwarded to :func:`simulate`.
    **kwargs : Any
        Additional keyword arguments forwarded to :func:`simulate`.

    Returns
    -------
    list[TechniqueResult] or dict[Any, TechniqueResult]
        Ordered list or mapping of simulation results ready for diagnostics.
    """
    if isinstance(techniques, BaseTechnique):
        raise TypeError(
            "techniques must be a sequence/mapping of BaseTechnique instances or "
            "a factory callable paired with 'values', not a single BaseTechnique."
        )

    if isinstance(techniques, Mapping):
        if values is not None:
            raise ValueError(
                "'values' cannot be specified when 'techniques' is a mapping."
            )
        if len(techniques) == 0:
            raise ValueError("'techniques' mapping must not be empty.")
        return {
            key: simulate(
                tech,
                mechanism,
                geometry=geometry,
                grid=grid,
                solver=solver,
                t_eval=t_eval,
                solver_kwargs=solver_kwargs,
                **kwargs,
            )
            for key, tech in techniques.items()
        }

    if isinstance(techniques, Sequence) and not isinstance(techniques, (str, bytes)):
        if values is not None:
            raise ValueError(
                "'values' cannot be specified when 'techniques' is a sequence."
            )
        if len(techniques) == 0:
            raise ValueError("'techniques' sequence must not be empty.")
        return [
            simulate(
                tech,
                mechanism,
                geometry=geometry,
                grid=grid,
                solver=solver,
                t_eval=t_eval,
                solver_kwargs=solver_kwargs,
                **kwargs,
            )
            for tech in techniques
        ]

    if callable(techniques):
        if values is None:
            raise ValueError(
                "'values' must be provided when 'techniques' is a factory callable."
            )
        if isinstance(values, (str, bytes)) or not isinstance(values, Sequence):
            raise TypeError(
                "'values' must be a non-empty sequence of parameter values."
            )
        if len(values) == 0:
            raise ValueError("'values' must not be empty.")
        results: dict[Any, TechniqueResult] = {}
        for val in values:
            tech = techniques(val)
            results[val] = simulate(
                tech,
                mechanism,
                geometry=geometry,
                grid=grid,
                solver=solver,
                t_eval=t_eval,
                solver_kwargs=solver_kwargs,
                **kwargs,
            )
        return results

    raise TypeError(
        "techniques must be a sequence/mapping of BaseTechnique instances or a "
        f"factory callable, got {type(techniques).__name__}."
    )

plot_charge_vs_time

plot_charge_vs_time(result: TechniqueResult, *, ax: Axes | None = None, step: int | None = None, title: str | None = None, xlabel: str | None = None, ylabel: str | None = None, grid: bool = True, figsize: tuple[float, float] | None = None, **plot_kwargs: Any) -> tuple[Figure, Axes]

Plot cumulative Faradaic charge vs. time (\(Q(t)\) vs. \(t\)).

Source code in src/softpotato/techniques/plotting.py
def plot_charge_vs_time(
    result: TechniqueResult,
    *,
    ax: Axes | None = None,
    step: int | None = None,
    title: str | None = None,
    xlabel: str | None = None,
    ylabel: str | None = None,
    grid: bool = True,
    figsize: tuple[float, float] | None = None,
    **plot_kwargs: Any,
) -> tuple[Figure, Axes]:
    """Plot cumulative Faradaic charge vs. time (:math:`Q(t)` vs. :math:`t`)."""
    spec = result.technique.plot_specs.get(
        "Q_vs_t",
        PlotSpec(
            kind="Q_vs_t",
            title="Chronocoulogram",
            x_label="$t$ / s",
            y_label="$Q$ / C",
        ),
    )
    fig, ax = _resolve_axes(ax, figsize=figsize)

    q_arr = result.Q
    if q_arr.ndim == 2:
        if step is not None:
            ax.plot(result.time, q_arr[step], **plot_kwargs)
        else:
            for idx in range(q_arr.shape[0]):
                kw = dict(plot_kwargs)
                kw.setdefault("label", f"Step {idx + 1}")
                ax.plot(result.time, q_arr[idx], **kw)
            ax.legend()
    else:
        ax.plot(result.time, q_arr, **plot_kwargs)

    _apply_labels(ax, spec, title=title, xlabel=xlabel, ylabel=ylabel, grid=grid)
    return fig, ax

plot_concentration_profile

plot_concentration_profile(result: TechniqueResult, *, t: float | Sequence[float] | None = None, species: str | Sequence[str] | None = None, step: int | None = None, ax: Axes | None = None, title: str | None = None, xlabel: str | None = None, ylabel: str | None = None, grid: bool = True, figsize: tuple[float, float] | None = None, **plot_kwargs: Any) -> tuple[Figure, Axes]

Plot species concentration vs. spatial distance at specific time(s).

Parameters:

Name Type Description Default
result TechniqueResult

Simulation result containing spatial concentration profiles.

required
t float or Sequence[float]

Target timestamp(s) in seconds. Defaults to the final simulated time result.time[-1]. Each requested timestamp is snapped to the nearest simulated evaluation point.

None
species str or Sequence[str]

Species name(s) to plot. Defaults to all species in result.species.

None
step int

For SampledCurrentVoltammetry, select which step's concentration profile to plot from result.metadata['step_results'].

None
ax Axes

Existing Axes to draw onto.

None
title str

Optional overrides for the default PlotSpec labels.

None
xlabel str

Optional overrides for the default PlotSpec labels.

None
ylabel str

Optional overrides for the default PlotSpec labels.

None
grid bool

Whether to show a light background grid.

True
figsize tuple[float, float]

Figure size passed to plt.subplots when ax is None.

None
**plot_kwargs Any

Additional keyword arguments forwarded to ax.plot.

{}

Returns:

Type Description
tuple[Figure, Axes]

Figure and Axes containing the concentration profile(s).

Source code in src/softpotato/techniques/plotting.py
def plot_concentration_profile(
    result: TechniqueResult,
    *,
    t: float | Sequence[float] | None = None,
    species: str | Sequence[str] | None = None,
    step: int | None = None,
    ax: Axes | None = None,
    title: str | None = None,
    xlabel: str | None = None,
    ylabel: str | None = None,
    grid: bool = True,
    figsize: tuple[float, float] | None = None,
    **plot_kwargs: Any,
) -> tuple[Figure, Axes]:
    """Plot species concentration vs. spatial distance at specific time(s).

    Parameters
    ----------
    result : TechniqueResult
        Simulation result containing spatial concentration profiles.
    t : float or Sequence[float], optional
        Target timestamp(s) in seconds. Defaults to the final simulated time
        ``result.time[-1]``. Each requested timestamp is snapped to the nearest
        simulated evaluation point.
    species : str or Sequence[str], optional
        Species name(s) to plot. Defaults to all species in ``result.species``.
    step : int, optional
        For :class:`SampledCurrentVoltammetry`, select which step's
        concentration profile to plot from ``result.metadata['step_results']``.
    ax : matplotlib.axes.Axes, optional
        Existing Axes to draw onto.
    title, xlabel, ylabel : str, optional
        Optional overrides for the default :class:`PlotSpec` labels.
    grid : bool, default True
        Whether to show a light background grid.
    figsize : tuple[float, float], optional
        Figure size passed to ``plt.subplots`` when ``ax`` is ``None``.
    **plot_kwargs : Any
        Additional keyword arguments forwarded to ``ax.plot``.

    Returns
    -------
    tuple[matplotlib.figure.Figure, matplotlib.axes.Axes]
        Figure and Axes containing the concentration profile(s).
    """
    target_result = result
    if step is not None and isinstance(result.technique, SampledCurrentVoltammetry):
        step_results = result.metadata.get("step_results")
        if step_results is not None:
            target_result = step_results[step]

    spec = target_result.technique.plot_specs["c_vs_x"]
    fig, ax = _resolve_axes(ax, figsize=figsize)

    # Resolve species list
    if species is None:
        selected_species = list(target_result.species)
    elif isinstance(species, str):
        selected_species = [species]
    else:
        selected_species = list(species)
    if not selected_species:
        raise ValueError("species must not be empty.")
    for sp_name in selected_species:
        if sp_name not in target_result:
            raise KeyError(
                f"Species {sp_name!r} not found in result. "
                f"Available species: {target_result.species}."
            )

    # Resolve target time(s)
    t_arr = target_result.time
    if t is None:
        t_targets = [float(t_arr[-1])]
    elif isinstance(t, (int, float, np.number)) and not isinstance(t, bool):
        t_targets = [_validate_finite_real(t, "t")]
    elif isinstance(t, Sequence) and not isinstance(t, (str, bytes)):
        t_targets = [_validate_finite_real(val, "t") for val in t]
        if not t_targets:
            raise ValueError("'t' must not be empty.")
    else:
        raise TypeError("'t' must be a float or sequence of floats.")

    t_min = float(t_arr[0])
    t_max = float(t_arr[-1])
    tol = 1e-12 * max(1.0, abs(t_max - t_min))
    snapped_indices: list[int] = []
    for t_val in t_targets:
        if t_val < t_min - tol or t_val > t_max + tol:
            raise ValueError(
                f"Requested time t={t_val!r} s lies outside simulated range "
                f"[{t_min!r}, {t_max!r}] s."
            )
        snapped_indices.append(int(np.argmin(np.abs(t_arr - t_val))))

    x_grid = target_result.x
    multi_time = len(snapped_indices) > 1
    for t_idx in snapped_indices:
        t_actual = float(t_arr[t_idx])
        for sp_name in selected_species:
            c_prof = target_result[sp_name][t_idx]
            kw = dict(plot_kwargs)
            if multi_time:
                kw.setdefault("label", f"{sp_name} ($t$ = {t_actual:.4g} s)")
            else:
                kw.setdefault("label", sp_name)
            ax.plot(x_grid, c_prof, **kw)

    ax.legend()

    resolved_title = title
    if resolved_title is None:
        if not multi_time:
            t_actual = float(t_arr[snapped_indices[0]])
            resolved_title = f"{spec.title} ($t$ = {t_actual:.4g} s)"
        else:
            resolved_title = spec.title

    resolved_xlabel = (
        _distance_axis_label(target_result, spec) if xlabel is None else xlabel
    )
    _apply_labels(
        ax,
        spec,
        title=resolved_title,
        xlabel=resolved_xlabel,
        ylabel=ylabel,
        grid=grid,
    )
    return fig, ax

plot_cottrell

plot_cottrell(result_or_t: TechniqueResult | ArrayLike, fit_result: CottrellFitResult, *, current: ArrayLike | None = None, t_min: float | None = None, t_max: float | None = None, ax: Axes | None = None, title: str | None = None, grid: bool = True, figsize: tuple[float, float] | None = None) -> tuple[Figure, Axes]

Plot a Cottrell diagnostic regression (\(I\) vs. \(t^{-1/2}\)).

Parameters:

Name Type Description Default
result_or_t TechniqueResult or array - like

Chronoamperometry TechniqueResult or 1D time array \(t\) (s).

required
fit_result CottrellFitResult

Fit output from analyze_cottrell or fit_cottrell.

required
current array - like

Optional raw current array when result_or_t is a time array. If omitted, reconstructed from fit_result.y_fit + fit_result.residuals.

None
t_min float

Time window bounds matching those passed to analyze_cottrell.

None
t_max float

Time window bounds matching those passed to analyze_cottrell.

None
ax Axes

Existing Axes to draw onto.

None
title str

Optional plot title override.

None
grid bool

Whether to display a background grid.

True
figsize tuple[float, float]

Figure size when ax is None.

None

Returns:

Type Description
tuple[Figure, Axes]

Figure and Axes containing the Cottrell plot.

Source code in src/softpotato/techniques/plotting.py
def plot_cottrell(
    result_or_t: TechniqueResult | ArrayLike,
    fit_result: CottrellFitResult,
    *,
    current: ArrayLike | None = None,
    t_min: float | None = None,
    t_max: float | None = None,
    ax: Axes | None = None,
    title: str | None = None,
    grid: bool = True,
    figsize: tuple[float, float] | None = None,
) -> tuple[Figure, Axes]:
    r"""Plot a Cottrell diagnostic regression (:math:`I` vs. :math:`t^{-1/2}`).

    Parameters
    ----------
    result_or_t : TechniqueResult or array-like
        Chronoamperometry :class:`TechniqueResult` or 1D time array :math:`t` (s).
    fit_result : CottrellFitResult
        Fit output from :func:`~softpotato.techniques.analyze_cottrell` or
        :func:`~softpotato.analytical.fitting.fit_cottrell`.
    current : array-like, optional
        Optional raw current array when ``result_or_t`` is a time array.
        If omitted, reconstructed from ``fit_result.y_fit + fit_result.residuals``.
    t_min, t_max : float, optional
        Time window bounds matching those passed to :func:`analyze_cottrell`.
    ax : matplotlib.axes.Axes, optional
        Existing Axes to draw onto.
    title : str, optional
        Optional plot title override.
    grid : bool, default True
        Whether to display a background grid.
    figsize : tuple[float, float], optional
        Figure size when ``ax`` is ``None``.

    Returns
    -------
    tuple[matplotlib.figure.Figure, matplotlib.axes.Axes]
        Figure and Axes containing the Cottrell plot.
    """
    if isinstance(result_or_t, TechniqueResult):
        t_arr = np.asarray(result_or_t.time, dtype=float)
    else:
        t_arr = np.asarray(result_or_t, dtype=float)

    mask = t_arr > 0.0
    if t_min is not None:
        mask &= t_arr >= t_min
    if t_max is not None:
        mask &= t_arr <= t_max
    t_sel = t_arr[mask]

    inv_sqrt_t = 1.0 / np.sqrt(t_sel)
    y_fit = np.asarray(fit_result.y_fit, dtype=float)
    if current is not None:
        curr_arr = np.asarray(current, dtype=float)
        y_data = curr_arr[mask] if curr_arr.size == t_arr.size else curr_arr
    else:
        y_data = y_fit + np.asarray(fit_result.residuals, dtype=float)

    order = np.argsort(inv_sqrt_t)
    fig, ax = _resolve_axes(ax, figsize=figsize)
    ax.scatter(inv_sqrt_t, y_data, s=18, color="tab:blue", zorder=4, label="Data")
    ax.plot(
        inv_sqrt_t[order],
        y_fit[order],
        color="tab:red",
        linewidth=1.5,
        label=rf"Fit ($D$ = {fit_result.d:.3e}, $R^2$ = {fit_result.r_squared:.4f})",
    )
    ax.legend()

    spec = PlotSpec(
        kind="cottrell",
        title="Cottrell Analysis",
        x_label=r"$t^{-1/2}$ / $\mathrm{s^{-1/2}}$",
        y_label="$I$ / A",
    )
    _apply_labels(ax, spec, title=title, grid=grid)
    return fig, ax

plot_current_vs_time

plot_current_vs_time(result: TechniqueResult, *, ax: Axes | None = None, step: int | None = None, title: str | None = None, xlabel: str | None = None, ylabel: str | None = None, grid: bool = True, figsize: tuple[float, float] | None = None, **plot_kwargs: Any) -> tuple[Figure, Axes]

Plot net Faradaic current vs. time (\(I(t)\) vs. \(t\)).

Handles both 1D current arrays and 2D SampledCurrentVoltammetry step families (using step to select a single step or plotting all steps).

Source code in src/softpotato/techniques/plotting.py
def plot_current_vs_time(
    result: TechniqueResult,
    *,
    ax: Axes | None = None,
    step: int | None = None,
    title: str | None = None,
    xlabel: str | None = None,
    ylabel: str | None = None,
    grid: bool = True,
    figsize: tuple[float, float] | None = None,
    **plot_kwargs: Any,
) -> tuple[Figure, Axes]:
    """Plot net Faradaic current vs. time (:math:`I(t)` vs. :math:`t`).

    Handles both 1D current arrays and 2D :class:`SampledCurrentVoltammetry`
    step families (using ``step`` to select a single step or plotting all steps).
    """
    spec = result.technique.plot_specs["i_vs_t"]
    fig, ax = _resolve_axes(ax, figsize=figsize)

    if result.current.ndim == 2:
        if step is not None:
            kw = dict(plot_kwargs)
            if isinstance(result.technique, SampledCurrentVoltammetry):
                kw.setdefault(
                    "label", f"$E$ = {result.technique.potentials[step]:.3g} V"
                )
            ax.plot(result.time, result.current[step], **kw)
            if "label" in kw:
                ax.legend()
        else:
            potentials = (
                result.technique.potentials
                if isinstance(result.technique, SampledCurrentVoltammetry)
                else None
            )
            for idx in range(result.current.shape[0]):
                kw = dict(plot_kwargs)
                if potentials is not None:
                    kw.setdefault("label", f"$E$ = {potentials[idx]:.3g} V")
                else:
                    kw.setdefault("label", f"Step {idx + 1}")
                ax.plot(result.time, result.current[idx], **kw)
            ax.legend()
    else:
        ax.plot(result.time, result.current, **plot_kwargs)

    _apply_labels(ax, spec, title=title, xlabel=xlabel, ylabel=ylabel, grid=grid)
    return fig, ax

plot_dpv

plot_dpv(result: TechniqueResult, *, ax: Axes | None = None, show_components: bool = False, title: str | None = None, xlabel: str | None = None, ylabel: str | None = None, grid: bool = True, figsize: tuple[float, float] | None = None, **plot_kwargs: Any) -> tuple[Figure, Axes]

Plot a Differential Pulse Voltammogram (\(\Delta I\) vs. \(E_{\mathrm{base}}\)).

Source code in src/softpotato/techniques/plotting.py
def plot_dpv(
    result: TechniqueResult,
    *,
    ax: Axes | None = None,
    show_components: bool = False,
    title: str | None = None,
    xlabel: str | None = None,
    ylabel: str | None = None,
    grid: bool = True,
    figsize: tuple[float, float] | None = None,
    **plot_kwargs: Any,
) -> tuple[Figure, Axes]:
    """Plot a Differential Pulse Voltammogram (:math:`\\Delta I` vs. :math:`E_{\\mathrm{base}}`)."""
    if not isinstance(result.technique, DifferentialPulseVoltammetry):
        raise TypeError(
            "plot_dpv requires a DifferentialPulseVoltammetry TechniqueResult, "
            f"got {type(result.technique).__name__}."
        )
    spec = result.technique.plot_specs["dpv"]
    fig, ax = _resolve_axes(ax, figsize=figsize)

    kw = dict(plot_kwargs)
    kw.setdefault("label", r"$\Delta I = I_{\mathrm{pulse}} - I_{\mathrm{pre}}$")
    ax.plot(result.E_base, result.i_diff, **kw)

    if show_components:
        ax.plot(
            result.E_base,
            result.i_pulse,
            linestyle="--",
            alpha=0.75,
            label=r"$I_{\mathrm{pulse}}$",
        )
        ax.plot(
            result.E_base,
            result.i_pre,
            linestyle=":",
            alpha=0.75,
            label=r"$I_{\mathrm{pre}}$",
        )
        ax.legend()
    elif "label" in plot_kwargs:
        ax.legend()

    _apply_labels(ax, spec, title=title, xlabel=xlabel, ylabel=ylabel, grid=grid)
    return fig, ax

plot_koutecky_levich

plot_koutecky_levich(results_or_omega: RDESweepResult | Sequence[TechniqueResult] | Mapping[Any, TechniqueResult] | ArrayLike, fit_result: KouteckyLevichFitResult, *, currents: ArrayLike | None = None, potential: float | None = None, ax: Axes | None = None, title: str | None = None, grid: bool = True, figsize: tuple[float, float] | None = None) -> tuple[Figure, Axes]

Plot a Koutecký–Levich diagnostic regression (\(I^{-1}\) vs. \(\omega^{-1/2}\)).

Source code in src/softpotato/techniques/plotting.py
def plot_koutecky_levich(
    results_or_omega: RDESweepResult
    | Sequence[TechniqueResult]
    | Mapping[Any, TechniqueResult]
    | ArrayLike,
    fit_result: KouteckyLevichFitResult,
    *,
    currents: ArrayLike | None = None,
    potential: float | None = None,
    ax: Axes | None = None,
    title: str | None = None,
    grid: bool = True,
    figsize: tuple[float, float] | None = None,
) -> tuple[Figure, Axes]:
    r"""Plot a Koutecký–Levich diagnostic regression (:math:`I^{-1}` vs. :math:`\omega^{-1/2}`)."""
    if isinstance(results_or_omega, (RDESweepResult, Mapping)) or (
        isinstance(results_or_omega, Sequence)
        and not isinstance(results_or_omega, (str, bytes))
        and len(results_or_omega) > 0
        and isinstance(results_or_omega[0], TechniqueResult)
    ):
        rde_input = cast(
            "RDESweepResult | Sequence[TechniqueResult] | Mapping[Any, TechniqueResult]",
            results_or_omega,
        )
        omega_arr, _, _ = _extract_rde_series(rde_input, potential=potential)
    else:
        omega_arr = np.asarray(results_or_omega, dtype=float)

    inv_sqrt_omega = 1.0 / np.sqrt(omega_arr)
    y_fit = np.asarray(fit_result.y_fit, dtype=float)
    if currents is not None:
        y_data = 1.0 / np.abs(np.asarray(currents, dtype=float))
    else:
        y_data = y_fit + np.asarray(fit_result.residuals, dtype=float)
    order = np.argsort(inv_sqrt_omega)

    fig, ax = _resolve_axes(ax, figsize=figsize)
    ax.scatter(inv_sqrt_omega, y_data, color="tab:blue", zorder=4, label="Data")
    ax.plot(
        inv_sqrt_omega[order],
        y_fit[order],
        color="tab:red",
        linewidth=1.5,
        label=rf"Fit ($I_K$ = {fit_result.i_k:.3e} A, $R^2$ = {fit_result.r_squared:.4f})",
    )
    ax.legend()

    spec = PlotSpec(
        kind="koutecky_levich",
        title="Koutecký–Levich Analysis",
        x_label=r"$\omega^{-1/2}$ / $\mathrm{rad^{-1/2}\,s^{1/2}}$",
        y_label=r"$|I|^{-1}$ / $\mathrm{A^{-1}}$",
    )
    _apply_labels(ax, spec, title=title, grid=grid)
    return fig, ax

plot_levich

plot_levich(results_or_omega: RDESweepResult | Sequence[TechniqueResult] | Mapping[Any, TechniqueResult] | ArrayLike, fit_result: LevichFitResult, *, currents: ArrayLike | None = None, ax: Axes | None = None, title: str | None = None, grid: bool = True, figsize: tuple[float, float] | None = None) -> tuple[Figure, Axes]

Plot a Levich RDE diagnostic regression (\(I_L\) vs. \(\omega^{1/2}\)).

Source code in src/softpotato/techniques/plotting.py
def plot_levich(
    results_or_omega: RDESweepResult
    | Sequence[TechniqueResult]
    | Mapping[Any, TechniqueResult]
    | ArrayLike,
    fit_result: LevichFitResult,
    *,
    currents: ArrayLike | None = None,
    ax: Axes | None = None,
    title: str | None = None,
    grid: bool = True,
    figsize: tuple[float, float] | None = None,
) -> tuple[Figure, Axes]:
    r"""Plot a Levich RDE diagnostic regression (:math:`I_L` vs. :math:`\omega^{1/2}`)."""
    if isinstance(results_or_omega, (RDESweepResult, Mapping)) or (
        isinstance(results_or_omega, Sequence)
        and not isinstance(results_or_omega, (str, bytes))
        and len(results_or_omega) > 0
        and isinstance(results_or_omega[0], TechniqueResult)
    ):
        rde_input = cast(
            "RDESweepResult | Sequence[TechniqueResult] | Mapping[Any, TechniqueResult]",
            results_or_omega,
        )
        omega_arr, _, _ = _extract_rde_series(rde_input)
    else:
        omega_arr = np.asarray(results_or_omega, dtype=float)

    sqrt_omega = np.sqrt(omega_arr)
    y_fit = np.asarray(fit_result.y_fit, dtype=float)
    y_data = (
        np.asarray(currents, dtype=float)
        if currents is not None
        else y_fit + np.asarray(fit_result.residuals, dtype=float)
    )
    order = np.argsort(sqrt_omega)

    fig, ax = _resolve_axes(ax, figsize=figsize)
    ax.scatter(sqrt_omega, y_data, color="tab:blue", zorder=4, label="Data")
    ax.plot(
        sqrt_omega[order],
        y_fit[order],
        color="tab:red",
        linewidth=1.5,
        label=rf"Fit ($D$ = {fit_result.d:.3e}, $R^2$ = {fit_result.r_squared:.4f})",
    )
    ax.legend()

    spec = PlotSpec(
        kind="levich",
        title="Levich Analysis",
        x_label=r"$\omega^{1/2}$ / $\mathrm{rad^{1/2}\,s^{-1/2}}$",
        y_label=r"$I_L$ / A",
    )
    _apply_labels(ax, spec, title=title, grid=grid)
    return fig, ax

plot_peaks

plot_peaks(result: TechniqueResult, peaks: CVDiagnostics | PeakInfo | Sequence[PeakInfo] | None = None, *, cycle: int | None = -1, ax: Axes | None = None, title: str | None = None, grid: bool = True, figsize: tuple[float, float] | None = None, **plot_kwargs: Any) -> tuple[Figure, Axes]

Plot a voltammogram with annotated anodic and cathodic peak diagnostics.

Parameters:

Name Type Description Default
result TechniqueResult

Voltammetric simulation result (CV, LSV, SWV, DPV).

required
peaks CVDiagnostics, PeakInfo, or Sequence[PeakInfo]

Pre-computed peak diagnostics from find_peaks. If None, automatically runs find_peaks(result, cycle=cycle).

None
cycle int or None

Cycle index for CyclicVoltammetry (-1 selects the final cycle; None plots the full trace).

-1
ax Axes

Existing Axes to draw onto.

None
title str

Optional title override. When None and peaks is a CVDiagnostics with delta_Ep, includes \(\Delta E_p\) in the title.

None
grid bool

Whether to display a grid.

True
figsize tuple[float, float]

Figure size when ax is None.

None
**plot_kwargs Any

Additional keyword arguments forwarded to ax.plot.

{}

Returns:

Type Description
tuple[Figure, Axes]

Figure and Axes with the voltammogram and peak markers.

Source code in src/softpotato/techniques/plotting.py
def plot_peaks(
    result: TechniqueResult,
    peaks: CVDiagnostics | PeakInfo | Sequence[PeakInfo] | None = None,
    *,
    cycle: int | None = -1,
    ax: Axes | None = None,
    title: str | None = None,
    grid: bool = True,
    figsize: tuple[float, float] | None = None,
    **plot_kwargs: Any,
) -> tuple[Figure, Axes]:
    """Plot a voltammogram with annotated anodic and cathodic peak diagnostics.

    Parameters
    ----------
    result : TechniqueResult
        Voltammetric simulation result (CV, LSV, SWV, DPV).
    peaks : CVDiagnostics, PeakInfo, or Sequence[PeakInfo], optional
        Pre-computed peak diagnostics from :func:`find_peaks`. If ``None``,
        automatically runs ``find_peaks(result, cycle=cycle)``.
    cycle : int or None, default -1
        Cycle index for :class:`CyclicVoltammetry` (``-1`` selects the final
        cycle; ``None`` plots the full trace).
    ax : matplotlib.axes.Axes, optional
        Existing Axes to draw onto.
    title : str, optional
        Optional title override. When ``None`` and ``peaks`` is a
        :class:`CVDiagnostics` with ``delta_Ep``, includes :math:`\\Delta E_p`
        in the title.
    grid : bool, default True
        Whether to display a grid.
    figsize : tuple[float, float], optional
        Figure size when ``ax`` is ``None``.
    **plot_kwargs : Any
        Additional keyword arguments forwarded to ``ax.plot``.

    Returns
    -------
    tuple[matplotlib.figure.Figure, matplotlib.axes.Axes]
        Figure and Axes with the voltammogram and peak markers.
    """
    e_arr, i_arr = _extract_potential_current(result, cycle=cycle)
    resolved_peaks = find_peaks(result, cycle=cycle) if peaks is None else peaks

    fig, ax = _resolve_axes(ax, figsize=figsize)
    ax.plot(e_arr, i_arr, **plot_kwargs)
    _overlay_peaks_on_axes(ax, resolved_peaks)
    ax.legend()

    resolved_title = title
    if resolved_title is None:
        base_title = "Voltammetric Peak Diagnostics"
        if (
            isinstance(resolved_peaks, CVDiagnostics)
            and resolved_peaks.delta_Ep is not None
        ):
            resolved_title = (
                rf"{base_title} ($\Delta E_p$ = {resolved_peaks.delta_Ep * 1e3:.1f} mV)"
            )
        else:
            resolved_title = base_title

    spec = PlotSpec(
        kind="voltammogram",
        title=resolved_title,
        x_label="$E$ / V",
        y_label="$I$ / A",
    )
    _apply_labels(ax, spec, title=resolved_title, grid=grid)
    return fig, ax

plot_potential_vs_time

plot_potential_vs_time(result: TechniqueResult, *, ax: Axes | None = None, step: int | None = None, show_transition_time: bool = True, title: str | None = None, xlabel: str | None = None, ylabel: str | None = None, grid: bool = True, figsize: tuple[float, float] | None = None, **plot_kwargs: Any) -> tuple[Figure, Axes]

Plot electrode potential vs. time (\(E(t)\) vs. \(t\)).

For Chronopotentiometry, optionally marks the detected transition time \(\tau\) with a vertical dashed reference line when show_transition_time=True.

Source code in src/softpotato/techniques/plotting.py
def plot_potential_vs_time(
    result: TechniqueResult,
    *,
    ax: Axes | None = None,
    step: int | None = None,
    show_transition_time: bool = True,
    title: str | None = None,
    xlabel: str | None = None,
    ylabel: str | None = None,
    grid: bool = True,
    figsize: tuple[float, float] | None = None,
    **plot_kwargs: Any,
) -> tuple[Figure, Axes]:
    """Plot electrode potential vs. time (:math:`E(t)` vs. :math:`t`).

    For :class:`Chronopotentiometry`, optionally marks the detected transition
    time :math:`\\tau` with a vertical dashed reference line when
    ``show_transition_time=True``.
    """
    spec = result.technique.plot_specs["E_vs_t"]
    fig, ax = _resolve_axes(ax, figsize=figsize)

    if result.potential.ndim == 2:
        if step is not None:
            ax.plot(result.time, result.potential[step], **plot_kwargs)
        else:
            potentials = (
                result.technique.potentials
                if isinstance(result.technique, SampledCurrentVoltammetry)
                else None
            )
            for idx in range(result.potential.shape[0]):
                kw = dict(plot_kwargs)
                if potentials is not None:
                    kw.setdefault("label", f"$E$ = {potentials[idx]:.3g} V")
                else:
                    kw.setdefault("label", f"Step {idx + 1}")
                ax.plot(result.time, result.potential[idx], **kw)
            ax.legend()
    else:
        ax.plot(result.time, result.potential, **plot_kwargs)

    if (
        show_transition_time
        and isinstance(result.technique, Chronopotentiometry)
        and result.transition_time is not None
    ):
        tau = result.transition_time
        ax.axvline(
            tau,
            color="tab:red",
            linestyle="--",
            linewidth=1.2,
            label=rf"$\tau$ = {tau:.4g} s",
        )
        ax.legend()

    _apply_labels(ax, spec, title=title, xlabel=xlabel, ylabel=ylabel, grid=grid)
    return fig, ax

plot_randles_sevcik

plot_randles_sevcik(results_or_v: Sequence[TechniqueResult] | Mapping[Any, TechniqueResult] | ArrayLike, fit_result: RandlesSevcikFitResult, *, peak_currents: ArrayLike | None = None, polarity: PeakPolarity = 'cathodic', cycle: int | None = -1, ax: Axes | None = None, title: str | None = None, grid: bool = True, figsize: tuple[float, float] | None = None) -> tuple[Figure, Axes]

Plot a Randles–Ševčík diagnostic regression (\(|I_p|\) vs. \(v^{1/2}\)).

Parameters:

Name Type Description Default
results_or_v Sequence[TechniqueResult], Mapping[Any, TechniqueResult], or array-like

Collection of CV/LSV results or raw 1D array of scan rates \(v\) (V/s).

required
fit_result RandlesSevcikFitResult required
peak_currents array - like

Optional raw peak current array when results_or_v is a scan-rate array. If omitted, reconstructed from fit_result.y_fit + fit_result.residuals.

None
polarity ('cathodic', 'anodic')

Peak polarity label used when extracting from TechniqueResult objects.

'cathodic'
cycle int or None

Unused placeholder for API parity with analyze_randles_sevcik.

-1
ax Axes

Existing Axes to draw onto.

None
title str

Optional plot title override.

None
grid bool

Whether to display a background grid.

True
figsize tuple[float, float]

Figure size when ax is None.

None

Returns:

Type Description
tuple[Figure, Axes]

Figure and Axes containing the Randles–Ševčík plot.

Source code in src/softpotato/techniques/plotting.py
def plot_randles_sevcik(
    results_or_v: Sequence[TechniqueResult] | Mapping[Any, TechniqueResult] | ArrayLike,
    fit_result: RandlesSevcikFitResult,
    *,
    peak_currents: ArrayLike | None = None,
    polarity: PeakPolarity = "cathodic",
    cycle: int | None = -1,
    ax: Axes | None = None,
    title: str | None = None,
    grid: bool = True,
    figsize: tuple[float, float] | None = None,
) -> tuple[Figure, Axes]:
    r"""Plot a Randles–Ševčík diagnostic regression (:math:`|I_p|` vs. :math:`v^{1/2}`).

    Parameters
    ----------
    results_or_v : Sequence[TechniqueResult], Mapping[Any, TechniqueResult], or array-like
        Collection of CV/LSV results or raw 1D array of scan rates :math:`v` (V/s).
    fit_result : RandlesSevcikFitResult
        Fit output from :func:`~softpotato.techniques.analyze_randles_sevcik`
        or :func:`~softpotato.analytical.fitting.fit_randles_sevcik`.
    peak_currents : array-like, optional
        Optional raw peak current array when ``results_or_v`` is a scan-rate array.
        If omitted, reconstructed from ``fit_result.y_fit + fit_result.residuals``.
    polarity : {'cathodic', 'anodic'}, default 'cathodic'
        Peak polarity label used when extracting from ``TechniqueResult`` objects.
    cycle : int or None, default -1
        Unused placeholder for API parity with :func:`analyze_randles_sevcik`.
    ax : matplotlib.axes.Axes, optional
        Existing Axes to draw onto.
    title : str, optional
        Optional plot title override.
    grid : bool, default True
        Whether to display a background grid.
    figsize : tuple[float, float], optional
        Figure size when ``ax`` is ``None``.

    Returns
    -------
    tuple[matplotlib.figure.Figure, matplotlib.axes.Axes]
        Figure and Axes containing the Randles–Ševčík plot.
    """
    _ = (polarity, cycle)
    if isinstance(results_or_v, Mapping):
        v_list: list[float] = []
        for key, res in results_or_v.items():
            sr = getattr(res.technique, "scan_rate", None)
            v_list.append(float(sr if sr is not None else key))
        v_arr = np.asarray(v_list, dtype=float)
    elif (
        isinstance(results_or_v, Sequence)
        and not isinstance(results_or_v, (str, bytes))
        and len(results_or_v) > 0
        and isinstance(results_or_v[0], TechniqueResult)
    ):
        tr_seq = [r for r in results_or_v if isinstance(r, TechniqueResult)]
        v_arr = np.asarray(
            [float(getattr(r.technique, "scan_rate", np.nan)) for r in tr_seq],
            dtype=float,
        )
    else:
        v_arr = np.asarray(results_or_v, dtype=float)

    sqrt_v = np.sqrt(v_arr)
    y_fit = np.asarray(fit_result.y_fit, dtype=float)
    y_data = (
        np.asarray(peak_currents, dtype=float)
        if peak_currents is not None
        else y_fit + np.asarray(fit_result.residuals, dtype=float)
    )
    order = np.argsort(sqrt_v)

    fig, ax = _resolve_axes(ax, figsize=figsize)
    ax.scatter(sqrt_v, y_data, color="tab:blue", zorder=4, label="Data")
    ax.plot(
        sqrt_v[order],
        y_fit[order],
        color="tab:red",
        linewidth=1.5,
        label=rf"Fit ($D$ = {fit_result.d:.3e}, $R^2$ = {fit_result.r_squared:.4f})",
    )
    ax.legend()

    spec = PlotSpec(
        kind="randles_sevcik",
        title="Randles–Ševčík Analysis",
        x_label=r"$\sqrt{v}$ / $\mathrm{V^{1/2}\,s^{-1/2}}$",
        y_label=r"$I_p$ / A",
    )
    _apply_labels(ax, spec, title=title, grid=grid)
    return fig, ax

plot_result

plot_result(result: TechniqueResult, kind: str | None = None, *, ax: Axes | None = None, **kwargs: Any) -> tuple[Figure, Axes]

Dispatch a plot for result using the technique's declarative plot specs.

Parameters:

Name Type Description Default
result TechniqueResult

Output from simulate.

required
kind str

Concise plot key (e.g. 'voltammogram', 'i_vs_t', 'E_vs_t', 'c_vs_x', 'Q_vs_t', 'dpv', 'swv', 'scv') or verbose alias (e.g. 'current_vs_potential', 'current_vs_time', 'potential_vs_time', 'concentration_profile'). Defaults to result.default_plot.

None
ax Axes

Existing Axes to draw onto.

None
**kwargs Any

Additional keyword arguments forwarded to the plot renderer.

{}

Returns:

Type Description
tuple[Figure, Axes]

Figure and Axes containing the rendered plot.

Raises:

Type Description
TypeError

If result is not a TechniqueResult or kind is not a string.

ValueError

If kind is not supported by result.technique.

Source code in src/softpotato/techniques/plotting.py
def plot_result(
    result: TechniqueResult,
    kind: str | None = None,
    *,
    ax: Axes | None = None,
    **kwargs: Any,
) -> tuple[Figure, Axes]:
    """Dispatch a plot for ``result`` using the technique's declarative plot specs.

    Parameters
    ----------
    result : TechniqueResult
        Output from :func:`~softpotato.techniques.simulate`.
    kind : str, optional
        Concise plot key (e.g. ``'voltammogram'``, ``'i_vs_t'``, ``'E_vs_t'``,
        ``'c_vs_x'``, ``'Q_vs_t'``, ``'dpv'``, ``'swv'``, ``'scv'``) or verbose
        alias (e.g. ``'current_vs_potential'``, ``'current_vs_time'``,
        ``'potential_vs_time'``, ``'concentration_profile'``). Defaults to
        ``result.default_plot``.
    ax : matplotlib.axes.Axes, optional
        Existing Axes to draw onto.
    **kwargs : Any
        Additional keyword arguments forwarded to the plot renderer.

    Returns
    -------
    tuple[matplotlib.figure.Figure, matplotlib.axes.Axes]
        Figure and Axes containing the rendered plot.

    Raises
    ------
    TypeError
        If ``result`` is not a :class:`TechniqueResult` or ``kind`` is not a string.
    ValueError
        If ``kind`` is not supported by ``result.technique``.
    """
    if not isinstance(result, TechniqueResult):
        raise TypeError(
            f"result must be a TechniqueResult instance, got {type(result).__name__}."
        )

    canonical = result.default_plot if kind is None else resolve_plot_kind(kind)
    _get_spec(result, canonical)
    renderer = _PLOT_RENDERERS[canonical]
    return renderer(result, ax=ax, **kwargs)

plot_scv

plot_scv(result: TechniqueResult, *, ax: Axes | None = None, sample_times: float | Sequence[float] | ndarray | None = None, title: str | None = None, xlabel: str | None = None, ylabel: str | None = None, grid: bool = True, figsize: tuple[float, float] | None = None, **plot_kwargs: Any) -> tuple[Figure, Axes]

Plot a Sampled-Current Voltammogram (\(I(\tau)\) vs. \(E_{\mathrm{step}}\)).

Source code in src/softpotato/techniques/plotting.py
def plot_scv(
    result: TechniqueResult,
    *,
    ax: Axes | None = None,
    sample_times: float | Sequence[float] | np.ndarray | None = None,
    title: str | None = None,
    xlabel: str | None = None,
    ylabel: str | None = None,
    grid: bool = True,
    figsize: tuple[float, float] | None = None,
    **plot_kwargs: Any,
) -> tuple[Figure, Axes]:
    """Plot a Sampled-Current Voltammogram (:math:`I(\\tau)` vs. :math:`E_{\\mathrm{step}}`)."""
    if not isinstance(result.technique, SampledCurrentVoltammetry):
        raise TypeError(
            "plot_scv requires a SampledCurrentVoltammetry TechniqueResult, "
            f"got {type(result.technique).__name__}."
        )
    spec = result.technique.plot_specs["scv"]
    fig, ax = _resolve_axes(ax, figsize=figsize)

    sample_times_arg: float | list[float] | tuple[float, ...] | np.ndarray | None
    if sample_times is None or isinstance(
        sample_times, (float, int, list, tuple, np.ndarray)
    ):
        sample_times_arg = (
            float(sample_times) if isinstance(sample_times, int) else sample_times
        )
    else:
        sample_times_arg = list(sample_times)

    e_steps, i_sampled = result.sample_currents(sample_times=sample_times_arg)
    if i_sampled.ndim == 1:
        kw = dict(plot_kwargs)
        kw.setdefault("marker", "o")
        ax.plot(e_steps, i_sampled, **kw)
    else:
        times_used: tuple[float, ...]
        if sample_times is None:
            raw_times = result.technique.sample_times
            times_used = () if raw_times is None else tuple(float(x) for x in raw_times)
        elif np.isscalar(sample_times):
            times_used = (float(sample_times),)  # type: ignore[arg-type]
        else:
            times_used = tuple(float(x) for x in sample_times)  # type: ignore[union-attr]
        for idx in range(i_sampled.shape[0]):
            kw = dict(plot_kwargs)
            kw.setdefault("marker", "o")
            if idx < len(times_used):
                kw.setdefault("label", rf"$\tau$ = {times_used[idx]:.4g} s")
            else:
                kw.setdefault("label", f"Sample {idx + 1}")
            ax.plot(e_steps, i_sampled[idx], **kw)
        ax.legend()

    _apply_labels(ax, spec, title=title, xlabel=xlabel, ylabel=ylabel, grid=grid)
    return fig, ax

plot_summary

plot_summary(result: TechniqueResult, *, t: float | Sequence[float] | None = None, species: str | Sequence[str] | None = None, figsize: tuple[float, float] | None = None, **kwargs: Any) -> tuple[Figure, np.ndarray]

Render a multi-panel summary figure for a TechniqueResult.

Panels include the technique's default plot together with the universal views ('i_vs_t', 'E_vs_t', 'c_vs_x'), deduplicated in order (producing a 1x3 layout when the default plot is already 'i_vs_t' or 'E_vs_t', or a 2x2 layout otherwise).

Parameters:

Name Type Description Default
result TechniqueResult

Simulation result to summarize.

required
t float or Sequence[float]

Target time(s) in seconds passed to the 'c_vs_x' panel.

None
species str or Sequence[str]

Species subset passed to the 'c_vs_x' panel.

None
figsize tuple[float, float]

Optional figure size override.

None
**kwargs Any

Additional keyword arguments forwarded to each panel's plot_result.

{}

Returns:

Type Description
tuple[Figure, ndarray]

Figure and array of Axes objects.

Source code in src/softpotato/techniques/plotting.py
def plot_summary(
    result: TechniqueResult,
    *,
    t: float | Sequence[float] | None = None,
    species: str | Sequence[str] | None = None,
    figsize: tuple[float, float] | None = None,
    **kwargs: Any,
) -> tuple[Figure, np.ndarray]:
    """Render a multi-panel summary figure for a :class:`TechniqueResult`.

    Panels include the technique's default plot together with the universal
    views (``'i_vs_t'``, ``'E_vs_t'``, ``'c_vs_x'``), deduplicated in order
    (producing a 1x3 layout when the default plot is already ``'i_vs_t'`` or
    ``'E_vs_t'``, or a 2x2 layout otherwise).

    Parameters
    ----------
    result : TechniqueResult
        Simulation result to summarize.
    t : float or Sequence[float], optional
        Target time(s) in seconds passed to the ``'c_vs_x'`` panel.
    species : str or Sequence[str], optional
        Species subset passed to the ``'c_vs_x'`` panel.
    figsize : tuple[float, float], optional
        Optional figure size override.
    **kwargs : Any
        Additional keyword arguments forwarded to each panel's :func:`plot_result`.

    Returns
    -------
    tuple[matplotlib.figure.Figure, np.ndarray]
        Figure and array of Axes objects.
    """
    if not isinstance(result, TechniqueResult):
        raise TypeError(
            f"result must be a TechniqueResult instance, got {type(result).__name__}."
        )

    panel_kinds: list[str] = []
    for k in (result.default_plot, "i_vs_t", "E_vs_t", "c_vs_x"):
        if k not in panel_kinds:
            panel_kinds.append(k)

    if len(panel_kinds) == 3:
        nrows, ncols = 1, 3
        default_size = (13.5, 4.0)
    else:
        nrows, ncols = 2, 2
        default_size = (10.5, 8.0)

    fig, axes = plt.subplots(
        nrows,
        ncols,
        figsize=default_size if figsize is None else figsize,
    )
    axes_arr = np.asarray(axes)
    flat_axes = axes_arr.ravel()

    for ax_item, panel_kind in zip(flat_axes, panel_kinds):
        panel_kwargs = dict(kwargs)
        if panel_kind == "c_vs_x":
            if t is not None:
                panel_kwargs["t"] = t
            if species is not None:
                panel_kwargs["species"] = species
        plot_result(result, kind=panel_kind, ax=ax_item, **panel_kwargs)

    fig.tight_layout()
    return fig, axes_arr

plot_sweep

plot_sweep(results: Sequence[TechniqueResult] | Mapping[Any, TechniqueResult] | RDESweepResult, kind: str | None = None, *, ax: Axes | None = None, labels: Sequence[str] | None = None, legend_title: str | None = None, figsize: tuple[float, float] | None = None, **kwargs: Any) -> tuple[Figure, Axes]

Overlay a series of simulation results on a single set of axes.

Accepts output from simulate_sweep (either a Sequence[TechniqueResult] or Mapping[Any, TechniqueResult]) or RDESweepResult.

Parameters:

Name Type Description Default
results Sequence[TechniqueResult], Mapping[Any, TechniqueResult], or RDESweepResult

Collection of simulation results to overlay.

required
kind str

Concise plot key or verbose alias. Defaults to the first result's default_plot.

None
ax Axes

Existing Axes to draw onto.

None
labels Sequence[str]

Custom legend labels matching the length of results.

None
legend_title str

Optional title for the legend.

None
figsize tuple[float, float]

Figure size passed to plt.subplots when ax is None.

None
**kwargs Any

Additional keyword arguments forwarded to plot_result.

{}

Returns:

Type Description
tuple[Figure, Axes]

Figure and Axes containing the overlaid sweep traces.

Source code in src/softpotato/techniques/plotting.py
def plot_sweep(
    results: Sequence[TechniqueResult] | Mapping[Any, TechniqueResult] | RDESweepResult,
    kind: str | None = None,
    *,
    ax: Axes | None = None,
    labels: Sequence[str] | None = None,
    legend_title: str | None = None,
    figsize: tuple[float, float] | None = None,
    **kwargs: Any,
) -> tuple[Figure, Axes]:
    """Overlay a series of simulation results on a single set of axes.

    Accepts output from :func:`~softpotato.techniques.simulate_sweep` (either
    a ``Sequence[TechniqueResult]`` or ``Mapping[Any, TechniqueResult]``) or
    :class:`~softpotato.techniques.RDESweepResult`.

    Parameters
    ----------
    results : Sequence[TechniqueResult], Mapping[Any, TechniqueResult], or RDESweepResult
        Collection of simulation results to overlay.
    kind : str, optional
        Concise plot key or verbose alias. Defaults to the first result's
        ``default_plot``.
    ax : matplotlib.axes.Axes, optional
        Existing Axes to draw onto.
    labels : Sequence[str], optional
        Custom legend labels matching the length of ``results``.
    legend_title : str, optional
        Optional title for the legend.
    figsize : tuple[float, float], optional
        Figure size passed to ``plt.subplots`` when ``ax`` is ``None``.
    **kwargs : Any
        Additional keyword arguments forwarded to :func:`plot_result`.

    Returns
    -------
    tuple[matplotlib.figure.Figure, matplotlib.axes.Axes]
        Figure and Axes containing the overlaid sweep traces.
    """
    labeled_items: list[tuple[str, TechniqueResult]] = []
    if isinstance(results, RDESweepResult):
        labeled_items = _rde_sweep_to_technique_results(results)
    elif isinstance(results, Mapping):
        if len(results) == 0:
            raise ValueError("'results' mapping must not be empty.")
        for key, res in results.items():
            if not isinstance(res, TechniqueResult):
                raise TypeError(
                    f"Expected TechniqueResult values, got {type(res).__name__}."
                )
            labeled_items.append((str(key), res))
    elif isinstance(results, Sequence) and not isinstance(results, (str, bytes)):
        if len(results) == 0:
            raise ValueError("'results' sequence must not be empty.")
        for idx, res in enumerate(results):
            if not isinstance(res, TechniqueResult):
                raise TypeError(
                    f"Expected TechniqueResult entries, got {type(res).__name__}."
                )
            tech = res.technique
            if hasattr(tech, "scan_rate"):
                auto_label = f"$v$ = {tech.scan_rate:.4g} V/s"
            elif hasattr(tech, "rpm"):
                auto_label = f"{tech.rpm:.0f} rpm"
            elif hasattr(tech, "omega"):
                auto_label = rf"$\omega$ = {tech.omega:.4g} rad/s"
            else:
                auto_label = f"Run {idx + 1}"
            labeled_items.append((auto_label, res))
    else:
        raise TypeError(
            "results must be a Sequence/Mapping of TechniqueResult or an "
            f"RDESweepResult, got {type(results).__name__}."
        )

    if labels is not None:
        if len(labels) != len(labeled_items):
            raise ValueError(
                f"Length of 'labels' ({len(labels)}) must match number of "
                f"results ({len(labeled_items)})."
            )
        labeled_items = [
            (str(lbl), res) for lbl, (_, res) in zip(labels, labeled_items)
        ]

    fig, ax = _resolve_axes(ax, figsize=figsize)
    resolved_kind = kind if kind is not None else labeled_items[0][1].default_plot

    for lbl, res in labeled_items:
        item_kwargs = dict(kwargs)
        item_kwargs["label"] = lbl
        # Avoid cluttering sweep overlays with multiple component lines unless requested
        canonical = resolve_plot_kind(resolved_kind)
        if canonical == "swv":
            item_kwargs.setdefault("show_components", False)
        plot_result(res, kind=resolved_kind, ax=ax, **item_kwargs)

    ax.legend(title=legend_title)
    return fig, ax

plot_swv

plot_swv(result: TechniqueResult, *, ax: Axes | None = None, show_components: bool = True, title: str | None = None, xlabel: str | None = None, ylabel: str | None = None, grid: bool = True, figsize: tuple[float, float] | None = None, **plot_kwargs: Any) -> tuple[Figure, Axes]

Plot a Square-Wave Voltammogram (\(I_{\mathrm{net}}\), \(I_f\), \(I_r\) vs. \(E_{\mathrm{step}}\)).

Source code in src/softpotato/techniques/plotting.py
def plot_swv(
    result: TechniqueResult,
    *,
    ax: Axes | None = None,
    show_components: bool = True,
    title: str | None = None,
    xlabel: str | None = None,
    ylabel: str | None = None,
    grid: bool = True,
    figsize: tuple[float, float] | None = None,
    **plot_kwargs: Any,
) -> tuple[Figure, Axes]:
    """Plot a Square-Wave Voltammogram (:math:`I_{\\mathrm{net}}`, :math:`I_f`, :math:`I_r` vs. :math:`E_{\\mathrm{step}}`)."""
    if not isinstance(result.technique, SquareWaveVoltammetry):
        raise TypeError(
            "plot_swv requires a SquareWaveVoltammetry TechniqueResult, "
            f"got {type(result.technique).__name__}."
        )
    spec = result.technique.plot_specs["swv"]
    fig, ax = _resolve_axes(ax, figsize=figsize)

    kw = dict(plot_kwargs)
    kw.setdefault("label", r"$I_{\mathrm{net}}$")
    ax.plot(result.E_step, result.i_net, **kw)

    if show_components:
        ax.plot(
            result.E_step,
            result.i_forward,
            linestyle="--",
            alpha=0.75,
            label=r"$I_{\mathrm{forward}}$",
        )
        ax.plot(
            result.E_step,
            result.i_reverse,
            linestyle=":",
            alpha=0.75,
            label=r"$I_{\mathrm{reverse}}$",
        )
        ax.legend()
    elif "label" in plot_kwargs:
        ax.legend()

    _apply_labels(ax, spec, title=title, xlabel=xlabel, ylabel=ylabel, grid=grid)
    return fig, ax

plot_tafel

plot_tafel(overpotential_or_result: TechniqueResult | ArrayLike, fit_result: TafelFitResult, *, current: ArrayLike | None = None, E0: float | None = None, overpotential_window: tuple[float, float] | None = None, branch: Literal['cathodic', 'anodic'] = 'cathodic', cycle: int | None = -1, ax: Axes | None = None, title: str | None = None, grid: bool = True, figsize: tuple[float, float] | None = None) -> tuple[Figure, Axes]

Plot a Tafel diagnostic regression (\(\eta\) vs. \(\log_{10}|I|\)).

Source code in src/softpotato/techniques/plotting.py
def plot_tafel(
    overpotential_or_result: TechniqueResult | ArrayLike,
    fit_result: TafelFitResult,
    *,
    current: ArrayLike | None = None,
    E0: float | None = None,
    overpotential_window: tuple[float, float] | None = None,
    branch: Literal["cathodic", "anodic"] = "cathodic",
    cycle: int | None = -1,
    ax: Axes | None = None,
    title: str | None = None,
    grid: bool = True,
    figsize: tuple[float, float] | None = None,
) -> tuple[Figure, Axes]:
    r"""Plot a Tafel diagnostic regression (:math:`\eta` vs. :math:`\log_{10}|I|`)."""
    if isinstance(overpotential_or_result, TechniqueResult):
        if E0 is None:
            raise ValueError(
                "'E0' must be provided when plotting Tafel analysis from a TechniqueResult."
            )
        e_arr, i_arr = _extract_potential_current(overpotential_or_result, cycle=cycle)
        eta_all = e_arr - float(E0)
        if branch == "anodic":
            mask = (eta_all > 0.0) & (i_arr > 0.0)
        else:
            mask = (eta_all < 0.0) & (i_arr < 0.0)
        if overpotential_window is not None:
            lo, hi = overpotential_window
            mask &= (eta_all >= lo) & (eta_all <= hi)
        log_i = np.log10(np.abs(i_arr[mask]))
    else:
        if current is None:
            raise ValueError(
                "'current' must be provided when the first argument is an overpotential array."
            )
        eta_all = np.asarray(overpotential_or_result, dtype=float)
        i_arr = np.asarray(current, dtype=float)
        mask = np.isfinite(eta_all) & np.isfinite(i_arr) & (np.abs(i_arr) > 0.0)
        if overpotential_window is not None:
            lo, hi = overpotential_window
            mask &= (eta_all >= lo) & (eta_all <= hi)
        log_i = np.log10(np.abs(i_arr[mask]))

    y_fit = np.asarray(fit_result.y_fit, dtype=float)
    y_data = y_fit + np.asarray(fit_result.residuals, dtype=float)
    if log_i.size != y_fit.size:
        raise ValueError(
            f"Filtered data length ({log_i.size}) does not match fit_result.y_fit "
            f"length ({y_fit.size}). Ensure E0, branch, and overpotential_window "
            "match those used in analyze_tafel()."
        )

    order = np.argsort(log_i)
    fig, ax = _resolve_axes(ax, figsize=figsize)
    ax.scatter(log_i, y_data, s=18, color="tab:blue", zorder=4, label="Data")
    slope_mv = (
        fit_result.slope_mv
        if math.isfinite(fit_result.slope_mv)
        else fit_result.slope * 1e3
    )
    ax.plot(
        log_i[order],
        y_fit[order],
        color="tab:red",
        linewidth=1.5,
        label=rf"Fit ($b$ = {slope_mv:.1f} mV/dec, $I_0$ = {fit_result.i0:.2e} A)",
    )
    ax.legend()

    spec = PlotSpec(
        kind="tafel",
        title="Tafel Analysis",
        x_label=r"$\log_{10}(|I| / \mathrm{A})$",
        y_label=r"$\eta$ / V",
    )
    _apply_labels(ax, spec, title=title, grid=grid)
    return fig, ax

plot_voltammogram

plot_voltammogram(result: TechniqueResult, *, ax: Axes | None = None, cycle: int | Literal['all'] | None = None, peaks: bool | CVDiagnostics | PeakInfo | Sequence[PeakInfo] | None = None, title: str | None = None, xlabel: str | None = None, ylabel: str | None = None, grid: bool = True, figsize: tuple[float, float] | None = None, **plot_kwargs: Any) -> tuple[Figure, Axes]

Plot Faradaic current vs. electrode potential (\(I\) vs. \(E\)).

Parameters:

Name Type Description Default
result TechniqueResult

Simulation result to plot.

required
ax Axes

Existing Axes to draw onto.

None
cycle int, 'all', or None

For CyclicVoltammetry, select a specific cycle index (e.g. -1 for the final cycle), 'all' to plot each cycle as a separate labeled trace, or None to plot the continuous trace.

None
peaks bool, CVDiagnostics, PeakInfo, or Sequence[PeakInfo]

If True, runs find_peaks and overlays detected peaks. If a CVDiagnostics or PeakInfo (sequence) is given, overlays those peaks directly.

None
title str

Optional overrides for the default PlotSpec labels.

None
xlabel str

Optional overrides for the default PlotSpec labels.

None
ylabel str

Optional overrides for the default PlotSpec labels.

None
grid bool

Whether to show a light background grid.

True
figsize tuple[float, float]

Figure size passed to plt.subplots when ax is None.

None
**plot_kwargs Any

Additional keyword arguments forwarded to ax.plot.

{}

Returns:

Type Description
tuple[Figure, Axes]

Figure and Axes containing the voltammogram.

Source code in src/softpotato/techniques/plotting.py
def plot_voltammogram(
    result: TechniqueResult,
    *,
    ax: Axes | None = None,
    cycle: int | Literal["all"] | None = None,
    peaks: bool | CVDiagnostics | PeakInfo | Sequence[PeakInfo] | None = None,
    title: str | None = None,
    xlabel: str | None = None,
    ylabel: str | None = None,
    grid: bool = True,
    figsize: tuple[float, float] | None = None,
    **plot_kwargs: Any,
) -> tuple[Figure, Axes]:
    """Plot Faradaic current vs. electrode potential (:math:`I` vs. :math:`E`).

    Parameters
    ----------
    result : TechniqueResult
        Simulation result to plot.
    ax : matplotlib.axes.Axes, optional
        Existing Axes to draw onto.
    cycle : int, 'all', or None, default None
        For :class:`CyclicVoltammetry`, select a specific cycle index (e.g.
        ``-1`` for the final cycle), ``'all'`` to plot each cycle as a separate
        labeled trace, or ``None`` to plot the continuous trace.
    peaks : bool, CVDiagnostics, PeakInfo, or Sequence[PeakInfo], optional
        If ``True``, runs :func:`find_peaks` and overlays detected peaks.
        If a :class:`CVDiagnostics` or :class:`PeakInfo` (sequence) is given,
        overlays those peaks directly.
    title, xlabel, ylabel : str, optional
        Optional overrides for the default :class:`PlotSpec` labels.
    grid : bool, default True
        Whether to show a light background grid.
    figsize : tuple[float, float], optional
        Figure size passed to ``plt.subplots`` when ``ax`` is ``None``.
    **plot_kwargs : Any
        Additional keyword arguments forwarded to ``ax.plot``.

    Returns
    -------
    tuple[matplotlib.figure.Figure, matplotlib.axes.Axes]
        Figure and Axes containing the voltammogram.
    """
    spec = result.technique.plot_specs.get(
        "voltammogram",
        PlotSpec(
            kind="voltammogram",
            title="Voltammogram",
            x_label="$E$ / V",
            y_label="$I$ / A",
        ),
    )
    fig, ax = _resolve_axes(ax, figsize=figsize)

    if isinstance(result.technique, CyclicVoltammetry) and cycle is not None:
        if cycle == "all":
            for idx, cyc in enumerate(result.cycles):
                kw = dict(plot_kwargs)
                kw.setdefault("label", f"Cycle {idx + 1}")
                ax.plot(cyc.potential, cyc.current, **kw)
            ax.legend()
        elif isinstance(cycle, int) and not isinstance(cycle, bool):
            cyc = result.cycles[cycle]
            ax.plot(cyc.potential, cyc.current, **plot_kwargs)
        else:
            raise ValueError(f"cycle must be an int, 'all', or None, got {cycle!r}.")
    else:
        ax.plot(result.potential, result.current, **plot_kwargs)

    if peaks is True:
        peak_cycle = cycle if isinstance(cycle, int) else -1
        detected = find_peaks(result, cycle=peak_cycle)
        _overlay_peaks_on_axes(ax, detected)
        ax.legend()
    elif peaks is not None and peaks is not False:
        _overlay_peaks_on_axes(ax, peaks)
        ax.legend()

    _apply_labels(ax, spec, title=title, xlabel=xlabel, ylabel=ylabel, grid=grid)
    return fig, ax

simulate_rde_sweep

simulate_rde_sweep(*, sweep: RDESweep | None = None, waveform: BaseTechnique | None = None, omegas: Sequence[float] | ArrayLike | None = None, rpms: Sequence[float] | ArrayLike | None = None, kinematic_viscosity: float = _DEFAULT_KINEMATIC_VISCOSITY, model: RDEModel = 'nernst_layer', E_start: float | None = None, E_end: float | None = None, scan_rate: float | None = None, dE: float | None = None, n_time_points: int | None = None, D: float | None = None, diffusivity: Mapping[str, float] | None = None, c_bulk: float = 1.0, initial_conditions: Mapping[str, Any] | None = None, boundary_conditions: Mapping[str, tuple[BoundaryCondition, BoundaryCondition]] | None = None, kinetics: HeterogeneousKinetics | NernstianEquilibrium | None = None, species_name: str = 'Ox', red_species_name: str = 'Red', c_red_bulk: float = 0.0, n_electrons: int | Mapping[str, int] = 1, area: float = 1.0, reactions: Any = None, n_points: int = 80, grid_kind: str = 'geometric', gamma: float = 1.06, beta: float = 3.0, domain_factor: float | None = None, solver: str = 'scipy_ivp', t_eval: ndarray | None = None, solver_kwargs: Mapping[str, Any] | None = None) -> RDESweepResult

Simulate a multi-rotation-rate RDE sweep for Levich or Koutecký–Levich analysis.

Accepts either a pre-configured RDESweep instance or direct sweep parameters (omegas/rpms plus waveform or LSV parameters), builds a rotation-rate-specific DiffusionProblem for each speed, and solves all cases in a single call.

Parameters:

Name Type Description Default
sweep RDESweep

Pre-configured sweep object. If omitted, one is constructed from omegas/rpms and waveform (or LSV parameters).

None
waveform BaseTechnique

Shared potentiostatic waveform (ignored if sweep is supplied).

None
omegas Sequence[float]

Rotation rates in rad/s or RPM (ignored if sweep is supplied).

None
rpms Sequence[float]

Rotation rates in rad/s or RPM (ignored if sweep is supplied).

None
kinematic_viscosity float

Electrolyte kinematic viscosity in \(\text{m}^2/\text{s}\).

1e-6
model ('nernst_layer', 'convective_diffusion')

Hydrodynamic transport model.

'nernst_layer'
D float

Scalar diffusion coefficient \(D > 0\). Mutually exclusive with diffusivity.

None
diffusivity Mapping[str, float]

Per-species diffusion coefficients. Mutually exclusive with D.

None
c_bulk float

Bulk concentration of the primary electroactive species.

1.0
initial_conditions Mapping[str, Any]

Optional explicit initial concentration profiles.

None
boundary_conditions Mapping[str, tuple[BoundaryCondition, BoundaryCondition]]

Optional explicit boundary conditions.

None
kinetics HeterogeneousKinetics or NernstianEquilibrium

Interfacial charge-transfer model used to generate boundary conditions when boundary_conditions is omitted.

None
species_name str

Primary electroactive species name.

'Ox'
red_species_name str

Reduced partner species name (used when kinetics is supplied).

'Red'
c_red_bulk float

Bulk concentration of the reduced partner species.

0.0
n_electrons int or Mapping[str, int]

Electrons transferred per species (matches DiffusionProblem; n_electrons=1 yields IUPAC negative cathodic currents when Ox is reduced).

1
area float

Electrode geometric surface area.

1.0
reactions Any

Optional homogeneous reaction term.

None
n_points int

Number of spatial grid nodes per simulation.

80
grid_kind ('geometric', 'exponential', 'uniform')

Mesh family passed to RotatingDiskElectrode.build_grid.

'geometric'
gamma float

Geometric expansion ratio for grid_kind='geometric'.

1.06
beta float

Stretching parameter for grid_kind='exponential'.

3.0
domain_factor float

Override domain multiplier \(k\) applied to \(\delta_N\).

None
solver str

Registered solver name passed to get_solver.

'scipy_ivp'
t_eval ndarray

Evaluation timestamps shared across all rotation rates. Defaults to sweep.waveform.time_grid().

None
solver_kwargs Mapping[str, Any]

Additional keyword arguments forwarded to solver.solve(...).

None

Returns:

Type Description
RDESweepResult

Aggregated rotation rates, per-rate solver results, and limiting currents suitable for Levich or Koutecký–Levich analysis.

Source code in src/softpotato/techniques/rde.py
def simulate_rde_sweep(
    *,
    sweep: RDESweep | None = None,
    waveform: BaseTechnique | None = None,
    omegas: Sequence[float] | ArrayLike | None = None,
    rpms: Sequence[float] | ArrayLike | None = None,
    kinematic_viscosity: float = _DEFAULT_KINEMATIC_VISCOSITY,
    model: RDEModel = "nernst_layer",
    E_start: float | None = None,
    E_end: float | None = None,
    scan_rate: float | None = None,
    dE: float | None = None,
    n_time_points: int | None = None,
    D: float | None = None,
    diffusivity: Mapping[str, float] | None = None,
    c_bulk: float = 1.0,
    initial_conditions: Mapping[str, Any] | None = None,
    boundary_conditions: Mapping[str, tuple[BoundaryCondition, BoundaryCondition]]
    | None = None,
    kinetics: HeterogeneousKinetics | NernstianEquilibrium | None = None,
    species_name: str = "Ox",
    red_species_name: str = "Red",
    c_red_bulk: float = 0.0,
    n_electrons: int | Mapping[str, int] = 1,
    area: float = 1.0,
    reactions: Any = None,
    n_points: int = 80,
    grid_kind: str = "geometric",
    gamma: float = 1.06,
    beta: float = 3.0,
    domain_factor: float | None = None,
    solver: str = "scipy_ivp",
    t_eval: np.ndarray | None = None,
    solver_kwargs: Mapping[str, Any] | None = None,
) -> RDESweepResult:
    """Simulate a multi-rotation-rate RDE sweep for Levich or Koutecký–Levich analysis.

    Accepts either a pre-configured :class:`RDESweep` instance or direct sweep
    parameters (``omegas``/``rpms`` plus ``waveform`` or LSV parameters), builds
    a rotation-rate-specific :class:`~softpotato.solver.DiffusionProblem` for
    each speed, and solves all cases in a single call.

    Parameters
    ----------
    sweep : RDESweep, optional
        Pre-configured sweep object. If omitted, one is constructed from
        ``omegas``/``rpms`` and ``waveform`` (or LSV parameters).
    waveform : BaseTechnique, optional
        Shared potentiostatic waveform (ignored if ``sweep`` is supplied).
    omegas, rpms : Sequence[float], optional
        Rotation rates in rad/s or RPM (ignored if ``sweep`` is supplied).
    kinematic_viscosity : float, default 1e-6
        Electrolyte kinematic viscosity in :math:`\\text{m}^2/\\text{s}`.
    model : {'nernst_layer', 'convective_diffusion'}, default 'nernst_layer'
        Hydrodynamic transport model.
    D : float, optional
        Scalar diffusion coefficient :math:`D > 0`. Mutually exclusive with
        ``diffusivity``.
    diffusivity : Mapping[str, float], optional
        Per-species diffusion coefficients. Mutually exclusive with ``D``.
    c_bulk : float, default 1.0
        Bulk concentration of the primary electroactive species.
    initial_conditions : Mapping[str, Any], optional
        Optional explicit initial concentration profiles.
    boundary_conditions : Mapping[str, tuple[BoundaryCondition, BoundaryCondition]], optional
        Optional explicit boundary conditions.
    kinetics : HeterogeneousKinetics or NernstianEquilibrium, optional
        Interfacial charge-transfer model used to generate boundary conditions
        when ``boundary_conditions`` is omitted.
    species_name : str, default 'Ox'
        Primary electroactive species name.
    red_species_name : str, default 'Red'
        Reduced partner species name (used when ``kinetics`` is supplied).
    c_red_bulk : float, default 0.0
        Bulk concentration of the reduced partner species.
    n_electrons : int or Mapping[str, int], default 1
        Electrons transferred per species (matches :class:`~softpotato.solver.DiffusionProblem`;
        ``n_electrons=1`` yields IUPAC negative cathodic currents when ``Ox`` is reduced).
    area : float, default 1.0
        Electrode geometric surface area.
    reactions : Any, optional
        Optional homogeneous reaction term.
    n_points : int, default 80
        Number of spatial grid nodes per simulation.
    grid_kind : {'geometric', 'exponential', 'uniform'}, default 'geometric'
        Mesh family passed to :meth:`RotatingDiskElectrode.build_grid`.
    gamma : float, default 1.06
        Geometric expansion ratio for ``grid_kind='geometric'``.
    beta : float, default 3.0
        Stretching parameter for ``grid_kind='exponential'``.
    domain_factor : float, optional
        Override domain multiplier :math:`k` applied to :math:`\\delta_N`.
    solver : str, default 'scipy_ivp'
        Registered solver name passed to :func:`~softpotato.solver.get_solver`.
    t_eval : np.ndarray, optional
        Evaluation timestamps shared across all rotation rates. Defaults to
        ``sweep.waveform.time_grid()``.
    solver_kwargs : Mapping[str, Any], optional
        Additional keyword arguments forwarded to ``solver.solve(...)``.

    Returns
    -------
    RDESweepResult
        Aggregated rotation rates, per-rate solver results, and limiting
        currents suitable for Levich or Koutecký–Levich analysis.
    """
    if sweep is None:
        sweep = RDESweep(
            waveform,
            omegas=omegas,
            rpms=rpms,
            kinematic_viscosity=kinematic_viscosity,
            model=model,
            E_start=E_start,
            E_end=E_end,
            scan_rate=scan_rate,
            dE=dE,
            n_points=n_time_points,
            domain_factor=domain_factor,
        )
    elif not isinstance(sweep, RDESweep):
        raise TypeError(
            f"sweep must be an instance of RDESweep, got {type(sweep).__name__}."
        )

    solver_inst = get_solver(solver)
    extra_kwargs = dict(solver_kwargs) if solver_kwargs is not None else {}
    t_grid = (
        sweep.waveform.time_grid()
        if t_eval is None
        else np.asarray(t_eval, dtype=float)
    )
    t_span = (0.0, sweep.waveform.duration)

    results_list: list[SolverResult] = []
    limiting: list[float] = []
    primary_species = species_name

    for tech in sweep.techniques:
        problem = tech.build_problem(
            D=D,
            diffusivity=diffusivity,
            c_bulk=c_bulk,
            initial_conditions=initial_conditions,
            boundary_conditions=boundary_conditions,
            kinetics=kinetics,
            species_name=species_name,
            red_species_name=red_species_name,
            c_red_bulk=c_red_bulk,
            n_electrons=n_electrons,
            area=area,
            reactions=reactions,
            n_points=n_points,
            grid_kind=grid_kind,
            gamma=gamma,
            beta=beta,
            domain_factor=domain_factor,
        )
        if primary_species not in problem.species:
            primary_species = problem.species[0]

        res = solver_inst.solve(
            problem,
            t_span=t_span,
            t_eval=t_grid,
            **extra_kwargs,
        )
        results_list.append(res)
        if res.success and primary_species in res.currents:
            limiting.append(float(res.currents[primary_species][-1]))
        else:
            limiting.append(float("nan"))

    return RDESweepResult(
        omegas=sweep.omegas,
        rpms=sweep.rpms,
        results=tuple(results_list),
        limiting_currents=np.asarray(limiting, dtype=float),
        techniques=sweep.techniques,
        species=primary_species,
    )