Skip to content

Reactions Module (softpotato.reactions)

The softpotato.reactions subpackage provides modular abstractions for multi-species chemical metadata, homogeneous (solution-phase) reaction kinetics with automated analytical Jacobians, heterogeneous interfacial charge-transfer kinetics, and unified electrochemical mechanism containers that plug directly into DiffusionProblem and ScipyIVPSolver.


Theoretical Background

1. Coupled Reaction–Diffusion Transport & Analytical Jacobians

In a 1D multi-species electrochemical system with coupled solution-phase chemistry, the concentration \(c_i(x, t)\) of each chemical species \(i\) evolves according to the reaction–diffusion partial differential equation:

\[ \frac{\partial c_i}{\partial t} = D_i \nabla^2 c_i + R_i(\mathbf{c}, x, t), \qquad R_i(\mathbf{c}) = \sum_j \nu_{i,j}\, r_j(\mathbf{c}) \]

where \(D_i > 0\) is the diffusion coefficient of species \(i\), \(\nu_{i,j}\) is its net stoichiometric coefficient in reaction \(j\) (negative for consumed reactants, positive for produced products), and \(r_j(\mathbf{c})\) is the volumetric reaction rate.

Because homogeneous chemical rate constants \(k\) can span many orders of magnitude (\(10^{-2}\) to \(10^{6}\,\text{s}^{-1}\)), reaction–diffusion ODE systems produced by Method-of-Lines discretization are frequently stiff. Every HomogeneousReaction subclass provides exact analytical partial derivatives \(\partial r_j / \partial c_k\), allowing ReactionNetwork to assemble the exact local and global sparse kinetic Jacobian:

\[ J_{ik} = \frac{\partial R_i}{\partial c_k} = \sum_j \nu_{i,j} \frac{\partial r_j}{\partial c_k} \]

ScipyIVPSolver automatically combines the sparse spatial diffusion Jacobian with the sparse kinetic Jacobian for implicit stiff integrators (Radau and BDF), dramatically accelerating convergence and maintaining machine-precision mass conservation.

2. Characteristic Reaction Layer Thickness & Expanding Grids

For a coupled catalytic (EC') or follow-up (EC) mechanism with pseudo-first-order rate constant \(k'\), homogeneous chemical conversion confines concentration gradients within a reaction layer of characteristic thickness:

\[ \mu = \sqrt{\frac{D}{k'}} \]

When \(k'\) is large, \(\mu \ll \delta = 6\sqrt{D t_{\max}}\) and the interfacial concentration profile becomes exponentially steep near \(x = 0\):

\[ c_{\text{Ox}}(x) = c^* \left(1 - e^{-x/\mu}\right), \qquad I_{\text{cat}} = -n F A c^* \sqrt{D k'} \]

Pairing GeometricExpandingMesh or ExponentialMesh from softpotato.grid with ScipyIVPSolver (method="Radau") concentrates spatial nodes inside the thin reaction layer \(\mu\) while smoothly coarsening into the bulk, achieving \(< 1\%\) current accuracy with fewer than 100 grid nodes.

3. Heterogeneous Interfacial Charge-Transfer Kinetics

For a single-step interfacial redox reaction at the electrode surface (\(x = 0\)):

\[ \text{Ox} + n e^- \underset{k_b(E)}{\overset{k_f(E)}{\rightleftharpoons}} \text{Red} \]
  • Butler–Volmer kinetics (ButlerVolmer) relates forward (reduction) and backward (oxidation) rate constants to the overpotential \(\eta = E(t) - E^{0\prime}\):

$$ k_f(E) = k^0 \exp!\left(-\frac{\alpha n F}{R T}(E - E^{0\prime})\right), \qquad k_b(E) = k^0 \exp!\left(\frac{(1 - \alpha) n F}{R T}(E - E^{0\prime})\right) $$

yielding the net interfacial reduction flux \(J = k_f(E) c_{\text{Ox}}(0, t) - k_b(E) c_{\text{Red}}(0, t)\) and IUPAC Faradaic current density (anodic positive):

$$ j = -n F J = n F \left[k_b(E) c_{\text{Red}}(0, t) - k_f(E) c_{\text{Ox}}(0, t)\right] $$

  • Tafel kinetics (TafelKinetics / Tafel) isolates the dominant unidirectional branch at high overpotential (\(|\eta| \gg RT/nF\)), retaining only \(k_f(E)\) on the cathodic branch or \(k_b(E)\) on the anodic branch.

  • Nernstian equilibrium (NernstianEquilibrium) models infinitely fast (reversible) electron transfer by enforcing the thermodynamic surface concentration ratio directly as time-dependent Dirichlet boundary conditions:

$$ \frac{c_{\text{Ox}}(0, t)}{c_{\text{Red}}(0, t)} = \exp!\left(\frac{n F}{R T}\left(E(t) - E^{0\prime}\right)\right) $$


API Overview

Chemical Species & Collections

Class Key Parameters / Properties Description
Species name, diffusivity, bulk_concentration, charge, standard_potential, n_electrons Immutable dataclass encapsulating a chemical species and its physicochemical transport/thermodynamic metadata.
SpeciesCollection names, diffusivities, bulk_concentrations, n_electrons_map Ordered mapping container managing a group of Species objects with dict-like lookup and DiffusionProblem export helpers.

Homogeneous Reaction Kinetics

Class Mechanism / Rate Law Key Parameters Description
HomogeneousReaction Abstract stoichiometry, rate(), rate_derivatives() Abstract base class for custom solution-phase reactions with analytical or finite-difference Jacobians.
MassActionReaction \(\sum a_i A_i \rightleftharpoons \sum b_j B_j\) reactants, products, k_f, k_b General elementary mass-action reaction supporting arbitrary integer stoichiometric orders and reversibility.
FirstOrderReaction \(A \xrightarrow{k} B\) reactant, product, k Irreversible unimolecular reaction (\(r = k c_A\)), e.g. EC follow-up decay.
ReversibleReaction \(A \underset{k_b}{\overset{k_f}{\rightleftharpoons}} B\) reactant, product, k_f, k_b Reversible first-order equilibrium (\(r = k_f c_A - k_b c_B\)) with equilibrium constant \(K_{\text{eq}} = k_f / k_b\).
SecondOrderReaction \(A + B \xrightarrow{k} C\) reactant_1, reactant_2, product, k Irreversible bimolecular reaction (\(r = k c_A c_B\)).
DimerizationReaction \(2 A \xrightarrow{k} A_2\) monomer, dimer, k Irreversible homodimerization (\(r = k c_A^2\)).
DisproportionationReaction \(2 B \xrightarrow{k} A + C\) reactant, product_1, product_2, k Irreversible disproportionation (\(r = k c_B^2\)).
CatalyticReaction \(B (+ Z) \xrightarrow{k} A (+ P)\) reactant, regenerated, k, substrate, product Pseudo-first-order (\(r = k c_B\)) or bimolecular (\(r = k c_B c_Z\)) EC' catalytic regeneration step.
CustomReaction User callable \(r(\mathbf{c}, x, t)\) stoichiometry, rate, rate_derivatives Wraps arbitrary user-defined rate laws (e.g. Michaelis–Menten) with optional analytical or automatic finite-difference derivatives.
ReactionNetwork \(\mathbf{R}(\mathbf{c}) = \sum_j \boldsymbol{\nu}_j r_j(\mathbf{c})\) reactions, species Composes multiple homogeneous reactions and assembles vectorized rates and sparse block Jacobians for DiffusionProblem.

Heterogeneous Charge-Transfer Kinetics

Class / Function Key Parameters Description
HeterogeneousKinetics E0, n, T, R, F Abstract base class for finite-rate interfacial electron-transfer models providing rate_constants, net_flux, current_density, and boundary_conditions.
ButlerVolmer k0, alpha, E0, n, T Reversible and quasi-reversible Butler–Volmer charge-transfer kinetics.
TafelKinetics (Tafel) k0, alpha, E0, n, branch, T High-overpotential / irreversible unidirectional Tafel kinetics ('auto', 'cathodic', or 'anodic').
NernstianEquilibrium E0, n, T Reversible thermodynamic equilibrium helper computing surface concentration ratios and Dirichlet boundary conditions.
create_electrochemical_bcs kinetics, potential, ox, red, electrode_side, bulk_bc Factory constructing matched (left_bc, right_bc) boundary condition tuples for a redox pair in DiffusionProblem.

Mechanism Containers

Class Key Parameters Description
ElectrochemicalStep ox, red, kinetics, electrode_side, bulk_bc Declarative specification of a single interfacial redox step at an electrode boundary.
Mechanism species, reactions, electrochemical_steps, name Complete chemical/electrochemical model independent of grid and solver, with create_problem(...) helper.
CustomMechanism species, reactions, rates, local_jacobian_func, electrochemical_steps, boundary_conditions_func Declarative extension point combining built-in reactions, custom rate/Jacobian callables, and custom boundary conditions.

User Guide & Examples

1. Defining Species and a Catalytic (EC') Reaction Network

Define Species objects and combine homogeneous steps in a ReactionNetwork, then pass them directly to DiffusionProblem:

import math
import numpy as np
from softpotato.constants import FARADAY
from softpotato.geometry import PlanarGeometry
from softpotato.grid import GeometricExpandingMesh
from softpotato.reactions import CatalyticReaction, ReactionNetwork, Species
from softpotato.solver import DiffusionProblem, DirichletBC, ScipyIVPSolver

D = 1e-9  # m^2/s
c_bulk = 1.0  # mol/m^3 (1 mM)
area = 1e-4  # m^2 (1 cm^2)
k_prime = 10.0  # s^-1 (pseudo-first-order catalytic rate constant)

# Reaction layer thickness mu = sqrt(D / k'); span 10 * mu with an expanding mesh
mu = math.sqrt(D / k_prime)
mesh = GeometricExpandingMesh(0.0, 10.0 * mu, n_points=80, gamma=1.06)

ox = Species("Ox", diffusivity=D, bulk_concentration=c_bulk, n_electrons=1)
red = Species("Red", diffusivity=D, bulk_concentration=0.0, n_electrons=-1)
network = ReactionNetwork([CatalyticReaction(red, ox, k=k_prime)])

problem = DiffusionProblem(
    grid=mesh,
    species=[ox, red],
    boundary_conditions={
        "Ox": (DirichletBC(0.0), DirichletBC(c_bulk)),
        "Red": (DirichletBC(c_bulk), DirichletBC(0.0)),
    },
    reactions=network,
    geometry=PlanarGeometry(area=area),
)

solver = ScipyIVPSolver(method="Radau", rtol=1e-7, atol=1e-10)
result = solver.solve(problem, t_span=(0.0, 1.0), t_eval=np.linspace(0.0, 1.0, 100))

i_cat_exact = -FARADAY * area * c_bulk * math.sqrt(D * k_prime)
print(f"Simulated steady-state current: {result.currents['Ox'][-1] * 1e3:.4f} mA")
print(f"Analytical catalytic limit:     {i_cat_exact * 1e3:.4f} mA")

2. Heterogeneous Kinetics & Mechanism Containers

Evaluate Butler–Volmer rate constants and construct boundary conditions via create_electrochemical_bcs or package species, homogeneous steps, and interfacial kinetics together in a Mechanism:

from softpotato.grid import create_diffusion_mesh
from softpotato.reactions import (
    ButlerVolmer,
    ElectrochemicalStep,
    FirstOrderReaction,
    Mechanism,
    NernstianEquilibrium,
    Species,
)
from softpotato.solver import ScipyIVPSolver

# 1. Inspect Butler-Volmer kinetics
bv = ButlerVolmer(k0=1e-4, alpha=0.5, E0=0.0, n=1)
kf, kb = bv.rate_constants(E=-0.1)
j0 = bv.exchange_current_density(c_ox=1.0, c_red=1.0)

# 2. Build a complete EC mechanism (reversible E step + follow-up chemical decay)
ox = Species("Ox", diffusivity=1e-9, bulk_concentration=1.0, n_electrons=1)
red = Species("Red", diffusivity=1e-9, bulk_concentration=0.0, n_electrons=-1)
prod = Species("P", diffusivity=1e-9, bulk_concentration=0.0)

ec_mech = Mechanism(
    species=[ox, red, prod],
    reactions=[FirstOrderReaction(red, prod, k=2.0)],
    electrochemical_steps=[
        ElectrochemicalStep(ox, red, NernstianEquilibrium(E0=0.0, n=1))
    ],
    name="EC_Mechanism",
)

mesh = create_diffusion_mesh(
    D=1e-9, t_max=1.0, kind="geometric", n_points=60, gamma=1.08
)
problem = ec_mech.create_problem(mesh, potential=-0.3)
result = ScipyIVPSolver(method="Radau").solve(problem, t_span=(0.0, 1.0))

3. Interactive Tutorials

For full worked examples with plots and analytical benchmarks, explore the interactive Jupyter notebooks:

  • Catalytic EC' Mechanism: tutorials/mechanisms/catalytic_ec.ipynb — chronoamperometry of an EC' catalytic cycle, steady-state concentration profiles, and validation against the Delahay–Stiehl and catalytic limiting current equations.
  • Heterogeneous Kinetics & Cyclic Voltammetry: tutorials/mechanisms/cv_butler_volmer.ipynb — Butler–Volmer cyclic voltammetry across reversible, quasi-reversible, and irreversible regimes, with \(\Delta E_p\) vs. scan rate analysis against Randles–Ševčík and Nicholson theory.

Module Contents

reactions

Chemical species and electrochemical reaction kinetics for Soft Potato.

This subpackage provides modular abstractions for chemical species metadata, homogeneous (solution-phase) reaction kinetics with automated analytical Jacobians, and heterogeneous charge-transfer kinetics.

Examples:

>>> from softpotato.reactions import ButlerVolmer, Species, SpeciesCollection
>>> ox = Species("Ox", diffusivity=1e-9, bulk_concentration=1.0, n_electrons=1)
>>> red = Species("Red", diffusivity=1e-9, bulk_concentration=0.0, n_electrons=-1)
>>> species = SpeciesCollection([ox, red])
>>> species.diffusivities
{'Ox': 1e-09, 'Red': 1e-09}
>>> bv = ButlerVolmer(k0=1e-4, alpha=0.5, E0=0.0, n=1)
>>> bv.rate_constants(0.0)
(0.0001, 0.0001)

Homogeneous reactions are combined in a ReactionNetwork, which can be passed directly to DiffusionProblem(..., reactions=network):

>>> from softpotato.reactions import FirstOrderReaction, ReactionNetwork
>>> network = ReactionNetwork([FirstOrderReaction(red, "P", k=1.0)])
>>> network.species
['Red', 'P']

ButlerVolmer dataclass

Bases: HeterogeneousKinetics

Butler–Volmer heterogeneous charge-transfer kinetics.

Models forward (cathodic) and backward (anodic) electron-transfer rate constants for \(\text{Ox} + n e^- \rightleftharpoons \text{Red}\):

\[ k_f(E) = k^0 \exp\left(-\frac{\alpha n F}{R T}(E - E^{0\prime})\right) \]
\[ k_b(E) = k^0 \exp\left(\frac{(1 - \alpha) n F}{R T}(E - E^{0\prime})\right) \]

Rate constants, exchange current density, Faradaic current density, and Tafel slopes are evaluated by delegating to softpotato.analytical.kinetics.

Parameters:

Name Type Description Default
k0 float

Standard heterogeneous rate constant \(k^0 > 0\) in \(\text{m}/\text{s}\) or \(\text{cm}/\text{s}\).

required
alpha float

Cathodic charge-transfer coefficient (\(0 < \alpha < 1\)).

0.5
E0 float

Formal reduction potential \(E^{0\prime}\) in Volts (V).

0.0
n float

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

1
T float

Temperature in Kelvin (\(T > 0\), default 298.15 K).

STANDARD_TEMPERATURE
R float

Molar gas constant (\(R > 0\)).

GAS_CONSTANT
F float

Faraday constant (\(F > 0\)).

FARADAY

Examples:

>>> from softpotato.reactions import ButlerVolmer
>>> bv = ButlerVolmer(k0=1e-4, alpha=0.5, E0=0.2, n=1)
>>> kf, kb = bv.rate_constants(0.2)
>>> kf == kb == 1e-4
True
>>> bv.current_density(0.2, c_ox=1.0, c_red=1.0)
0.0
Source code in src/softpotato/reactions/heterogeneous.py
@dataclass(frozen=True)
class ButlerVolmer(HeterogeneousKinetics):
    r"""Butler–Volmer heterogeneous charge-transfer kinetics.

    Models forward (cathodic) and backward (anodic) electron-transfer rate constants
    for :math:`\text{Ox} + n e^- \rightleftharpoons \text{Red}`:

    .. math::

        k_f(E) = k^0 \exp\left(-\frac{\alpha n F}{R T}(E - E^{0\prime})\right)

    .. math::

        k_b(E) = k^0 \exp\left(\frac{(1 - \alpha) n F}{R T}(E - E^{0\prime})\right)

    Rate constants, exchange current density, Faradaic current density, and Tafel
    slopes are evaluated by delegating to :mod:`softpotato.analytical.kinetics`.

    Parameters
    ----------
    k0 : float
        Standard heterogeneous rate constant :math:`k^0 > 0` in
        :math:`\text{m}/\text{s}` or :math:`\text{cm}/\text{s}`.
    alpha : float, default 0.5
        Cathodic charge-transfer coefficient (:math:`0 < \alpha < 1`).
    E0 : float, default 0.0
        Formal reduction potential :math:`E^{0\prime}` in Volts (V).
    n : float, default 1
        Number of electrons transferred (:math:`n > 0`).
    T : float, default STANDARD_TEMPERATURE
        Temperature in Kelvin (:math:`T > 0`, default 298.15 K).
    R : float, default GAS_CONSTANT
        Molar gas constant (:math:`R > 0`).
    F : float, default FARADAY
        Faraday constant (:math:`F > 0`).

    Examples
    --------
    >>> from softpotato.reactions import ButlerVolmer
    >>> bv = ButlerVolmer(k0=1e-4, alpha=0.5, E0=0.2, n=1)
    >>> kf, kb = bv.rate_constants(0.2)
    >>> kf == kb == 1e-4
    True
    >>> bv.current_density(0.2, c_ox=1.0, c_red=1.0)
    0.0
    """

    k0: float
    alpha: float = 0.5
    E0: float = 0.0
    n: float = 1
    T: float = STANDARD_TEMPERATURE
    R: float = GAS_CONSTANT
    F: float = FARADAY

    def __post_init__(self) -> None:
        object.__setattr__(
            self, "k0", _validate_positive_finite(self.k0, "Standard rate constant k0")
        )
        object.__setattr__(self, "alpha", _validate_alpha(self.alpha))
        object.__setattr__(
            self, "E0", _validate_finite_real(self.E0, "Formal potential E0")
        )
        object.__setattr__(
            self, "n", _validate_positive_finite(self.n, "Number of electrons n")
        )
        object.__setattr__(
            self, "T", _validate_positive_finite(self.T, "Temperature T")
        )
        object.__setattr__(
            self, "R", _validate_positive_finite(self.R, "Gas constant R")
        )
        object.__setattr__(
            self, "F", _validate_positive_finite(self.F, "Faraday constant F")
        )

    def k_f(self, E: float | ArrayLike) -> float | np.ndarray:
        r"""Evaluate forward (cathodic reduction) rate constant :math:`k_f(E)`."""
        eta = self.overpotential(E)
        return _ak.tafel(
            eta,
            i0=self.k0,
            alpha=self.alpha,
            branch="cathodic",
            n=self.n,
            T=self.T,
            R=self.R,
            F=self.F,
            anodic_positive=False,
        )

    def k_b(self, E: float | ArrayLike) -> float | np.ndarray:
        r"""Evaluate backward (anodic oxidation) rate constant :math:`k_b(E)`."""
        eta = self.overpotential(E)
        return _ak.tafel(
            eta,
            i0=self.k0,
            alpha=self.alpha,
            branch="anodic",
            n=self.n,
            T=self.T,
            R=self.R,
            F=self.F,
            anodic_positive=True,
        )

    def rate_constants(
        self, E: float | ArrayLike
    ) -> tuple[float | np.ndarray, float | np.ndarray]:
        r"""Evaluate :math:`(k_f(E), k_b(E))` at electrode potential :math:`E`."""
        return self.k_f(E), self.k_b(E)

    def exchange_current_density(self, c_ox: float = 1.0, c_red: float = 1.0) -> float:
        r"""Compute exchange current density :math:`j_0` via :func:`softpotato.analytical.kinetics.exchange_current_density`."""
        return _ak.exchange_current_density(
            self.k0,
            c_ox=c_ox,
            c_red=c_red,
            alpha=self.alpha,
            n=self.n,
            F=self.F,
        )

    def current_density(
        self,
        E: float | ArrayLike,
        c_ox: float | ArrayLike,
        c_red: float | ArrayLike = 0.0,
        *,
        anodic_positive: bool = True,
    ) -> float | np.ndarray:
        r"""Evaluate net Butler–Volmer current density via :func:`softpotato.analytical.kinetics.butler_volmer_current_density`."""
        all_scalar = np.isscalar(E) and np.isscalar(c_ox) and np.isscalar(c_red)
        eta = self.overpotential(E)
        if not all_scalar:
            eta = np.asarray(eta, dtype=float)

        j0_unit = _ak.exchange_current_density(
            self.k0,
            c_ox=1.0,
            c_red=1.0,
            alpha=self.alpha,
            n=self.n,
            F=self.F,
        )
        return _ak.butler_volmer_current_density(
            eta,
            j0=j0_unit,
            alpha=self.alpha,
            n=self.n,
            T=self.T,
            R=self.R,
            F=self.F,
            c_ox_surf=c_ox,
            c_red_surf=c_red,
            c_ox_bulk=1.0,
            c_red_bulk=1.0,
            anodic_positive=anodic_positive,
        )

    def tafel_slope(
        self,
        branch: Literal["anodic", "cathodic"] = "anodic",
        *,
        signed: bool = True,
    ) -> float:
        r"""Compute theoretical Tafel slope :math:`b` in :math:`\text{V}/\text{dec}` via :func:`softpotato.analytical.kinetics.tafel_slope`."""
        return _ak.tafel_slope(
            alpha=self.alpha,
            n=self.n,
            branch=branch,
            T=self.T,
            R=self.R,
            F=self.F,
            signed=signed,
        )

k_f

k_f(E: float | ArrayLike) -> float | np.ndarray

Evaluate forward (cathodic reduction) rate constant \(k_f(E)\).

Source code in src/softpotato/reactions/heterogeneous.py
def k_f(self, E: float | ArrayLike) -> float | np.ndarray:
    r"""Evaluate forward (cathodic reduction) rate constant :math:`k_f(E)`."""
    eta = self.overpotential(E)
    return _ak.tafel(
        eta,
        i0=self.k0,
        alpha=self.alpha,
        branch="cathodic",
        n=self.n,
        T=self.T,
        R=self.R,
        F=self.F,
        anodic_positive=False,
    )

k_b

k_b(E: float | ArrayLike) -> float | np.ndarray

Evaluate backward (anodic oxidation) rate constant \(k_b(E)\).

Source code in src/softpotato/reactions/heterogeneous.py
def k_b(self, E: float | ArrayLike) -> float | np.ndarray:
    r"""Evaluate backward (anodic oxidation) rate constant :math:`k_b(E)`."""
    eta = self.overpotential(E)
    return _ak.tafel(
        eta,
        i0=self.k0,
        alpha=self.alpha,
        branch="anodic",
        n=self.n,
        T=self.T,
        R=self.R,
        F=self.F,
        anodic_positive=True,
    )

rate_constants

rate_constants(E: float | ArrayLike) -> tuple[float | np.ndarray, float | np.ndarray]

Evaluate \((k_f(E), k_b(E))\) at electrode potential \(E\).

Source code in src/softpotato/reactions/heterogeneous.py
def rate_constants(
    self, E: float | ArrayLike
) -> tuple[float | np.ndarray, float | np.ndarray]:
    r"""Evaluate :math:`(k_f(E), k_b(E))` at electrode potential :math:`E`."""
    return self.k_f(E), self.k_b(E)

exchange_current_density

exchange_current_density(c_ox: float = 1.0, c_red: float = 1.0) -> float

Compute exchange current density \(j_0\) via softpotato.analytical.kinetics.exchange_current_density.

Source code in src/softpotato/reactions/heterogeneous.py
def exchange_current_density(self, c_ox: float = 1.0, c_red: float = 1.0) -> float:
    r"""Compute exchange current density :math:`j_0` via :func:`softpotato.analytical.kinetics.exchange_current_density`."""
    return _ak.exchange_current_density(
        self.k0,
        c_ox=c_ox,
        c_red=c_red,
        alpha=self.alpha,
        n=self.n,
        F=self.F,
    )

current_density

current_density(E: float | ArrayLike, c_ox: float | ArrayLike, c_red: float | ArrayLike = 0.0, *, anodic_positive: bool = True) -> float | np.ndarray

Evaluate net Butler–Volmer current density via softpotato.analytical.kinetics.butler_volmer_current_density.

Source code in src/softpotato/reactions/heterogeneous.py
def current_density(
    self,
    E: float | ArrayLike,
    c_ox: float | ArrayLike,
    c_red: float | ArrayLike = 0.0,
    *,
    anodic_positive: bool = True,
) -> float | np.ndarray:
    r"""Evaluate net Butler–Volmer current density via :func:`softpotato.analytical.kinetics.butler_volmer_current_density`."""
    all_scalar = np.isscalar(E) and np.isscalar(c_ox) and np.isscalar(c_red)
    eta = self.overpotential(E)
    if not all_scalar:
        eta = np.asarray(eta, dtype=float)

    j0_unit = _ak.exchange_current_density(
        self.k0,
        c_ox=1.0,
        c_red=1.0,
        alpha=self.alpha,
        n=self.n,
        F=self.F,
    )
    return _ak.butler_volmer_current_density(
        eta,
        j0=j0_unit,
        alpha=self.alpha,
        n=self.n,
        T=self.T,
        R=self.R,
        F=self.F,
        c_ox_surf=c_ox,
        c_red_surf=c_red,
        c_ox_bulk=1.0,
        c_red_bulk=1.0,
        anodic_positive=anodic_positive,
    )

tafel_slope

tafel_slope(branch: Literal['anodic', 'cathodic'] = 'anodic', *, signed: bool = True) -> float

Compute theoretical Tafel slope \(b\) in \(\text{V}/\text{dec}\) via softpotato.analytical.kinetics.tafel_slope.

Source code in src/softpotato/reactions/heterogeneous.py
def tafel_slope(
    self,
    branch: Literal["anodic", "cathodic"] = "anodic",
    *,
    signed: bool = True,
) -> float:
    r"""Compute theoretical Tafel slope :math:`b` in :math:`\text{V}/\text{dec}` via :func:`softpotato.analytical.kinetics.tafel_slope`."""
    return _ak.tafel_slope(
        alpha=self.alpha,
        n=self.n,
        branch=branch,
        T=self.T,
        R=self.R,
        F=self.F,
        signed=signed,
    )

HeterogeneousKinetics

Bases: ABC

Abstract base class for heterogeneous interfacial charge-transfer kinetics.

Models single-step electron transfer at an electrode interface:

\[ \text{Ox} + n e^- \underset{k_b(E)}{\overset{k_f(E)}{\rightleftharpoons}} \text{Red} \]

Subclasses must implement rate_constants and provide attributes E0, n, T, R, and F.

Source code in src/softpotato/reactions/heterogeneous.py
class HeterogeneousKinetics(ABC):
    r"""Abstract base class for heterogeneous interfacial charge-transfer kinetics.

    Models single-step electron transfer at an electrode interface:

    .. math::

        \text{Ox} + n e^- \underset{k_b(E)}{\overset{k_f(E)}{\rightleftharpoons}} \text{Red}

    Subclasses must implement :meth:`rate_constants` and provide attributes
    ``E0``, ``n``, ``T``, ``R``, and ``F``.
    """

    E0: float
    n: float
    T: float
    R: float
    F: float

    def overpotential(self, E: float | ArrayLike) -> float | np.ndarray:
        r"""Compute formal overpotential :math:`\eta = E - E^{0\prime}`.

        Parameters
        ----------
        E : float or array-like
            Electrode potential :math:`E` in Volts (V).

        Returns
        -------
        float or np.ndarray
            Overpotential :math:`E - E^{0\prime}` in Volts (V).
        """
        if np.isscalar(E):
            return float(np.asarray(E, dtype=float).item() - self.E0)
        return np.asarray(E, dtype=float) - self.E0

    @abstractmethod
    def rate_constants(
        self, E: float | ArrayLike
    ) -> tuple[float | np.ndarray, float | np.ndarray]:
        r"""Evaluate forward and backward heterogeneous rate constants :math:`(k_f, k_b)`.

        Parameters
        ----------
        E : float or array-like
            Electrode potential :math:`E` in Volts (V).

        Returns
        -------
        tuple of (float or np.ndarray, float or np.ndarray)
            ``(k_f, k_b)`` where ``k_f`` is the forward (cathodic reduction) rate
            constant and ``k_b`` is the backward (anodic oxidation) rate constant.
        """
        raise NotImplementedError

    def flux(
        self,
        E: float | ArrayLike,
        c_ox: float | ArrayLike,
        c_red: float | ArrayLike = 0.0,
    ) -> float | np.ndarray:
        r"""Evaluate net interfacial reduction flux :math:`J`.

        .. math::

            J = k_f(E) c_{\text{Ox}} - k_b(E) c_{\text{Red}}

        Parameters
        ----------
        E : float or array-like
            Electrode potential :math:`E` in Volts (V).
        c_ox : float or array-like
            Surface concentration of oxidized species :math:`c_{\text{Ox}}(0, t) \ge 0`.
        c_red : float or array-like, default 0.0
            Surface concentration of reduced species :math:`c_{\text{Red}}(0, t) \ge 0`.

        Returns
        -------
        float or np.ndarray
            Net interfacial flux :math:`J` (positive for net reduction of Ox to Red).
        """
        ox_val, ox_scalar = _validate_non_negative_conc(c_ox, "c_ox")
        red_val, red_scalar = _validate_non_negative_conc(c_red, "c_red")
        kf, kb = self.rate_constants(E)
        result = kf * ox_val - kb * red_val
        if np.isscalar(E) and ox_scalar and red_scalar:
            return float(np.asarray(result, dtype=float).item())
        return np.asarray(result, dtype=float)

    def current_density(
        self,
        E: float | ArrayLike,
        c_ox: float | ArrayLike,
        c_red: float | ArrayLike = 0.0,
        *,
        anodic_positive: bool = True,
    ) -> float | np.ndarray:
        r"""Evaluate net interfacial Faradaic current density :math:`j`.

        Parameters
        ----------
        E : float or array-like
            Electrode potential :math:`E` in Volts (V).
        c_ox : float or array-like
            Surface concentration of oxidized species :math:`c_{\text{Ox}}(0, t) \ge 0`.
        c_red : float or array-like, default 0.0
            Surface concentration of reduced species :math:`c_{\text{Red}}(0, t) \ge 0`.
        anodic_positive : bool, default True
            If ``True`` (IUPAC convention), anodic oxidation current is positive
            (:math:`j = -n F J`). If ``False`` (polarographic convention),
            cathodic reduction current is positive (:math:`j = +n F J`).

        Returns
        -------
        float or np.ndarray
            Interfacial Faradaic current density :math:`j` in :math:`\text{A}/\text{m}^2`
            or :math:`\text{A}/\text{cm}^2`.
        """
        j_flux = self.flux(E, c_ox, c_red)
        sign = -1.0 if anodic_positive else 1.0
        result = sign * self.n * self.F * j_flux
        if np.isscalar(j_flux):
            return float(result)
        return np.asarray(result, dtype=float)

overpotential

overpotential(E: float | ArrayLike) -> float | np.ndarray

Compute formal overpotential \(\eta = E - E^{0\prime}\).

Parameters:

Name Type Description Default
E float or array - like

Electrode potential \(E\) in Volts (V).

required

Returns:

Type Description
float or ndarray

Overpotential \(E - E^{0\prime}\) in Volts (V).

Source code in src/softpotato/reactions/heterogeneous.py
def overpotential(self, E: float | ArrayLike) -> float | np.ndarray:
    r"""Compute formal overpotential :math:`\eta = E - E^{0\prime}`.

    Parameters
    ----------
    E : float or array-like
        Electrode potential :math:`E` in Volts (V).

    Returns
    -------
    float or np.ndarray
        Overpotential :math:`E - E^{0\prime}` in Volts (V).
    """
    if np.isscalar(E):
        return float(np.asarray(E, dtype=float).item() - self.E0)
    return np.asarray(E, dtype=float) - self.E0

rate_constants abstractmethod

rate_constants(E: float | ArrayLike) -> tuple[float | np.ndarray, float | np.ndarray]

Evaluate forward and backward heterogeneous rate constants \((k_f, k_b)\).

Parameters:

Name Type Description Default
E float or array - like

Electrode potential \(E\) in Volts (V).

required

Returns:

Type Description
tuple of (float or np.ndarray, float or np.ndarray)

(k_f, k_b) where k_f is the forward (cathodic reduction) rate constant and k_b is the backward (anodic oxidation) rate constant.

Source code in src/softpotato/reactions/heterogeneous.py
@abstractmethod
def rate_constants(
    self, E: float | ArrayLike
) -> tuple[float | np.ndarray, float | np.ndarray]:
    r"""Evaluate forward and backward heterogeneous rate constants :math:`(k_f, k_b)`.

    Parameters
    ----------
    E : float or array-like
        Electrode potential :math:`E` in Volts (V).

    Returns
    -------
    tuple of (float or np.ndarray, float or np.ndarray)
        ``(k_f, k_b)`` where ``k_f`` is the forward (cathodic reduction) rate
        constant and ``k_b`` is the backward (anodic oxidation) rate constant.
    """
    raise NotImplementedError

flux

flux(E: float | ArrayLike, c_ox: float | ArrayLike, c_red: float | ArrayLike = 0.0) -> float | np.ndarray

Evaluate net interfacial reduction flux \(J\).

\[ J = k_f(E) c_{\text{Ox}} - k_b(E) c_{\text{Red}} \]

Parameters:

Name Type Description Default
E float or array - like

Electrode potential \(E\) in Volts (V).

required
c_ox float or array - like

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

required
c_red float or array - like

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

0.0

Returns:

Type Description
float or ndarray

Net interfacial flux \(J\) (positive for net reduction of Ox to Red).

Source code in src/softpotato/reactions/heterogeneous.py
def flux(
    self,
    E: float | ArrayLike,
    c_ox: float | ArrayLike,
    c_red: float | ArrayLike = 0.0,
) -> float | np.ndarray:
    r"""Evaluate net interfacial reduction flux :math:`J`.

    .. math::

        J = k_f(E) c_{\text{Ox}} - k_b(E) c_{\text{Red}}

    Parameters
    ----------
    E : float or array-like
        Electrode potential :math:`E` in Volts (V).
    c_ox : float or array-like
        Surface concentration of oxidized species :math:`c_{\text{Ox}}(0, t) \ge 0`.
    c_red : float or array-like, default 0.0
        Surface concentration of reduced species :math:`c_{\text{Red}}(0, t) \ge 0`.

    Returns
    -------
    float or np.ndarray
        Net interfacial flux :math:`J` (positive for net reduction of Ox to Red).
    """
    ox_val, ox_scalar = _validate_non_negative_conc(c_ox, "c_ox")
    red_val, red_scalar = _validate_non_negative_conc(c_red, "c_red")
    kf, kb = self.rate_constants(E)
    result = kf * ox_val - kb * red_val
    if np.isscalar(E) and ox_scalar and red_scalar:
        return float(np.asarray(result, dtype=float).item())
    return np.asarray(result, dtype=float)

current_density

current_density(E: float | ArrayLike, c_ox: float | ArrayLike, c_red: float | ArrayLike = 0.0, *, anodic_positive: bool = True) -> float | np.ndarray

Evaluate net interfacial Faradaic current density \(j\).

Parameters:

Name Type Description Default
E float or array - like

Electrode potential \(E\) in Volts (V).

required
c_ox float or array - like

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

required
c_red float or array - like

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

0.0
anodic_positive bool

If True (IUPAC convention), anodic oxidation current is positive (\(j = -n F J\)). If False (polarographic convention), cathodic reduction current is positive (\(j = +n F J\)).

True

Returns:

Type Description
float or ndarray

Interfacial Faradaic current density \(j\) in \(\text{A}/\text{m}^2\) or \(\text{A}/\text{cm}^2\).

Source code in src/softpotato/reactions/heterogeneous.py
def current_density(
    self,
    E: float | ArrayLike,
    c_ox: float | ArrayLike,
    c_red: float | ArrayLike = 0.0,
    *,
    anodic_positive: bool = True,
) -> float | np.ndarray:
    r"""Evaluate net interfacial Faradaic current density :math:`j`.

    Parameters
    ----------
    E : float or array-like
        Electrode potential :math:`E` in Volts (V).
    c_ox : float or array-like
        Surface concentration of oxidized species :math:`c_{\text{Ox}}(0, t) \ge 0`.
    c_red : float or array-like, default 0.0
        Surface concentration of reduced species :math:`c_{\text{Red}}(0, t) \ge 0`.
    anodic_positive : bool, default True
        If ``True`` (IUPAC convention), anodic oxidation current is positive
        (:math:`j = -n F J`). If ``False`` (polarographic convention),
        cathodic reduction current is positive (:math:`j = +n F J`).

    Returns
    -------
    float or np.ndarray
        Interfacial Faradaic current density :math:`j` in :math:`\text{A}/\text{m}^2`
        or :math:`\text{A}/\text{cm}^2`.
    """
    j_flux = self.flux(E, c_ox, c_red)
    sign = -1.0 if anodic_positive else 1.0
    result = sign * self.n * self.F * j_flux
    if np.isscalar(j_flux):
        return float(result)
    return np.asarray(result, dtype=float)

NernstianEquilibrium dataclass

Reversible Nernstian charge-transfer equilibrium helper.

Enforces thermodynamic surface equilibrium at an electrode interface:

\[ \frac{c_{\text{Ox}}(0, t)}{c_{\text{Red}}(0, t)} = \exp\left(\frac{n F}{R T}(E(t) - E^{0\prime})\right) \]

All thermodynamic calculations delegate directly to nernst, nernst_ratio, and nernst_equilibrium_concentrations.

Parameters:

Name Type Description Default
E0 float

Formal reduction potential \(E^{0\prime}\) in Volts (V).

0.0
n float

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

1
T float

Temperature in Kelvin (\(T > 0\), default 298.15 K).

STANDARD_TEMPERATURE
R float

Molar gas constant (\(R > 0\)).

GAS_CONSTANT
F float

Faraday constant (\(F > 0\)).

FARADAY

Examples:

>>> from softpotato.reactions import NernstianEquilibrium
>>> eq = NernstianEquilibrium(E0=0.2, n=1)
>>> eq.concentration_ratio(0.2)
1.0
>>> eq.surface_concentrations(0.2, c_total=2.0)
(1.0, 1.0)
Source code in src/softpotato/reactions/heterogeneous.py
@dataclass(frozen=True)
class NernstianEquilibrium:
    r"""Reversible Nernstian charge-transfer equilibrium helper.

    Enforces thermodynamic surface equilibrium at an electrode interface:

    .. math::

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

    All thermodynamic calculations delegate directly to
    :func:`~softpotato.analytical.kinetics.nernst`,
    :func:`~softpotato.analytical.kinetics.nernst_ratio`, and
    :func:`~softpotato.analytical.kinetics.nernst_equilibrium_concentrations`.

    Parameters
    ----------
    E0 : float, default 0.0
        Formal reduction potential :math:`E^{0\prime}` in Volts (V).
    n : float, default 1
        Number of electrons transferred (:math:`n > 0`).
    T : float, default STANDARD_TEMPERATURE
        Temperature in Kelvin (:math:`T > 0`, default 298.15 K).
    R : float, default GAS_CONSTANT
        Molar gas constant (:math:`R > 0`).
    F : float, default FARADAY
        Faraday constant (:math:`F > 0`).

    Examples
    --------
    >>> from softpotato.reactions import NernstianEquilibrium
    >>> eq = NernstianEquilibrium(E0=0.2, n=1)
    >>> eq.concentration_ratio(0.2)
    1.0
    >>> eq.surface_concentrations(0.2, c_total=2.0)
    (1.0, 1.0)
    """

    E0: float = 0.0
    n: float = 1
    T: float = STANDARD_TEMPERATURE
    R: float = GAS_CONSTANT
    F: float = FARADAY

    def __post_init__(self) -> None:
        object.__setattr__(
            self, "E0", _validate_finite_real(self.E0, "Formal potential E0")
        )
        object.__setattr__(
            self, "n", _validate_positive_finite(self.n, "Number of electrons n")
        )
        object.__setattr__(
            self, "T", _validate_positive_finite(self.T, "Temperature T")
        )
        object.__setattr__(
            self, "R", _validate_positive_finite(self.R, "Gas constant R")
        )
        object.__setattr__(
            self, "F", _validate_positive_finite(self.F, "Faraday constant F")
        )

    def potential(
        self,
        c_ox: float | ArrayLike,
        c_red: float | ArrayLike | None = None,
    ) -> float | np.ndarray:
        r"""Compute equilibrium electrode potential :math:`E_{\text{eq}}` via :func:`softpotato.analytical.kinetics.nernst`."""
        return _ak.nernst(
            c_ox,
            c_red=c_red,
            E0=self.E0,
            n=self.n,
            T=self.T,
            R=self.R,
            F=self.F,
        )

    def concentration_ratio(self, E: float | ArrayLike) -> float | np.ndarray:
        r"""Compute equilibrium ratio :math:`c_{\text{Ox}} / c_{\text{Red}}` via :func:`softpotato.analytical.kinetics.nernst_ratio`."""
        return _ak.nernst_ratio(
            E,
            E0=self.E0,
            n=self.n,
            T=self.T,
            R=self.R,
            F=self.F,
        )

    def surface_concentrations(
        self,
        E: float | ArrayLike,
        c_total: float | ArrayLike = 1.0,
        *,
        D_ox: float | None = None,
        D_red: float | None = None,
        c_ox_bulk: float | None = None,
        c_red_bulk: float | None = None,
    ) -> tuple[float | np.ndarray, float | np.ndarray]:
        r"""Compute equilibrium surface concentrations :math:`(c_{\text{Ox}}(0), c_{\text{Red}}(0))`.

        When ``D_ox`` and ``D_red`` are omitted or equal, delegates directly to
        :func:`softpotato.analytical.kinetics.nernst_equilibrium_concentrations`
        with :math:`c_{\text{Ox}}(0) + c_{\text{Red}}(0) = c_{\text{total}}`.

        When unequal diffusivities ``D_ox != D_red`` are provided, applies the
        semi-infinite planar flux-balanced Nernstian relation using the reversible
        half-wave potential
        :math:`E_{1/2} = E^{0\prime} - \frac{R T}{n F} \ln\sqrt{D_{\text{Ox}} / D_{\text{Red}}}`.

        Parameters
        ----------
        E : float or array-like
            Electrode potential :math:`E` in Volts (V).
        c_total : float or array-like, default 1.0
            Total electroactive concentration :math:`c_{\text{Ox}}^* + c_{\text{Red}}^*`.
        D_ox : float, optional
            Diffusion coefficient of oxidized species (:math:`D_{\text{Ox}} > 0`).
        D_red : float, optional
            Diffusion coefficient of reduced species (:math:`D_{\text{Red}} > 0`).
        c_ox_bulk : float, optional
            Bulk concentration of oxidized species (used when ``D_ox != D_red``).
        c_red_bulk : float, optional
            Bulk concentration of reduced species (used when ``D_ox != D_red``).

        Returns
        -------
        tuple of (float or np.ndarray, float or np.ndarray)
            Equilibrium surface concentrations ``(c_ox_surf, c_red_surf)``.
        """
        if D_ox is not None:
            D_ox = _validate_positive_finite(D_ox, "D_ox")
        if D_red is not None:
            D_red = _validate_positive_finite(D_red, "D_red")

        if D_ox is None or D_red is None or math.isclose(D_ox, D_red, rel_tol=1e-12):
            return _ak.nernst_equilibrium_concentrations(
                E,
                c_total=c_total,
                E0=self.E0,
                n=self.n,
                T=self.T,
                R=self.R,
                F=self.F,
            )

        xi = math.sqrt(D_ox / D_red)
        e_half = self.E0 - (self.R * self.T / (self.n * self.F)) * math.log(xi)

        if c_ox_bulk is None and c_red_bulk is None:
            c_ox_b: float | np.ndarray = _validate_non_negative_conc(
                c_total, "c_total"
            )[0]
            c_red_b: float | np.ndarray = 0.0
        else:
            c_ox_b = (
                0.0
                if c_ox_bulk is None
                else _validate_non_negative_conc(c_ox_bulk, "c_ox_bulk")[0]
            )
            c_red_b = (
                0.0
                if c_red_bulk is None
                else _validate_non_negative_conc(c_red_bulk, "c_red_bulk")[0]
            )

        s_ox = c_ox_b + c_red_b / xi
        s_red = xi * c_ox_b + c_red_b

        f_ox, f_red = _ak.nernst_equilibrium_concentrations(
            E,
            c_total=1.0,
            E0=e_half,
            n=self.n,
            T=self.T,
            R=self.R,
            F=self.F,
        )
        c_ox_out = s_ox * f_ox
        c_red_out = s_red * f_red

        if np.isscalar(E) and np.isscalar(s_ox) and np.isscalar(s_red):
            return (
                float(np.asarray(c_ox_out, dtype=float).item()),
                float(np.asarray(c_red_out, dtype=float).item()),
            )
        return np.asarray(c_ox_out, dtype=float), np.asarray(c_red_out, dtype=float)

potential

potential(c_ox: float | ArrayLike, c_red: float | ArrayLike | None = None) -> float | np.ndarray

Compute equilibrium electrode potential \(E_{\text{eq}}\) via softpotato.analytical.kinetics.nernst.

Source code in src/softpotato/reactions/heterogeneous.py
def potential(
    self,
    c_ox: float | ArrayLike,
    c_red: float | ArrayLike | None = None,
) -> float | np.ndarray:
    r"""Compute equilibrium electrode potential :math:`E_{\text{eq}}` via :func:`softpotato.analytical.kinetics.nernst`."""
    return _ak.nernst(
        c_ox,
        c_red=c_red,
        E0=self.E0,
        n=self.n,
        T=self.T,
        R=self.R,
        F=self.F,
    )

concentration_ratio

concentration_ratio(E: float | ArrayLike) -> float | np.ndarray

Compute equilibrium ratio \(c_{\text{Ox}} / c_{\text{Red}}\) via softpotato.analytical.kinetics.nernst_ratio.

Source code in src/softpotato/reactions/heterogeneous.py
def concentration_ratio(self, E: float | ArrayLike) -> float | np.ndarray:
    r"""Compute equilibrium ratio :math:`c_{\text{Ox}} / c_{\text{Red}}` via :func:`softpotato.analytical.kinetics.nernst_ratio`."""
    return _ak.nernst_ratio(
        E,
        E0=self.E0,
        n=self.n,
        T=self.T,
        R=self.R,
        F=self.F,
    )

surface_concentrations

surface_concentrations(E: float | ArrayLike, c_total: float | ArrayLike = 1.0, *, D_ox: float | None = None, D_red: float | None = None, c_ox_bulk: float | None = None, c_red_bulk: float | None = None) -> tuple[float | np.ndarray, float | np.ndarray]

Compute equilibrium surface concentrations \((c_{\text{Ox}}(0), c_{\text{Red}}(0))\).

When D_ox and D_red are omitted or equal, delegates directly to softpotato.analytical.kinetics.nernst_equilibrium_concentrations with \(c_{\text{Ox}}(0) + c_{\text{Red}}(0) = c_{\text{total}}\).

When unequal diffusivities D_ox != D_red are provided, applies the semi-infinite planar flux-balanced Nernstian relation using the reversible half-wave potential \(E_{1/2} = E^{0\prime} - \frac{R T}{n F} \ln\sqrt{D_{\text{Ox}} / D_{\text{Red}}}\).

Parameters:

Name Type Description Default
E float or array - like

Electrode potential \(E\) in Volts (V).

required
c_total float or array - like

Total electroactive concentration \(c_{\text{Ox}}^* + c_{\text{Red}}^*\).

1.0
D_ox float

Diffusion coefficient of oxidized species (\(D_{\text{Ox}} > 0\)).

None
D_red float

Diffusion coefficient of reduced species (\(D_{\text{Red}} > 0\)).

None
c_ox_bulk float

Bulk concentration of oxidized species (used when D_ox != D_red).

None
c_red_bulk float

Bulk concentration of reduced species (used when D_ox != D_red).

None

Returns:

Type Description
tuple of (float or np.ndarray, float or np.ndarray)

Equilibrium surface concentrations (c_ox_surf, c_red_surf).

Source code in src/softpotato/reactions/heterogeneous.py
def surface_concentrations(
    self,
    E: float | ArrayLike,
    c_total: float | ArrayLike = 1.0,
    *,
    D_ox: float | None = None,
    D_red: float | None = None,
    c_ox_bulk: float | None = None,
    c_red_bulk: float | None = None,
) -> tuple[float | np.ndarray, float | np.ndarray]:
    r"""Compute equilibrium surface concentrations :math:`(c_{\text{Ox}}(0), c_{\text{Red}}(0))`.

    When ``D_ox`` and ``D_red`` are omitted or equal, delegates directly to
    :func:`softpotato.analytical.kinetics.nernst_equilibrium_concentrations`
    with :math:`c_{\text{Ox}}(0) + c_{\text{Red}}(0) = c_{\text{total}}`.

    When unequal diffusivities ``D_ox != D_red`` are provided, applies the
    semi-infinite planar flux-balanced Nernstian relation using the reversible
    half-wave potential
    :math:`E_{1/2} = E^{0\prime} - \frac{R T}{n F} \ln\sqrt{D_{\text{Ox}} / D_{\text{Red}}}`.

    Parameters
    ----------
    E : float or array-like
        Electrode potential :math:`E` in Volts (V).
    c_total : float or array-like, default 1.0
        Total electroactive concentration :math:`c_{\text{Ox}}^* + c_{\text{Red}}^*`.
    D_ox : float, optional
        Diffusion coefficient of oxidized species (:math:`D_{\text{Ox}} > 0`).
    D_red : float, optional
        Diffusion coefficient of reduced species (:math:`D_{\text{Red}} > 0`).
    c_ox_bulk : float, optional
        Bulk concentration of oxidized species (used when ``D_ox != D_red``).
    c_red_bulk : float, optional
        Bulk concentration of reduced species (used when ``D_ox != D_red``).

    Returns
    -------
    tuple of (float or np.ndarray, float or np.ndarray)
        Equilibrium surface concentrations ``(c_ox_surf, c_red_surf)``.
    """
    if D_ox is not None:
        D_ox = _validate_positive_finite(D_ox, "D_ox")
    if D_red is not None:
        D_red = _validate_positive_finite(D_red, "D_red")

    if D_ox is None or D_red is None or math.isclose(D_ox, D_red, rel_tol=1e-12):
        return _ak.nernst_equilibrium_concentrations(
            E,
            c_total=c_total,
            E0=self.E0,
            n=self.n,
            T=self.T,
            R=self.R,
            F=self.F,
        )

    xi = math.sqrt(D_ox / D_red)
    e_half = self.E0 - (self.R * self.T / (self.n * self.F)) * math.log(xi)

    if c_ox_bulk is None and c_red_bulk is None:
        c_ox_b: float | np.ndarray = _validate_non_negative_conc(
            c_total, "c_total"
        )[0]
        c_red_b: float | np.ndarray = 0.0
    else:
        c_ox_b = (
            0.0
            if c_ox_bulk is None
            else _validate_non_negative_conc(c_ox_bulk, "c_ox_bulk")[0]
        )
        c_red_b = (
            0.0
            if c_red_bulk is None
            else _validate_non_negative_conc(c_red_bulk, "c_red_bulk")[0]
        )

    s_ox = c_ox_b + c_red_b / xi
    s_red = xi * c_ox_b + c_red_b

    f_ox, f_red = _ak.nernst_equilibrium_concentrations(
        E,
        c_total=1.0,
        E0=e_half,
        n=self.n,
        T=self.T,
        R=self.R,
        F=self.F,
    )
    c_ox_out = s_ox * f_ox
    c_red_out = s_red * f_red

    if np.isscalar(E) and np.isscalar(s_ox) and np.isscalar(s_red):
        return (
            float(np.asarray(c_ox_out, dtype=float).item()),
            float(np.asarray(c_red_out, dtype=float).item()),
        )
    return np.asarray(c_ox_out, dtype=float), np.asarray(c_red_out, dtype=float)

TafelKinetics dataclass

Bases: HeterogeneousKinetics

High-overpotential / irreversible Tafel heterogeneous charge-transfer kinetics.

Retains only the dominant exponential branch of Butler–Volmer kinetics:

  • branch='cathodic' (irreversible reduction): \(k_f(E) = k^0 \exp(-\alpha n F (E - E^{0\prime}) / (R T))\), \(k_b(E) = 0\).
  • branch='anodic' (irreversible oxidation): \(k_f(E) = 0\), \(k_b(E) = k^0 \exp((1 - \alpha) n F (E - E^{0\prime}) / (R T))\).
  • branch='auto': selects the anodic branch for \(E \ge E^{0\prime}\) and the cathodic branch for \(E < E^{0\prime}\).

All rate constants, current densities, Tafel slopes, and inverse overpotentials delegate directly to softpotato.analytical.kinetics.

Parameters:

Name Type Description Default
k0 float

Standard heterogeneous rate constant \(k^0 > 0\) in \(\text{m}/\text{s}\) or \(\text{cm}/\text{s}\).

required
alpha float

Cathodic charge-transfer coefficient (\(0 < \alpha < 1\)).

0.5
E0 float

Formal reduction potential \(E^{0\prime}\) in Volts (V).

0.0
n float

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

1
branch ('auto', 'anodic', 'cathodic')

Polarization branch to model.

'auto'
T float

Temperature in Kelvin (\(T > 0\), default 298.15 K).

STANDARD_TEMPERATURE
R float

Molar gas constant (\(R > 0\)).

GAS_CONSTANT
F float

Faraday constant (\(F > 0\)).

FARADAY

Examples:

>>> from softpotato.reactions import TafelKinetics
>>> tk = TafelKinetics(k0=1e-4, alpha=0.5, E0=0.0, n=1, branch="cathodic")
>>> kf, kb = tk.rate_constants(-0.1)
>>> kf > 1e-4 and kb == 0.0
True
>>> round(tk.tafel_slope(signed=True) * 1000, 1)
-118.3
Source code in src/softpotato/reactions/heterogeneous.py
@dataclass(frozen=True)
class TafelKinetics(HeterogeneousKinetics):
    r"""High-overpotential / irreversible Tafel heterogeneous charge-transfer kinetics.

    Retains only the dominant exponential branch of Butler–Volmer kinetics:

    - ``branch='cathodic'`` (irreversible reduction):
      :math:`k_f(E) = k^0 \exp(-\alpha n F (E - E^{0\prime}) / (R T))`, :math:`k_b(E) = 0`.
    - ``branch='anodic'`` (irreversible oxidation):
      :math:`k_f(E) = 0`, :math:`k_b(E) = k^0 \exp((1 - \alpha) n F (E - E^{0\prime}) / (R T))`.
    - ``branch='auto'``: selects the anodic branch for :math:`E \ge E^{0\prime}` and
      the cathodic branch for :math:`E < E^{0\prime}`.

    All rate constants, current densities, Tafel slopes, and inverse overpotentials
    delegate directly to :mod:`softpotato.analytical.kinetics`.

    Parameters
    ----------
    k0 : float
        Standard heterogeneous rate constant :math:`k^0 > 0` in
        :math:`\text{m}/\text{s}` or :math:`\text{cm}/\text{s}`.
    alpha : float, default 0.5
        Cathodic charge-transfer coefficient (:math:`0 < \alpha < 1`).
    E0 : float, default 0.0
        Formal reduction potential :math:`E^{0\prime}` in Volts (V).
    n : float, default 1
        Number of electrons transferred (:math:`n > 0`).
    branch : {'auto', 'anodic', 'cathodic'}, default 'auto'
        Polarization branch to model.
    T : float, default STANDARD_TEMPERATURE
        Temperature in Kelvin (:math:`T > 0`, default 298.15 K).
    R : float, default GAS_CONSTANT
        Molar gas constant (:math:`R > 0`).
    F : float, default FARADAY
        Faraday constant (:math:`F > 0`).

    Examples
    --------
    >>> from softpotato.reactions import TafelKinetics
    >>> tk = TafelKinetics(k0=1e-4, alpha=0.5, E0=0.0, n=1, branch="cathodic")
    >>> kf, kb = tk.rate_constants(-0.1)
    >>> kf > 1e-4 and kb == 0.0
    True
    >>> round(tk.tafel_slope(signed=True) * 1000, 1)
    -118.3
    """

    k0: float
    alpha: float = 0.5
    E0: float = 0.0
    n: float = 1
    branch: Literal["auto", "anodic", "cathodic"] = "auto"
    T: float = STANDARD_TEMPERATURE
    R: float = GAS_CONSTANT
    F: float = FARADAY

    def __post_init__(self) -> None:
        object.__setattr__(
            self, "k0", _validate_positive_finite(self.k0, "Standard rate constant k0")
        )
        object.__setattr__(self, "alpha", _validate_alpha(self.alpha))
        object.__setattr__(
            self, "E0", _validate_finite_real(self.E0, "Formal potential E0")
        )
        object.__setattr__(
            self, "n", _validate_positive_finite(self.n, "Number of electrons n")
        )
        if not isinstance(self.branch, str):
            raise TypeError(
                f"branch must be a string ('auto', 'anodic', or 'cathodic'), "
                f"got {type(self.branch).__name__}."
            )
        branch_norm = self.branch.lower().strip()
        if branch_norm not in ("auto", "anodic", "cathodic"):
            raise ValueError(
                f"Invalid branch '{self.branch}'. Must be 'auto', 'anodic', or 'cathodic'."
            )
        object.__setattr__(self, "branch", branch_norm)
        object.__setattr__(
            self, "T", _validate_positive_finite(self.T, "Temperature T")
        )
        object.__setattr__(
            self, "R", _validate_positive_finite(self.R, "Gas constant R")
        )
        object.__setattr__(
            self, "F", _validate_positive_finite(self.F, "Faraday constant F")
        )

    def rate_constants(
        self, E: float | ArrayLike
    ) -> tuple[float | np.ndarray, float | np.ndarray]:
        r"""Evaluate Tafel rate constants :math:`(k_f(E), k_b(E))` via :func:`softpotato.analytical.kinetics.tafel`."""
        is_scalar = np.isscalar(E)
        eta = self.overpotential(E)

        if self.branch == "cathodic":
            kf = _ak.tafel(
                eta,
                i0=self.k0,
                alpha=self.alpha,
                branch="cathodic",
                n=self.n,
                T=self.T,
                R=self.R,
                F=self.F,
                anodic_positive=False,
            )
            kb: float | np.ndarray = (
                0.0 if is_scalar else np.zeros_like(kf, dtype=float)
            )
            return kf, kb

        if self.branch == "anodic":
            kb = _ak.tafel(
                eta,
                i0=self.k0,
                alpha=self.alpha,
                branch="anodic",
                n=self.n,
                T=self.T,
                R=self.R,
                F=self.F,
                anodic_positive=True,
            )
            kf = 0.0 if is_scalar else np.zeros_like(kb, dtype=float)
            return kf, kb

        # branch == "auto"
        kf_raw = _ak.tafel(
            eta,
            i0=self.k0,
            alpha=self.alpha,
            branch="cathodic",
            n=self.n,
            T=self.T,
            R=self.R,
            F=self.F,
            anodic_positive=False,
        )
        kb_raw = _ak.tafel(
            eta,
            i0=self.k0,
            alpha=self.alpha,
            branch="anodic",
            n=self.n,
            T=self.T,
            R=self.R,
            F=self.F,
            anodic_positive=True,
        )
        if is_scalar:
            if float(eta) >= 0.0:
                return 0.0, float(kb_raw)
            return float(kf_raw), 0.0
        eta_arr = np.asarray(eta, dtype=float)
        return (
            np.where(eta_arr < 0.0, kf_raw, 0.0),
            np.where(eta_arr >= 0.0, kb_raw, 0.0),
        )

    def current_density(
        self,
        E: float | ArrayLike,
        c_ox: float | ArrayLike,
        c_red: float | ArrayLike = 0.0,
        *,
        anodic_positive: bool = True,
    ) -> float | np.ndarray:
        r"""Evaluate Tafel Faradaic current density via :func:`softpotato.analytical.kinetics.tafel`."""
        ox_val, ox_scalar = _validate_non_negative_conc(c_ox, "c_ox")
        red_val, red_scalar = _validate_non_negative_conc(c_red, "c_red")
        all_scalar = np.isscalar(E) and ox_scalar and red_scalar
        eta = self.overpotential(E)
        j0_unit = _ak.exchange_current_density(
            self.k0,
            c_ox=1.0,
            c_red=1.0,
            alpha=self.alpha,
            n=self.n,
            F=self.F,
        )

        if self.branch == "anodic":
            j_unit = _ak.tafel(
                eta,
                i0=j0_unit,
                alpha=self.alpha,
                branch="anodic",
                n=self.n,
                T=self.T,
                R=self.R,
                F=self.F,
                anodic_positive=anodic_positive,
            )
            res = j_unit * red_val
        elif self.branch == "cathodic":
            j_unit = _ak.tafel(
                eta,
                i0=j0_unit,
                alpha=self.alpha,
                branch="cathodic",
                n=self.n,
                T=self.T,
                R=self.R,
                F=self.F,
                anodic_positive=anodic_positive,
            )
            res = j_unit * ox_val
        else:
            j_anodic = (
                _ak.tafel(
                    eta,
                    i0=j0_unit,
                    alpha=self.alpha,
                    branch="anodic",
                    n=self.n,
                    T=self.T,
                    R=self.R,
                    F=self.F,
                    anodic_positive=anodic_positive,
                )
                * red_val
            )
            j_cathodic = (
                _ak.tafel(
                    eta,
                    i0=j0_unit,
                    alpha=self.alpha,
                    branch="cathodic",
                    n=self.n,
                    T=self.T,
                    R=self.R,
                    F=self.F,
                    anodic_positive=anodic_positive,
                )
                * ox_val
            )
            eta_arr = np.asarray(eta, dtype=float)
            res = np.where(eta_arr >= 0.0, j_anodic, j_cathodic)

        if all_scalar:
            return float(np.asarray(res, dtype=float).item())
        return np.asarray(res, dtype=float)

    def tafel_slope(
        self,
        branch: Literal["anodic", "cathodic"] | None = None,
        *,
        signed: bool = True,
    ) -> float:
        r"""Compute theoretical Tafel slope :math:`b` in :math:`\text{V}/\text{dec}` via :func:`softpotato.analytical.kinetics.tafel_slope`."""
        resolved: Literal["anodic", "cathodic"]
        if branch is None:
            if self.branch == "auto":
                raise ValueError(
                    "Tafel slope requires an explicit branch ('anodic' or 'cathodic') "
                    "when TafelKinetics.branch='auto'."
                )
            resolved = self.branch
        else:
            resolved = branch
        return _ak.tafel_slope(
            alpha=self.alpha,
            n=self.n,
            branch=resolved,
            T=self.T,
            R=self.R,
            F=self.F,
            signed=signed,
        )

    def overpotential_for_current(
        self,
        current_density: float | ArrayLike,
        *,
        c_ox: float = 1.0,
        c_red: float = 1.0,
        branch: Literal["anodic", "cathodic"] | None = None,
    ) -> float | np.ndarray:
        r"""Compute activation overpotential :math:`\eta` for a target current density via :func:`softpotato.analytical.kinetics.tafel_overpotential`."""
        resolved: Literal["anodic", "cathodic"]
        if branch is None:
            if self.branch == "auto":
                raise ValueError(
                    "overpotential_for_current requires an explicit branch "
                    "('anodic' or 'cathodic') when TafelKinetics.branch='auto'."
                )
            resolved = self.branch
        else:
            resolved = branch

        c_ref = c_red if resolved == "anodic" else c_ox
        _validate_positive_finite(c_ref, "c_red" if resolved == "anodic" else "c_ox")
        j0_branch = _ak.exchange_current_density(
            self.k0,
            c_ox=c_ref,
            c_red=c_ref,
            alpha=self.alpha,
            n=self.n,
            F=self.F,
        )
        return _ak.tafel_overpotential(
            current_density,
            i0=j0_branch,
            alpha=self.alpha,
            branch=resolved,
            n=self.n,
            T=self.T,
            R=self.R,
            F=self.F,
        )

rate_constants

rate_constants(E: float | ArrayLike) -> tuple[float | np.ndarray, float | np.ndarray]

Evaluate Tafel rate constants \((k_f(E), k_b(E))\) via softpotato.analytical.kinetics.tafel.

Source code in src/softpotato/reactions/heterogeneous.py
def rate_constants(
    self, E: float | ArrayLike
) -> tuple[float | np.ndarray, float | np.ndarray]:
    r"""Evaluate Tafel rate constants :math:`(k_f(E), k_b(E))` via :func:`softpotato.analytical.kinetics.tafel`."""
    is_scalar = np.isscalar(E)
    eta = self.overpotential(E)

    if self.branch == "cathodic":
        kf = _ak.tafel(
            eta,
            i0=self.k0,
            alpha=self.alpha,
            branch="cathodic",
            n=self.n,
            T=self.T,
            R=self.R,
            F=self.F,
            anodic_positive=False,
        )
        kb: float | np.ndarray = (
            0.0 if is_scalar else np.zeros_like(kf, dtype=float)
        )
        return kf, kb

    if self.branch == "anodic":
        kb = _ak.tafel(
            eta,
            i0=self.k0,
            alpha=self.alpha,
            branch="anodic",
            n=self.n,
            T=self.T,
            R=self.R,
            F=self.F,
            anodic_positive=True,
        )
        kf = 0.0 if is_scalar else np.zeros_like(kb, dtype=float)
        return kf, kb

    # branch == "auto"
    kf_raw = _ak.tafel(
        eta,
        i0=self.k0,
        alpha=self.alpha,
        branch="cathodic",
        n=self.n,
        T=self.T,
        R=self.R,
        F=self.F,
        anodic_positive=False,
    )
    kb_raw = _ak.tafel(
        eta,
        i0=self.k0,
        alpha=self.alpha,
        branch="anodic",
        n=self.n,
        T=self.T,
        R=self.R,
        F=self.F,
        anodic_positive=True,
    )
    if is_scalar:
        if float(eta) >= 0.0:
            return 0.0, float(kb_raw)
        return float(kf_raw), 0.0
    eta_arr = np.asarray(eta, dtype=float)
    return (
        np.where(eta_arr < 0.0, kf_raw, 0.0),
        np.where(eta_arr >= 0.0, kb_raw, 0.0),
    )

current_density

current_density(E: float | ArrayLike, c_ox: float | ArrayLike, c_red: float | ArrayLike = 0.0, *, anodic_positive: bool = True) -> float | np.ndarray

Evaluate Tafel Faradaic current density via softpotato.analytical.kinetics.tafel.

Source code in src/softpotato/reactions/heterogeneous.py
def current_density(
    self,
    E: float | ArrayLike,
    c_ox: float | ArrayLike,
    c_red: float | ArrayLike = 0.0,
    *,
    anodic_positive: bool = True,
) -> float | np.ndarray:
    r"""Evaluate Tafel Faradaic current density via :func:`softpotato.analytical.kinetics.tafel`."""
    ox_val, ox_scalar = _validate_non_negative_conc(c_ox, "c_ox")
    red_val, red_scalar = _validate_non_negative_conc(c_red, "c_red")
    all_scalar = np.isscalar(E) and ox_scalar and red_scalar
    eta = self.overpotential(E)
    j0_unit = _ak.exchange_current_density(
        self.k0,
        c_ox=1.0,
        c_red=1.0,
        alpha=self.alpha,
        n=self.n,
        F=self.F,
    )

    if self.branch == "anodic":
        j_unit = _ak.tafel(
            eta,
            i0=j0_unit,
            alpha=self.alpha,
            branch="anodic",
            n=self.n,
            T=self.T,
            R=self.R,
            F=self.F,
            anodic_positive=anodic_positive,
        )
        res = j_unit * red_val
    elif self.branch == "cathodic":
        j_unit = _ak.tafel(
            eta,
            i0=j0_unit,
            alpha=self.alpha,
            branch="cathodic",
            n=self.n,
            T=self.T,
            R=self.R,
            F=self.F,
            anodic_positive=anodic_positive,
        )
        res = j_unit * ox_val
    else:
        j_anodic = (
            _ak.tafel(
                eta,
                i0=j0_unit,
                alpha=self.alpha,
                branch="anodic",
                n=self.n,
                T=self.T,
                R=self.R,
                F=self.F,
                anodic_positive=anodic_positive,
            )
            * red_val
        )
        j_cathodic = (
            _ak.tafel(
                eta,
                i0=j0_unit,
                alpha=self.alpha,
                branch="cathodic",
                n=self.n,
                T=self.T,
                R=self.R,
                F=self.F,
                anodic_positive=anodic_positive,
            )
            * ox_val
        )
        eta_arr = np.asarray(eta, dtype=float)
        res = np.where(eta_arr >= 0.0, j_anodic, j_cathodic)

    if all_scalar:
        return float(np.asarray(res, dtype=float).item())
    return np.asarray(res, dtype=float)

tafel_slope

tafel_slope(branch: Literal['anodic', 'cathodic'] | None = None, *, signed: bool = True) -> float

Compute theoretical Tafel slope \(b\) in \(\text{V}/\text{dec}\) via softpotato.analytical.kinetics.tafel_slope.

Source code in src/softpotato/reactions/heterogeneous.py
def tafel_slope(
    self,
    branch: Literal["anodic", "cathodic"] | None = None,
    *,
    signed: bool = True,
) -> float:
    r"""Compute theoretical Tafel slope :math:`b` in :math:`\text{V}/\text{dec}` via :func:`softpotato.analytical.kinetics.tafel_slope`."""
    resolved: Literal["anodic", "cathodic"]
    if branch is None:
        if self.branch == "auto":
            raise ValueError(
                "Tafel slope requires an explicit branch ('anodic' or 'cathodic') "
                "when TafelKinetics.branch='auto'."
            )
        resolved = self.branch
    else:
        resolved = branch
    return _ak.tafel_slope(
        alpha=self.alpha,
        n=self.n,
        branch=resolved,
        T=self.T,
        R=self.R,
        F=self.F,
        signed=signed,
    )

overpotential_for_current

overpotential_for_current(current_density: float | ArrayLike, *, c_ox: float = 1.0, c_red: float = 1.0, branch: Literal['anodic', 'cathodic'] | None = None) -> float | np.ndarray

Compute activation overpotential \(\eta\) for a target current density via softpotato.analytical.kinetics.tafel_overpotential.

Source code in src/softpotato/reactions/heterogeneous.py
def overpotential_for_current(
    self,
    current_density: float | ArrayLike,
    *,
    c_ox: float = 1.0,
    c_red: float = 1.0,
    branch: Literal["anodic", "cathodic"] | None = None,
) -> float | np.ndarray:
    r"""Compute activation overpotential :math:`\eta` for a target current density via :func:`softpotato.analytical.kinetics.tafel_overpotential`."""
    resolved: Literal["anodic", "cathodic"]
    if branch is None:
        if self.branch == "auto":
            raise ValueError(
                "overpotential_for_current requires an explicit branch "
                "('anodic' or 'cathodic') when TafelKinetics.branch='auto'."
            )
        resolved = self.branch
    else:
        resolved = branch

    c_ref = c_red if resolved == "anodic" else c_ox
    _validate_positive_finite(c_ref, "c_red" if resolved == "anodic" else "c_ox")
    j0_branch = _ak.exchange_current_density(
        self.k0,
        c_ox=c_ref,
        c_red=c_ref,
        alpha=self.alpha,
        n=self.n,
        F=self.F,
    )
    return _ak.tafel_overpotential(
        current_density,
        i0=j0_branch,
        alpha=self.alpha,
        branch=resolved,
        n=self.n,
        T=self.T,
        R=self.R,
        F=self.F,
    )

CatalyticReaction

Bases: MassActionReaction

Catalytic regeneration step of an EC' mechanism.

\[ B + Z \xrightarrow{k} A + Y \]

The electrogenerated species \(B\) reacts with a substrate \(Z\), regenerating the electroactive species \(A\):

\[ R_B = R_Z = -k c_B c_Z, \qquad R_A = R_Y = +k c_B c_Z \]

If substrate is None the substrate is assumed to be in large excess and the step reduces to pseudo-first-order regeneration \(B \xrightarrow{k'} A\) with \(k' = k c_Z^*\).

Parameters:

Name Type Description Default
reactant str or Species

Electrogenerated catalyst form \(B\).

required
regenerated str or Species

Regenerated catalyst form \(A\).

required
k float

Rate constant (second-order, or pseudo-first-order if substrate is None).

required
substrate str or Species or None

Substrate \(Z\) (explicitly tracked if given).

None
product str or Species or None

Substrate-derived product \(Y\) (explicitly tracked if given).

None

Examples:

>>> import numpy as np
>>> from softpotato.reactions import CatalyticReaction
>>> rxn = CatalyticReaction("Red", "Ox", k=5.0, substrate="Z", product="Y")
>>> c = {"Red": np.array([0.2]), "Ox": np.array([0.8]),
...      "Z": np.array([1.0]), "Y": np.array([0.0])}
>>> rxn.rates(c, None, 0.0)
{'Red': array([-1.]), 'Z': array([-1.]), 'Ox': array([1.]), 'Y': array([1.])}
Source code in src/softpotato/reactions/homogeneous.py
class CatalyticReaction(MassActionReaction):
    r"""Catalytic regeneration step of an EC' mechanism.

    .. math::

        B + Z \xrightarrow{k} A + Y

    The electrogenerated species :math:`B` reacts with a substrate :math:`Z`,
    regenerating the electroactive species :math:`A`:

    .. math::

        R_B = R_Z = -k c_B c_Z, \qquad R_A = R_Y = +k c_B c_Z

    If ``substrate`` is ``None`` the substrate is assumed to be in large excess
    and the step reduces to pseudo-first-order regeneration
    :math:`B \xrightarrow{k'} A` with :math:`k' = k c_Z^*`.

    Parameters
    ----------
    reactant : str or Species
        Electrogenerated catalyst form :math:`B`.
    regenerated : str or Species
        Regenerated catalyst form :math:`A`.
    k : float
        Rate constant (second-order, or pseudo-first-order if
        ``substrate is None``).
    substrate : str or Species or None, default None
        Substrate :math:`Z` (explicitly tracked if given).
    product : str or Species or None, default None
        Substrate-derived product :math:`Y` (explicitly tracked if given).

    Examples
    --------
    >>> import numpy as np
    >>> from softpotato.reactions import CatalyticReaction
    >>> rxn = CatalyticReaction("Red", "Ox", k=5.0, substrate="Z", product="Y")
    >>> c = {"Red": np.array([0.2]), "Ox": np.array([0.8]),
    ...      "Z": np.array([1.0]), "Y": np.array([0.0])}
    >>> rxn.rates(c, None, 0.0)
    {'Red': array([-1.]), 'Z': array([-1.]), 'Ox': array([1.]), 'Y': array([1.])}
    """

    def __init__(
        self,
        reactant: SpeciesLike,
        regenerated: SpeciesLike,
        k: float,
        substrate: SpeciesLike | None = None,
        product: SpeciesLike | None = None,
    ) -> None:
        reactants: dict[SpeciesLike, int] = {reactant: 1}
        if substrate is not None:
            reactants[substrate] = 1
        products: dict[SpeciesLike, int] = {regenerated: 1}
        if product is not None:
            products[product] = 1
        super().__init__(reactants, products, k_f=k)

    @property
    def k(self) -> float:
        """Catalytic rate constant."""
        return self.k_f

k property

k: float

Catalytic rate constant.

CustomReaction

Bases: HomogeneousReaction

User-defined homogeneous reaction with an arbitrary rate law.

Build your own reaction by supplying its net stoichiometry and a rate law rate(c, x, t). Source terms are \(R_i = \nu_i\, r(\mathbf{c}, x, t)\). Analytical derivatives \(\partial r / \partial c_k\) can be supplied through rate_derivatives; any dependency without one is differentiated automatically with central finite differences, so the kinetic Jacobian is always available.

Parameters:

Name Type Description Default
stoichiometry Mapping[str | Species, float]

Net stoichiometric coefficients {species: nu_i}: negative for consumed species and positive for produced species. Non-integer coefficients are allowed for non-elementary rate laws.

required
rate Callable[[dict[str, ndarray], ndarray, float], array_like]

Rate law \(r(\mathbf{c}, x, t)\). Receives the concentration dictionary, the spatial grid and the time, and returns a scalar or an array broadcastable to the concentration profiles. The rate law must be local (node-wise).

required
rate_derivatives Mapping[str | Species, Callable]

Analytical partial derivatives {species: dr_dc(c, x, t)}.

None
dependencies Sequence[str | Species]

Species the rate law depends on. Defaults to the species in stoichiometry plus those in rate_derivatives. List here any species that affect the rate without being consumed or produced (e.g., an enzyme or a homogeneous catalyst).

None
name str

Human-readable label used in repr.

None

Examples:

Michaelis–Menten kinetics \(S \rightarrow P\) with \(r = V_{max} c_S / (K_M + c_S)\):

>>> import numpy as np
>>> from softpotato.reactions import CustomReaction
>>> mm = CustomReaction(
...     stoichiometry={"S": -1, "P": +1},
...     rate=lambda c, x, t: 2.0 * c["S"] / (1.0 + c["S"]),
...     name="Michaelis-Menten",
... )
>>> c = {"S": np.array([1.0, 3.0]), "P": np.zeros(2)}
>>> mm.rates(c, None, 0.0)["P"]
array([1. , 1.5])
>>> jac = mm.jacobian(c, None, 0.0)  # finite-difference derivatives
>>> bool(np.allclose(jac[("P", "S")], 2.0 / (1.0 + c["S"]) ** 2))
True

Supplying the analytical derivative instead:

>>> mm_exact = CustomReaction(
...     stoichiometry={"S": -1, "P": +1},
...     rate=lambda c, x, t: 2.0 * c["S"] / (1.0 + c["S"]),
...     rate_derivatives={"S": lambda c, x, t: 2.0 / (1.0 + c["S"]) ** 2},
... )
>>> mm_exact.jacobian(c, None, 0.0)[("S", "S")]
array([-0.5  , -0.125])
Source code in src/softpotato/reactions/homogeneous.py
class CustomReaction(HomogeneousReaction):
    r"""User-defined homogeneous reaction with an arbitrary rate law.

    Build your own reaction by supplying its net stoichiometry and a rate law
    ``rate(c, x, t)``. Source terms are :math:`R_i = \nu_i\, r(\mathbf{c}, x, t)`.
    Analytical derivatives :math:`\partial r / \partial c_k` can be supplied
    through ``rate_derivatives``; any dependency without one is differentiated
    automatically with central finite differences, so the kinetic Jacobian is
    always available.

    Parameters
    ----------
    stoichiometry : Mapping[str | Species, float]
        Net stoichiometric coefficients ``{species: nu_i}``: negative for
        consumed species and positive for produced species. Non-integer
        coefficients are allowed for non-elementary rate laws.
    rate : Callable[[dict[str, np.ndarray], np.ndarray, float], array_like]
        Rate law :math:`r(\mathbf{c}, x, t)`. Receives the concentration
        dictionary, the spatial grid and the time, and returns a scalar or an
        array broadcastable to the concentration profiles. The rate law must be
        local (node-wise).
    rate_derivatives : Mapping[str | Species, Callable], optional
        Analytical partial derivatives ``{species: dr_dc(c, x, t)}``.
    dependencies : Sequence[str | Species], optional
        Species the rate law depends on. Defaults to the species in
        ``stoichiometry`` plus those in ``rate_derivatives``. List here any
        species that affect the rate without being consumed or produced
        (e.g., an enzyme or a homogeneous catalyst).
    name : str, optional
        Human-readable label used in ``repr``.

    Examples
    --------
    Michaelis–Menten kinetics :math:`S \rightarrow P` with
    :math:`r = V_{max} c_S / (K_M + c_S)`:

    >>> import numpy as np
    >>> from softpotato.reactions import CustomReaction
    >>> mm = CustomReaction(
    ...     stoichiometry={"S": -1, "P": +1},
    ...     rate=lambda c, x, t: 2.0 * c["S"] / (1.0 + c["S"]),
    ...     name="Michaelis-Menten",
    ... )
    >>> c = {"S": np.array([1.0, 3.0]), "P": np.zeros(2)}
    >>> mm.rates(c, None, 0.0)["P"]
    array([1. , 1.5])
    >>> jac = mm.jacobian(c, None, 0.0)  # finite-difference derivatives
    >>> bool(np.allclose(jac[("P", "S")], 2.0 / (1.0 + c["S"]) ** 2))
    True

    Supplying the analytical derivative instead:

    >>> mm_exact = CustomReaction(
    ...     stoichiometry={"S": -1, "P": +1},
    ...     rate=lambda c, x, t: 2.0 * c["S"] / (1.0 + c["S"]),
    ...     rate_derivatives={"S": lambda c, x, t: 2.0 / (1.0 + c["S"]) ** 2},
    ... )
    >>> mm_exact.jacobian(c, None, 0.0)[("S", "S")]
    array([-0.5  , -0.125])
    """

    def __init__(
        self,
        stoichiometry: Mapping[SpeciesLike, float],
        rate: RateFunction,
        rate_derivatives: Mapping[SpeciesLike, RateFunction] | None = None,
        dependencies: Sequence[SpeciesLike] | None = None,
        name: str | None = None,
    ) -> None:
        if not isinstance(stoichiometry, Mapping) or not stoichiometry:
            raise ValueError("stoichiometry must be a non-empty mapping.")
        stoich: dict[str, float] = {}
        for species, nu in stoichiometry.items():
            sp_name = _species_name(species, "stoichiometry species")
            if isinstance(nu, bool) or not isinstance(nu, (int, float, np.number)):
                raise TypeError(
                    f"Stoichiometric coefficient of '{sp_name}' must be a real "
                    f"number, got {type(nu).__name__}."
                )
            if not math.isfinite(float(nu)):
                raise ValueError(
                    f"Stoichiometric coefficient of '{sp_name}' must be finite."
                )
            if sp_name in stoich:
                raise ValueError(f"Species '{sp_name}' appears twice in stoichiometry.")
            stoich[sp_name] = nu
        if all(nu == 0 for nu in stoich.values()):
            raise ValueError(
                "At least one stoichiometric coefficient must be non-zero."
            )
        if not callable(rate):
            raise TypeError("rate must be a callable rate(c, x, t).")

        derivs: dict[str, RateFunction] = {}
        for species, func in (rate_derivatives or {}).items():
            sp_name = _species_name(species, "rate_derivatives species")
            if not callable(func):
                raise TypeError(
                    f"rate derivative for '{sp_name}' must be a callable "
                    f"dr_dc(c, x, t)."
                )
            derivs[sp_name] = func

        if dependencies is None:
            deps = list(stoich)
            deps += [s for s in derivs if s not in deps]
        else:
            deps = []
            for species in dependencies:
                sp_name = _species_name(species, "dependencies species")
                if sp_name not in deps:
                    deps.append(sp_name)
            missing = [s for s in derivs if s not in deps]
            if missing:
                raise ValueError(
                    f"rate_derivatives given for species {missing} that are not "
                    f"listed in dependencies."
                )

        self._stoichiometry = stoich
        self._rate = rate
        self._rate_derivatives = derivs
        self._dependencies = tuple(deps)
        self.name = name

    @property
    def stoichiometry(self) -> dict[str, float]:
        """Net stoichiometric coefficients ``{species: nu_i}``."""
        return dict(self._stoichiometry)

    @property
    def dependencies(self) -> tuple[str, ...]:
        """Species the rate law depends on."""
        return self._dependencies

    def rate(self, c: ConcentrationDict, x: Any, t: float) -> Any:
        """Evaluate the user-supplied rate law."""
        return self._rate(c, x, t)

    def rate_derivatives(
        self, c: ConcentrationDict, x: Any, t: float
    ) -> dict[str, np.ndarray]:
        """Analytical derivatives where supplied, finite differences otherwise."""
        derivs = {
            name: np.asarray(func(c, x, t), dtype=float)
            for name, func in self._rate_derivatives.items()
        }
        missing = [name for name in self._dependencies if name not in derivs]
        if missing:
            derivs.update(self._finite_difference_derivatives(c, x, t, missing))
        return {name: derivs[name] for name in self._dependencies}

    def __repr__(self) -> str:
        label = f"{self.name!r}, " if self.name else ""
        return f"CustomReaction({label}stoichiometry={self._stoichiometry!r})"

stoichiometry property

stoichiometry: dict[str, float]

Net stoichiometric coefficients {species: nu_i}.

dependencies property

dependencies: tuple[str, ...]

Species the rate law depends on.

rate

rate(c: ConcentrationDict, x: Any, t: float) -> Any

Evaluate the user-supplied rate law.

Source code in src/softpotato/reactions/homogeneous.py
def rate(self, c: ConcentrationDict, x: Any, t: float) -> Any:
    """Evaluate the user-supplied rate law."""
    return self._rate(c, x, t)

rate_derivatives

rate_derivatives(c: ConcentrationDict, x: Any, t: float) -> dict[str, np.ndarray]

Analytical derivatives where supplied, finite differences otherwise.

Source code in src/softpotato/reactions/homogeneous.py
def rate_derivatives(
    self, c: ConcentrationDict, x: Any, t: float
) -> dict[str, np.ndarray]:
    """Analytical derivatives where supplied, finite differences otherwise."""
    derivs = {
        name: np.asarray(func(c, x, t), dtype=float)
        for name, func in self._rate_derivatives.items()
    }
    missing = [name for name in self._dependencies if name not in derivs]
    if missing:
        derivs.update(self._finite_difference_derivatives(c, x, t, missing))
    return {name: derivs[name] for name in self._dependencies}

DimerizationReaction

Bases: MassActionReaction

Irreversible dimerization \(2A \xrightarrow{k} A_2\).

With rate \(r = k c_A^2\):

\[ R_A = -2 k c_A^2, \qquad R_{A_2} = +k c_A^2 \]

Parameters:

Name Type Description Default
monomer str or Species

Monomer species \(A\).

required
dimer str or Species or None

Dimer species \(A_2\); None if untracked.

required
k float

Rate constant \(k \ge 0\).

required

Examples:

>>> import numpy as np
>>> from softpotato.reactions import DimerizationReaction
>>> rxn = DimerizationReaction("B", "B2", k=1.0)
>>> rxn.rates({"B": np.array([2.0]), "B2": np.array([0.0])}, None, 0.0)
{'B': array([-8.]), 'B2': array([4.])}
Source code in src/softpotato/reactions/homogeneous.py
class DimerizationReaction(MassActionReaction):
    r"""Irreversible dimerization :math:`2A \xrightarrow{k} A_2`.

    With rate :math:`r = k c_A^2`:

    .. math::

        R_A = -2 k c_A^2, \qquad R_{A_2} = +k c_A^2

    Parameters
    ----------
    monomer : str or Species
        Monomer species :math:`A`.
    dimer : str or Species or None
        Dimer species :math:`A_2`; ``None`` if untracked.
    k : float
        Rate constant :math:`k \ge 0`.

    Examples
    --------
    >>> import numpy as np
    >>> from softpotato.reactions import DimerizationReaction
    >>> rxn = DimerizationReaction("B", "B2", k=1.0)
    >>> rxn.rates({"B": np.array([2.0]), "B2": np.array([0.0])}, None, 0.0)
    {'B': array([-8.]), 'B2': array([4.])}
    """

    def __init__(
        self, monomer: SpeciesLike, dimer: SpeciesLike | None, k: float
    ) -> None:
        products = {} if dimer is None else {dimer: 1}
        super().__init__({monomer: 2}, products, k_f=k)

    @property
    def k(self) -> float:
        """Dimerization rate constant."""
        return self.k_f

k property

k: float

Dimerization rate constant.

DisproportionationReaction

Bases: MassActionReaction

Irreversible disproportionation \(2B \xrightarrow{k} A + C\).

With rate \(r = k c_B^2\):

\[ R_B = -2 k c_B^2, \qquad R_A = R_C = +k c_B^2 \]

Parameters:

Name Type Description Default
reactant str or Species

Disproportionating species \(B\).

required
product_1 str or Species or None

Products \(A\) and \(C\) (None if untracked). If both refer to the same species it receives a coefficient of 2.

required
product_2 str or Species or None

Products \(A\) and \(C\) (None if untracked). If both refer to the same species it receives a coefficient of 2.

required
k float

Rate constant \(k \ge 0\).

required

Examples:

>>> import numpy as np
>>> from softpotato.reactions import DisproportionationReaction
>>> rxn = DisproportionationReaction("B", "A", "C", k=0.5)
>>> rxn.rates({"B": np.array([2.0]), "A": np.zeros(1), "C": np.zeros(1)}, None, 0.0)
{'B': array([-4.]), 'A': array([2.]), 'C': array([2.])}
Source code in src/softpotato/reactions/homogeneous.py
class DisproportionationReaction(MassActionReaction):
    r"""Irreversible disproportionation :math:`2B \xrightarrow{k} A + C`.

    With rate :math:`r = k c_B^2`:

    .. math::

        R_B = -2 k c_B^2, \qquad R_A = R_C = +k c_B^2

    Parameters
    ----------
    reactant : str or Species
        Disproportionating species :math:`B`.
    product_1, product_2 : str or Species or None
        Products :math:`A` and :math:`C` (``None`` if untracked). If both refer
        to the same species it receives a coefficient of 2.
    k : float
        Rate constant :math:`k \ge 0`.

    Examples
    --------
    >>> import numpy as np
    >>> from softpotato.reactions import DisproportionationReaction
    >>> rxn = DisproportionationReaction("B", "A", "C", k=0.5)
    >>> rxn.rates({"B": np.array([2.0]), "A": np.zeros(1), "C": np.zeros(1)}, None, 0.0)
    {'B': array([-4.]), 'A': array([2.]), 'C': array([2.])}
    """

    def __init__(
        self,
        reactant: SpeciesLike,
        product_1: SpeciesLike | None,
        product_2: SpeciesLike | None,
        k: float,
    ) -> None:
        products: dict[SpeciesLike, int] = {}
        for prod in (product_1, product_2):
            if prod is not None:
                name = _species_name(prod, "product")
                products[name] = products.get(name, 0) + 1
        super().__init__({reactant: 2}, products, k_f=k)

    @property
    def k(self) -> float:
        """Disproportionation rate constant."""
        return self.k_f

k property

k: float

Disproportionation rate constant.

FirstOrderReaction

Bases: MassActionReaction

Irreversible first-order (unimolecular) reaction \(A \xrightarrow{k} B\).

\[ R_A = -k c_A, \qquad R_B = +k c_A \]

Parameters:

Name Type Description Default
reactant str or Species

Decaying species \(A\).

required
product str or Species or None

Product species \(B\). None models decay into an electro-inactive, untracked product.

required
k float

First-order rate constant \(k \ge 0\) (s\ :sup:-1).

required

Examples:

>>> import numpy as np
>>> from softpotato.reactions import FirstOrderReaction
>>> rxn = FirstOrderReaction("A", "B", k=0.5)
>>> rxn.rates({"A": np.array([2.0]), "B": np.array([0.0])}, None, 0.0)
{'A': array([-1.]), 'B': array([1.])}
Source code in src/softpotato/reactions/homogeneous.py
class FirstOrderReaction(MassActionReaction):
    r"""Irreversible first-order (unimolecular) reaction :math:`A \xrightarrow{k} B`.

    .. math::

        R_A = -k c_A, \qquad R_B = +k c_A

    Parameters
    ----------
    reactant : str or Species
        Decaying species :math:`A`.
    product : str or Species or None
        Product species :math:`B`. ``None`` models decay into an electro-inactive,
        untracked product.
    k : float
        First-order rate constant :math:`k \ge 0` (s\ :sup:`-1`).

    Examples
    --------
    >>> import numpy as np
    >>> from softpotato.reactions import FirstOrderReaction
    >>> rxn = FirstOrderReaction("A", "B", k=0.5)
    >>> rxn.rates({"A": np.array([2.0]), "B": np.array([0.0])}, None, 0.0)
    {'A': array([-1.]), 'B': array([1.])}
    """

    def __init__(
        self, reactant: SpeciesLike, product: SpeciesLike | None, k: float
    ) -> None:
        products = {} if product is None else {product: 1}
        super().__init__({reactant: 1}, products, k_f=k)

    @property
    def k(self) -> float:
        """First-order rate constant."""
        return self.k_f

k property

k: float

First-order rate constant.

HomogeneousReaction

Bases: ABC

Abstract base class for a single homogeneous (solution-phase) reaction.

A reaction is fully described by its net stoichiometry \(\nu_i\) and its rate law \(r(\mathbf{c}, x, t)\). The species source terms and the kinetic Jacobian follow automatically:

\[ R_i = \nu_i\, r, \qquad \frac{\partial R_i}{\partial c_k} = \nu_i \frac{\partial r}{\partial c_k} \]

Subclass this to implement a new reaction type. Required members:

  • stoichiometry: mapping {species: net coefficient}.
  • rate: the reaction rate \(r(\mathbf{c}, x, t)\).

Optional members:

  • dependencies: species whose concentrations the rate depends on (defaults to the species in stoichiometry).
  • rate_derivatives: analytical \(\partial r/\partial c_k\). The default implementation uses central finite differences, so it only needs overriding for speed or accuracy.

Rate laws must be local: the rate at grid node \(k\) may only depend on the concentrations at that same node (true for all homogeneous kinetics). This makes the kinetic Jacobian block-diagonal in space.

Examples:

A Michaelis–Menten enzymatic conversion \(S \rightarrow P\) written as a subclass:

>>> import numpy as np
>>> from softpotato.reactions import HomogeneousReaction
>>> class MichaelisMenten(HomogeneousReaction):
...     def __init__(self, vmax, km):
...         self.vmax, self.km = vmax, km
...     @property
...     def stoichiometry(self):
...         return {"S": -1, "P": 1}
...     def rate(self, c, x, t):
...         s = np.asarray(c["S"], dtype=float)
...         return self.vmax * s / (self.km + s)
>>> rxn = MichaelisMenten(vmax=2.0, km=1.0)
>>> rxn.rates({"S": np.array([1.0]), "P": np.array([0.0])}, None, 0.0)
{'S': array([-1.]), 'P': array([1.])}
>>> jac = rxn.jacobian({"S": np.array([1.0]), "P": np.array([0.0])}, None, 0.0)
>>> bool(np.isclose(jac[("S", "S")][0], -0.5))
True
Source code in src/softpotato/reactions/homogeneous.py
class HomogeneousReaction(ABC):
    r"""Abstract base class for a single homogeneous (solution-phase) reaction.

    A reaction is fully described by its net stoichiometry :math:`\nu_i` and
    its rate law :math:`r(\mathbf{c}, x, t)`. The species source terms and the
    kinetic Jacobian follow automatically:

    .. math::

        R_i = \nu_i\, r, \qquad
        \frac{\partial R_i}{\partial c_k} = \nu_i \frac{\partial r}{\partial c_k}

    Subclass this to implement a new reaction type. Required members:

    - :attr:`stoichiometry`: mapping ``{species: net coefficient}``.
    - :meth:`rate`: the reaction rate :math:`r(\mathbf{c}, x, t)`.

    Optional members:

    - :attr:`dependencies`: species whose concentrations the rate depends on
      (defaults to the species in :attr:`stoichiometry`).
    - :meth:`rate_derivatives`: analytical :math:`\partial r/\partial c_k`.
      The default implementation uses central finite differences, so it only
      needs overriding for speed or accuracy.

    Rate laws must be *local*: the rate at grid node :math:`k` may only depend
    on the concentrations at that same node (true for all homogeneous
    kinetics). This makes the kinetic Jacobian block-diagonal in space.

    Examples
    --------
    A Michaelis–Menten enzymatic conversion :math:`S \rightarrow P` written as
    a subclass:

    >>> import numpy as np
    >>> from softpotato.reactions import HomogeneousReaction
    >>> class MichaelisMenten(HomogeneousReaction):
    ...     def __init__(self, vmax, km):
    ...         self.vmax, self.km = vmax, km
    ...     @property
    ...     def stoichiometry(self):
    ...         return {"S": -1, "P": 1}
    ...     def rate(self, c, x, t):
    ...         s = np.asarray(c["S"], dtype=float)
    ...         return self.vmax * s / (self.km + s)
    >>> rxn = MichaelisMenten(vmax=2.0, km=1.0)
    >>> rxn.rates({"S": np.array([1.0]), "P": np.array([0.0])}, None, 0.0)
    {'S': array([-1.]), 'P': array([1.])}
    >>> jac = rxn.jacobian({"S": np.array([1.0]), "P": np.array([0.0])}, None, 0.0)
    >>> bool(np.isclose(jac[("S", "S")][0], -0.5))
    True
    """

    #: Relative step used for central finite-difference rate derivatives.
    fd_rel_step: float = float(np.finfo(float).eps ** (1.0 / 3.0))

    # -- required interface -------------------------------------------------
    @property
    @abstractmethod
    def stoichiometry(self) -> Mapping[str, float]:
        """Net stoichiometric coefficients ``{species: nu_i}`` (products > 0)."""

    @abstractmethod
    def rate(self, c: ConcentrationDict, x: Any, t: float) -> Any:
        r"""Reaction rate :math:`r(\mathbf{c}, x, t)` (scalar or array)."""

    # -- optional interface -------------------------------------------------
    @property
    def dependencies(self) -> tuple[str, ...]:
        """Species whose concentrations the rate law depends on."""
        return tuple(self.stoichiometry)

    def rate_derivatives(
        self, c: ConcentrationDict, x: Any, t: float
    ) -> dict[str, np.ndarray]:
        r"""Partial derivatives :math:`\partial r/\partial c_k` for each dependency.

        The default implementation uses vectorized central finite differences:
        because rate laws are local, perturbing an entire concentration profile
        at once yields the node-wise derivative at every grid point.

        Parameters
        ----------
        c : Mapping[str, array_like]
            Concentrations keyed by species name.
        x : array_like
            Spatial grid (passed through to :meth:`rate`).
        t : float
            Time.

        Returns
        -------
        dict[str, np.ndarray]
            Mapping ``{species: dr/dc_species}``.
        """
        return self._finite_difference_derivatives(c, x, t, self.dependencies)

    # -- derived quantities -------------------------------------------------
    @property
    def species(self) -> tuple[str, ...]:
        """All species involved (stoichiometry first, then extra dependencies)."""
        names = list(self.stoichiometry)
        for name in self.dependencies:
            if name not in names:
                names.append(name)
        return tuple(names)

    def rates(self, c: ConcentrationDict, x: Any, t: float) -> dict[str, np.ndarray]:
        r"""Species source terms :math:`R_i = \nu_i r` for this reaction.

        Parameters
        ----------
        c : Mapping[str, array_like]
            Concentrations keyed by species name.
        x : array_like
            Spatial grid.
        t : float
            Time.

        Returns
        -------
        dict[str, np.ndarray]
            Mapping ``{species: R_i}`` for every species with non-zero
            stoichiometry.
        """
        r = self._broadcast(self.rate(c, x, t), c)
        return {name: nu * r for name, nu in self.stoichiometry.items() if nu != 0}

    def jacobian(
        self, c: ConcentrationDict, x: Any, t: float
    ) -> dict[tuple[str, str], np.ndarray]:
        r"""Node-wise kinetic Jacobian entries :math:`\partial R_i/\partial c_k`.

        Returns
        -------
        dict[tuple[str, str], np.ndarray]
            Mapping ``{(i, k): dR_i/dc_k}``; only structurally non-zero entries
            are included.
        """
        derivs = self.rate_derivatives(c, x, t)
        jac: dict[tuple[str, str], np.ndarray] = {}
        for name_i, nu in self.stoichiometry.items():
            if nu == 0:
                continue
            for name_k, dr in derivs.items():
                jac[(name_i, name_k)] = nu * self._broadcast(dr, c)
        return jac

    def __call__(self, c: ConcentrationDict, x: Any, t: float) -> dict[str, np.ndarray]:
        """Alias for :meth:`rates`, usable directly as ``DiffusionProblem.reactions``."""
        return self.rates(c, x, t)

    # -- helpers ------------------------------------------------------------
    def _shape(self, c: ConcentrationDict) -> tuple[int, ...]:
        shapes = [np.shape(c[name]) for name in self.species if name in c]
        return np.broadcast_shapes(*shapes) if shapes else ()

    def _broadcast(self, value: Any, c: ConcentrationDict) -> np.ndarray:
        arr = np.asarray(value, dtype=float)
        shape = np.broadcast_shapes(arr.shape, self._shape(c))
        return np.array(np.broadcast_to(arr, shape), dtype=float)

    def _finite_difference_derivatives(
        self,
        c: ConcentrationDict,
        x: Any,
        t: float,
        names: Iterable[str],
    ) -> dict[str, np.ndarray]:
        """Central finite-difference derivatives of :meth:`rate` w.r.t. ``names``."""
        derivs: dict[str, np.ndarray] = {}
        for name in names:
            ck = _get_concentration(c, name)
            scale = np.maximum(np.abs(ck), np.max(np.abs(ck), initial=0.0))
            scale = np.where(scale > 0.0, scale, 1.0)
            h = self.fd_rel_step * scale
            c_plus = dict(c)
            c_minus = dict(c)
            c_plus[name] = ck + h
            c_minus[name] = ck - h
            r_plus = np.asarray(self.rate(c_plus, x, t), dtype=float)
            r_minus = np.asarray(self.rate(c_minus, x, t), dtype=float)
            derivs[name] = (r_plus - r_minus) / (2.0 * h)
        return derivs

stoichiometry abstractmethod property

stoichiometry: Mapping[str, float]

Net stoichiometric coefficients {species: nu_i} (products > 0).

dependencies property

dependencies: tuple[str, ...]

Species whose concentrations the rate law depends on.

species property

species: tuple[str, ...]

All species involved (stoichiometry first, then extra dependencies).

rate abstractmethod

rate(c: ConcentrationDict, x: Any, t: float) -> Any

Reaction rate \(r(\mathbf{c}, x, t)\) (scalar or array).

Source code in src/softpotato/reactions/homogeneous.py
@abstractmethod
def rate(self, c: ConcentrationDict, x: Any, t: float) -> Any:
    r"""Reaction rate :math:`r(\mathbf{c}, x, t)` (scalar or array)."""

rate_derivatives

rate_derivatives(c: ConcentrationDict, x: Any, t: float) -> dict[str, np.ndarray]

Partial derivatives \(\partial r/\partial c_k\) for each dependency.

The default implementation uses vectorized central finite differences: because rate laws are local, perturbing an entire concentration profile at once yields the node-wise derivative at every grid point.

Parameters:

Name Type Description Default
c Mapping[str, array_like]

Concentrations keyed by species name.

required
x array_like

Spatial grid (passed through to rate).

required
t float

Time.

required

Returns:

Type Description
dict[str, ndarray]

Mapping {species: dr/dc_species}.

Source code in src/softpotato/reactions/homogeneous.py
def rate_derivatives(
    self, c: ConcentrationDict, x: Any, t: float
) -> dict[str, np.ndarray]:
    r"""Partial derivatives :math:`\partial r/\partial c_k` for each dependency.

    The default implementation uses vectorized central finite differences:
    because rate laws are local, perturbing an entire concentration profile
    at once yields the node-wise derivative at every grid point.

    Parameters
    ----------
    c : Mapping[str, array_like]
        Concentrations keyed by species name.
    x : array_like
        Spatial grid (passed through to :meth:`rate`).
    t : float
        Time.

    Returns
    -------
    dict[str, np.ndarray]
        Mapping ``{species: dr/dc_species}``.
    """
    return self._finite_difference_derivatives(c, x, t, self.dependencies)

rates

rates(c: ConcentrationDict, x: Any, t: float) -> dict[str, np.ndarray]

Species source terms \(R_i = \nu_i r\) for this reaction.

Parameters:

Name Type Description Default
c Mapping[str, array_like]

Concentrations keyed by species name.

required
x array_like

Spatial grid.

required
t float

Time.

required

Returns:

Type Description
dict[str, ndarray]

Mapping {species: R_i} for every species with non-zero stoichiometry.

Source code in src/softpotato/reactions/homogeneous.py
def rates(self, c: ConcentrationDict, x: Any, t: float) -> dict[str, np.ndarray]:
    r"""Species source terms :math:`R_i = \nu_i r` for this reaction.

    Parameters
    ----------
    c : Mapping[str, array_like]
        Concentrations keyed by species name.
    x : array_like
        Spatial grid.
    t : float
        Time.

    Returns
    -------
    dict[str, np.ndarray]
        Mapping ``{species: R_i}`` for every species with non-zero
        stoichiometry.
    """
    r = self._broadcast(self.rate(c, x, t), c)
    return {name: nu * r for name, nu in self.stoichiometry.items() if nu != 0}

jacobian

jacobian(c: ConcentrationDict, x: Any, t: float) -> dict[tuple[str, str], np.ndarray]

Node-wise kinetic Jacobian entries \(\partial R_i/\partial c_k\).

Returns:

Type Description
dict[tuple[str, str], ndarray]

Mapping {(i, k): dR_i/dc_k}; only structurally non-zero entries are included.

Source code in src/softpotato/reactions/homogeneous.py
def jacobian(
    self, c: ConcentrationDict, x: Any, t: float
) -> dict[tuple[str, str], np.ndarray]:
    r"""Node-wise kinetic Jacobian entries :math:`\partial R_i/\partial c_k`.

    Returns
    -------
    dict[tuple[str, str], np.ndarray]
        Mapping ``{(i, k): dR_i/dc_k}``; only structurally non-zero entries
        are included.
    """
    derivs = self.rate_derivatives(c, x, t)
    jac: dict[tuple[str, str], np.ndarray] = {}
    for name_i, nu in self.stoichiometry.items():
        if nu == 0:
            continue
        for name_k, dr in derivs.items():
            jac[(name_i, name_k)] = nu * self._broadcast(dr, c)
    return jac

__call__

__call__(c: ConcentrationDict, x: Any, t: float) -> dict[str, np.ndarray]

Alias for rates, usable directly as DiffusionProblem.reactions.

Source code in src/softpotato/reactions/homogeneous.py
def __call__(self, c: ConcentrationDict, x: Any, t: float) -> dict[str, np.ndarray]:
    """Alias for :meth:`rates`, usable directly as ``DiffusionProblem.reactions``."""
    return self.rates(c, x, t)

MassActionReaction

Bases: HomogeneousReaction

General elementary reaction obeying the law of mass action.

\[ \sum_i a_i\, X_i \;\underset{k_b}{\overset{k_f}{\rightleftharpoons}}\; \sum_j b_j\, Y_j, \qquad r = k_f \prod_i c_{X_i}^{a_i} - k_b \prod_j c_{Y_j}^{b_j} \]

The net stoichiometry is \(\nu = b - a\), so a species appearing on both sides (e.g. a catalyst) has its coefficients cancelled. Rate derivatives are computed analytically.

This class is also a convenient way to build custom elementary mechanisms with arbitrary stoichiometry.

Parameters:

Name Type Description Default
reactants Mapping[str | Species, int]

Reactant species and their (positive integer) stoichiometric coefficients \(a_i\), which are also the reaction orders.

required
products Mapping[str | Species, int]

Product species and their coefficients \(b_j\). May be empty (e.g. irreversible decay into untracked species).

required
k_f float

Forward rate constant \(k_f \ge 0\).

required
k_b float

Backward rate constant \(k_b \ge 0\).

0.0

Examples:

>>> import numpy as np
>>> from softpotato.reactions import MassActionReaction
>>> rxn = MassActionReaction({"A": 1, "B": 2}, {"C": 1}, k_f=3.0)
>>> c = {"A": np.array([2.0]), "B": np.array([1.0]), "C": np.array([0.0])}
>>> rxn.rate(c, None, 0.0)
array([6.])
>>> rxn.rates(c, None, 0.0)
{'A': array([-6.]), 'B': array([-12.]), 'C': array([6.])}
Source code in src/softpotato/reactions/homogeneous.py
class MassActionReaction(HomogeneousReaction):
    r"""General elementary reaction obeying the law of mass action.

    .. math::

        \sum_i a_i\, X_i \;\underset{k_b}{\overset{k_f}{\rightleftharpoons}}\;
        \sum_j b_j\, Y_j,
        \qquad r = k_f \prod_i c_{X_i}^{a_i} - k_b \prod_j c_{Y_j}^{b_j}

    The net stoichiometry is :math:`\nu = b - a`, so a species appearing on
    both sides (e.g. a catalyst) has its coefficients cancelled. Rate
    derivatives are computed analytically.

    This class is also a convenient way to build custom *elementary*
    mechanisms with arbitrary stoichiometry.

    Parameters
    ----------
    reactants : Mapping[str | Species, int]
        Reactant species and their (positive integer) stoichiometric
        coefficients :math:`a_i`, which are also the reaction orders.
    products : Mapping[str | Species, int]
        Product species and their coefficients :math:`b_j`. May be empty
        (e.g. irreversible decay into untracked species).
    k_f : float
        Forward rate constant :math:`k_f \ge 0`.
    k_b : float, default 0.0
        Backward rate constant :math:`k_b \ge 0`.

    Examples
    --------
    >>> import numpy as np
    >>> from softpotato.reactions import MassActionReaction
    >>> rxn = MassActionReaction({"A": 1, "B": 2}, {"C": 1}, k_f=3.0)
    >>> c = {"A": np.array([2.0]), "B": np.array([1.0]), "C": np.array([0.0])}
    >>> rxn.rate(c, None, 0.0)
    array([6.])
    >>> rxn.rates(c, None, 0.0)
    {'A': array([-6.]), 'B': array([-12.]), 'C': array([6.])}
    """

    def __init__(
        self,
        reactants: Mapping[SpeciesLike, int],
        products: Mapping[SpeciesLike, int],
        k_f: float,
        k_b: float = 0.0,
    ) -> None:
        self._reactants = _validate_order_mapping(reactants, "reactants")
        self._products = _validate_order_mapping(products, "products")
        if not self._reactants:
            raise ValueError("A mass-action reaction requires at least one reactant.")
        self._k_f = _validate_rate_constant(k_f, "k_f")
        self._k_b = _validate_rate_constant(k_b, "k_b")
        if self._k_b > 0.0 and not self._products:
            raise ValueError("A reversible reaction (k_b > 0) requires products.")

        stoich: dict[str, int] = {}
        for name, a in self._reactants.items():
            stoich[name] = stoich.get(name, 0) - a
        for name, b in self._products.items():
            stoich[name] = stoich.get(name, 0) + b
        self._stoichiometry = stoich

    # -- properties ---------------------------------------------------------
    @property
    def reactants(self) -> dict[str, int]:
        """Reactant stoichiometric coefficients (forward reaction orders)."""
        return dict(self._reactants)

    @property
    def products(self) -> dict[str, int]:
        """Product stoichiometric coefficients (backward reaction orders)."""
        return dict(self._products)

    @property
    def k_f(self) -> float:
        """Forward rate constant."""
        return self._k_f

    @property
    def k_b(self) -> float:
        """Backward rate constant."""
        return self._k_b

    @property
    def is_reversible(self) -> bool:
        """``True`` if the backward rate constant is non-zero."""
        return self._k_b > 0.0

    @property
    def stoichiometry(self) -> dict[str, int]:
        """Net stoichiometric coefficients ``{species: b_i - a_i}``."""
        return dict(self._stoichiometry)

    @property
    def dependencies(self) -> tuple[str, ...]:
        """Species appearing in a non-zero rate term."""
        names = list(self._reactants)
        if self.is_reversible:
            names += [s for s in self._products if s not in names]
        return tuple(names)

    @property
    def species(self) -> tuple[str, ...]:
        """All species appearing in the reaction equation."""
        names = list(self._reactants)
        names += [s for s in self._products if s not in names]
        return tuple(names)

    # -- kinetics -----------------------------------------------------------
    @staticmethod
    def _monomial(c: ConcentrationDict, orders: Mapping[str, int]) -> np.ndarray:
        result = np.asarray(1.0)
        for name, order in orders.items():
            result = result * _get_concentration(c, name) ** order
        return np.asarray(result, dtype=float)

    @staticmethod
    def _monomial_derivative(
        c: ConcentrationDict, orders: Mapping[str, int], wrt: str
    ) -> np.ndarray:
        result = np.asarray(float(orders[wrt]))
        for name, order in orders.items():
            power = order - 1 if name == wrt else order
            if power > 0:
                result = result * _get_concentration(c, name) ** power
        return np.asarray(result, dtype=float)

    def rate(self, c: ConcentrationDict, x: Any, t: float) -> np.ndarray:
        r"""Net mass-action rate :math:`k_f \prod c^{a} - k_b \prod c^{b}`."""
        r = self._k_f * self._monomial(c, self._reactants)
        if self.is_reversible:
            r = r - self._k_b * self._monomial(c, self._products)
        return np.asarray(r, dtype=float)

    def rate_derivatives(
        self, c: ConcentrationDict, x: Any, t: float
    ) -> dict[str, np.ndarray]:
        r"""Analytical derivatives :math:`\partial r / \partial c_k`."""
        derivs: dict[str, np.ndarray] = {}
        for name in self.dependencies:
            d = np.asarray(0.0)
            if name in self._reactants:
                d = d + self._k_f * self._monomial_derivative(c, self._reactants, name)
            if self.is_reversible and name in self._products:
                d = d - self._k_b * self._monomial_derivative(c, self._products, name)
            derivs[name] = np.asarray(d, dtype=float)
        return derivs

    def __repr__(self) -> str:
        def side(orders: Mapping[str, int]) -> str:
            if not orders:
                return "∅"
            return " + ".join(f"{n if n > 1 else ''}{s}" for s, n in orders.items())

        arrow = "<=>" if self.is_reversible else "->"
        rates = f"k_f={self._k_f!r}" + (
            f", k_b={self._k_b!r}" if self.is_reversible else ""
        )
        return (
            f"{type(self).__name__}("
            f"{side(self._reactants)} {arrow} {side(self._products)}, {rates})"
        )

reactants property

reactants: dict[str, int]

Reactant stoichiometric coefficients (forward reaction orders).

products property

products: dict[str, int]

Product stoichiometric coefficients (backward reaction orders).

k_f property

k_f: float

Forward rate constant.

k_b property

k_b: float

Backward rate constant.

is_reversible property

is_reversible: bool

True if the backward rate constant is non-zero.

stoichiometry property

stoichiometry: dict[str, int]

Net stoichiometric coefficients {species: b_i - a_i}.

dependencies property

dependencies: tuple[str, ...]

Species appearing in a non-zero rate term.

species property

species: tuple[str, ...]

All species appearing in the reaction equation.

rate

rate(c: ConcentrationDict, x: Any, t: float) -> np.ndarray

Net mass-action rate \(k_f \prod c^{a} - k_b \prod c^{b}\).

Source code in src/softpotato/reactions/homogeneous.py
def rate(self, c: ConcentrationDict, x: Any, t: float) -> np.ndarray:
    r"""Net mass-action rate :math:`k_f \prod c^{a} - k_b \prod c^{b}`."""
    r = self._k_f * self._monomial(c, self._reactants)
    if self.is_reversible:
        r = r - self._k_b * self._monomial(c, self._products)
    return np.asarray(r, dtype=float)

rate_derivatives

rate_derivatives(c: ConcentrationDict, x: Any, t: float) -> dict[str, np.ndarray]

Analytical derivatives \(\partial r / \partial c_k\).

Source code in src/softpotato/reactions/homogeneous.py
def rate_derivatives(
    self, c: ConcentrationDict, x: Any, t: float
) -> dict[str, np.ndarray]:
    r"""Analytical derivatives :math:`\partial r / \partial c_k`."""
    derivs: dict[str, np.ndarray] = {}
    for name in self.dependencies:
        d = np.asarray(0.0)
        if name in self._reactants:
            d = d + self._k_f * self._monomial_derivative(c, self._reactants, name)
        if self.is_reversible and name in self._products:
            d = d - self._k_b * self._monomial_derivative(c, self._products, name)
        derivs[name] = np.asarray(d, dtype=float)
    return derivs

ReactionNetwork

Collection of homogeneous reactions with summed rates and Jacobian.

Computes the combined species source terms \(R_i = \sum_j \nu_{i,j} r_j\) and the kinetic Jacobian \(\partial R_i / \partial c_k\). Instances are callable with the signature expected by DiffusionProblem (reactions(c_dict, grid, t) -> dict) and can be passed directly as DiffusionProblem(..., reactions=network).

Parameters:

Name Type Description Default
reactions Iterable[HomogeneousReaction]

Initial reactions.

()
species Sequence[str | Species]

Explicit species ordering used for the Jacobian and stoichiometry matrix (e.g. problem.species). Defaults to the order of first appearance across reactions. If given, it must contain every species involved in the reactions.

None

Examples:

EC' catalytic mechanism with pseudo-first-order regeneration, solved with the SciPy Method of Lines solver:

>>> import numpy as np
>>> from softpotato.reactions import CatalyticReaction, ReactionNetwork
>>> from softpotato.solver import DiffusionProblem, DirichletBC, get_solver
>>> network = ReactionNetwork([CatalyticReaction("Red", "Ox", k=10.0)])
>>> problem = DiffusionProblem(
...     grid=np.linspace(0.0, 1e-3, 41),
...     diffusivity={"Ox": 1e-9, "Red": 1e-9},
...     boundary_conditions={
...         "Ox": (DirichletBC(0.0), DirichletBC(1.0)),
...         "Red": (DirichletBC(1.0), DirichletBC(0.0)),
...     },
...     initial_conditions={"Ox": 1.0, "Red": 0.0},
...     reactions=network,
... )
>>> result = get_solver("scipy_ivp").solve(problem, t_span=(0.0, 1.0))
>>> result.success
True

Kinetic Jacobian (species-major block ordering, sparse by default):

>>> c = {"Ox": np.ones(41), "Red": np.zeros(41)}
>>> J = network.jacobian(c, problem.grid, 0.0, species=problem.species)
>>> J.shape
(82, 82)
>>> network.local_jacobian(c, problem.grid, 0.0, species=problem.species)[:, :, 0]
array([[  0.,  10.],
       [  0., -10.]])
Source code in src/softpotato/reactions/homogeneous.py
class ReactionNetwork:
    r"""Collection of homogeneous reactions with summed rates and Jacobian.

    Computes the combined species source terms
    :math:`R_i = \sum_j \nu_{i,j} r_j` and the kinetic Jacobian
    :math:`\partial R_i / \partial c_k`. Instances are callable with the
    signature expected by :class:`~softpotato.solver.DiffusionProblem`
    (``reactions(c_dict, grid, t) -> dict``) and can be passed directly as
    ``DiffusionProblem(..., reactions=network)``.

    Parameters
    ----------
    reactions : Iterable[HomogeneousReaction], optional
        Initial reactions.
    species : Sequence[str | Species], optional
        Explicit species ordering used for the Jacobian and stoichiometry
        matrix (e.g. ``problem.species``). Defaults to the order of first
        appearance across reactions. If given, it must contain every species
        involved in the reactions.

    Examples
    --------
    EC' catalytic mechanism with pseudo-first-order regeneration, solved with
    the SciPy Method of Lines solver:

    >>> import numpy as np
    >>> from softpotato.reactions import CatalyticReaction, ReactionNetwork
    >>> from softpotato.solver import DiffusionProblem, DirichletBC, get_solver
    >>> network = ReactionNetwork([CatalyticReaction("Red", "Ox", k=10.0)])
    >>> problem = DiffusionProblem(
    ...     grid=np.linspace(0.0, 1e-3, 41),
    ...     diffusivity={"Ox": 1e-9, "Red": 1e-9},
    ...     boundary_conditions={
    ...         "Ox": (DirichletBC(0.0), DirichletBC(1.0)),
    ...         "Red": (DirichletBC(1.0), DirichletBC(0.0)),
    ...     },
    ...     initial_conditions={"Ox": 1.0, "Red": 0.0},
    ...     reactions=network,
    ... )
    >>> result = get_solver("scipy_ivp").solve(problem, t_span=(0.0, 1.0))
    >>> result.success
    True

    Kinetic Jacobian (species-major block ordering, sparse by default):

    >>> c = {"Ox": np.ones(41), "Red": np.zeros(41)}
    >>> J = network.jacobian(c, problem.grid, 0.0, species=problem.species)
    >>> J.shape
    (82, 82)
    >>> network.local_jacobian(c, problem.grid, 0.0, species=problem.species)[:, :, 0]
    array([[  0.,  10.],
           [  0., -10.]])
    """

    def __init__(
        self,
        reactions: Iterable[HomogeneousReaction] = (),
        species: Sequence[SpeciesLike] | None = None,
    ) -> None:
        self._reactions: list[HomogeneousReaction] = []
        self._species_order: list[str] | None = None
        if species is not None:
            order: list[str] = []
            for item in species:
                name = _species_name(item)
                if name in order:
                    raise ValueError(f"Species '{name}' is listed twice.")
                order.append(name)
            self._species_order = order
        for reaction in reactions:
            self.add(reaction)

    # -- container interface ------------------------------------------------
    def add(self, reaction: HomogeneousReaction) -> None:
        """Append a reaction to the network.

        Raises
        ------
        TypeError
            If ``reaction`` is not a :class:`HomogeneousReaction`.
        ValueError
            If an explicit species order was given and the reaction involves a
            species not contained in it.
        """
        if not isinstance(reaction, HomogeneousReaction):
            raise TypeError(
                f"Expected a HomogeneousReaction instance, got "
                f"{type(reaction).__name__}."
            )
        if self._species_order is not None:
            unknown = [s for s in reaction.species if s not in self._species_order]
            if unknown:
                raise ValueError(
                    f"Reaction {reaction!r} involves species {unknown} not present "
                    f"in the network species list {self._species_order}."
                )
        self._reactions.append(reaction)

    @property
    def reactions(self) -> list[HomogeneousReaction]:
        """List of reactions in the network."""
        return list(self._reactions)

    def __iter__(self) -> Iterator[HomogeneousReaction]:
        return iter(self._reactions)

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

    def __getitem__(self, index: int) -> HomogeneousReaction:
        return self._reactions[index]

    def __repr__(self) -> str:
        return f"ReactionNetwork({self._reactions!r})"

    @property
    def species(self) -> list[str]:
        """Ordered species names used for Jacobian and stoichiometry indexing."""
        if self._species_order is not None:
            return list(self._species_order)
        names: list[str] = []
        for reaction in self._reactions:
            for name in reaction.species:
                if name not in names:
                    names.append(name)
        return names

    @property
    def stoichiometry_matrix(self) -> np.ndarray:
        r"""Net stoichiometric matrix :math:`\nu_{i,j}` of shape ``(n_species, n_reactions)``."""
        names = self.species
        index = {name: i for i, name in enumerate(names)}
        nu = np.zeros((len(names), len(self._reactions)), dtype=float)
        for j, reaction in enumerate(self._reactions):
            for name, coeff in reaction.stoichiometry.items():
                nu[index[name], j] += coeff
        return nu

    # -- kinetics -----------------------------------------------------------
    def _profile_shape(self, c: ConcentrationDict) -> tuple[int, ...]:
        shapes = [np.shape(c[name]) for name in self.species if name in c]
        return np.broadcast_shapes(*shapes) if shapes else ()

    def evaluate(self, c: ConcentrationDict, x: Any, t: float) -> dict[str, np.ndarray]:
        r"""Combined species source terms :math:`R_i = \sum_j \nu_{i,j} r_j`.

        Parameters
        ----------
        c : Mapping[str, array_like]
            Concentration profiles keyed by species name.
        x : array_like
            Spatial grid.
        t : float
            Time.

        Returns
        -------
        dict[str, np.ndarray]
            Source term for every species in :attr:`species` (zeros for
            species that are not consumed or produced).
        """
        shape = self._profile_shape(c)
        total = {name: np.zeros(shape, dtype=float) for name in self.species}
        for reaction in self._reactions:
            for name, rate in reaction.rates(c, x, t).items():
                total[name] = total[name] + rate
        return total

    def __call__(self, c: ConcentrationDict, x: Any, t: float) -> dict[str, np.ndarray]:
        """Alias for :meth:`evaluate` (``DiffusionProblem.reactions`` signature)."""
        return self.evaluate(c, x, t)

    def local_jacobian(
        self,
        c: ConcentrationDict,
        x: Any,
        t: float,
        species: Sequence[str] | None = None,
    ) -> np.ndarray:
        r"""Node-wise kinetic Jacobian :math:`J_{ik}(x) = \partial R_i / \partial c_k`.

        Parameters
        ----------
        c : Mapping[str, array_like]
            Concentration profiles keyed by species name.
        x : array_like
            Spatial grid.
        t : float
            Time.
        species : Sequence[str], optional
            Species ordering for the rows/columns; defaults to :attr:`species`.
            Extra species not involved in any reaction give zero rows/columns;
            omitting a species involved in a reaction raises ``KeyError``.

        Returns
        -------
        np.ndarray
            Array of shape ``(n_species, n_species, *profile_shape)``.
        """
        names = list(species) if species is not None else self.species
        index = {name: i for i, name in enumerate(names)}
        shape = self._profile_shape(c)
        jac = np.zeros((len(names), len(names), *shape), dtype=float)
        for reaction in self._reactions:
            for (name_i, name_k), value in reaction.jacobian(c, x, t).items():
                if name_i not in index or name_k not in index:
                    raise KeyError(
                        f"Jacobian entry ({name_i!r}, {name_k!r}) refers to a species "
                        f"not contained in the species ordering {names}."
                    )
                jac[index[name_i], index[name_k]] += value
        return jac

    def jacobian(
        self,
        c: ConcentrationDict,
        x: Any,
        t: float,
        species: Sequence[str] | None = None,
        sparse: bool = True,
    ) -> Any:
        r"""Full kinetic Jacobian of the semi-discretized reaction term.

        The state vector is ordered species-major,
        :math:`\mathbf{y} = [c_{1,0}, \ldots, c_{1,N-1}, c_{2,0}, \ldots]`, so the
        Jacobian is an ``(S*N, S*N)`` block matrix whose ``(i, k)`` block is the
        diagonal matrix :math:`\mathrm{diag}(\partial R_i / \partial c_k)`.

        Parameters
        ----------
        c : Mapping[str, array_like]
            1D concentration profiles keyed by species name.
        x : array_like
            Spatial grid.
        t : float
            Time.
        species : Sequence[str], optional
            Species ordering; defaults to :attr:`species`.
        sparse : bool, default True
            Return a ``scipy.sparse.csr_matrix`` if ``True``, otherwise a dense
            ``numpy.ndarray``.

        Returns
        -------
        scipy.sparse.csr_matrix or np.ndarray
            Kinetic Jacobian of shape ``(S*N, S*N)``.
        """
        local = self.local_jacobian(c, x, t, species=species)
        n_species = local.shape[0]
        if local.ndim == 2:
            local = local[:, :, np.newaxis]
        elif local.ndim != 3:
            raise ValueError(
                "jacobian() requires 1D concentration profiles; "
                f"got profile shape {local.shape[2:]}."
            )
        n_points = local.shape[2]
        size = n_species * n_points
        nodes = np.arange(n_points)

        rows: list[np.ndarray] = []
        cols: list[np.ndarray] = []
        data: list[np.ndarray] = []
        for i in range(n_species):
            for k in range(n_species):
                block = local[i, k]
                if np.any(block != 0.0):
                    rows.append(i * n_points + nodes)
                    cols.append(k * n_points + nodes)
                    data.append(block)
        if data:
            coo = _sparse.coo_matrix(
                (np.concatenate(data), (np.concatenate(rows), np.concatenate(cols))),
                shape=(size, size),
            )
        else:
            coo = _sparse.coo_matrix((size, size), dtype=float)
        mat = coo.tocsr()
        return mat if sparse else mat.toarray()

reactions property

reactions: list[HomogeneousReaction]

List of reactions in the network.

species property

species: list[str]

Ordered species names used for Jacobian and stoichiometry indexing.

stoichiometry_matrix property

stoichiometry_matrix: ndarray

Net stoichiometric matrix \(\nu_{i,j}\) of shape (n_species, n_reactions).

add

add(reaction: HomogeneousReaction) -> None

Append a reaction to the network.

Raises:

Type Description
TypeError

If reaction is not a HomogeneousReaction.

ValueError

If an explicit species order was given and the reaction involves a species not contained in it.

Source code in src/softpotato/reactions/homogeneous.py
def add(self, reaction: HomogeneousReaction) -> None:
    """Append a reaction to the network.

    Raises
    ------
    TypeError
        If ``reaction`` is not a :class:`HomogeneousReaction`.
    ValueError
        If an explicit species order was given and the reaction involves a
        species not contained in it.
    """
    if not isinstance(reaction, HomogeneousReaction):
        raise TypeError(
            f"Expected a HomogeneousReaction instance, got "
            f"{type(reaction).__name__}."
        )
    if self._species_order is not None:
        unknown = [s for s in reaction.species if s not in self._species_order]
        if unknown:
            raise ValueError(
                f"Reaction {reaction!r} involves species {unknown} not present "
                f"in the network species list {self._species_order}."
            )
    self._reactions.append(reaction)

evaluate

evaluate(c: ConcentrationDict, x: Any, t: float) -> dict[str, np.ndarray]

Combined species source terms \(R_i = \sum_j \nu_{i,j} r_j\).

Parameters:

Name Type Description Default
c Mapping[str, array_like]

Concentration profiles keyed by species name.

required
x array_like

Spatial grid.

required
t float

Time.

required

Returns:

Type Description
dict[str, ndarray]

Source term for every species in species (zeros for species that are not consumed or produced).

Source code in src/softpotato/reactions/homogeneous.py
def evaluate(self, c: ConcentrationDict, x: Any, t: float) -> dict[str, np.ndarray]:
    r"""Combined species source terms :math:`R_i = \sum_j \nu_{i,j} r_j`.

    Parameters
    ----------
    c : Mapping[str, array_like]
        Concentration profiles keyed by species name.
    x : array_like
        Spatial grid.
    t : float
        Time.

    Returns
    -------
    dict[str, np.ndarray]
        Source term for every species in :attr:`species` (zeros for
        species that are not consumed or produced).
    """
    shape = self._profile_shape(c)
    total = {name: np.zeros(shape, dtype=float) for name in self.species}
    for reaction in self._reactions:
        for name, rate in reaction.rates(c, x, t).items():
            total[name] = total[name] + rate
    return total

__call__

__call__(c: ConcentrationDict, x: Any, t: float) -> dict[str, np.ndarray]

Alias for evaluate (DiffusionProblem.reactions signature).

Source code in src/softpotato/reactions/homogeneous.py
def __call__(self, c: ConcentrationDict, x: Any, t: float) -> dict[str, np.ndarray]:
    """Alias for :meth:`evaluate` (``DiffusionProblem.reactions`` signature)."""
    return self.evaluate(c, x, t)

local_jacobian

local_jacobian(c: ConcentrationDict, x: Any, t: float, species: Sequence[str] | None = None) -> np.ndarray

Node-wise kinetic Jacobian \(J_{ik}(x) = \partial R_i / \partial c_k\).

Parameters:

Name Type Description Default
c Mapping[str, array_like]

Concentration profiles keyed by species name.

required
x array_like

Spatial grid.

required
t float

Time.

required
species Sequence[str]

Species ordering for the rows/columns; defaults to species. Extra species not involved in any reaction give zero rows/columns; omitting a species involved in a reaction raises KeyError.

None

Returns:

Type Description
ndarray

Array of shape (n_species, n_species, *profile_shape).

Source code in src/softpotato/reactions/homogeneous.py
def local_jacobian(
    self,
    c: ConcentrationDict,
    x: Any,
    t: float,
    species: Sequence[str] | None = None,
) -> np.ndarray:
    r"""Node-wise kinetic Jacobian :math:`J_{ik}(x) = \partial R_i / \partial c_k`.

    Parameters
    ----------
    c : Mapping[str, array_like]
        Concentration profiles keyed by species name.
    x : array_like
        Spatial grid.
    t : float
        Time.
    species : Sequence[str], optional
        Species ordering for the rows/columns; defaults to :attr:`species`.
        Extra species not involved in any reaction give zero rows/columns;
        omitting a species involved in a reaction raises ``KeyError``.

    Returns
    -------
    np.ndarray
        Array of shape ``(n_species, n_species, *profile_shape)``.
    """
    names = list(species) if species is not None else self.species
    index = {name: i for i, name in enumerate(names)}
    shape = self._profile_shape(c)
    jac = np.zeros((len(names), len(names), *shape), dtype=float)
    for reaction in self._reactions:
        for (name_i, name_k), value in reaction.jacobian(c, x, t).items():
            if name_i not in index or name_k not in index:
                raise KeyError(
                    f"Jacobian entry ({name_i!r}, {name_k!r}) refers to a species "
                    f"not contained in the species ordering {names}."
                )
            jac[index[name_i], index[name_k]] += value
    return jac

jacobian

jacobian(c: ConcentrationDict, x: Any, t: float, species: Sequence[str] | None = None, sparse: bool = True) -> Any

Full kinetic Jacobian of the semi-discretized reaction term.

The state vector is ordered species-major, \(\mathbf{y} = [c_{1,0}, \ldots, c_{1,N-1}, c_{2,0}, \ldots]\), so the Jacobian is an (S*N, S*N) block matrix whose (i, k) block is the diagonal matrix \(\mathrm{diag}(\partial R_i / \partial c_k)\).

Parameters:

Name Type Description Default
c Mapping[str, array_like]

1D concentration profiles keyed by species name.

required
x array_like

Spatial grid.

required
t float

Time.

required
species Sequence[str]

Species ordering; defaults to species.

None
sparse bool

Return a scipy.sparse.csr_matrix if True, otherwise a dense numpy.ndarray.

True

Returns:

Type Description
csr_matrix or ndarray

Kinetic Jacobian of shape (S*N, S*N).

Source code in src/softpotato/reactions/homogeneous.py
def jacobian(
    self,
    c: ConcentrationDict,
    x: Any,
    t: float,
    species: Sequence[str] | None = None,
    sparse: bool = True,
) -> Any:
    r"""Full kinetic Jacobian of the semi-discretized reaction term.

    The state vector is ordered species-major,
    :math:`\mathbf{y} = [c_{1,0}, \ldots, c_{1,N-1}, c_{2,0}, \ldots]`, so the
    Jacobian is an ``(S*N, S*N)`` block matrix whose ``(i, k)`` block is the
    diagonal matrix :math:`\mathrm{diag}(\partial R_i / \partial c_k)`.

    Parameters
    ----------
    c : Mapping[str, array_like]
        1D concentration profiles keyed by species name.
    x : array_like
        Spatial grid.
    t : float
        Time.
    species : Sequence[str], optional
        Species ordering; defaults to :attr:`species`.
    sparse : bool, default True
        Return a ``scipy.sparse.csr_matrix`` if ``True``, otherwise a dense
        ``numpy.ndarray``.

    Returns
    -------
    scipy.sparse.csr_matrix or np.ndarray
        Kinetic Jacobian of shape ``(S*N, S*N)``.
    """
    local = self.local_jacobian(c, x, t, species=species)
    n_species = local.shape[0]
    if local.ndim == 2:
        local = local[:, :, np.newaxis]
    elif local.ndim != 3:
        raise ValueError(
            "jacobian() requires 1D concentration profiles; "
            f"got profile shape {local.shape[2:]}."
        )
    n_points = local.shape[2]
    size = n_species * n_points
    nodes = np.arange(n_points)

    rows: list[np.ndarray] = []
    cols: list[np.ndarray] = []
    data: list[np.ndarray] = []
    for i in range(n_species):
        for k in range(n_species):
            block = local[i, k]
            if np.any(block != 0.0):
                rows.append(i * n_points + nodes)
                cols.append(k * n_points + nodes)
                data.append(block)
    if data:
        coo = _sparse.coo_matrix(
            (np.concatenate(data), (np.concatenate(rows), np.concatenate(cols))),
            shape=(size, size),
        )
    else:
        coo = _sparse.coo_matrix((size, size), dtype=float)
    mat = coo.tocsr()
    return mat if sparse else mat.toarray()

ReversibleReaction

Bases: MassActionReaction

Reversible first-order equilibrium \(A \underset{k_b}{\overset{k_f}{\rightleftharpoons}} B\).

\[ R_A = -k_f c_A + k_b c_B, \qquad R_B = +k_f c_A - k_b c_B \]

Parameters:

Name Type Description Default
reactant str or Species

Species \(A\).

required
product str or Species

Species \(B\).

required
k_f float

Forward rate constant \(k_f \ge 0\).

required
k_b float

Backward rate constant \(k_b \ge 0\).

required

Examples:

>>> from softpotato.reactions import ReversibleReaction
>>> rxn = ReversibleReaction("A", "B", k_f=10.0, k_b=2.0)
>>> rxn.equilibrium_constant
5.0
>>> rxn2 = ReversibleReaction.from_equilibrium("A", "B", K=5.0, k_f=10.0)
>>> rxn2.k_b
2.0
Source code in src/softpotato/reactions/homogeneous.py
class ReversibleReaction(MassActionReaction):
    r"""Reversible first-order equilibrium :math:`A \underset{k_b}{\overset{k_f}{\rightleftharpoons}} B`.

    .. math::

        R_A = -k_f c_A + k_b c_B, \qquad R_B = +k_f c_A - k_b c_B

    Parameters
    ----------
    reactant : str or Species
        Species :math:`A`.
    product : str or Species
        Species :math:`B`.
    k_f : float
        Forward rate constant :math:`k_f \ge 0`.
    k_b : float
        Backward rate constant :math:`k_b \ge 0`.

    Examples
    --------
    >>> from softpotato.reactions import ReversibleReaction
    >>> rxn = ReversibleReaction("A", "B", k_f=10.0, k_b=2.0)
    >>> rxn.equilibrium_constant
    5.0
    >>> rxn2 = ReversibleReaction.from_equilibrium("A", "B", K=5.0, k_f=10.0)
    >>> rxn2.k_b
    2.0
    """

    def __init__(
        self, reactant: SpeciesLike, product: SpeciesLike, k_f: float, k_b: float
    ) -> None:
        super().__init__({reactant: 1}, {product: 1}, k_f=k_f, k_b=k_b)

    @classmethod
    def from_equilibrium(
        cls, reactant: SpeciesLike, product: SpeciesLike, K: float, k_f: float
    ) -> ReversibleReaction:
        r"""Create from the equilibrium constant :math:`K = k_f / k_b` and :math:`k_f`."""
        K = _validate_rate_constant(K, "K")
        if K == 0.0:
            raise ValueError("Equilibrium constant K must be positive.")
        k_f = _validate_rate_constant(k_f, "k_f")
        return cls(reactant, product, k_f=k_f, k_b=k_f / K)

    @property
    def equilibrium_constant(self) -> float:
        r"""Equilibrium constant :math:`K = k_f / k_b` (``inf`` if :math:`k_b = 0`)."""
        return self.k_f / self.k_b if self.k_b > 0.0 else math.inf

equilibrium_constant property

equilibrium_constant: float

Equilibrium constant \(K = k_f / k_b\) (inf if \(k_b = 0\)).

from_equilibrium classmethod

from_equilibrium(reactant: SpeciesLike, product: SpeciesLike, K: float, k_f: float) -> ReversibleReaction

Create from the equilibrium constant \(K = k_f / k_b\) and \(k_f\).

Source code in src/softpotato/reactions/homogeneous.py
@classmethod
def from_equilibrium(
    cls, reactant: SpeciesLike, product: SpeciesLike, K: float, k_f: float
) -> ReversibleReaction:
    r"""Create from the equilibrium constant :math:`K = k_f / k_b` and :math:`k_f`."""
    K = _validate_rate_constant(K, "K")
    if K == 0.0:
        raise ValueError("Equilibrium constant K must be positive.")
    k_f = _validate_rate_constant(k_f, "k_f")
    return cls(reactant, product, k_f=k_f, k_b=k_f / K)

SecondOrderReaction

Bases: MassActionReaction

Irreversible bimolecular reaction \(A + B \xrightarrow{k} C\).

\[ R_A = R_B = -k c_A c_B, \qquad R_C = +k c_A c_B \]

Parameters:

Name Type Description Default
reactant_1 str or Species

Reacting species \(A\) and \(B\) (must differ; use DimerizationReaction for \(2A \rightarrow P\)).

required
reactant_2 str or Species

Reacting species \(A\) and \(B\) (must differ; use DimerizationReaction for \(2A \rightarrow P\)).

required
product str or Species or None

Product \(C\); None if untracked.

required
k float

Second-order rate constant \(k \ge 0\) (concentration\ :sup:-1 s\ :sup:-1).

required

Examples:

>>> import numpy as np
>>> from softpotato.reactions import SecondOrderReaction
>>> rxn = SecondOrderReaction("A", "B", "C", k=2.0)
>>> c = {"A": np.array([1.0]), "B": np.array([3.0]), "C": np.array([0.0])}
>>> rxn.rates(c, None, 0.0)
{'A': array([-6.]), 'B': array([-6.]), 'C': array([6.])}
Source code in src/softpotato/reactions/homogeneous.py
class SecondOrderReaction(MassActionReaction):
    r"""Irreversible bimolecular reaction :math:`A + B \xrightarrow{k} C`.

    .. math::

        R_A = R_B = -k c_A c_B, \qquad R_C = +k c_A c_B

    Parameters
    ----------
    reactant_1, reactant_2 : str or Species
        Reacting species :math:`A` and :math:`B` (must differ; use
        :class:`DimerizationReaction` for :math:`2A \rightarrow P`).
    product : str or Species or None
        Product :math:`C`; ``None`` if untracked.
    k : float
        Second-order rate constant :math:`k \ge 0`
        (concentration\ :sup:`-1` s\ :sup:`-1`).

    Examples
    --------
    >>> import numpy as np
    >>> from softpotato.reactions import SecondOrderReaction
    >>> rxn = SecondOrderReaction("A", "B", "C", k=2.0)
    >>> c = {"A": np.array([1.0]), "B": np.array([3.0]), "C": np.array([0.0])}
    >>> rxn.rates(c, None, 0.0)
    {'A': array([-6.]), 'B': array([-6.]), 'C': array([6.])}
    """

    def __init__(
        self,
        reactant_1: SpeciesLike,
        reactant_2: SpeciesLike,
        product: SpeciesLike | None,
        k: float,
    ) -> None:
        if _species_name(reactant_1) == _species_name(reactant_2):
            raise ValueError(
                "SecondOrderReaction requires two distinct reactants; "
                "use DimerizationReaction for 2A -> P."
            )
        products = {} if product is None else {product: 1}
        super().__init__({reactant_1: 1, reactant_2: 1}, products, k_f=k)

    @property
    def k(self) -> float:
        """Second-order rate constant."""
        return self.k_f

k property

k: float

Second-order rate constant.

CustomMechanism

Bases: Mechanism

User-defined chemical or electrochemical reaction mechanism.

Extends Mechanism with optional functional hooks so users can define arbitrary mechanisms without subclassing:

  • reactions: built-in or CustomReaction objects (analytical Jacobian assembled automatically).
  • rates: arbitrary user callable rates(c, x, t) -> dict[str, ndarray] added on top of (or used instead of) reactions.
  • local_jacobian_func: optional analytical node-wise Jacobian jac(c, x, t, species) -> ndarray of shape (S, S, N) for rates. If omitted, vectorized central finite differences are computed automatically (only 2 * S evaluations of rates per step).
  • electrochemical_steps: list of ElectrochemicalStep objects.
  • boundary_conditions_func: optional custom callable returning the boundary condition dictionary for boundary_conditions.

Parameters:

Name Type Description Default
species SpeciesCollection or Iterable[Species]

Chemical species in the mechanism.

required
reactions ReactionNetwork, HomogeneousReaction, or Iterable[HomogeneousReaction]

Structured homogeneous reactions.

None
rates Callable[[ConcentrationDict, Any, float], dict[str, ndarray]]

Custom homogeneous rate law returning {species_name: rate_array}.

None
local_jacobian_func Callable[[ConcentrationDict, Any, float, Sequence[str]], ndarray]

Analytical node-wise Jacobian for rates of shape (S, S, *profile_shape).

None
electrochemical_steps Iterable[ElectrochemicalStep]

Heterogeneous electron-transfer steps at electrode boundaries.

()
boundary_conditions_func Callable

Custom boundary condition builder invoked by boundary_conditions.

None
name str

Human-readable label for this mechanism.

None

Examples:

Custom nonlinear mechanism with an arbitrary rate law and automatic local Jacobian:

>>> import numpy as np
>>> from softpotato.reactions import CustomMechanism, Species
>>> a = Species("A", diffusivity=1e-9, bulk_concentration=1.0)
>>> b = Species("B", diffusivity=1e-9, bulk_concentration=0.0)
>>> mech = CustomMechanism(
...     species=[a, b],
...     rates=lambda c, x, t: {
...         "A": -5.0 * c["A"] / (1.0 + c["A"]),
...         "B": +5.0 * c["A"] / (1.0 + c["A"]),
...     },
...     name="MichaelisMenten",
... )
>>> c = {"A": np.array([1.0, 1.0]), "B": np.array([0.0, 0.0])}
>>> mech(c, None, 0.0)["B"]
array([2.5, 2.5])
Source code in src/softpotato/reactions/mechanisms.py
class CustomMechanism(Mechanism):
    r"""User-defined chemical or electrochemical reaction mechanism.

    Extends :class:`Mechanism` with optional functional hooks so users can
    define arbitrary mechanisms without subclassing:

    - ``reactions``: built-in or :class:`~softpotato.reactions.CustomReaction`
      objects (analytical Jacobian assembled automatically).
    - ``rates``: arbitrary user callable ``rates(c, x, t) -> dict[str, ndarray]``
      added on top of (or used instead of) ``reactions``.
    - ``local_jacobian_func``: optional analytical node-wise Jacobian
      ``jac(c, x, t, species) -> ndarray`` of shape ``(S, S, N)`` for ``rates``.
      If omitted, vectorized central finite differences are computed
      automatically (only ``2 * S`` evaluations of ``rates`` per step).
    - ``electrochemical_steps``: list of :class:`ElectrochemicalStep` objects.
    - ``boundary_conditions_func``: optional custom callable returning the
      boundary condition dictionary for :meth:`boundary_conditions`.

    Parameters
    ----------
    species : SpeciesCollection or Iterable[Species]
        Chemical species in the mechanism.
    reactions : ReactionNetwork, HomogeneousReaction, or Iterable[HomogeneousReaction], optional
        Structured homogeneous reactions.
    rates : Callable[[ConcentrationDict, Any, float], dict[str, np.ndarray]], optional
        Custom homogeneous rate law returning ``{species_name: rate_array}``.
    local_jacobian_func : Callable[[ConcentrationDict, Any, float, Sequence[str]], np.ndarray], optional
        Analytical node-wise Jacobian for ``rates`` of shape ``(S, S, *profile_shape)``.
    electrochemical_steps : Iterable[ElectrochemicalStep], optional
        Heterogeneous electron-transfer steps at electrode boundaries.
    boundary_conditions_func : Callable, optional
        Custom boundary condition builder invoked by :meth:`boundary_conditions`.
    name : str, optional
        Human-readable label for this mechanism.

    Examples
    --------
    Custom nonlinear mechanism with an arbitrary rate law and automatic local
    Jacobian:

    >>> import numpy as np
    >>> from softpotato.reactions import CustomMechanism, Species
    >>> a = Species("A", diffusivity=1e-9, bulk_concentration=1.0)
    >>> b = Species("B", diffusivity=1e-9, bulk_concentration=0.0)
    >>> mech = CustomMechanism(
    ...     species=[a, b],
    ...     rates=lambda c, x, t: {
    ...         "A": -5.0 * c["A"] / (1.0 + c["A"]),
    ...         "B": +5.0 * c["A"] / (1.0 + c["A"]),
    ...     },
    ...     name="MichaelisMenten",
    ... )
    >>> c = {"A": np.array([1.0, 1.0]), "B": np.array([0.0, 0.0])}
    >>> mech(c, None, 0.0)["B"]
    array([2.5, 2.5])
    """

    def __init__(
        self,
        species: SpeciesCollection | Iterable[Species],
        reactions: ReactionNetwork
        | HomogeneousReaction
        | Iterable[HomogeneousReaction]
        | None = None,
        *,
        rates: MechanismRatesFunction | None = None,
        local_jacobian_func: MechanismJacobianFunction | None = None,
        electrochemical_steps: Iterable[ElectrochemicalStep] = (),
        boundary_conditions_func: Callable[
            ..., dict[str, tuple[BoundaryCondition, BoundaryCondition]]
        ]
        | None = None,
        name: str | None = None,
    ) -> None:
        if rates is not None and not callable(rates):
            raise TypeError("rates must be a callable rates(c, x, t).")
        if local_jacobian_func is not None and not callable(local_jacobian_func):
            raise TypeError(
                "local_jacobian_func must be a callable jac(c, x, t, species)."
            )
        if local_jacobian_func is not None and rates is None:
            raise ValueError("local_jacobian_func cannot be provided without rates.")
        if boundary_conditions_func is not None and not callable(
            boundary_conditions_func
        ):
            raise TypeError("boundary_conditions_func must be callable.")

        super().__init__(
            species=species,
            reactions=reactions,
            electrochemical_steps=electrochemical_steps,
            name=name or "CustomMechanism",
        )
        self._custom_rates = rates
        self._custom_local_jacobian = local_jacobian_func
        self._custom_bc_func = boundary_conditions_func

    def _eval_custom_rates(
        self, c: ConcentrationDict, x: Any, t: float
    ) -> dict[str, np.ndarray]:
        assert self._custom_rates is not None
        raw = self._custom_rates(c, x, t)
        if not isinstance(raw, Mapping):
            raise TypeError(
                f"Custom rates callable must return a mapping, got {type(raw).__name__}."
            )
        shape = self._profile_shape(c, self._species.names)
        result: dict[str, np.ndarray] = {}
        for name, val in raw.items():
            if name not in self._species:
                raise KeyError(
                    f"Custom rates returned unknown species '{name}'. "
                    f"Known species: {self._species.names}."
                )
            arr = np.asarray(val, dtype=float)
            bshape = np.broadcast_shapes(arr.shape, shape)
            result[name] = np.array(np.broadcast_to(arr, bshape), dtype=float)
        return result

    def evaluate(self, c: ConcentrationDict, x: Any, t: float) -> dict[str, np.ndarray]:
        """Evaluate combined rates from structured reactions and custom rate callable."""
        total = self._reactions.evaluate(c, x, t)
        if self._custom_rates is not None:
            custom = self._eval_custom_rates(c, x, t)
            for name, arr in custom.items():
                total[name] = total[name] + arr
        return total

    def local_jacobian(
        self,
        c: ConcentrationDict,
        x: Any,
        t: float,
        species: Sequence[str] | None = None,
    ) -> np.ndarray:
        """Compute node-wise kinetic Jacobian combining structured and custom terms."""
        names = list(species) if species is not None else self._species.names
        jac = self._reactions.local_jacobian(c, x, t, species=names)
        if self._custom_rates is None:
            return jac

        if self._custom_local_jacobian is not None:
            custom_jac = np.asarray(
                self._custom_local_jacobian(c, x, t, names), dtype=float
            )
            if custom_jac.shape != jac.shape:
                raise ValueError(
                    f"local_jacobian_func returned shape {custom_jac.shape}, "
                    f"expected {jac.shape}."
                )
            return jac + custom_jac

        # Vectorized central finite differences on the custom rate contribution only
        shape = self._profile_shape(c, names)
        custom_fd = np.zeros((len(names), len(names), *shape), dtype=float)
        for k, name_k in enumerate(names):
            if name_k not in c:
                continue
            ck = np.asarray(c[name_k], dtype=float)
            scale = np.maximum(np.abs(ck), np.max(np.abs(ck), initial=0.0))
            scale = np.where(scale > 0.0, scale, 1.0)
            h = self.fd_rel_step * scale

            c_plus = dict(c)
            c_minus = dict(c)
            c_plus[name_k] = ck + h
            c_minus[name_k] = ck - h

            r_plus = self._eval_custom_rates(c_plus, x, t)
            r_minus = self._eval_custom_rates(c_minus, x, t)

            for i, name_i in enumerate(names):
                if name_i in r_plus or name_i in r_minus:
                    rp = r_plus.get(name_i, 0.0)
                    rm = r_minus.get(name_i, 0.0)
                    custom_fd[i, k] = (rp - rm) / (2.0 * h)

        return jac + custom_fd

    def boundary_conditions(
        self,
        potential: float | Callable[[float], float] | None = None,
        *,
        electrode_side: Literal["left", "right"] | None = None,
        bulk_bc: Literal["dirichlet", "neumann"] = "dirichlet",
        overrides: Mapping[str, tuple[BoundaryCondition, BoundaryCondition]]
        | None = None,
        **bc_kwargs: Any,
    ) -> dict[str, tuple[BoundaryCondition, BoundaryCondition]]:
        """Build boundary conditions using ``boundary_conditions_func`` if provided."""
        if self._custom_bc_func is not None:
            bcs = dict(
                self._custom_bc_func(
                    potential,
                    electrode_side=electrode_side,
                    bulk_bc=bulk_bc,
                    **bc_kwargs,
                )
            )
            if overrides:
                bcs.update(overrides)
            return bcs
        return super().boundary_conditions(
            potential=potential,
            electrode_side=electrode_side,
            bulk_bc=bulk_bc,
            overrides=overrides,
            **bc_kwargs,
        )

evaluate

evaluate(c: ConcentrationDict, x: Any, t: float) -> dict[str, np.ndarray]

Evaluate combined rates from structured reactions and custom rate callable.

Source code in src/softpotato/reactions/mechanisms.py
def evaluate(self, c: ConcentrationDict, x: Any, t: float) -> dict[str, np.ndarray]:
    """Evaluate combined rates from structured reactions and custom rate callable."""
    total = self._reactions.evaluate(c, x, t)
    if self._custom_rates is not None:
        custom = self._eval_custom_rates(c, x, t)
        for name, arr in custom.items():
            total[name] = total[name] + arr
    return total

local_jacobian

local_jacobian(c: ConcentrationDict, x: Any, t: float, species: Sequence[str] | None = None) -> np.ndarray

Compute node-wise kinetic Jacobian combining structured and custom terms.

Source code in src/softpotato/reactions/mechanisms.py
def local_jacobian(
    self,
    c: ConcentrationDict,
    x: Any,
    t: float,
    species: Sequence[str] | None = None,
) -> np.ndarray:
    """Compute node-wise kinetic Jacobian combining structured and custom terms."""
    names = list(species) if species is not None else self._species.names
    jac = self._reactions.local_jacobian(c, x, t, species=names)
    if self._custom_rates is None:
        return jac

    if self._custom_local_jacobian is not None:
        custom_jac = np.asarray(
            self._custom_local_jacobian(c, x, t, names), dtype=float
        )
        if custom_jac.shape != jac.shape:
            raise ValueError(
                f"local_jacobian_func returned shape {custom_jac.shape}, "
                f"expected {jac.shape}."
            )
        return jac + custom_jac

    # Vectorized central finite differences on the custom rate contribution only
    shape = self._profile_shape(c, names)
    custom_fd = np.zeros((len(names), len(names), *shape), dtype=float)
    for k, name_k in enumerate(names):
        if name_k not in c:
            continue
        ck = np.asarray(c[name_k], dtype=float)
        scale = np.maximum(np.abs(ck), np.max(np.abs(ck), initial=0.0))
        scale = np.where(scale > 0.0, scale, 1.0)
        h = self.fd_rel_step * scale

        c_plus = dict(c)
        c_minus = dict(c)
        c_plus[name_k] = ck + h
        c_minus[name_k] = ck - h

        r_plus = self._eval_custom_rates(c_plus, x, t)
        r_minus = self._eval_custom_rates(c_minus, x, t)

        for i, name_i in enumerate(names):
            if name_i in r_plus or name_i in r_minus:
                rp = r_plus.get(name_i, 0.0)
                rm = r_minus.get(name_i, 0.0)
                custom_fd[i, k] = (rp - rm) / (2.0 * h)

    return jac + custom_fd

boundary_conditions

boundary_conditions(potential: float | Callable[[float], float] | None = None, *, electrode_side: Literal['left', 'right'] | None = None, bulk_bc: Literal['dirichlet', 'neumann'] = 'dirichlet', overrides: Mapping[str, tuple[BoundaryCondition, BoundaryCondition]] | None = None, **bc_kwargs: Any) -> dict[str, tuple[BoundaryCondition, BoundaryCondition]]

Build boundary conditions using boundary_conditions_func if provided.

Source code in src/softpotato/reactions/mechanisms.py
def boundary_conditions(
    self,
    potential: float | Callable[[float], float] | None = None,
    *,
    electrode_side: Literal["left", "right"] | None = None,
    bulk_bc: Literal["dirichlet", "neumann"] = "dirichlet",
    overrides: Mapping[str, tuple[BoundaryCondition, BoundaryCondition]]
    | None = None,
    **bc_kwargs: Any,
) -> dict[str, tuple[BoundaryCondition, BoundaryCondition]]:
    """Build boundary conditions using ``boundary_conditions_func`` if provided."""
    if self._custom_bc_func is not None:
        bcs = dict(
            self._custom_bc_func(
                potential,
                electrode_side=electrode_side,
                bulk_bc=bulk_bc,
                **bc_kwargs,
            )
        )
        if overrides:
            bcs.update(overrides)
        return bcs
    return super().boundary_conditions(
        potential=potential,
        electrode_side=electrode_side,
        bulk_bc=bulk_bc,
        overrides=overrides,
        **bc_kwargs,
    )

ElectrochemicalStep dataclass

Specification of a single interfacial electron-transfer step.

Represents the heterogeneous redox reaction at an electrode boundary:

\[ \text{Ox} + n e^- \rightleftharpoons \text{Red} \]

Parameters:

Name Type Description Default
ox Species or str

Oxidized species involved in the charge-transfer step.

required
red Species or str

Reduced species involved in the charge-transfer step.

required
kinetics HeterogeneousKinetics or NernstianEquilibrium

Interfacial charge-transfer model (ButlerVolmer, TafelKinetics, NernstianEquilibrium, or a custom HeterogeneousKinetics subclass).

required
electrode_side ('left', 'right')

Domain boundary where this electrochemical step takes place.

'left'
bulk_bc ('dirichlet', 'neumann')

Default boundary condition type applied at the opposite (bulk) boundary.

'dirichlet'
Source code in src/softpotato/reactions/mechanisms.py
@dataclass(frozen=True)
class ElectrochemicalStep:
    r"""Specification of a single interfacial electron-transfer step.

    Represents the heterogeneous redox reaction at an electrode boundary:

    .. math::

        \text{Ox} + n e^- \rightleftharpoons \text{Red}

    Parameters
    ----------
    ox : Species or str
        Oxidized species involved in the charge-transfer step.
    red : Species or str
        Reduced species involved in the charge-transfer step.
    kinetics : HeterogeneousKinetics or NernstianEquilibrium
        Interfacial charge-transfer model (:class:`ButlerVolmer`,
        :class:`TafelKinetics`, :class:`NernstianEquilibrium`, or a custom
        :class:`HeterogeneousKinetics` subclass).
    electrode_side : {'left', 'right'}, default 'left'
        Domain boundary where this electrochemical step takes place.
    bulk_bc : {'dirichlet', 'neumann'}, default 'dirichlet'
        Default boundary condition type applied at the opposite (bulk) boundary.
    """

    ox: SpeciesLike
    red: SpeciesLike
    kinetics: HeterogeneousKinetics | NernstianEquilibrium
    electrode_side: Literal["left", "right"] = "left"
    bulk_bc: Literal["dirichlet", "neumann"] = "dirichlet"

    def __post_init__(self) -> None:
        ox_name = _species_name(self.ox, "ox")
        red_name = _species_name(self.red, "red")
        if ox_name == red_name:
            raise ValueError(
                f"Oxidized and reduced species must differ, both got '{ox_name}'."
            )
        if not isinstance(self.kinetics, (HeterogeneousKinetics, NernstianEquilibrium)):
            raise TypeError(
                "kinetics must be an instance of HeterogeneousKinetics or "
                f"NernstianEquilibrium, got {type(self.kinetics).__name__}."
            )
        if self.electrode_side not in ("left", "right"):
            raise ValueError(
                f"electrode_side must be 'left' or 'right', got {self.electrode_side!r}."
            )
        if self.bulk_bc not in ("dirichlet", "neumann"):
            raise ValueError(
                f"bulk_bc must be 'dirichlet' or 'neumann', got {self.bulk_bc!r}."
            )

    @property
    def ox_name(self) -> str:
        """Canonical name of the oxidized species."""
        return _species_name(self.ox, "ox")

    @property
    def red_name(self) -> str:
        """Canonical name of the reduced species."""
        return _species_name(self.red, "red")

ox_name property

ox_name: str

Canonical name of the oxidized species.

red_name property

red_name: str

Canonical name of the reduced species.

Mechanism

Modular chemical and electrochemical reaction mechanism.

Encapsulates species metadata, homogeneous solution-phase reactions, and optional heterogeneous electrode charge-transfer steps into a single reusable object that integrates directly with DiffusionProblem and ScipyIVPSolver.

Subclasses can override evaluate (and optionally local_jacobian and boundary_conditions) to implement custom mechanisms. When a subclass overrides evaluate without overriding local_jacobian, the node-wise local Jacobian is computed automatically via vectorized central finite differences, preserving the block-diagonal sparsity structure required by stiff solvers.

Parameters:

Name Type Description Default
species SpeciesCollection or Iterable[Species]

Chemical species participating in the mechanism.

required
reactions ReactionNetwork, HomogeneousReaction, or Iterable[HomogeneousReaction]

Homogeneous solution-phase reaction(s).

None
electrochemical_steps Iterable[ElectrochemicalStep]

Heterogeneous electron-transfer steps occurring at electrode boundaries.

()
name str

Human-readable label for the mechanism.

None

Examples:

EC mechanism with Nernstian electron transfer and first-order decay:

>>> import numpy as np
>>> from softpotato.reactions import (
...     ElectrochemicalStep,
...     FirstOrderReaction,
...     Mechanism,
...     NernstianEquilibrium,
...     Species,
... )
>>> ox = Species("Ox", diffusivity=1e-9, bulk_concentration=1.0, n_electrons=1)
>>> red = Species("Red", diffusivity=1e-9, bulk_concentration=0.0, n_electrons=-1)
>>> prod = Species("P", diffusivity=1e-9, bulk_concentration=0.0, n_electrons=0)
>>> ec = Mechanism(
...     species=[ox, red, prod],
...     reactions=[FirstOrderReaction(red, prod, k=10.0)],
...     electrochemical_steps=[
...         ElectrochemicalStep(ox, red, NernstianEquilibrium(E0=0.0, n=1))
...     ],
...     name="EC",
... )
>>> problem = ec.create_problem(np.linspace(0.0, 1e-3, 31), potential=-0.2)
>>> problem.species
['Ox', 'Red', 'P']
Source code in src/softpotato/reactions/mechanisms.py
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
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
class Mechanism:
    r"""Modular chemical and electrochemical reaction mechanism.

    Encapsulates species metadata, homogeneous solution-phase reactions, and
    optional heterogeneous electrode charge-transfer steps into a single
    reusable object that integrates directly with
    :class:`~softpotato.solver.DiffusionProblem` and
    :class:`~softpotato.solver.ScipyIVPSolver`.

    Subclasses can override :meth:`evaluate` (and optionally
    :meth:`local_jacobian` and :meth:`boundary_conditions`) to implement custom
    mechanisms. When a subclass overrides :meth:`evaluate` without overriding
    :meth:`local_jacobian`, the node-wise local Jacobian is computed
    automatically via vectorized central finite differences, preserving the
    block-diagonal sparsity structure required by stiff solvers.

    Parameters
    ----------
    species : SpeciesCollection or Iterable[Species]
        Chemical species participating in the mechanism.
    reactions : ReactionNetwork, HomogeneousReaction, or Iterable[HomogeneousReaction], optional
        Homogeneous solution-phase reaction(s).
    electrochemical_steps : Iterable[ElectrochemicalStep], optional
        Heterogeneous electron-transfer steps occurring at electrode boundaries.
    name : str, optional
        Human-readable label for the mechanism.

    Examples
    --------
    EC mechanism with Nernstian electron transfer and first-order decay:

    >>> import numpy as np
    >>> from softpotato.reactions import (
    ...     ElectrochemicalStep,
    ...     FirstOrderReaction,
    ...     Mechanism,
    ...     NernstianEquilibrium,
    ...     Species,
    ... )
    >>> ox = Species("Ox", diffusivity=1e-9, bulk_concentration=1.0, n_electrons=1)
    >>> red = Species("Red", diffusivity=1e-9, bulk_concentration=0.0, n_electrons=-1)
    >>> prod = Species("P", diffusivity=1e-9, bulk_concentration=0.0, n_electrons=0)
    >>> ec = Mechanism(
    ...     species=[ox, red, prod],
    ...     reactions=[FirstOrderReaction(red, prod, k=10.0)],
    ...     electrochemical_steps=[
    ...         ElectrochemicalStep(ox, red, NernstianEquilibrium(E0=0.0, n=1))
    ...     ],
    ...     name="EC",
    ... )
    >>> problem = ec.create_problem(np.linspace(0.0, 1e-3, 31), potential=-0.2)
    >>> problem.species
    ['Ox', 'Red', 'P']
    """

    #: Relative step used for central finite-difference local Jacobians.
    fd_rel_step: float = float(np.finfo(float).eps ** (1.0 / 3.0))

    def __init__(
        self,
        species: SpeciesCollection | Iterable[Species],
        reactions: ReactionNetwork
        | HomogeneousReaction
        | Iterable[HomogeneousReaction]
        | None = None,
        electrochemical_steps: Iterable[ElectrochemicalStep] = (),
        *,
        name: str | None = None,
    ) -> None:
        self._species = _normalize_species_collection(species)
        self._reactions = _normalize_reaction_network(reactions, self._species.names)
        self._electrochemical_steps: list[ElectrochemicalStep] = []
        for step in electrochemical_steps:
            self.add_electrochemical_step(step)
        self.name = name or type(self).__name__

    # -- properties & builders ----------------------------------------------
    @property
    def species(self) -> SpeciesCollection:
        """Ordered :class:`SpeciesCollection` of species in the mechanism."""
        return self._species

    @property
    def species_names(self) -> list[str]:
        """Ordered list of species names."""
        return self._species.names

    @property
    def reactions(self) -> ReactionNetwork:
        """Homogeneous :class:`ReactionNetwork` of the mechanism."""
        return self._reactions

    @property
    def electrochemical_steps(self) -> tuple[ElectrochemicalStep, ...]:
        """Tuple of registered :class:`ElectrochemicalStep` objects."""
        return tuple(self._electrochemical_steps)

    def add_reaction(self, reaction: HomogeneousReaction) -> Mechanism:
        """Add a homogeneous reaction to the mechanism (returns ``self``)."""
        self._reactions.add(reaction)
        return self

    def add_electrochemical_step(self, step: ElectrochemicalStep) -> Mechanism:
        """Register an interfacial :class:`ElectrochemicalStep` (returns ``self``)."""
        if not isinstance(step, ElectrochemicalStep):
            raise TypeError(
                f"Expected an ElectrochemicalStep instance, got {type(step).__name__}."
            )
        for sp_name in (step.ox_name, step.red_name):
            if sp_name not in self._species:
                raise ValueError(
                    f"ElectrochemicalStep references species '{sp_name}' not present "
                    f"in mechanism species {self._species.names}."
                )
        self._electrochemical_steps.append(step)
        return self

    # -- homogeneous kinetics & Jacobian interface --------------------------
    def _profile_shape(
        self, c: ConcentrationDict, names: Sequence[str]
    ) -> tuple[int, ...]:
        shapes = [np.shape(c[name]) for name in names if name in c]
        return np.broadcast_shapes(*shapes) if shapes else ()

    def evaluate(self, c: ConcentrationDict, x: Any, t: float) -> dict[str, np.ndarray]:
        """Evaluate combined homogeneous species source terms :math:`R_i(c, x, t)`."""
        return self._reactions.evaluate(c, x, t)

    def __call__(self, c: ConcentrationDict, x: Any, t: float) -> dict[str, np.ndarray]:
        """Alias for :meth:`evaluate` (``DiffusionProblem.reactions`` signature)."""
        return self.evaluate(c, x, t)

    def _finite_difference_local_jacobian(
        self,
        c: ConcentrationDict,
        x: Any,
        t: float,
        names: Sequence[str],
    ) -> np.ndarray:
        """Compute node-wise local Jacobian via vectorized central finite differences."""
        shape = self._profile_shape(c, names)
        n_sp = len(names)
        jac = np.zeros((n_sp, n_sp, *shape), dtype=float)

        for k, name_k in enumerate(names):
            if name_k not in c:
                continue
            ck = np.asarray(c[name_k], dtype=float)
            scale = np.maximum(np.abs(ck), np.max(np.abs(ck), initial=0.0))
            scale = np.where(scale > 0.0, scale, 1.0)
            h = self.fd_rel_step * scale

            c_plus = dict(c)
            c_minus = dict(c)
            c_plus[name_k] = ck + h
            c_minus[name_k] = ck - h

            r_plus = self.evaluate(c_plus, x, t)
            r_minus = self.evaluate(c_minus, x, t)

            for i, name_i in enumerate(names):
                if name_i in r_plus or name_i in r_minus:
                    rp = np.asarray(r_plus.get(name_i, 0.0), dtype=float)
                    rm = np.asarray(r_minus.get(name_i, 0.0), dtype=float)
                    jac[i, k] = (rp - rm) / (2.0 * h)

        return jac

    def local_jacobian(
        self,
        c: ConcentrationDict,
        x: Any,
        t: float,
        species: Sequence[str] | None = None,
    ) -> np.ndarray:
        r"""Node-wise kinetic Jacobian :math:`J_{ik}(x) = \partial R_i / \partial c_k`.

        Returns an array of shape ``(n_species, n_species, *profile_shape)``.
        """
        names = list(species) if species is not None else self._species.names
        if type(self).evaluate is Mechanism.evaluate:
            return self._reactions.local_jacobian(c, x, t, species=names)
        return self._finite_difference_local_jacobian(c, x, t, names)

    def jacobian(
        self,
        c: ConcentrationDict,
        x: Any,
        t: float,
        species: Sequence[str] | None = None,
        sparse: bool = True,
    ) -> Any:
        """Full ``(S*N, S*N)`` sparse or dense kinetic Jacobian in species-major order."""
        local = self.local_jacobian(c, x, t, species=species)
        n_species = local.shape[0]
        if local.ndim == 2:
            local = local[:, :, np.newaxis]
        elif local.ndim != 3:
            raise ValueError(
                "jacobian() requires 1D concentration profiles; "
                f"got profile shape {local.shape[2:]}."
            )
        n_points = local.shape[2]
        size = n_species * n_points
        nodes = np.arange(n_points)

        rows: list[np.ndarray] = []
        cols: list[np.ndarray] = []
        data: list[np.ndarray] = []
        for i in range(n_species):
            for k in range(n_species):
                block = local[i, k]
                if np.any(block != 0.0):
                    rows.append(i * n_points + nodes)
                    cols.append(k * n_points + nodes)
                    data.append(block)
        if data:
            coo = _sparse.coo_matrix(
                (np.concatenate(data), (np.concatenate(rows), np.concatenate(cols))),
                shape=(size, size),
            )
        else:
            coo = _sparse.coo_matrix((size, size), dtype=float)
        mat = coo.tocsr()
        return mat if sparse else mat.toarray()

    # -- boundary conditions & problem construction -------------------------
    def boundary_conditions(
        self,
        potential: float | Callable[[float], float] | None = None,
        *,
        electrode_side: Literal["left", "right"] | None = None,
        bulk_bc: Literal["dirichlet", "neumann"] = "dirichlet",
        overrides: Mapping[str, tuple[BoundaryCondition, BoundaryCondition]]
        | None = None,
        **bc_kwargs: Any,
    ) -> dict[str, tuple[BoundaryCondition, BoundaryCondition]]:
        """Build boundary conditions for all species in the mechanism.

        Electroactive species from :attr:`electrochemical_steps` receive
        matched interfacial boundary conditions via
        :func:`~softpotato.reactions.create_electrochemical_bcs`. Non-electroactive
        species receive zero-flux (:func:`~softpotato.solver.NeumannBC`) at the
        electrode boundary and bulk concentration (or zero-flux) at the bulk
        boundary.
        """
        from softpotato.solver.base import DirichletBC, NeumannBC

        if bulk_bc not in ("dirichlet", "neumann"):
            raise ValueError(
                f"bulk_bc must be 'dirichlet' or 'neumann', got {bulk_bc!r}."
            )
        if electrode_side is not None and electrode_side not in ("left", "right"):
            raise ValueError(
                f"electrode_side must be 'left' or 'right', got {electrode_side!r}."
            )

        bcs: dict[str, tuple[BoundaryCondition, BoundaryCondition]] = {}

        if self._electrochemical_steps:
            if potential is None:
                raise ValueError(
                    "potential must be provided to generate boundary conditions "
                    "for a mechanism with electrochemical steps."
                )
            for step in self._electrochemical_steps:
                side = (
                    electrode_side
                    if electrode_side is not None
                    else step.electrode_side
                )
                step_bcs = create_electrochemical_bcs(
                    step.kinetics,
                    potential=potential,
                    ox=self._species[step.ox_name],
                    red=self._species[step.red_name],
                    electrode_side=side,
                    bulk_bc=bulk_bc,
                    **bc_kwargs,
                )
                bcs.update(step_bcs)

        default_side: Literal["left", "right"] = (
            electrode_side
            if electrode_side is not None
            else (
                self._electrochemical_steps[0].electrode_side
                if self._electrochemical_steps
                else "left"
            )
        )

        for sp_name, sp_obj in self._species.items():
            if sp_name in bcs:
                continue
            elec_bc = NeumannBC(0.0)
            far_bc = (
                DirichletBC(sp_obj.bulk_concentration)
                if bulk_bc == "dirichlet"
                else NeumannBC(0.0)
            )
            bcs[sp_name] = (
                (elec_bc, far_bc) if default_side == "left" else (far_bc, elec_bc)
            )

        if overrides:
            bcs.update(overrides)

        return bcs

    def create_problem(
        self,
        grid: np.ndarray | Mesh1D,
        *,
        potential: float | Callable[[float], float] | None = None,
        boundary_conditions: Mapping[str, tuple[BoundaryCondition, BoundaryCondition]]
        | None = None,
        geometry: Geometry | str = "planar",
        diffusivity: Mapping[str, float] | None = None,
        initial_conditions: Mapping[
            str, float | np.ndarray | Callable[[np.ndarray], np.ndarray]
        ]
        | None = None,
        n_electrons: int | dict[str, int] | None = None,
        electrodes: Literal["left", "right", "both"] = "left",
        electrode_side: Literal["left", "right", "both"] | None = None,
        bulk_bc: Literal["dirichlet", "neumann"] = "dirichlet",
        bc_overrides: Mapping[str, tuple[BoundaryCondition, BoundaryCondition]]
        | None = None,
        **bc_kwargs: Any,
    ) -> DiffusionProblem:
        """Create a :class:`~softpotato.solver.DiffusionProblem` from this mechanism.

        Parameters
        ----------
        grid : np.ndarray or Mesh1D
            1D spatial grid or mesh.
        potential : float or Callable[[float], float], optional
            Electrode potential :math:`E` or waveform :math:`E(t)` used to build
            boundary conditions when ``boundary_conditions`` is not explicitly given.
        boundary_conditions : Mapping[str, tuple[BoundaryCondition, BoundaryCondition]], optional
            Explicit boundary conditions per species (overrides automatic generation).
        geometry : Geometry or str, default 'planar'
            Coordinate geometry passed to :class:`~softpotato.solver.DiffusionProblem`.
        diffusivity : Mapping[str, float], optional
            Optional diffusivity overrides.
        initial_conditions : Mapping, optional
            Optional initial condition overrides.
        n_electrons : int or dict[str, int], optional
            Optional electron transfer count overrides.
        electrodes : {'left', 'right', 'both'}, default 'left'
            Active electrode boundary for current evaluation.
        electrode_side : {'left', 'right', 'both'}, optional
            Alias for ``electrodes``.
        bulk_bc : {'dirichlet', 'neumann'}, default 'dirichlet'
            Bulk boundary condition type when auto-generating BCs.
        bc_overrides : Mapping, optional
            Per-species boundary condition overrides applied on top of generated BCs.
        **bc_kwargs : Any
            Additional keyword arguments forwarded to :meth:`boundary_conditions`.

        Returns
        -------
        DiffusionProblem
            Configured reaction-diffusion problem ready for solving.
        """
        from softpotato.solver.base import DiffusionProblem, NeumannBC

        if boundary_conditions is not None:
            resolved_bcs = dict(boundary_conditions)
            if bc_overrides:
                resolved_bcs.update(bc_overrides)
            reactions_obj: Any = self
        else:
            bc_side: Literal["left", "right"] | None = None
            target_side = electrode_side if electrode_side is not None else electrodes
            if target_side in ("left", "right"):
                bc_side = target_side
            resolved_bcs = self.boundary_conditions(
                potential=potential,
                electrode_side=bc_side,
                bulk_bc=bulk_bc,
                overrides=bc_overrides,
                **bc_kwargs,
            )
            reactions_obj = self

            override_names = set(bc_overrides) if bc_overrides else set()
            het_steps = [
                step
                for step in self._electrochemical_steps
                if isinstance(step.kinetics, HeterogeneousKinetics)
                and step.ox_name not in override_names
                and step.red_name not in override_names
            ]
            if het_steps and potential is not None:
                x_nodes = np.asarray(
                    grid.nodes if hasattr(grid, "nodes") else grid, dtype=float
                )
                if x_nodes.ndim != 1 or x_nodes.size < 2:
                    raise ValueError(
                        "grid must be 1D with at least 2 points for heterogeneous kinetics."
                    )
                if callable(potential):
                    eval_potential: Callable[[float], float] = potential
                else:
                    const_e = float(potential)

                    def eval_potential(_t: float) -> float:
                        return const_e

                step_specs: list[
                    tuple[str, str, HeterogeneousKinetics, int, float]
                ] = []
                for step in het_steps:
                    side = bc_side if bc_side is not None else step.electrode_side
                    if side == "left":
                        node_idx = 0
                        inv_half_cell = 2.0 / float(x_nodes[1] - x_nodes[0])
                        resolved_bcs[step.ox_name] = (
                            NeumannBC(0.0),
                            resolved_bcs[step.ox_name][1],
                        )
                        resolved_bcs[step.red_name] = (
                            NeumannBC(0.0),
                            resolved_bcs[step.red_name][1],
                        )
                    else:
                        node_idx = -1
                        inv_half_cell = 2.0 / float(x_nodes[-1] - x_nodes[-2])
                        resolved_bcs[step.ox_name] = (
                            resolved_bcs[step.ox_name][0],
                            NeumannBC(0.0),
                        )
                        resolved_bcs[step.red_name] = (
                            resolved_bcs[step.red_name][0],
                            NeumannBC(0.0),
                        )
                    kinetics = step.kinetics
                    assert isinstance(kinetics, HeterogeneousKinetics)
                    step_specs.append(
                        (step.ox_name, step.red_name, kinetics, node_idx, inv_half_cell)
                    )

                reactions_obj = _MechanismWithInterfacialKinetics(
                    self, eval_potential, step_specs
                )

        return DiffusionProblem(
            grid=grid,
            diffusivity=dict(diffusivity) if diffusivity is not None else {},
            boundary_conditions=resolved_bcs,
            initial_conditions=(
                dict(initial_conditions) if initial_conditions is not None else {}
            ),
            reactions=reactions_obj,
            species=self._species,
            geometry=geometry,
            n_electrons=n_electrons,
            electrodes=electrodes,
            electrode_side=electrode_side,
            mechanism=self,
        )

    def __repr__(self) -> str:
        return (
            f"{type(self).__name__}(name={self.name!r}, "
            f"species={self._species.names!r}, "
            f"n_reactions={len(self._reactions)}, "
            f"n_electrochemical_steps={len(self._electrochemical_steps)})"
        )

species property

species: SpeciesCollection

Ordered SpeciesCollection of species in the mechanism.

species_names property

species_names: list[str]

Ordered list of species names.

reactions property

reactions: ReactionNetwork

Homogeneous ReactionNetwork of the mechanism.

electrochemical_steps property

electrochemical_steps: tuple[ElectrochemicalStep, ...]

Tuple of registered ElectrochemicalStep objects.

add_reaction

add_reaction(reaction: HomogeneousReaction) -> Mechanism

Add a homogeneous reaction to the mechanism (returns self).

Source code in src/softpotato/reactions/mechanisms.py
def add_reaction(self, reaction: HomogeneousReaction) -> Mechanism:
    """Add a homogeneous reaction to the mechanism (returns ``self``)."""
    self._reactions.add(reaction)
    return self

add_electrochemical_step

add_electrochemical_step(step: ElectrochemicalStep) -> Mechanism

Register an interfacial ElectrochemicalStep (returns self).

Source code in src/softpotato/reactions/mechanisms.py
def add_electrochemical_step(self, step: ElectrochemicalStep) -> Mechanism:
    """Register an interfacial :class:`ElectrochemicalStep` (returns ``self``)."""
    if not isinstance(step, ElectrochemicalStep):
        raise TypeError(
            f"Expected an ElectrochemicalStep instance, got {type(step).__name__}."
        )
    for sp_name in (step.ox_name, step.red_name):
        if sp_name not in self._species:
            raise ValueError(
                f"ElectrochemicalStep references species '{sp_name}' not present "
                f"in mechanism species {self._species.names}."
            )
    self._electrochemical_steps.append(step)
    return self

evaluate

evaluate(c: ConcentrationDict, x: Any, t: float) -> dict[str, np.ndarray]

Evaluate combined homogeneous species source terms \(R_i(c, x, t)\).

Source code in src/softpotato/reactions/mechanisms.py
def evaluate(self, c: ConcentrationDict, x: Any, t: float) -> dict[str, np.ndarray]:
    """Evaluate combined homogeneous species source terms :math:`R_i(c, x, t)`."""
    return self._reactions.evaluate(c, x, t)

__call__

__call__(c: ConcentrationDict, x: Any, t: float) -> dict[str, np.ndarray]

Alias for evaluate (DiffusionProblem.reactions signature).

Source code in src/softpotato/reactions/mechanisms.py
def __call__(self, c: ConcentrationDict, x: Any, t: float) -> dict[str, np.ndarray]:
    """Alias for :meth:`evaluate` (``DiffusionProblem.reactions`` signature)."""
    return self.evaluate(c, x, t)

local_jacobian

local_jacobian(c: ConcentrationDict, x: Any, t: float, species: Sequence[str] | None = None) -> np.ndarray

Node-wise kinetic Jacobian \(J_{ik}(x) = \partial R_i / \partial c_k\).

Returns an array of shape (n_species, n_species, *profile_shape).

Source code in src/softpotato/reactions/mechanisms.py
def local_jacobian(
    self,
    c: ConcentrationDict,
    x: Any,
    t: float,
    species: Sequence[str] | None = None,
) -> np.ndarray:
    r"""Node-wise kinetic Jacobian :math:`J_{ik}(x) = \partial R_i / \partial c_k`.

    Returns an array of shape ``(n_species, n_species, *profile_shape)``.
    """
    names = list(species) if species is not None else self._species.names
    if type(self).evaluate is Mechanism.evaluate:
        return self._reactions.local_jacobian(c, x, t, species=names)
    return self._finite_difference_local_jacobian(c, x, t, names)

jacobian

jacobian(c: ConcentrationDict, x: Any, t: float, species: Sequence[str] | None = None, sparse: bool = True) -> Any

Full (S*N, S*N) sparse or dense kinetic Jacobian in species-major order.

Source code in src/softpotato/reactions/mechanisms.py
def jacobian(
    self,
    c: ConcentrationDict,
    x: Any,
    t: float,
    species: Sequence[str] | None = None,
    sparse: bool = True,
) -> Any:
    """Full ``(S*N, S*N)`` sparse or dense kinetic Jacobian in species-major order."""
    local = self.local_jacobian(c, x, t, species=species)
    n_species = local.shape[0]
    if local.ndim == 2:
        local = local[:, :, np.newaxis]
    elif local.ndim != 3:
        raise ValueError(
            "jacobian() requires 1D concentration profiles; "
            f"got profile shape {local.shape[2:]}."
        )
    n_points = local.shape[2]
    size = n_species * n_points
    nodes = np.arange(n_points)

    rows: list[np.ndarray] = []
    cols: list[np.ndarray] = []
    data: list[np.ndarray] = []
    for i in range(n_species):
        for k in range(n_species):
            block = local[i, k]
            if np.any(block != 0.0):
                rows.append(i * n_points + nodes)
                cols.append(k * n_points + nodes)
                data.append(block)
    if data:
        coo = _sparse.coo_matrix(
            (np.concatenate(data), (np.concatenate(rows), np.concatenate(cols))),
            shape=(size, size),
        )
    else:
        coo = _sparse.coo_matrix((size, size), dtype=float)
    mat = coo.tocsr()
    return mat if sparse else mat.toarray()

boundary_conditions

boundary_conditions(potential: float | Callable[[float], float] | None = None, *, electrode_side: Literal['left', 'right'] | None = None, bulk_bc: Literal['dirichlet', 'neumann'] = 'dirichlet', overrides: Mapping[str, tuple[BoundaryCondition, BoundaryCondition]] | None = None, **bc_kwargs: Any) -> dict[str, tuple[BoundaryCondition, BoundaryCondition]]

Build boundary conditions for all species in the mechanism.

Electroactive species from electrochemical_steps receive matched interfacial boundary conditions via create_electrochemical_bcs. Non-electroactive species receive zero-flux (NeumannBC) at the electrode boundary and bulk concentration (or zero-flux) at the bulk boundary.

Source code in src/softpotato/reactions/mechanisms.py
def boundary_conditions(
    self,
    potential: float | Callable[[float], float] | None = None,
    *,
    electrode_side: Literal["left", "right"] | None = None,
    bulk_bc: Literal["dirichlet", "neumann"] = "dirichlet",
    overrides: Mapping[str, tuple[BoundaryCondition, BoundaryCondition]]
    | None = None,
    **bc_kwargs: Any,
) -> dict[str, tuple[BoundaryCondition, BoundaryCondition]]:
    """Build boundary conditions for all species in the mechanism.

    Electroactive species from :attr:`electrochemical_steps` receive
    matched interfacial boundary conditions via
    :func:`~softpotato.reactions.create_electrochemical_bcs`. Non-electroactive
    species receive zero-flux (:func:`~softpotato.solver.NeumannBC`) at the
    electrode boundary and bulk concentration (or zero-flux) at the bulk
    boundary.
    """
    from softpotato.solver.base import DirichletBC, NeumannBC

    if bulk_bc not in ("dirichlet", "neumann"):
        raise ValueError(
            f"bulk_bc must be 'dirichlet' or 'neumann', got {bulk_bc!r}."
        )
    if electrode_side is not None and electrode_side not in ("left", "right"):
        raise ValueError(
            f"electrode_side must be 'left' or 'right', got {electrode_side!r}."
        )

    bcs: dict[str, tuple[BoundaryCondition, BoundaryCondition]] = {}

    if self._electrochemical_steps:
        if potential is None:
            raise ValueError(
                "potential must be provided to generate boundary conditions "
                "for a mechanism with electrochemical steps."
            )
        for step in self._electrochemical_steps:
            side = (
                electrode_side
                if electrode_side is not None
                else step.electrode_side
            )
            step_bcs = create_electrochemical_bcs(
                step.kinetics,
                potential=potential,
                ox=self._species[step.ox_name],
                red=self._species[step.red_name],
                electrode_side=side,
                bulk_bc=bulk_bc,
                **bc_kwargs,
            )
            bcs.update(step_bcs)

    default_side: Literal["left", "right"] = (
        electrode_side
        if electrode_side is not None
        else (
            self._electrochemical_steps[0].electrode_side
            if self._electrochemical_steps
            else "left"
        )
    )

    for sp_name, sp_obj in self._species.items():
        if sp_name in bcs:
            continue
        elec_bc = NeumannBC(0.0)
        far_bc = (
            DirichletBC(sp_obj.bulk_concentration)
            if bulk_bc == "dirichlet"
            else NeumannBC(0.0)
        )
        bcs[sp_name] = (
            (elec_bc, far_bc) if default_side == "left" else (far_bc, elec_bc)
        )

    if overrides:
        bcs.update(overrides)

    return bcs

create_problem

create_problem(grid: ndarray | Mesh1D, *, potential: float | Callable[[float], float] | None = None, boundary_conditions: Mapping[str, tuple[BoundaryCondition, BoundaryCondition]] | None = None, geometry: Geometry | str = 'planar', diffusivity: Mapping[str, float] | None = None, initial_conditions: Mapping[str, float | ndarray | Callable[[ndarray], ndarray]] | None = None, n_electrons: int | dict[str, int] | None = None, electrodes: Literal['left', 'right', 'both'] = 'left', electrode_side: Literal['left', 'right', 'both'] | None = None, bulk_bc: Literal['dirichlet', 'neumann'] = 'dirichlet', bc_overrides: Mapping[str, tuple[BoundaryCondition, BoundaryCondition]] | None = None, **bc_kwargs: Any) -> DiffusionProblem

Create a DiffusionProblem from this mechanism.

Parameters:

Name Type Description Default
grid ndarray or Mesh1D

1D spatial grid or mesh.

required
potential float or Callable[[float], float]

Electrode potential \(E\) or waveform \(E(t)\) used to build boundary conditions when boundary_conditions is not explicitly given.

None
boundary_conditions Mapping[str, tuple[BoundaryCondition, BoundaryCondition]]

Explicit boundary conditions per species (overrides automatic generation).

None
geometry Geometry or str

Coordinate geometry passed to DiffusionProblem.

'planar'
diffusivity Mapping[str, float]

Optional diffusivity overrides.

None
initial_conditions Mapping

Optional initial condition overrides.

None
n_electrons int or dict[str, int]

Optional electron transfer count overrides.

None
electrodes ('left', 'right', 'both')

Active electrode boundary for current evaluation.

'left'
electrode_side ('left', 'right', 'both')

Alias for electrodes.

'left'
bulk_bc ('dirichlet', 'neumann')

Bulk boundary condition type when auto-generating BCs.

'dirichlet'
bc_overrides Mapping

Per-species boundary condition overrides applied on top of generated BCs.

None
**bc_kwargs Any

Additional keyword arguments forwarded to boundary_conditions.

{}

Returns:

Type Description
DiffusionProblem

Configured reaction-diffusion problem ready for solving.

Source code in src/softpotato/reactions/mechanisms.py
def create_problem(
    self,
    grid: np.ndarray | Mesh1D,
    *,
    potential: float | Callable[[float], float] | None = None,
    boundary_conditions: Mapping[str, tuple[BoundaryCondition, BoundaryCondition]]
    | None = None,
    geometry: Geometry | str = "planar",
    diffusivity: Mapping[str, float] | None = None,
    initial_conditions: Mapping[
        str, float | np.ndarray | Callable[[np.ndarray], np.ndarray]
    ]
    | None = None,
    n_electrons: int | dict[str, int] | None = None,
    electrodes: Literal["left", "right", "both"] = "left",
    electrode_side: Literal["left", "right", "both"] | None = None,
    bulk_bc: Literal["dirichlet", "neumann"] = "dirichlet",
    bc_overrides: Mapping[str, tuple[BoundaryCondition, BoundaryCondition]]
    | None = None,
    **bc_kwargs: Any,
) -> DiffusionProblem:
    """Create a :class:`~softpotato.solver.DiffusionProblem` from this mechanism.

    Parameters
    ----------
    grid : np.ndarray or Mesh1D
        1D spatial grid or mesh.
    potential : float or Callable[[float], float], optional
        Electrode potential :math:`E` or waveform :math:`E(t)` used to build
        boundary conditions when ``boundary_conditions`` is not explicitly given.
    boundary_conditions : Mapping[str, tuple[BoundaryCondition, BoundaryCondition]], optional
        Explicit boundary conditions per species (overrides automatic generation).
    geometry : Geometry or str, default 'planar'
        Coordinate geometry passed to :class:`~softpotato.solver.DiffusionProblem`.
    diffusivity : Mapping[str, float], optional
        Optional diffusivity overrides.
    initial_conditions : Mapping, optional
        Optional initial condition overrides.
    n_electrons : int or dict[str, int], optional
        Optional electron transfer count overrides.
    electrodes : {'left', 'right', 'both'}, default 'left'
        Active electrode boundary for current evaluation.
    electrode_side : {'left', 'right', 'both'}, optional
        Alias for ``electrodes``.
    bulk_bc : {'dirichlet', 'neumann'}, default 'dirichlet'
        Bulk boundary condition type when auto-generating BCs.
    bc_overrides : Mapping, optional
        Per-species boundary condition overrides applied on top of generated BCs.
    **bc_kwargs : Any
        Additional keyword arguments forwarded to :meth:`boundary_conditions`.

    Returns
    -------
    DiffusionProblem
        Configured reaction-diffusion problem ready for solving.
    """
    from softpotato.solver.base import DiffusionProblem, NeumannBC

    if boundary_conditions is not None:
        resolved_bcs = dict(boundary_conditions)
        if bc_overrides:
            resolved_bcs.update(bc_overrides)
        reactions_obj: Any = self
    else:
        bc_side: Literal["left", "right"] | None = None
        target_side = electrode_side if electrode_side is not None else electrodes
        if target_side in ("left", "right"):
            bc_side = target_side
        resolved_bcs = self.boundary_conditions(
            potential=potential,
            electrode_side=bc_side,
            bulk_bc=bulk_bc,
            overrides=bc_overrides,
            **bc_kwargs,
        )
        reactions_obj = self

        override_names = set(bc_overrides) if bc_overrides else set()
        het_steps = [
            step
            for step in self._electrochemical_steps
            if isinstance(step.kinetics, HeterogeneousKinetics)
            and step.ox_name not in override_names
            and step.red_name not in override_names
        ]
        if het_steps and potential is not None:
            x_nodes = np.asarray(
                grid.nodes if hasattr(grid, "nodes") else grid, dtype=float
            )
            if x_nodes.ndim != 1 or x_nodes.size < 2:
                raise ValueError(
                    "grid must be 1D with at least 2 points for heterogeneous kinetics."
                )
            if callable(potential):
                eval_potential: Callable[[float], float] = potential
            else:
                const_e = float(potential)

                def eval_potential(_t: float) -> float:
                    return const_e

            step_specs: list[
                tuple[str, str, HeterogeneousKinetics, int, float]
            ] = []
            for step in het_steps:
                side = bc_side if bc_side is not None else step.electrode_side
                if side == "left":
                    node_idx = 0
                    inv_half_cell = 2.0 / float(x_nodes[1] - x_nodes[0])
                    resolved_bcs[step.ox_name] = (
                        NeumannBC(0.0),
                        resolved_bcs[step.ox_name][1],
                    )
                    resolved_bcs[step.red_name] = (
                        NeumannBC(0.0),
                        resolved_bcs[step.red_name][1],
                    )
                else:
                    node_idx = -1
                    inv_half_cell = 2.0 / float(x_nodes[-1] - x_nodes[-2])
                    resolved_bcs[step.ox_name] = (
                        resolved_bcs[step.ox_name][0],
                        NeumannBC(0.0),
                    )
                    resolved_bcs[step.red_name] = (
                        resolved_bcs[step.red_name][0],
                        NeumannBC(0.0),
                    )
                kinetics = step.kinetics
                assert isinstance(kinetics, HeterogeneousKinetics)
                step_specs.append(
                    (step.ox_name, step.red_name, kinetics, node_idx, inv_half_cell)
                )

            reactions_obj = _MechanismWithInterfacialKinetics(
                self, eval_potential, step_specs
            )

    return DiffusionProblem(
        grid=grid,
        diffusivity=dict(diffusivity) if diffusivity is not None else {},
        boundary_conditions=resolved_bcs,
        initial_conditions=(
            dict(initial_conditions) if initial_conditions is not None else {}
        ),
        reactions=reactions_obj,
        species=self._species,
        geometry=geometry,
        n_electrons=n_electrons,
        electrodes=electrodes,
        electrode_side=electrode_side,
        mechanism=self,
    )

Species dataclass

Encapsulation of a chemical species and its physicochemical properties.

Parameters:

Name Type Description Default
name str

Unique chemical identifier (e.g., 'Ox', 'Red', 'Fe(CN)6_3-').

required
diffusivity float

Standard diffusion coefficient \(D_i > 0\) in \(\text{m}^2/\text{s}\) (or \(\text{cm}^2/\text{s}\) depending on system units).

required
bulk_concentration float

Bulk / resting concentration \(c_i^* \ge 0\) (\(\text{mol/m}^3\) or M).

0.0
charge int

Formal ionic charge \(z_i\) (e.g., -3 for ferricyanide).

0
standard_potential float or None

Standard formal reduction potential \(E^{0\prime}\) in Volts vs. reference electrode.

None
n_electrons int or None

Number of electrons transferred in the primary redox reaction.

None

Examples:

>>> from softpotato.reactions import Species
>>> ox = Species(
...     name="Ox",
...     diffusivity=1e-9,
...     bulk_concentration=1.0,
...     charge=-3,
...     standard_potential=0.2,
...     n_electrons=1,
... )
>>> ox.name
'Ox'
>>> ox.diffusivity
1e-09
Source code in src/softpotato/reactions/species.py
@dataclass(frozen=True)
class Species:
    r"""Encapsulation of a chemical species and its physicochemical properties.

    Parameters
    ----------
    name : str
        Unique chemical identifier (e.g., ``'Ox'``, ``'Red'``, ``'Fe(CN)6_3-'``).
    diffusivity : float
        Standard diffusion coefficient :math:`D_i > 0` in :math:`\text{m}^2/\text{s}`
        (or :math:`\text{cm}^2/\text{s}` depending on system units).
    bulk_concentration : float, default 0.0
        Bulk / resting concentration :math:`c_i^* \ge 0` (:math:`\text{mol/m}^3` or M).
    charge : int, default 0
        Formal ionic charge :math:`z_i` (e.g., ``-3`` for ferricyanide).
    standard_potential : float or None, default None
        Standard formal reduction potential :math:`E^{0\prime}` in Volts vs.
        reference electrode.
    n_electrons : int or None, default None
        Number of electrons transferred in the primary redox reaction.

    Examples
    --------
    >>> from softpotato.reactions import Species
    >>> ox = Species(
    ...     name="Ox",
    ...     diffusivity=1e-9,
    ...     bulk_concentration=1.0,
    ...     charge=-3,
    ...     standard_potential=0.2,
    ...     n_electrons=1,
    ... )
    >>> ox.name
    'Ox'
    >>> ox.diffusivity
    1e-09
    """

    name: str
    diffusivity: float
    bulk_concentration: float = 0.0
    charge: int = 0
    standard_potential: float | None = None
    n_electrons: int | None = None

    def __post_init__(self) -> None:
        if not isinstance(self.name, str) or not self.name.strip():
            raise ValueError("Species name must be a non-empty string.")

        diffusivity = _validate_finite_real(self.diffusivity, "Diffusivity", self.name)
        if diffusivity <= 0.0:
            raise ValueError(
                f"Diffusivity for species '{self.name}' must be positive, "
                f"got {self.diffusivity}."
            )
        object.__setattr__(self, "diffusivity", diffusivity)

        bulk_conc = _validate_finite_real(
            self.bulk_concentration, "Bulk concentration", self.name
        )
        if bulk_conc < 0.0:
            raise ValueError(
                f"Bulk concentration for species '{self.name}' must be non-negative, "
                f"got {self.bulk_concentration}."
            )
        object.__setattr__(self, "bulk_concentration", bulk_conc)

        _validate_int(self.charge, "Charge", self.name)

        if self.standard_potential is not None:
            e0 = _validate_finite_real(
                self.standard_potential, "Standard potential", self.name
            )
            object.__setattr__(self, "standard_potential", e0)

        if self.n_electrons is not None:
            _validate_int(self.n_electrons, "n_electrons", self.name)

SpeciesCollection

Bases: Mapping[str, Species]

Ordered container and registry managing a group of Species objects.

Supports dict-like lookup by species name (collection["Ox"]) and provides convenience property exports compatible with DiffusionProblem.

Parameters:

Name Type Description Default
species Iterable[Species]

Initial collection of Species instances. Duplicate species names raise ValueError.

()

Examples:

>>> from softpotato.reactions import Species, SpeciesCollection
>>> ox = Species("Ox", diffusivity=1e-9, bulk_concentration=1.0, n_electrons=1)
>>> red = Species("Red", diffusivity=1.2e-9, bulk_concentration=0.0, n_electrons=-1)
>>> col = SpeciesCollection([ox, red])
>>> col["Ox"].diffusivity
1e-09
>>> col.diffusivities
{'Ox': 1e-09, 'Red': 1.2e-09}
>>> col.initial_conditions
{'Ox': 1.0, 'Red': 0.0}
>>> col.n_electrons
{'Ox': 1, 'Red': -1}
Source code in src/softpotato/reactions/species.py
class SpeciesCollection(Mapping[str, Species]):
    """Ordered container and registry managing a group of :class:`Species` objects.

    Supports dict-like lookup by species name (``collection["Ox"]``) and provides
    convenience property exports compatible with
    :class:`~softpotato.solver.DiffusionProblem`.

    Parameters
    ----------
    species : Iterable[Species], optional
        Initial collection of :class:`Species` instances. Duplicate species names
        raise ``ValueError``.

    Examples
    --------
    >>> from softpotato.reactions import Species, SpeciesCollection
    >>> ox = Species("Ox", diffusivity=1e-9, bulk_concentration=1.0, n_electrons=1)
    >>> red = Species("Red", diffusivity=1.2e-9, bulk_concentration=0.0, n_electrons=-1)
    >>> col = SpeciesCollection([ox, red])
    >>> col["Ox"].diffusivity
    1e-09
    >>> col.diffusivities
    {'Ox': 1e-09, 'Red': 1.2e-09}
    >>> col.initial_conditions
    {'Ox': 1.0, 'Red': 0.0}
    >>> col.n_electrons
    {'Ox': 1, 'Red': -1}
    """

    def __init__(self, species: Iterable[Species] = ()) -> None:
        self._species: dict[str, Species] = {}
        for item in species:
            self.add(item)

    def add(self, species: Species) -> None:
        """Register a :class:`Species` instance in the collection.

        Parameters
        ----------
        species : Species
            Species object to add.

        Raises
        ------
        TypeError
            If ``species`` is not a :class:`Species` instance.
        ValueError
            If a species with the same name is already registered.
        """
        if not isinstance(species, Species):
            raise TypeError(
                f"Expected a Species instance, got {type(species).__name__}."
            )
        if species.name in self._species:
            raise ValueError(
                f"Species '{species.name}' is already present in the collection."
            )
        self._species[species.name] = species

    def remove(self, name: str) -> Species:
        """Remove and return a species by name.

        Parameters
        ----------
        name : str
            Name of the species to remove.

        Returns
        -------
        Species
            The removed species instance.

        Raises
        ------
        KeyError
            If ``name`` is not found in the collection.
        """
        return self._species.pop(name)

    def __getitem__(self, name: str) -> Species:
        return self._species[name]

    def __iter__(self) -> Iterator[str]:
        return iter(self._species)

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

    def __contains__(self, item: object) -> bool:
        if isinstance(item, Species):
            return self._species.get(item.name) == item
        return item in self._species

    def __eq__(self, other: object) -> bool:
        if isinstance(other, SpeciesCollection):
            return self._species == other._species
        return NotImplemented

    def __repr__(self) -> str:
        return f"SpeciesCollection({list(self._species.values())!r})"

    @property
    def names(self) -> list[str]:
        """Ordered list of registered species names."""
        return list(self._species.keys())

    @property
    def diffusivities(self) -> dict[str, float]:
        """Mapping from species name to diffusion coefficient :math:`D_i`."""
        return {name: sp.diffusivity for name, sp in self._species.items()}

    @property
    def bulk_concentrations(self) -> dict[str, float]:
        """Mapping from species name to bulk concentration :math:`c_i^*`."""
        return {name: sp.bulk_concentration for name, sp in self._species.items()}

    @property
    def initial_conditions(self) -> dict[str, float]:
        """Mapping from species name to initial (bulk) concentration for ``DiffusionProblem``."""
        return self.bulk_concentrations

    @property
    def charges(self) -> dict[str, int]:
        """Mapping from species name to formal ionic charge :math:`z_i`."""
        return {name: sp.charge for name, sp in self._species.items()}

    @property
    def standard_potentials(self) -> dict[str, float]:
        """Mapping from species name to standard potential :math:`E^{0\\prime}` for species defining it."""
        return {
            name: sp.standard_potential
            for name, sp in self._species.items()
            if sp.standard_potential is not None
        }

    @property
    def n_electrons(self) -> dict[str, int]:
        """Mapping from species name to electron transfer count for species defining ``n_electrons``."""
        return {
            name: sp.n_electrons
            for name, sp in self._species.items()
            if sp.n_electrons is not None
        }

names property

names: list[str]

Ordered list of registered species names.

diffusivities property

diffusivities: dict[str, float]

Mapping from species name to diffusion coefficient \(D_i\).

bulk_concentrations property

bulk_concentrations: dict[str, float]

Mapping from species name to bulk concentration \(c_i^*\).

initial_conditions property

initial_conditions: dict[str, float]

Mapping from species name to initial (bulk) concentration for DiffusionProblem.

charges property

charges: dict[str, int]

Mapping from species name to formal ionic charge \(z_i\).

standard_potentials property

standard_potentials: dict[str, float]

Mapping from species name to standard potential \(E^{0\prime}\) for species defining it.

n_electrons property

n_electrons: dict[str, int]

Mapping from species name to electron transfer count for species defining n_electrons.

add

add(species: Species) -> None

Register a Species instance in the collection.

Parameters:

Name Type Description Default
species Species

Species object to add.

required

Raises:

Type Description
TypeError

If species is not a Species instance.

ValueError

If a species with the same name is already registered.

Source code in src/softpotato/reactions/species.py
def add(self, species: Species) -> None:
    """Register a :class:`Species` instance in the collection.

    Parameters
    ----------
    species : Species
        Species object to add.

    Raises
    ------
    TypeError
        If ``species`` is not a :class:`Species` instance.
    ValueError
        If a species with the same name is already registered.
    """
    if not isinstance(species, Species):
        raise TypeError(
            f"Expected a Species instance, got {type(species).__name__}."
        )
    if species.name in self._species:
        raise ValueError(
            f"Species '{species.name}' is already present in the collection."
        )
    self._species[species.name] = species

remove

remove(name: str) -> Species

Remove and return a species by name.

Parameters:

Name Type Description Default
name str

Name of the species to remove.

required

Returns:

Type Description
Species

The removed species instance.

Raises:

Type Description
KeyError

If name is not found in the collection.

Source code in src/softpotato/reactions/species.py
def remove(self, name: str) -> Species:
    """Remove and return a species by name.

    Parameters
    ----------
    name : str
        Name of the species to remove.

    Returns
    -------
    Species
        The removed species instance.

    Raises
    ------
    KeyError
        If ``name`` is not found in the collection.
    """
    return self._species.pop(name)

create_electrochemical_bcs

create_electrochemical_bcs(kinetics: HeterogeneousKinetics | NernstianEquilibrium, potential: float | Callable[[float], float], ox: Species | str = 'Ox', red: Species | str = 'Red', *, D_ox: float | None = None, D_red: float | None = None, c_ox_bulk: float | None = None, c_red_bulk: float | None = None, c_ox_surface: float | Callable[[float], float] | None = None, c_red_surface: float | Callable[[float], float] | None = None, electrode_side: Literal['left', 'right'] = 'left', bulk_bc: Literal['dirichlet', 'neumann'] = 'dirichlet') -> dict[str, tuple[BoundaryCondition, BoundaryCondition]]

Construct matched (left_bc, right_bc) boundary conditions for a redox pair.

Generates a dictionary mapping {ox_name: (left_bc, right_bc), red_name: (left_bc, right_bc)} compatible with DiffusionProblem:

  • For NernstianEquilibrium: generates time-dependent DirichletBC conditions enforcing the Nernst equilibrium surface concentrations at the electrode boundary.
  • For HeterogeneousKinetics (e.g., ButlerVolmer, TafelKinetics): generates matched NeumannBC flux boundary conditions satisfying flux continuity \(J_{\text{Ox}} = -J_{\text{Red}}\):

    \[ \left.\frac{\partial c_{\text{Ox}}}{\partial x}\right|_{\text{left}} = +\frac{J(t)}{D_{\text{Ox}}}, \qquad \left.\frac{\partial c_{\text{Red}}}{\partial x}\right|_{\text{left}} = -\frac{J(t)}{D_{\text{Red}}} \]

Parameters:

Name Type Description Default
kinetics HeterogeneousKinetics or NernstianEquilibrium

Interfacial charge-transfer model or Nernstian equilibrium helper.

required
potential float or Callable[[float], float]

Constant electrode potential \(E\) or time-dependent waveform \(E(t)\) in Volts.

required
ox Species or str

Oxidized species object or name.

'Ox'
red Species or str

Reduced species object or name.

'Red'
D_ox float

Diffusion coefficient of oxidized species. Inferred from ox if a Species is passed; required for HeterogeneousKinetics when ox is a string.

None
D_red float

Diffusion coefficient of reduced species. Inferred from red if a Species is passed; required for HeterogeneousKinetics when red is a string.

None
c_ox_bulk float

Bulk concentration of oxidized species (inferred from ox if Species, else defaults to 1.0).

None
c_red_bulk float

Bulk concentration of reduced species (inferred from red if Species, else defaults to 0.0).

None
c_ox_surface float or Callable[[float], float]

Prescribed surface concentration \(c_{\text{Ox}}(0, t)\) used when evaluating Neumann kinetic fluxes (defaults to c_ox_bulk).

None
c_red_surface float or Callable[[float], float]

Prescribed surface concentration \(c_{\text{Red}}(0, t)\) used when evaluating Neumann kinetic fluxes (defaults to c_red_bulk).

None
electrode_side ('left', 'right')

Domain boundary acting as the working electrode.

'left'
bulk_bc ('dirichlet', 'neumann')

Boundary condition type at the opposite (bulk) boundary: 'dirichlet' fixes bulk concentrations \(c_i^*\), while 'neumann' applies a zero-flux condition (\(\partial c_i / \partial x = 0\)).

'dirichlet'

Returns:

Type Description
dict[str, tuple[BoundaryCondition, BoundaryCondition]]

Dictionary ready to pass to DiffusionProblem(..., boundary_conditions=...).

Examples:

>>> from softpotato.reactions import (
...     NernstianEquilibrium,
...     Species,
...     create_electrochemical_bcs,
... )
>>> ox = Species("Ox", diffusivity=1e-9, bulk_concentration=1.0)
>>> red = Species("Red", diffusivity=1e-9, bulk_concentration=0.0)
>>> eq = NernstianEquilibrium(E0=0.0, n=1)
>>> bcs = create_electrochemical_bcs(eq, potential=0.0, ox=ox, red=red)
>>> bcs["Ox"][0].evaluate(0.0), bcs["Red"][0].evaluate(0.0)
(0.5, 0.5)
Source code in src/softpotato/reactions/heterogeneous.py
def create_electrochemical_bcs(
    kinetics: HeterogeneousKinetics | NernstianEquilibrium,
    potential: float | Callable[[float], float],
    ox: Species | str = "Ox",
    red: Species | str = "Red",
    *,
    D_ox: float | None = None,
    D_red: float | None = None,
    c_ox_bulk: float | None = None,
    c_red_bulk: float | None = None,
    c_ox_surface: float | Callable[[float], float] | None = None,
    c_red_surface: float | Callable[[float], float] | None = None,
    electrode_side: Literal["left", "right"] = "left",
    bulk_bc: Literal["dirichlet", "neumann"] = "dirichlet",
) -> dict[str, tuple[BoundaryCondition, BoundaryCondition]]:
    r"""Construct matched ``(left_bc, right_bc)`` boundary conditions for a redox pair.

    Generates a dictionary mapping ``{ox_name: (left_bc, right_bc), red_name: (left_bc, right_bc)}``
    compatible with :class:`~softpotato.solver.DiffusionProblem`:

    - For :class:`NernstianEquilibrium`: generates time-dependent
      :func:`~softpotato.solver.DirichletBC` conditions enforcing the Nernst
      equilibrium surface concentrations at the electrode boundary.
    - For :class:`HeterogeneousKinetics` (e.g., :class:`ButlerVolmer`,
      :class:`TafelKinetics`): generates matched :func:`~softpotato.solver.NeumannBC`
      flux boundary conditions satisfying flux continuity
      :math:`J_{\text{Ox}} = -J_{\text{Red}}`:

      .. math::

          \left.\frac{\partial c_{\text{Ox}}}{\partial x}\right|_{\text{left}} = +\frac{J(t)}{D_{\text{Ox}}}, \qquad
          \left.\frac{\partial c_{\text{Red}}}{\partial x}\right|_{\text{left}} = -\frac{J(t)}{D_{\text{Red}}}

    Parameters
    ----------
    kinetics : HeterogeneousKinetics or NernstianEquilibrium
        Interfacial charge-transfer model or Nernstian equilibrium helper.
    potential : float or Callable[[float], float]
        Constant electrode potential :math:`E` or time-dependent waveform :math:`E(t)` in Volts.
    ox : Species or str, default 'Ox'
        Oxidized species object or name.
    red : Species or str, default 'Red'
        Reduced species object or name.
    D_ox : float, optional
        Diffusion coefficient of oxidized species. Inferred from ``ox`` if a
        :class:`~softpotato.reactions.Species` is passed; required for
        :class:`HeterogeneousKinetics` when ``ox`` is a string.
    D_red : float, optional
        Diffusion coefficient of reduced species. Inferred from ``red`` if a
        :class:`~softpotato.reactions.Species` is passed; required for
        :class:`HeterogeneousKinetics` when ``red`` is a string.
    c_ox_bulk : float, optional
        Bulk concentration of oxidized species (inferred from ``ox`` if
        :class:`~softpotato.reactions.Species`, else defaults to ``1.0``).
    c_red_bulk : float, optional
        Bulk concentration of reduced species (inferred from ``red`` if
        :class:`~softpotato.reactions.Species`, else defaults to ``0.0``).
    c_ox_surface : float or Callable[[float], float], optional
        Prescribed surface concentration :math:`c_{\text{Ox}}(0, t)` used when
        evaluating Neumann kinetic fluxes (defaults to ``c_ox_bulk``).
    c_red_surface : float or Callable[[float], float], optional
        Prescribed surface concentration :math:`c_{\text{Red}}(0, t)` used when
        evaluating Neumann kinetic fluxes (defaults to ``c_red_bulk``).
    electrode_side : {'left', 'right'}, default 'left'
        Domain boundary acting as the working electrode.
    bulk_bc : {'dirichlet', 'neumann'}, default 'dirichlet'
        Boundary condition type at the opposite (bulk) boundary: ``'dirichlet'``
        fixes bulk concentrations :math:`c_i^*`, while ``'neumann'`` applies a
        zero-flux condition (:math:`\partial c_i / \partial x = 0`).

    Returns
    -------
    dict[str, tuple[BoundaryCondition, BoundaryCondition]]
        Dictionary ready to pass to ``DiffusionProblem(..., boundary_conditions=...)``.

    Examples
    --------
    >>> from softpotato.reactions import (
    ...     NernstianEquilibrium,
    ...     Species,
    ...     create_electrochemical_bcs,
    ... )
    >>> ox = Species("Ox", diffusivity=1e-9, bulk_concentration=1.0)
    >>> red = Species("Red", diffusivity=1e-9, bulk_concentration=0.0)
    >>> eq = NernstianEquilibrium(E0=0.0, n=1)
    >>> bcs = create_electrochemical_bcs(eq, potential=0.0, ox=ox, red=red)
    >>> bcs["Ox"][0].evaluate(0.0), bcs["Red"][0].evaluate(0.0)
    (0.5, 0.5)
    """
    if electrode_side not in ("left", "right"):
        raise ValueError(
            f"electrode_side must be 'left' or 'right', got {electrode_side!r}."
        )
    if bulk_bc not in ("dirichlet", "neumann"):
        raise ValueError(f"bulk_bc must be 'dirichlet' or 'neumann', got {bulk_bc!r}.")

    ox_name, d_ox_val, c_ox_b = _resolve_species_params(
        ox, "ox", D_ox, c_ox_bulk, default_bulk=1.0
    )
    red_name, d_red_val, c_red_b = _resolve_species_params(
        red, "red", D_red, c_red_bulk, default_bulk=0.0
    )
    if ox_name == red_name:
        raise ValueError(
            f"Oxidized and reduced species must have distinct names, both got '{ox_name}'."
        )

    if callable(potential):
        eval_potential = potential
    else:
        const_e = _validate_finite_real(potential, "potential")

        def eval_potential(_t: float) -> float:
            return const_e

    electrode_bc_ox: BoundaryCondition
    electrode_bc_red: BoundaryCondition

    if isinstance(kinetics, NernstianEquilibrium):
        c_total = c_ox_b + c_red_b

        def _ox_dirichlet(t: float) -> float:
            c_ox_s, _ = kinetics.surface_concentrations(
                float(eval_potential(t)),
                c_total=c_total,
                D_ox=d_ox_val,
                D_red=d_red_val,
                c_ox_bulk=c_ox_b,
                c_red_bulk=c_red_b,
            )
            return float(c_ox_s)

        def _red_dirichlet(t: float) -> float:
            _, c_red_s = kinetics.surface_concentrations(
                float(eval_potential(t)),
                c_total=c_total,
                D_ox=d_ox_val,
                D_red=d_red_val,
                c_ox_bulk=c_ox_b,
                c_red_bulk=c_red_b,
            )
            return float(c_red_s)

        electrode_bc_ox = DirichletBC(_ox_dirichlet)
        electrode_bc_red = DirichletBC(_red_dirichlet)

    elif isinstance(kinetics, HeterogeneousKinetics):
        if d_ox_val is None or d_red_val is None:
            raise ValueError(
                "D_ox and D_red must be provided (directly or via Species instances) "
                "when creating Neumann boundary conditions for HeterogeneousKinetics."
            )

        if callable(c_ox_surface):
            eval_c_ox = c_ox_surface
        else:
            c_ox_const = (
                c_ox_b
                if c_ox_surface is None
                else float(_validate_non_negative_conc(c_ox_surface, "c_ox_surface")[0])
            )

            def eval_c_ox(_t: float) -> float:
                return c_ox_const

        if callable(c_red_surface):
            eval_c_red = c_red_surface
        else:
            c_red_const = (
                c_red_b
                if c_red_surface is None
                else float(
                    _validate_non_negative_conc(c_red_surface, "c_red_surface")[0]
                )
            )

            def eval_c_red(_t: float) -> float:
                return c_red_const

        side_sign = 1.0 if electrode_side == "left" else -1.0
        d_ox_f = d_ox_val
        d_red_f = d_red_val

        def _ox_neumann(t: float) -> float:
            flux_val = float(
                kinetics.flux(
                    float(eval_potential(t)),
                    float(eval_c_ox(t)),
                    float(eval_c_red(t)),
                )
            )
            return side_sign * flux_val / d_ox_f

        def _red_neumann(t: float) -> float:
            flux_val = float(
                kinetics.flux(
                    float(eval_potential(t)),
                    float(eval_c_ox(t)),
                    float(eval_c_red(t)),
                )
            )
            return -side_sign * flux_val / d_red_f

        electrode_bc_ox = NeumannBC(_ox_neumann)
        electrode_bc_red = NeumannBC(_red_neumann)

    else:
        raise TypeError(
            "kinetics must be an instance of HeterogeneousKinetics or "
            f"NernstianEquilibrium, got {type(kinetics).__name__}."
        )

    if bulk_bc == "dirichlet":
        bulk_bc_ox = DirichletBC(c_ox_b)
        bulk_bc_red = DirichletBC(c_red_b)
    else:
        bulk_bc_ox = NeumannBC(0.0)
        bulk_bc_red = NeumannBC(0.0)

    if electrode_side == "left":
        return {
            ox_name: (electrode_bc_ox, bulk_bc_ox),
            red_name: (electrode_bc_red, bulk_bc_red),
        }
    return {
        ox_name: (bulk_bc_ox, electrode_bc_ox),
        red_name: (bulk_bc_red, electrode_bc_red),
    }