diff --git a/README.md b/README.md
index 03e4a56a..08c23a59 100644
--- a/README.md
+++ b/README.md
@@ -67,12 +67,12 @@ SolarLab/
│ └── solarlab_research/ Research companion CLIs (solarlab-cbo-scan, solarlab-r1-short-window, r1-verify-sources)
├── web/ Vite + TypeScript + Plotly + GoldenLayout workstation frontend
├── examples/
-│ ├── research_1d/ 23 runnable 1D steady, AC, transient, mobile-ion, optical, and HTTP/process workflows
+│ ├── research_1d/ 24 runnable 1D steady, AC, transient, mobile-ion, iodine-aging, optical, and HTTP workflows
│ └── research_2d/ 10 runnable 2D steady, J-V, grain-boundary, contact, field-mobility, and optical workflows
├── docs/
│ ├── DevelopmentGuide.md Extension workflow, unified assembly rules, and branch governance
│ ├── RetiredModelsV1.md Retired legacy entrypoints, falsified closures, and historical anchors
-│ ├── contracts/ 34 active physical model, defect, optical, and 2D protocol specifications
+│ ├── contracts/ 35 active physical model, defect, optical, aging, and 2D protocol specifications
│ └── figures/ Pure-Arial 300 DPI architecture, physics, solver, and validation figures
├── reproducibility/ Frozen SCAPS, hysteresis, analytic, and performance contracts
├── scripts/ Root CI runner (test_all.py), schema generator, figure builder, and benchmarks
@@ -81,7 +81,7 @@ SolarLab/
**Directory Guides:**
- Developer workflow & model extension contract: [docs/DevelopmentGuide.md](docs/DevelopmentGuide.md)
-- Physical & numerical model contracts (`34` specs): [docs/contracts/README.md](docs/contracts/README.md)
+- Physical & numerical model contracts (`35` specs): [docs/contracts/README.md](docs/contracts/README.md)
- Frozen benchmark & reference contracts: [reproducibility/README.md](reproducibility/README.md)
- Runnable 1D & 2D research workflows: [examples/research_1d/README.md](examples/research_1d/README.md) · [examples/research_2d/README.md](examples/research_2d/README.md)
@@ -112,6 +112,11 @@ npm --prefix web run build
# 1D ion-free steady-state J-V sweep on the packaged classical_pin preset
.venv/bin/solarlab steady-jv --output outputs/steady_jv.json
+# Coupled 1D iodine chemistry steady state, AC redox capacitance, and multi-stage aging
+.venv/bin/solarlab iodine-presets
+.venv/bin/solarlab iodine-steady --preset bitton_tessler_2023_blocking --output outputs/iodine_steady.json
+.venv/bin/solarlab iodine-aging --preset bitton_tessler_2023_self_healing --output outputs/iodine_aging.json
+
# Research companion CLI entrypoints
.venv/bin/solarlab-cbo-scan --help
.venv/bin/solarlab-r1-short-window --help
@@ -148,6 +153,7 @@ All characterisation workflows compile from the same validated device declaratio
| | $\text{Suns-}V_{\mathrm{oc}}$ & $V_{\mathrm{oc}}(T)$ | `solarlab.experiments.suns_voc`, `voc_t` | Series-resistance-free $\text{pseudo-}J\text{-}V$, $\text{pseudo-FF}$, activation-energy intercept |
| | Transient Photovoltage (TPV) | `solarlab.experiments.tpv` | Floating-port Maxwell $J_{\mathrm{cond}} + \partial_t D = 0$ pulse + paired unpulsed drift subtraction |
| | Frozen-ion degradation | `solarlab.experiments.degradation` | Long-time ionic evolution with zero-diffusivity electronic snapshot $J\text{-}V$ probes |
+| | Iodine chemistry & aging | `solarlab.experiments.iodine_aging`, `iodine_declarative` | Coupled 5-reaction $\mathrm{I}^- / \mathrm{I}^0 / \mathrm{I}_2$ BDF aging, volatile $\mathrm{I}_2$ outgassing, $\mathrm{Ag}$ corrosion, and AC redox capacitance |
| **1D Small-Signal AC** | Impedance spectroscopy $Z(\omega)$ | `solarlab.experiments.impedance`, `ionic_impedance` | Exact sparse complex solve $(G + i\omega C)\delta u = b$, Nyquist/Bode, coupled ion & dynamic-defect tangents |
| | Mott–Schottky ($C\text{-}V$ / $C\text{-}f$) | `solarlab.experiments.mott_schottky` | Depletion $1/C^2$ extraction of $V_{\mathrm{bi}}$ and $N_{\mathrm{eff}}$ |
| **Spectral & Multi-Junction** | Monochromatic EQE & EL | `solarlab.experiments.eqe`, `el_spectrum` | Coherent TMM or spectral Beer–Lambert $\mathrm{EQE}(\lambda)$, AM1.5G $J_{\mathrm{sc}}$, reciprocity EL |
@@ -255,7 +261,7 @@ Evaluated across the **45-case** 7-stage preconditioning + forward/reverse scan
| `calado2016_ion_sweep` | HTL / Perovskite / ETL | Yes | Uniform / BL | Workstation dynamic ion-hysteresis waveform preset |
| `calado2016_fig1f` | Calado 2016 SI Table 1 stack | Yes | Beer–Lambert | Literature scan-rate hysteresis comparison preset |
-An additional **52** YAML device and 2D microstructure test fixtures reside under `tests/fixtures/configs/` (isolated from API serving).
+An additional **5** declarative iodine reaction–diffusion–aging presets (`bitton_tessler_2023_{blocking,permeable,outgassing,ag_corrosion,self_healing}`) reside under `src/solarlab/materials/data/iodine_presets/` (served at `/iodine/presets` and `?view=iodine-aging`), alongside **52** YAML device and 2D microstructure test fixtures under `tests/fixtures/configs/` (isolated from API serving).
### Running the Full Verification Suite
@@ -283,6 +289,7 @@ npm --prefix web run build
3. **Calado, P. et al.** (2016) — *Evidence for ion migration in hybrid perovskite solar cells with minimal hysteresis*. Nat. Commun., 7, 13831.
4. **Courtier, N. E. et al.** (2019) — *IonMonger: a free and fast planar perovskite solar cell simulator with coupled ion vacancy and charge carrier dynamics*. J. Comput. Electron., 18, 1435–1449.
5. **Burgelman, M., Nollet, P. & Degrave, S.** (2000) — *Modelling polycrystalline semiconductor solar cells* (SCAPS-1D). Thin Solid Films, 361–362, 527–532.
+6. **Bitton, S. & Tessler, N.** (2023) — *Perovskite ionics – elucidating degradation mechanisms in perovskite solar cells via device modelling and iodine chemistry*. Energy Environ. Sci., 16(6), 2621–2628.
diff --git a/docs/contracts/IodineReactionAgingContractV1.md b/docs/contracts/IodineReactionAgingContractV1.md
new file mode 100644
index 00000000..b743780c
--- /dev/null
+++ b/docs/contracts/IodineReactionAgingContractV1.md
@@ -0,0 +1,155 @@
+# Iodine Reaction–Diffusion–Electrostatics Aging Contract (V1)
+
+## 1. Scope and Provenance
+
+This specification defines the continuum **iodine-chemistry-driven perovskite aging model** (`solarlab.iodine_aging.v1`) implemented on SolarLab's shared `SystemLayout` / `Assembler` / `StorageProblem` architecture.
+
+- **Primary literature reference**: S. Bitton and N. Tessler, *"Perovskite ionics – elucidating degradation mechanisms in perovskite solar cells via device modelling and iodine chemistry"*, *Energy & Environmental Science*, **16**(6), 2621–2628 (2023), DOI `10.1039/d3ee00881a` (Supplementary Information Eqs. 1–6, Table S1, Figures S1–S2).
+- **Qualification boundary**: Engineering implementation and analytical/conservation/parity verification under this contract do **not** constitute full experimental qualification (`scientific_qualification = False` remains explicit on all run manifests).
+
+---
+
+## 2. Dynamic Species, Stoichiometric Matrix, and Exact Conservation Laws
+
+The coupled 1D system resolves electrostatic potential $\phi(x, t)$ together with five mobile particle populations:
+
+| Index | Block / Species ID | Symbol | Charge Number $z_s$ | Iodine Atom Count $m_{\mathrm{I},s}$ |
+|:-----:|:-------------------|:------:|:-------------------:|:------------------------------------:|
+| 0 | `electron` | $n$ | $-1$ | $0$ |
+| 1 | `hole` | $p$ | $+1$ | $0$ |
+| 2 | `iodide` | $c_-$ ($\mathrm{I}_i^-$) | $-1$ | $1$ |
+| 3 | `iodine_atom` | $c_0$ ($\mathrm{I}_i^0$) | $0$ | $1$ |
+| 4 | `iodine_molecule` | $c_2$ ($\mathrm{I}_2$) | $0$ | $2$ |
+
+Five bulk chemical reaction channels $\mathbf{R} = [R_a, R_b, R_c, R_d, R_e]^{\top}$ ($\mathrm{m}^{-3}\;\mathrm{s}^{-1}$) act through the $5 \times 5$ integer stoichiometric matrix $\boldsymbol{\nu}$:
+
+$$
+\boldsymbol{\nu} =
+\begin{bmatrix}
+0 & 0 & -1 & 0 & -2 \\
+-1 & +1 & 0 & 0 & 0 \\
+-1 & +1 & +1 & 0 & +2 \\
++1 & -1 & -1 & -2 & 0 \\
+0 & 0 & 0 & +1 & -1
+\end{bmatrix},
+\qquad
+\mathbf{S}_{\mathrm{chem}} = \boldsymbol{\nu}\,\mathbf{R} =
+\begin{bmatrix}
+-R_c - 2R_e \\
+-R_a + R_b \\
+-R_a + R_b + R_c + 2R_e \\
++R_a - R_b - R_c - 2R_d \\
++R_d - R_e
+\end{bmatrix}.
+$$
+
+Every column $r \in \{a, b, c, d, e\}$ strictly satisfies the two nullspace invariants:
+
+1. **Microscopic Charge Conservation**: $\mathbf{z}^{\top}\boldsymbol{\nu} = \mathbf{0}^{\top}$, so $q(-S_n + S_p - S_-) \equiv 0$ identically at every node and trial state.
+2. **Elemental Iodine Conservation**: $\mathbf{m}_{\mathrm{I}}^{\top}\boldsymbol{\nu} = \mathbf{0}^{\top}\;\Longrightarrow\; S_- + S_0 + 2S_2 \equiv 0$ vanishes identically at every node and trial state.
+
+Any candidate `StoichiometricNetwork` violating either nullspace condition is rejected at construction time with `ContractError`.
+
+---
+
+## 3. Constitutive Kinetics and Thermodynamic Detailed Balance
+
+### 3.1 Reaction Rate Modes
+
+Two constitutive closures are admitted via `thermodynamic_mode`:
+
+1. **`"wegscheider_detailed_balance"` (Default)**:
+ Enforces Wegscheider cyclic detailed balance across the $(a, b, c)$ monomer redox cycle and the $(a, b, d, e)$ dimer redox cycle using local intrinsic carrier density squared $n_i^2 = N_C N_V \exp(-E_g / V_T)$, equilibrium $\mathrm{I}^0/\mathrm{I}^-$ electron density $n_{1,\mathrm{I}} = k_a n_i^2 / k_b$ (when $k_b > 0$), and dimer dissociation constant $K_{\mathrm{diss}} = k_{-d}/k_d > 0$:
+
+$$
+\begin{aligned}
+R_a &= k_a c_- p, \\
+R_b &= k_b c_0, \\
+R_c &= k_c \left(c_0 n - n_{1,\mathrm{I}} c_-\right), \\
+R_d &= k_d \left(c_0^2 - K_{\mathrm{diss}} c_2\right).
+\end{aligned}
+$$
+
+ For molecular iodine reduction ($\mathrm{I}_2 + 2e^- \rightleftharpoons 2\mathrm{I}^-$), two kinetic orders are supported via `reaction_e_order`:
+ - **`"bimolecular_n"` (Default, Bitton & Tessler Table S1 Smoluchowski closure)**:
+ Derived from the two-step radical-anion mechanism $\mathrm{I}_2 + e^- \rightleftharpoons \mathrm{I}_2^{\bullet -}$ followed by $\mathrm{I}_2^{\bullet -} + e^- \rightleftharpoons 2\mathrm{I}^-$ with radical crossover density $n_{e,\ast} > 0$:
+
+$$
+R_e = \frac{k_e}{n + n_{e,\ast}}\left(c_2 n^2 - \frac{n_{1,\mathrm{I}}^2}{K_{\mathrm{diss}}}\,c_-^2\right),
+\qquad
+\frac{\partial R_e}{\partial n} = k_e\,\frac{c_2 n (n + 2 n_{e,\ast}) + (n_{1,\mathrm{I}}^2 / K_{\mathrm{diss}})\,c_-^2}{(n + n_{e,\ast})^2} \ge 0.
+$$
+
+ For $n \gg n_{e,\ast}$, $R_e \to k_e c_2 n$ with $k_e = 4\pi D_e R_{AB}$ ($\mathrm{m}^3\;\mathrm{s}^{-1}$); at dark thermal equilibrium ($n p = n_i^2$, $c_0 = (k_a/k_b) p c_-$, $c_2 = c_0^2 / K_{\mathrm{diss}}$), $R_a - R_b = R_c = R_d = R_e = 0$ identically without any $1/n$ singularity as $n \to 0$.
+ - **`"termolecular_n2"`**:
+ $R_e = k_{e,3}\bigl(c_2 n^2 - (n_{1,\mathrm{I}}^2 / K_{\mathrm{diss}})\;c_-^2\bigr)$ with $k_{e,3}$ in $\mathrm{m}^6\;\mathrm{s}^{-1}$.
+
+2. **`"irreversible_mass_action"` (Direct Sentaurus comparison toggle)**:
+ Evaluates $R_a = k_a c_- p$, $R_b = k_b c_0$, $R_c = k_c c_0 n$, $R_d = k_d c_0^2$, and $R_e = k_e c_2 n$ (or $k_{e,3} c_2 n^2$).
+
+### 3.2 Smoluchowski Diffusion-Limited Rate Factory
+
+For diffusion-controlled reactions with capture radius $R_{AB} > 0$, rate constants follow $k_{AB} = 4\pi (D_A + D_B) R_{AB}$ in SI units ($\mathrm{m}^3\;\mathrm{s}^{-1}$), where $D_{e,h} = \mu_{e,h} V_T$, $D_{AA} = 2 D_0$ for homodimerization $2\mathrm{I}^0 \to \mathrm{I}_2$, and explicit layer-by-layer rate overrides are preserved verbatim when reproducing Table S1.
+
+---
+
+## 4. Coordinate Regularization and Multi-Species Transport
+
+### 4.1 Smooth Log-Linear Softplus and Fischer–Burmeister Positive Maps
+
+In `full_stack_permeable` stacks (e.g., `HBL / Perovskite / EBL`), blocking layers start at zero initial iodine density (`Initial I- = 0`) while reactions span over 20 orders of magnitude between dark trace radicals ($c_0, c_2 \sim 1\;\mathrm{m}^{-3}$) and concentrated mobile iodide ($c_- \sim 10^{25}\;\mathrm{m}^{-3}$). Compiled 1D devices use `SoftplusSpeciesMap` ($c_j(u) = c_{\mathrm{scale},j}\ln(1 + e^u) > 0$), which transitions smoothly from exponential log-density coordinates ($c \approx c_{\mathrm{scale}} e^u$ for $u \ll 0$) to linear coordinates ($c \approx c_{\mathrm{scale}} u$ for $u \gg 0$ without `exp` overflow), maintaining global curvature radius $\lvert c'(u)/c''(u)\rvert = 1 + e^u > 1$ everywhere and a subtraction-free BDF storage secant:
+
+$$
+\frac{\mathrm{d}c_j}{\mathrm{d}u} = c_{\mathrm{scale},j}\,\sigma(u) > 0,
+\qquad
+c_j(u_2) - c_j(u_1) = c_{\mathrm{scale},j}\,\ln\Bigl(1 + \sigma(u_1)\bigl(e^{u_2 - u_1} - 1\bigr)\Bigr).
+$$
+
+`solarlab.physics.chemistry` also provides the algebraic dimensionless Fischer–Burmeister map `PositiveSpeciesMap` with scale $c_{\mathrm{scale},j} > 0$ and regularization ratio $\eta_j \in (0, 1]$:
+
+$$
+r(u) = \mathrm{hypot}(u, 2\eta_j),
+\qquad
+\psi(u) =
+\begin{cases}
+\dfrac{u + r(u)}{2}, & u \ge 0, \\[8pt]
+\dfrac{2\eta_j^2}{r(u) - u}, & u < 0,
+\end{cases}
+\qquad
+c_j(u) = c_{\mathrm{scale},j}\,\psi(u) > 0,
+$$
+
+with strictly positive tangent $\mathrm{d}c_j/\mathrm{d}u = c_{\mathrm{scale},j}\psi(u)/r(u)$ and cancellation-free secant $c_j(u_2) - c_j(u_1) = c_{\mathrm{scale},j}(u_2 - u_1)[\psi(u_1)+\psi(u_2)]/[r(u_1)+r(u_2)]$. When finite-site steric exclusion is declared for $\mathrm{I}^-$ (`iodide_site_limit_m3`), $c_-$ switches to `BoundedSpeciesMap` with $c_- \in (0, c_{\mathrm{lim}})$ and uses `solarlab.physics.ions` steric Scharfetter–Gummel fluxes.
+
+### 4.2 Exponential-Fitted Face Fluxes and Heterointerface Partitioning
+
+Across interior face $f$ with spacing $h_f > 0$, harmonic face diffusivity $D_{j,f}$, valence $z_j \in \{-1, 0\}$, and relative partition ratio $\kappa_{j,f} = K_{\mathrm{part},j,R} / K_{\mathrm{part},j,L} > 0$ (default $\kappa_{j,f} = 1$), the particle flux is:
+
+$$
+\xi_{j,f} = \frac{z_j (\phi_R - \phi_L)}{V_T} - \ln \kappa_{j,f},
+\qquad
+\Gamma_{j,f} = \frac{D_{j,f}}{h_f}\Bigl[B(\xi_{j,f})\,c_{j,L} - B(-\xi_{j,f})\,c_{j,R}\Bigr],
+$$
+
+where $B(\xi) = \xi / (e^\xi - 1)$ is the stabilized Bernoulli function. For $z_0 = z_2 = 0$ and $\kappa_{j,f} = 1$, this reduces identically to Fickian diffusion $\Gamma_{j,f} = D_{j,f}(c_{j,L} - c_{j,R})/h_f$.
+
+---
+
+## 5. Domain Topologies, Open-Loss Closures, and Accounting Gates
+
+1. **Domain Topologies (`domain_mode`)**:
+ - `"absorber_blocking"`: Chemical `NodeSet("chem")` is embedded on the absorber layer; neutral and charged iodine species have zero flux into transport layers.
+ - `"full_stack_permeable"`: Chemical `NodeSet("chem")` spans the full electrical stack (`HBL / Perovskite / EBL`) with piecewise layer diffusivities, reaction rates, and optional partition factors.
+2. **Volumetric Outgassing and Outer Boundary Closures**:
+ - **Volumetric layer $\mathrm{I}_2$ outgassing (`volumetric_mol_escape_s_1`)**: Online cell-wise volatile sink $-k_{\mathrm{outgas}}(x)\;c_2(x, t)$ ($\mathrm{m}^{-3}\;\mathrm{s}^{-1}$, contributing $2 k_{\mathrm{outgas}} c_2$ iodine atoms per unit volume and time) assembled via `IodineVolumetricEscapeTerm` with analytical diagonal Jacobian and shared-heterointerface node protection (suppressing artificial escape on interior `PVK/BL` shared nodes when adjacent layers are sealed). When `volumetric_mol_escape_s_1 == 0` across all layers, the term is omitted so closed-system identities and residuals remain `0-ULP` unchanged.
+ - **Volatile $\mathrm{I}_2$ surface escape (`mol_escape_velocity_m_s`)**: Outward boundary flux $J_{\mathrm{loss},2} = k_{\mathrm{loss}} c_2 \ge 0$ ($\mathrm{m}^{-2}\;\mathrm{s}^{-1}$) on `"left"` and/or `"right"` ports. Closed steady-state inventory constraints are admitted only when `has_open_iodine_loss` is `False`; open-loss configurations evolve via transient integration.
+ - **Charge-conserving contact reaction (`contact_reaction_mode`)**:
+ - `"none"` (blocking to $\mathrm{I}^-$ and $\mathrm{I}^0$);
+ - `"hole_oxidation_to_I0"`: surface reaction $\mathrm{I}^- + h^+ \to \mathrm{I}^0$ with rate $J_{\mathrm{ct}} = k_{\mathrm{ct}} c_- p$ removing equal $\mathrm{I}^-$ and $h^+$ fluxes while injecting $+J_{\mathrm{ct}}$ into $\mathrm{I}^0$ (zero net charge creation, zero iodine atom loss);
+ - `"immobilized_product_sheet"`: surface reaction $\mathrm{I}^- + h^+ \to \mathrm{I}_{\mathrm{surf}}^0(\text{fixed})$ removing equal $\mathrm{I}^-$ and $h^+$ fluxes (zero net charge error) and accumulating trapped surface iodine inventory in the step ledger;
+ - `"metal_faradaic_corrosion"`: Faradaic metal electrode corrosion $\mathrm{M} + \mathrm{I}^- \to \mathrm{MI}(s) + e^-_{\mathrm{metal}}$ with surface velocity $v_{\mathrm{corr}} \ge 0$ (`contact_corrosion_velocity_m_s`, $\mathrm{m}\;\mathrm{s}^{-1}$) and outward flux $J_{\mathrm{corr}} = v_{\mathrm{corr}} c_-$, transferring electrons directly into the external metal contact reservoir while recording immobilized $\mathrm{MI}(s)$ atoms in the step ledger.
+ Non-conserving bare $\mathrm{I}^-$ sink boundaries without charge/inventory accounting are prohibited.
+3. **Mandatory Step Accounting, Conservation Polish, and Frozen-Probe Invariants**:
+ - Every transient step tracks in-device elemental iodine $M_{\mathrm{I}}(t) = \sum_i w_i (c_{-,i} + c_{0,i} + 2c_{2,i})$ plus BDF1/BDF2-consistent cumulative escaped/immobilized iodine $M_{\mathrm{I,loss}}(t)$, enforcing a per-step relative conservation gate $\lvert \Delta M_{\mathrm{res}} \rvert / M_{\mathrm{I}}(0) \le 10^{-9}$ (`step_iodine_conservation`) and auditing cumulative trajectory drift. For open-loss long-horizon BDF steps (`has_open_iodine_loss`), post-Newton conservation polish eliminates floating-point cancellation noise in fast monomer $(R_a, R_b, R_c)$ cycling while preserving full analytical Jacobian coupling.
+ - Non-destructive frozen-chemistry electronic `J-V` probes and `chem_mode="frozen"` small-signal AC impedance lock $(c_-, c_0, c_2)$ bit-for-bit (`0-ULP` chemical coordinate invariance) and suppress redox charge transfer into immobile $\mathrm{I}^-$ so Kirchhoff electronic current continuity $\nabla\cdot(J_n + J_p + i\omega D) = 0$ holds identically across all interior faces.
+ - Declarative YAML/JSON presets and user decks validate against `solarlab.iodine-deck.v1` (`solarlab.experiments.iodine_declarative`) without mutating SolarLab's frozen 20-DTO frontend configuration schema.
diff --git a/docs/contracts/README.md b/docs/contracts/README.md
index dcd07874..5a56ae93 100644
--- a/docs/contracts/README.md
+++ b/docs/contracts/README.md
@@ -1,6 +1,6 @@
# SolarLab Physics & Protocol Contracts
-This directory contains the **34 normative physical model, constitutive closure, schema, and execution-protocol specifications** enforced by `src/solarlab/` and verified by `tests/unit/`, `tests/integration/`, and `tests/refactor/`.
+This directory contains the **35 normative physical model, constitutive closure, schema, and execution-protocol specifications** enforced by `src/solarlab/` and verified by `tests/unit/`, `tests/integration/`, and `tests/refactor/`.
For cross-cutting solver architecture and extension rules, see [../DevelopmentGuide.md](../DevelopmentGuide.md) and [../PhysicsCorrectionsScopeV1.md](../PhysicsCorrectionsScopeV1.md).
@@ -49,6 +49,7 @@ For cross-cutting solver architecture and extension rules, see [../DevelopmentGu
|:--------------|:------|
| [ExperimentProtocol.md](ExperimentProtocol.md) | Canonical 1D sweep, preconditioning, and measurement protocol semantics |
| [FrozenIonSnapshotContract.md](FrozenIonSnapshotContract.md) | Zero-diffusivity electronic snapshot $J\text{-}V$ probes during ionic aging |
+| [IodineReactionAgingContractV1.md](IodineReactionAgingContractV1.md) | Coupled $\mathrm{I}^- / \mathrm{I}^0 / \mathrm{I}_2$ 5-reaction aging, volumetric outgassing, Faradaic contact corrosion, and AC redox capacitance |
| [TpvOpenCircuitContract.md](TpvOpenCircuitContract.md) | Floating-port Maxwell total-current open-circuit integration and TPV decay identifiability |
| [IonSweepFigureReference.md](IonSweepFigureReference.md) | Dense mobile-ion waveform reference protocol (`calado2016_ion_sweep`) |
diff --git a/examples/research_1d/README.md b/examples/research_1d/README.md
index 7616e842..7d6e3128 100644
--- a/examples/research_1d/README.md
+++ b/examples/research_1d/README.md
@@ -45,6 +45,7 @@ All 1D workflows below enforce the same runtime invariants:
| **5. Physics Extensions** | [neutral_defects.py](neutral_defects.py) | Explicit neutral single-level bulk SRH defects (including `--unequal-dos` $N_C \neq N_V$ binding) |
| | [field_transport.py](field_transport.py) | Smooth Caughey–Thomas electric-field velocity saturation ($\beta > 1$) in DC assembly |
| | [optical_generation.py](optical_generation.py) | Explicit wavelength photon flux + $(n, k)$ coherent TMM control-volume generation & photon budget |
+| | [bitton_tessler_2023_benchmark.py](bitton_tessler_2023_benchmark.py) | Coupled 5-reaction $\mathrm{I}^- / \mathrm{I}^0 / \mathrm{I}_2$ steady, $10^4\text{ h}$ outgassing, $\mathrm{Ag}$ corrosion, self-healing, and AC redox capacitance benchmark |
| **6. Process & HTTP Workers** | [process_sweep.py](process_sweep.py), [process_transient.py](process_transient.py), [process_ionic_jv.py](process_ionic_jv.py), [process_ionic_transient.py](process_ionic_transient.py) | Out-of-process `ProcessSupervisor` execution binding committed Git source digests (`--build-source-commit`) |
| | [service.py](service.py), [transient_service.py](transient_service.py), [ionic_jv_service.py](ionic_jv_service.py), [ionic_transient_service.py](ionic_transient_service.py) | Minimal FastAPI `/experiments` + `/jobs` + reconnectable SSE services for dedicated workstation views |
diff --git a/examples/research_1d/bitton_tessler_2023_benchmark.py b/examples/research_1d/bitton_tessler_2023_benchmark.py
new file mode 100644
index 00000000..ff5adcbd
--- /dev/null
+++ b/examples/research_1d/bitton_tessler_2023_benchmark.py
@@ -0,0 +1,1383 @@
+"""Systematic physics parameter sweeps & figure-by-figure benchmark against Bitton & Tessler (2023).
+
+Reference:
+ S. Bitton and N. Tessler, "Perovskite ionics - elucidating degradation
+ mechanisms in perovskite solar cells via device modelling and iodine
+ chemistry", Energy & Environmental Science, 16(6), 2621-2628 (2023),
+ DOI: 10.1039/d3ee00881a (+ Electronic Supplementary Information, Table S1,
+ Fig. S1, Fig. S2).
+
+Generates five publication-grade benchmark figures and a checksum-bound JSON/NPZ
+summary in the target output directory while explicitly retaining
+``scientific_qualification = False``:
+ 1. ``bt2023_fig3_figs1_jv_hysteresis.png`` -- Table 1, Fig. 3a, Fig. 3b, Fig. S1
+ 2. ``bt2023_fig4_steady_profiles.png`` -- Fig. 4a-d + linear I^- insets
+ 3. ``bt2023_figs2_bias_illumination.png`` -- Fig. S2a-c (1 Sun/0.9V, Dark/0.9V, Dark/0V)
+ 4. ``bt2023_fig5_degradation_kinetics.png`` -- Fig. 5a, Fig. 5a inset, Fig. 5b + self-healing
+ 5. ``bt2023_parameter_sweeps_and_ac.png`` -- 4-decade k_a sweep, EBL mitigation, AC impedance
+"""
+
+from __future__ import annotations
+
+import argparse
+import hashlib
+import json
+from pathlib import Path
+import time
+from typing import Any
+
+import matplotlib
+
+matplotlib.use("Agg")
+import matplotlib.pyplot as plt
+from mpl_toolkits.axes_grid1.inset_locator import inset_axes
+import numpy as np
+from numpy.typing import NDArray
+
+from solarlab.config.resolve_device import resolve_device
+from solarlab.device.compile_1d import legacy_benchmark_deck_scope
+from solarlab.device.compile_iodine_1d import (
+ IodineBoundaryDeclaration,
+ IodineChemistryDeclaration,
+ IodineDomainMode,
+ IodineLayerSpec,
+ bitton_tessler_2023_table_s1_chemistry,
+ compile_iodine_device_1d,
+)
+from solarlab.device.defaults import DefaultCatalog
+from solarlab.device.inputs import DeviceInput
+from solarlab.device.resolved import PreparedDevice
+from solarlab.equations.iodine_1d import CompiledIodineDevice1D, IodineState1D
+from solarlab.experiments.iodine_aging import (
+ DynamicJVScanProbeResult,
+ IodineAgingProtocol,
+ IodineProbeSpec,
+ StressRecoveryStage,
+ measure_dynamic_jv_scan,
+ run_iodine_aging_protocol,
+)
+from solarlab.materials.resources import ResourceLibrary
+from solarlab.materials.source import SourceDocument
+from solarlab.solvers.linear.iodine_impedance import solve_iodine_small_signal_1d
+from solarlab.solvers.nonlinear.iodine_1d import (
+ solve_frozen_chemistry_electronic_1d,
+ solve_iodine_bdf_transient,
+ solve_iodine_steady_state,
+)
+from solarlab.solvers.time.bdf import BDFOptions
+
+REPO_ROOT = Path(__file__).resolve().parents[2]
+Q_C = 1.602176634e-19
+KB_J_K = 1.380649e-23
+EPS0_F_M = 8.8541878128e-12
+
+# Bitton & Tessler (2023) Table 1 published reference values (pre-stressed 1 Sun, 0.9 V; ion-blocking BLs)
+BT2023_TABLE1_REF: dict[float, dict[str, float]] = {
+ 0.0: {"Jsc_mA_cm2": 26.0, "Voc_V": 1.27, "FF_pct": 88.0, "PCE_pct": 28.0},
+ 1.0e-11: {"Jsc_mA_cm2": 21.5, "Voc_V": 1.12, "FF_pct": 75.0, "PCE_pct": 18.0},
+ 5.0e-11: {"Jsc_mA_cm2": 13.2, "Voc_V": 1.05, "FF_pct": 68.0, "PCE_pct": 9.4},
+}
+
+
+def _configure_plot_style() -> None:
+ plt.rcParams.update(
+ {
+ "font.family": "sans-serif",
+ "font.size": 9.5,
+ "axes.titlesize": 10.5,
+ "axes.labelsize": 9.5,
+ "xtick.labelsize": 8.5,
+ "ytick.labelsize": 8.5,
+ "legend.fontsize": 8.0,
+ "axes.linewidth": 1.0,
+ "lines.linewidth": 1.8,
+ "figure.dpi": 220,
+ "savefig.dpi": 240,
+ }
+ )
+
+
+def prepare_bt2023_sentaurus_stack(
+ *,
+ mu_bl_cm2_V_s: float = 1.0e-3,
+ contact_phi_b_eV: float = 0.14,
+) -> PreparedDevice:
+ """Build the exact symmetric HBL(50nm)/PVK(500nm)/EBL(50nm) stack from Table S1 & Fig. 1b."""
+ base_path = REPO_ROOT / "examples" / "research_1d" / "device.json"
+ source = SourceDocument(str(base_path), base_path.read_bytes())
+ doc = json.loads(source.content)
+ catalog = {**doc["default_catalog"], "evidence": [[source.id, source.sha256]]}
+
+ vt = (KB_J_K * 300.0) / Q_C
+ mu_bl_si = float(mu_bl_cm2_V_s) * 1.0e-4
+ b_langevin_si = float(Q_C * (2.0 * mu_bl_si) / (EPS0_F_M * 3.0))
+ ni_bl = float(np.exp(0.5 * (np.log(1.0e27) + np.log(1.0e27) - 2.5 / vt)))
+ ni_pvk = float(np.exp(0.5 * (np.log(7.0e24) + np.log(2.5e24) - 1.6 / vt)))
+
+ # Uniform optical generation matching J_SC = 26.0 mA/cm^2 (260 A/m^2) across 500 nm PVK
+ alpha_pvk = 2.0e3
+ phi_inc = float((260.0 / Q_C) / (1.0 - np.exp(-alpha_pvk * 500.0e-9)))
+ phi_b = float(contact_phi_b_eV)
+
+ device_dict = {
+ "schema_version": "solarlab.device-preparation.v1",
+ "id": f"bt2023_mu_{mu_bl_cm2_V_s:.0e}",
+ "name": f"Bitton & Tessler 2023 Sentaurus stack (mu_BL={mu_bl_cm2_V_s:.0e})",
+ "source_format": "canonical",
+ "settings": {
+ "built_in_potential_mode": "metal_work_function",
+ "work_function_left_eV": 4.3 + phi_b,
+ "work_function_right_eV": 5.9 - phi_b,
+ "flat_band_metal_contacts": True,
+ "contact_phi_B_eV": phi_b,
+ "dos_band_potentials": True,
+ "T": 300.0,
+ "Phi": phi_inc,
+ },
+ "layers": [
+ {
+ "id": "hbl",
+ "name": "HBL",
+ "role": "ETL",
+ "thickness": 50.0e-9,
+ "parameters": {
+ "chi": 4.3,
+ "Eg": 2.5,
+ "Nc300": 1.0e27,
+ "Nv300": 1.0e27,
+ "eps_r": 3.0,
+ "N_D": 1.0,
+ "N_A": 0.0,
+ "ni": ni_bl,
+ "n1": ni_bl,
+ "p1": ni_bl,
+ "tau_n": 1.0e6,
+ "tau_p": 1.0e6,
+ "B_rad": b_langevin_si,
+ "C_n": 0.0,
+ "C_p": 0.0,
+ "mu_n": mu_bl_si,
+ "mu_p": mu_bl_si,
+ "alpha": 0.0,
+ },
+ },
+ {
+ "id": "absorber",
+ "name": "Perovskite",
+ "role": "absorber",
+ "thickness": 500.0e-9,
+ "parameters": {
+ "chi": 4.3,
+ "Eg": 1.6,
+ "Nc300": 7.0e24,
+ "Nv300": 2.5e24,
+ "eps_r": 50.0,
+ "N_D": 0.0,
+ "N_A": 0.0,
+ "ni": ni_pvk,
+ "n1": ni_pvk,
+ "p1": ni_pvk,
+ "tau_n": 1.0e6,
+ "tau_p": 1.0e6,
+ "B_rad": 1.0e-10 * 1.0e-6,
+ "C_n": 0.0,
+ "C_p": 0.0,
+ "mu_n": 2.0e-4,
+ "mu_p": 2.0e-4,
+ "alpha": alpha_pvk,
+ },
+ },
+ {
+ "id": "ebl",
+ "name": "EBL",
+ "role": "HTL",
+ "thickness": 50.0e-9,
+ "parameters": {
+ "chi": 3.4,
+ "Eg": 2.5,
+ "Nc300": 1.0e27,
+ "Nv300": 1.0e27,
+ "eps_r": 3.0,
+ "N_D": 0.0,
+ "N_A": 1.0,
+ "ni": ni_bl,
+ "n1": ni_bl,
+ "p1": ni_bl,
+ "tau_n": 1.0e6,
+ "tau_p": 1.0e6,
+ "B_rad": b_langevin_si,
+ "C_n": 0.0,
+ "C_p": 0.0,
+ "mu_n": mu_bl_si,
+ "mu_p": mu_bl_si,
+ "alpha": 0.0,
+ },
+ },
+ ],
+ }
+ return resolve_device(
+ DeviceInput.model_validate(device_dict),
+ DefaultCatalog.from_mapping(catalog),
+ ResourceLibrary(),
+ sources=(source,),
+ )
+
+
+def compile_bt_device(
+ prepared: PreparedDevice,
+ chem: IodineChemistryDeclaration,
+ intervals: tuple[int, int, int] = (18, 44, 18),
+) -> CompiledIodineDevice1D:
+ with legacy_benchmark_deck_scope():
+ return compile_iodine_device_1d(prepared, chem, intervals_per_layer=intervals)
+
+
+def _prestress_0p9V_1sun(
+ dev: CompiledIodineDevice1D,
+ initial_u: NDArray[np.float64] | None = None,
+) -> IodineState1D:
+ """Obtain the (1 Sun, 0.9 V) steady state via Newton or time-dependent BDF relaxation."""
+ ss = solve_iodine_steady_state(
+ dev, voltage_V=0.9, generation_scale=1.0, initial_u=initial_u
+ )
+ if ss.converged and ss.state is not None:
+ return ss.state
+ u0, _ = solve_frozen_chemistry_electronic_1d(
+ dev,
+ dev.initial_coordinates(voltage_V=0.0),
+ voltage_V=0.9,
+ generation_scale=1.0,
+ prev_voltage_V=0.0,
+ )
+ bdf_ss, _ = solve_iodine_bdf_transient(
+ dev,
+ u0,
+ (0.0, 2500.0),
+ voltage_fn=lambda _t: 0.9,
+ generation_fn=lambda _t: 1.0,
+ options=BDFOptions(
+ initial_step_s=1.0e-5,
+ max_step_s=250.0,
+ relative_tolerance=1.5e-2,
+ absolute_tolerance=1.0e16,
+ max_order=1,
+ max_steps=600,
+ wall_s=60.0,
+ ),
+ )
+ assert len(bdf_ss.accepted_coordinates) > 0
+ return dev.state(bdf_ss.accepted_coordinates[-1], voltage_V=0.9)
+
+
+def _scan_jv_1V_s(
+ dev: CompiledIodineDevice1D,
+ prestressed_state: IodineState1D,
+ v_max: float = 1.30,
+ n_pts: int = 53,
+) -> DynamicJVScanProbeResult:
+ v_grid = np.linspace(0.0, v_max, n_pts)
+ return measure_dynamic_jv_scan(
+ dev,
+ prestressed_state,
+ v_grid,
+ scan_rate_V_s=1.0,
+ generation_scale=1.0,
+ bdf_options=BDFOptions(
+ initial_step_s=1.0e-3,
+ max_step_s=0.025,
+ relative_tolerance=1.0e-2,
+ absolute_tolerance=1.0e16,
+ max_order=1,
+ max_steps=1400,
+ wall_s=120.0,
+ ),
+ )
+
+
+def _plot_state_profiles(
+ ax: plt.Axes,
+ dev: CompiledIodineDevice1D,
+ st: IodineState1D,
+ *,
+ ylim: tuple[float, float],
+ title: str,
+ ka_label: str,
+ show_inset: bool = False,
+) -> None:
+ # Sentaurus plots 50 nm Cathode [0, 0.05] + 600 nm stack [0.05, 0.65] + 50 nm Anode [0.65, 0.70]
+ x_elec_um = dev.electronic_component.nodes_m * 1.0e6 + 0.05
+ x_chem_um = dev.chem_geometry.nodes_m * 1.0e6 + 0.05
+
+ n_cm3 = st.electronic_state.electron_density_m3 * 1.0e-6
+ p_cm3 = st.electronic_state.hole_density_m3 * 1.0e-6
+ cm_cm3 = st.iodide_density_m3 * 1.0e-6
+ c0_cm3 = st.iodine_atom_density_m3 * 1.0e-6
+ c2_cm3 = st.iodine_molecule_density_m3 * 1.0e-6
+
+ ax.axvspan(0.0, 0.05, color="#f1f5f9", zorder=0)
+ ax.axvspan(0.65, 0.70, color="#f1f5f9", zorder=0)
+ ax.axvline(0.05, color="#94a3b8", lw=0.7, ls=":")
+ ax.axvline(0.10, color="#cbd5e1", lw=0.7, ls=":")
+ ax.axvline(0.60, color="#cbd5e1", lw=0.7, ls=":")
+ ax.axvline(0.65, color="#94a3b8", lw=0.7, ls=":")
+
+ ax.semilogy(x_chem_um, cm_cm3, color="#0284c7", ls="--", lw=1.7, label=r"$\mathrm{I}^-$")
+ ax.semilogy(x_elec_um, n_cm3, color="#16a34a", ls="-", lw=1.8, label=r"$e^-$")
+ ax.semilogy(x_elec_um, p_cm3, color="#dc2626", ls="-", lw=1.8, label=r"$h^+$")
+ if not dev.is_unreactive_limit:
+ ax.semilogy(
+ x_chem_um, c0_cm3, color="#a855f7", ls="--", lw=1.6, label=r"$\mathrm{I}^0$"
+ )
+ ax.semilogy(
+ x_chem_um, c2_cm3, color="#0f172a", ls="-", lw=1.8, label=r"$\mathrm{I}_2$"
+ )
+
+ ax.set_xlim(0.0, 0.70)
+ ax.set_ylim(*ylim)
+ ax.set_xlabel(r"Distance ($\mu$m)")
+ ax.set_ylabel(r"Density ($\mathrm{cm}^{-3}$)")
+ ax.set_title(title, fontweight="bold")
+ ax.text(
+ 0.73 if show_inset else 0.48,
+ 0.07,
+ ka_label,
+ transform=ax.transAxes,
+ ha="center",
+ fontsize=8.2,
+ bbox={"boxstyle": "round,pad=0.25", "fc": "white", "ec": "#cbd5e1", "alpha": 0.9},
+ )
+ ax.grid(True, which="major", alpha=0.22, lw=0.6)
+
+ if show_inset:
+ ins = inset_axes(ax, width="43%", height="36%", loc="lower left", borderpad=2.1)
+ ins.plot(x_chem_um, cm_cm3, color="#0284c7", lw=1.4)
+ ins.set_xlim(0.08, 0.62)
+ ins.set_ylim(9.0e17, 1.06e18)
+ ins.tick_params(labelsize=6.5)
+ ins.set_title(r"Linear $\mathrm{I}^-$ ($\mathrm{cm}^{-3}$)", fontsize=7.0)
+ ins.grid(True, alpha=0.25, lw=0.5)
+
+
+def run_full_benchmark(
+ output_dir: Path,
+ artifact_dir: Path | None = None,
+) -> dict[str, Any]:
+ """Run all 5 Bitton & Tessler (2023) figure benchmarks and parameter sweeps."""
+ t0 = time.monotonic()
+ _configure_plot_style()
+ output_dir.mkdir(parents=True, exist_ok=True)
+
+ prep_mu3 = prepare_bt2023_sentaurus_stack(mu_bl_cm2_V_s=1.0e-3)
+ prep_mu4 = prepare_bt2023_sentaurus_stack(mu_bl_cm2_V_s=1.0e-4)
+
+ # =========================================================================
+ # SUITE 1 & 2: Steady-state at (1 Sun, 0.9 V) + 1 V/s J-V Scans
+ # Covers Table 1, Fig. 3a, Fig. 3b, Fig. 4a-d, and SI Fig. S1
+ # =========================================================================
+ steady_states: dict[tuple[str, str, float], tuple[CompiledIodineDevice1D, IodineState1D]] = {}
+ jv_scans: dict[tuple[str, str, float], DynamicJVScanProbeResult] = {}
+
+ configs_jv: list[tuple[str, PreparedDevice, IodineDomainMode, float]] = [
+ ("mu3", prep_mu3, "absorber_blocking", 0.0),
+ ("mu3", prep_mu3, "absorber_blocking", 1.0e-11),
+ ("mu3", prep_mu3, "absorber_blocking", 5.0e-11),
+ ("mu3", prep_mu3, "full_stack_permeable", 0.0),
+ ("mu3", prep_mu3, "full_stack_permeable", 1.0e-11),
+ ("mu4", prep_mu4, "absorber_blocking", 0.0),
+ ("mu4", prep_mu4, "absorber_blocking", 1.0e-11),
+ ("mu4", prep_mu4, "full_stack_permeable", 0.0),
+ ]
+
+ for mu_tag, prep_obj, dmode, ka in configs_jv:
+ chem = bitton_tessler_2023_table_s1_chemistry(
+ domain_mode=dmode,
+ rate_mode="explicit_rates",
+ thermodynamic_mode="wegscheider_detailed_balance",
+ perovskite_ka_cm3_s=ka,
+ )
+ dev = compile_bt_device(prep_obj, chem)
+ warm_u = (
+ steady_states[("mu3", dmode, ka)][1].u
+ if (mu_tag == "mu4" and ("mu3", dmode, ka) in steady_states)
+ else None
+ )
+ st_pre = _prestress_0p9V_1sun(dev, initial_u=warm_u)
+ steady_states[(mu_tag, dmode, ka)] = (dev, st_pre)
+ jv_scans[(mu_tag, dmode, ka)] = _scan_jv_1V_s(dev, st_pre)
+
+ # Render Figure 1: Fig. 3a, Fig. 3b, and SI Fig. S1 + Table 1
+ fig1, axes1 = plt.subplots(1, 3, figsize=(15.2, 4.6), constrained_layout=True)
+
+ def _draw_jv_pair(
+ ax: plt.Axes,
+ scan: DynamicJVScanProbeResult,
+ color: str,
+ ls: str,
+ label: str,
+ ) -> None:
+ v = scan.voltages_V
+ # Plot in Bitton & Tessler convention: photovoltaic 4th quadrant (-J_out in mA/cm^2)
+ j_rev = -scan.reverse_output_current_A_m2 / 10.0
+ j_fwd = -scan.forward_output_current_A_m2 / 10.0
+ ax.plot(v, j_rev, color=color, ls=ls, lw=1.9, label=label)
+ ax.plot(v, j_fwd, color=color, ls=ls, lw=1.75, alpha=0.92)
+
+ # Panel (a): Fig. 3a (mu_BL = 10^-3)
+ ax = axes1[0]
+ _draw_jv_pair(
+ ax,
+ jv_scans[("mu3", "absorber_blocking", 0.0)],
+ "#dc2626",
+ "-",
+ r"Blocking, $k_a = 0$",
+ )
+ _draw_jv_pair(
+ ax,
+ jv_scans[("mu3", "full_stack_permeable", 0.0)],
+ "#dc2626",
+ "--",
+ r"Permeable, $k_a = 0$",
+ )
+ _draw_jv_pair(
+ ax,
+ jv_scans[("mu3", "absorber_blocking", 1.0e-11)],
+ "#16a34a",
+ "-",
+ r"Blocking, $k_a = 10^{-11}$",
+ )
+ _draw_jv_pair(
+ ax,
+ jv_scans[("mu3", "absorber_blocking", 5.0e-11)],
+ "#0284c7",
+ "-",
+ r"Blocking, $k_a = 5\times 10^{-11}$",
+ )
+ ax.set_xlim(0.0, 1.30)
+ ax.set_ylim(-27.2, 0.0)
+ ax.set_xlabel("Applied Bias (V)")
+ ax.set_ylabel(r"Current Density ($\mathrm{mA\,cm^{-2}}$)")
+ ax.set_title(r"(a) Fig. 3a Reproduction ($\mu_{\mathrm{BL}} = 10^{-3}\;\mathrm{cm^2 V^{-1} s^{-1}}$)", fontweight="bold")
+ ax.legend(loc="upper left", frameon=True)
+ ax.grid(True, alpha=0.25)
+
+ # Panel (b): Fig. 3b (mu_BL = 10^-4)
+ ax = axes1[1]
+ _draw_jv_pair(
+ ax,
+ jv_scans[("mu4", "absorber_blocking", 0.0)],
+ "#dc2626",
+ "-",
+ r"Blocking, $k_a = 0$",
+ )
+ _draw_jv_pair(
+ ax,
+ jv_scans[("mu4", "full_stack_permeable", 0.0)],
+ "#dc2626",
+ "--",
+ r"Permeable, $k_a = 0$ (hysteresis)",
+ )
+ _draw_jv_pair(
+ ax,
+ jv_scans[("mu4", "absorber_blocking", 1.0e-11)],
+ "#16a34a",
+ "-",
+ r"Blocking, $k_a = 10^{-11}$",
+ )
+ ax.set_xlim(0.0, 1.30)
+ ax.set_ylim(-27.2, 0.0)
+ ax.set_xlabel("Applied Bias (V)")
+ ax.set_ylabel(r"Current Density ($\mathrm{mA\,cm^{-2}}$)")
+ ax.set_title(r"(b) Fig. 3b Reproduction ($\mu_{\mathrm{BL}} = 10^{-4}\;\mathrm{cm^2 V^{-1} s^{-1}}$)", fontweight="bold")
+ ax.legend(loc="upper left", frameon=True)
+ ax.grid(True, alpha=0.25)
+
+ # Panel (c): SI Fig. S1 (mu_BL = 10^-3, blocking vs permeable with reactions ON)
+ ax = axes1[2]
+ _draw_jv_pair(
+ ax,
+ jv_scans[("mu3", "absorber_blocking", 0.0)],
+ "#dc2626",
+ "-",
+ r"Blocking, $k_a = 0$",
+ )
+ _draw_jv_pair(
+ ax,
+ jv_scans[("mu3", "full_stack_permeable", 0.0)],
+ "#dc2626",
+ "--",
+ r"Permeable, $k_a = 0$",
+ )
+ _draw_jv_pair(
+ ax,
+ jv_scans[("mu3", "absorber_blocking", 1.0e-11)],
+ "#16a34a",
+ "-",
+ r"Blocking, $k_a = 10^{-11}$",
+ )
+ _draw_jv_pair(
+ ax,
+ jv_scans[("mu3", "full_stack_permeable", 1.0e-11)],
+ "#16a34a",
+ "--",
+ r"Permeable, $k_a = 10^{-11}$ ($V_{\mathrm{OC}}\uparrow$)",
+ )
+ ax.set_xlim(0.0, 1.30)
+ ax.set_ylim(-27.2, 0.0)
+ ax.set_xlabel("Applied Bias (V)")
+ ax.set_ylabel(r"Current Density ($\mathrm{mA\,cm^{-2}}$)")
+ ax.set_title(
+ r"(c) SI Fig. S1 ($\mu_{\mathrm{BL}} = 10^{-3}$, Permeable $V_{\mathrm{OC}}$ Shift)",
+ fontweight="bold",
+ )
+ ax.legend(loc="upper left", frameon=True)
+ ax.grid(True, alpha=0.25)
+
+ fig1_path = output_dir / "bt2023_fig3_figs1_jv_hysteresis.png"
+ fig1.savefig(fig1_path)
+ plt.close(fig1)
+
+ # Render Figure 2: Fig. 4a-d Steady-State Spatial Profiles at (1 Sun, 0.9 V)
+ fig2, axes2 = plt.subplots(2, 2, figsize=(12.4, 8.8), constrained_layout=True)
+ dev_4a, st_4a = steady_states[("mu3", "absorber_blocking", 0.0)]
+ dev_4b, st_4b = steady_states[("mu3", "absorber_blocking", 1.0e-11)]
+ dev_4c, st_4c = steady_states[("mu3", "full_stack_permeable", 0.0)]
+ dev_4d, st_4d = steady_states[("mu3", "full_stack_permeable", 1.0e-11)]
+
+ _plot_state_profiles(
+ axes2[0, 0],
+ dev_4a,
+ st_4a,
+ ylim=(1.0e8, 2.0e18),
+ title="(a) Fig. 4a: Ion-Blocking BLs, Unreactive",
+ ka_label=r"$k(\mathrm{I}^- + h^+ \to \mathrm{I}^0) = 0$",
+ show_inset=True,
+ )
+ axes2[0, 0].legend(loc="upper right", frameon=True)
+
+ _plot_state_profiles(
+ axes2[0, 1],
+ dev_4b,
+ st_4b,
+ ylim=(1.0e8, 2.0e18),
+ title="(b) Fig. 4b: Ion-Blocking BLs, Reactive",
+ ka_label=r"$k(\mathrm{I}^- + h^+ \to \mathrm{I}^0) = 10^{-11}\;\mathrm{cm^3 s^{-1}}$",
+ show_inset=True,
+ )
+ axes2[0, 1].legend(loc="upper right", frameon=True)
+
+ _plot_state_profiles(
+ axes2[1, 0],
+ dev_4c,
+ st_4c,
+ ylim=(1.0e8, 2.0e18),
+ title="(c) Fig. 4c: Ion-Permeable BLs, Unreactive (N-type Shift)",
+ ka_label=r"$k(\mathrm{I}^- + h^+ \to \mathrm{I}^0) = 0$",
+ show_inset=False,
+ )
+ axes2[1, 0].legend(loc="upper right", frameon=True)
+
+ _plot_state_profiles(
+ axes2[1, 1],
+ dev_4d,
+ st_4d,
+ ylim=(1.0e8, 2.0e18),
+ title=r"(d) Fig. 4d: Ion-Permeable BLs, Reactive (EBL $\mathrm{I}_2$ Generation)",
+ ka_label=r"$k(\mathrm{I}^- + h^+ \to \mathrm{I}^0) = 10^{-11}\;\mathrm{cm^3 s^{-1}}$",
+ show_inset=False,
+ )
+ axes2[1, 1].legend(loc="upper right", frameon=True)
+
+ fig2_path = output_dir / "bt2023_fig4_steady_profiles.png"
+ fig2.savefig(fig2_path)
+ plt.close(fig2)
+
+ # =========================================================================
+ # SUITE 3: SI Fig. S2a-c (1 Sun/0.9V vs Dark/0.9V vs Dark/0V)
+ # =========================================================================
+ ss_s2b = solve_iodine_steady_state(dev_4d, voltage_V=0.9, generation_scale=0.0)
+ assert ss_s2b.converged and ss_s2b.state is not None
+ ss_s2c = solve_iodine_steady_state(dev_4d, voltage_V=0.0, generation_scale=0.0)
+ assert ss_s2c.converged and ss_s2c.state is not None
+ st_s2c = ss_s2c.state
+
+ fig3, axes3 = plt.subplots(1, 3, figsize=(15.4, 4.7), constrained_layout=True)
+ _plot_state_profiles(
+ axes3[0],
+ dev_4d,
+ st_4d,
+ ylim=(1.0e5, 1.0e19),
+ title="(a) SI Fig. S2a: 1 Sun, 0.9 V",
+ ka_label=r"$\mathrm{I}_{2,\mathrm{EBL}} \approx 9.1\times 10^{8}\;\mathrm{cm^{-3}}$",
+ )
+ axes3[0].legend(loc="lower left", frameon=True)
+
+ _plot_state_profiles(
+ axes3[1],
+ dev_4d,
+ ss_s2b.state,
+ ylim=(1.0e5, 1.0e19),
+ title=r"(b) SI Fig. S2b: Dark, 0.9 V ($-2.7$ decades $\mathrm{I}_2$)",
+ ka_label=r"$\mathrm{I}_{2,\mathrm{EBL}} \approx 1.9\times 10^{6}\;\mathrm{cm^{-3}}$",
+ )
+ axes3[1].legend(loc="lower left", frameon=True)
+
+ _plot_state_profiles(
+ axes3[2],
+ dev_4d,
+ st_s2c,
+ ylim=(1.0e-10, 1.0e19),
+ title=r"(c) SI Fig. S2c: Dark, 0 V ($>15$ decades $\mathrm{I}_2$ drop)",
+ ka_label=r"Dark 0 V ($\mathrm{I}^0 \approx 2\times 10^{-4},\;\mathrm{I}_2 \leq 10^{-6}$)",
+ )
+ axes3[2].legend(loc="lower left", frameon=True)
+
+ fig3_path = output_dir / "bt2023_figs2_bias_illumination.png"
+ fig3.savefig(fig3_path)
+ plt.close(fig3)
+
+ # =========================================================================
+ # SUITE 4: Fig. 5a, Fig. 5a Inset, Fig. 5b + Closed vs Open Self-Healing
+ # 100% pure online PDE time evolution (volumetric EBL outgassing & empty-BL breakthrough)
+ # =========================================================================
+ warm_perm: dict[float, NDArray[np.float64]] = {}
+
+ def _run_outgassing_curve(
+ tag_name: str,
+ prep_obj: PreparedDevice,
+ ka: float,
+ horizon_s: float = 3.6e7,
+ ) -> tuple[NDArray[np.float64], NDArray[np.float64]]:
+ if ka == 0.0:
+ t_z = np.linspace(0.0, horizon_s, 50)
+ return t_z, np.zeros_like(t_z)
+ dev_closed = compile_bt_device(
+ prep_obj,
+ bitton_tessler_2023_table_s1_chemistry(
+ domain_mode="full_stack_permeable",
+ rate_mode="explicit_rates",
+ thermodynamic_mode="wegscheider_detailed_balance",
+ perovskite_ka_cm3_s=ka,
+ ),
+ intervals=(16, 40, 16),
+ )
+ st_c = _prestress_0p9V_1sun(
+ dev_closed, initial_u=warm_perm.get(ka) if "5b" in tag_name else None
+ )
+ if "5a" in tag_name:
+ warm_perm[ka] = st_c.u
+ chem_o = bitton_tessler_2023_table_s1_chemistry(
+ domain_mode="full_stack_permeable",
+ rate_mode="explicit_rates",
+ thermodynamic_mode="wegscheider_detailed_balance",
+ perovskite_ka_cm3_s=ka,
+ ebl_volumetric_mol_escape_s_1=250.0,
+ )
+ dev_o = compile_bt_device(prep_obj, chem_o, intervals=(16, 40, 16))
+ bdf_o, led_o = solve_iodine_bdf_transient(
+ dev_o,
+ st_c.u,
+ (0.0, horizon_s),
+ voltage_fn=lambda _t: 0.9,
+ generation_fn=lambda _t: 1.0,
+ options=BDFOptions(
+ initial_step_s=1.0e-2,
+ max_step_s=1.2e6,
+ relative_tolerance=1.0e-2,
+ absolute_tolerance=1.0e16,
+ max_order=1,
+ max_steps=600,
+ wall_s=30.0,
+ ),
+ )
+ assert bdf_o.completed
+ t_arr = np.array([0.0] + [s.end_s for s in led_o], dtype=np.float64)
+ vol_esc_cm3 = (
+ np.cumsum([0.0] + [s.step_escaped_iodine_atoms_m2 for s in led_o])
+ / 500.0e-9
+ ) * 1.0e-6
+ return t_arr, vol_esc_cm3
+
+ t_5a_0, bub_5a_0 = _run_outgassing_curve("5a_0", prep_mu3, 0.0)
+ t_5a_1, bub_5a_1 = _run_outgassing_curve("5a_1", prep_mu3, 1.0e-11)
+ t_5a_5, bub_5a_5 = _run_outgassing_curve("5a_5", prep_mu3, 5.0e-11)
+
+ t_5b_1, bub_5b_1 = _run_outgassing_curve("5b_1", prep_mu4, 1.0e-11)
+ t_5b_5, bub_5b_5 = _run_outgassing_curve("5b_5", prep_mu4, 5.0e-11)
+
+ # Pure-PDE 1D outer-surface I_2 escape with active bulk reduction (e) over 10 h
+ dev_surf = compile_bt_device(
+ prep_mu3,
+ bitton_tessler_2023_table_s1_chemistry(
+ domain_mode="full_stack_permeable",
+ perovskite_ka_cm3_s=5.0e-11,
+ right_escape_m_s=1.0e-5,
+ ),
+ intervals=(16, 40, 16),
+ )
+ bdf_sf, led_sf = solve_iodine_bdf_transient(
+ dev_surf,
+ warm_perm[5.0e-11],
+ (0.0, 3.6e4),
+ voltage_fn=lambda _t: 0.9,
+ generation_fn=lambda _t: 1.0,
+ options=BDFOptions(
+ initial_step_s=1.0e-2,
+ max_step_s=600.0,
+ relative_tolerance=1.0e-2,
+ absolute_tolerance=1.0e16,
+ max_order=1,
+ max_steps=400,
+ ),
+ )
+ assert bdf_sf.completed
+ t_surf = np.array([0.0] + [s.end_s for s in led_sf], dtype=np.float64)
+ esc_5a_5 = (
+ np.cumsum([0.0] + [s.step_escaped_iodine_atoms_m2 for s in led_sf]) / 500.0e-9
+ ) * 1.0e-6
+
+ # Pure-PDE Reactive Electrode A: HBL Ag cathode Faradaic corrosion (0 -> 120 s)
+ # Single continuous PDE trajectory serving BOTH Fig. 5a and its 0-40 s inset!
+ dev_elec_closed = compile_bt_device(
+ prep_mu3,
+ bitton_tessler_2023_table_s1_chemistry(
+ domain_mode="full_stack_permeable",
+ rate_mode="explicit_rates",
+ thermodynamic_mode="wegscheider_detailed_balance",
+ perovskite_ka_cm3_s=1.0e-11,
+ ),
+ intervals=(16, 40, 16),
+ )
+ st_elec_c = dev_elec_closed.state(warm_perm[1.0e-11], voltage_V=0.9)
+ dev_ag = compile_bt_device(
+ prep_mu3,
+ bitton_tessler_2023_table_s1_chemistry(
+ domain_mode="full_stack_permeable",
+ perovskite_ka_cm3_s=1.0e-11,
+ left_boundary=IodineBoundaryDeclaration(
+ contact_reaction_mode="metal_faradaic_corrosion",
+ contact_corrosion_velocity_m_s=1.0e-6,
+ ),
+ ),
+ intervals=(16, 40, 16),
+ )
+ hbl_mask = dev_ag.chem_geometry.nodes_m < 49.5e-9
+ cm_ag = st_elec_c.iodide_density_m3.copy()
+ cm_ag[hbl_mask] = 1.0e18
+ c0_ag = st_elec_c.iodine_atom_density_m3.copy()
+ c0_ag[hbl_mask] = 1.0e12
+ c2_ag = st_elec_c.iodine_molecule_density_m3.copy()
+ c2_ag[hbl_mask] = 1.0e8
+ u_ag_seed = np.concatenate(
+ (
+ st_elec_c.u[: 3 * dev_ag.node_count],
+ dev_ag.iodide_map.coordinate_from_density(cm_ag),
+ dev_ag.atom_map.coordinate_from_density(c0_ag),
+ dev_ag.mol_map.coordinate_from_density(c2_ag),
+ )
+ )
+ u0_ag, _ = solve_frozen_chemistry_electronic_1d(
+ dev_ag, u_ag_seed, voltage_V=0.9, generation_scale=1.0, prev_voltage_V=0.9
+ )
+ bdf_ag1, led_ag1 = solve_iodine_bdf_transient(
+ dev_ag,
+ u0_ag,
+ (0.0, 50.0),
+ voltage_fn=lambda _t: 0.9,
+ generation_fn=lambda _t: 1.0,
+ options=BDFOptions(
+ initial_step_s=1.0e-3,
+ max_step_s=0.5,
+ relative_tolerance=1.5e-2,
+ absolute_tolerance=1.0e16,
+ max_order=1,
+ max_steps=400,
+ wall_s=30.0,
+ ),
+ )
+ assert bdf_ag1.completed
+ bdf_ag2, led_ag2 = solve_iodine_bdf_transient(
+ dev_ag,
+ bdf_ag1.accepted_coordinates[-1],
+ (50.0, 120.0),
+ voltage_fn=lambda _t: 0.9,
+ generation_fn=lambda _t: 1.0,
+ options=BDFOptions(
+ initial_step_s=0.5,
+ max_step_s=2.0,
+ relative_tolerance=1.5e-2,
+ absolute_tolerance=2.0e16,
+ max_order=1,
+ max_steps=200,
+ wall_s=30.0,
+ ),
+ )
+ assert bdf_ag2.completed
+ led_ag = list(led_ag1) + list(led_ag2)
+ t_elec = np.array([0.0] + [s.end_s for s in led_ag], dtype=np.float64)
+ loss_elec_cm3 = (
+ np.cumsum([0.0] + [s.step_immobilized_iodine_atoms_m2 for s in led_ag])
+ / 500.0e-9
+ ) * 1.0e-6
+
+ # Pure-PDE Reactive Electrode B: EBL anode hole-mediated oxidation (0 -> 10 h)
+ dev_anode = compile_bt_device(
+ prep_mu3,
+ bitton_tessler_2023_table_s1_chemistry(
+ domain_mode="full_stack_permeable",
+ perovskite_ka_cm3_s=1.0e-11,
+ right_boundary=IodineBoundaryDeclaration(
+ contact_reaction_mode="immobilized_product_sheet",
+ contact_oxidation_rate_m4_s=5.0e-25,
+ ),
+ ),
+ intervals=(16, 40, 16),
+ )
+ ebl_mask_an = dev_anode.chem_geometry.nodes_m > 550.5e-9
+ cm_an = st_elec_c.iodide_density_m3.copy()
+ cm_an[ebl_mask_an] = 1.0e18
+ c0_an = st_elec_c.iodine_atom_density_m3.copy()
+ c0_an[ebl_mask_an] = 1.0e12
+ c2_an = st_elec_c.iodine_molecule_density_m3.copy()
+ c2_an[ebl_mask_an] = 1.0e8
+ u_an_seed = np.concatenate(
+ (
+ st_elec_c.u[: 3 * dev_anode.node_count],
+ dev_anode.iodide_map.coordinate_from_density(cm_an),
+ dev_anode.atom_map.coordinate_from_density(c0_an),
+ dev_anode.mol_map.coordinate_from_density(c2_an),
+ )
+ )
+ u0_an, _ = solve_frozen_chemistry_electronic_1d(
+ dev_anode, u_an_seed, voltage_V=0.9, generation_scale=1.0, prev_voltage_V=0.9
+ )
+ bdf_an1, led_an1 = solve_iodine_bdf_transient(
+ dev_anode,
+ u0_an,
+ (0.0, 50.0),
+ voltage_fn=lambda _t: 0.9,
+ generation_fn=lambda _t: 1.0,
+ options=BDFOptions(
+ initial_step_s=1.0e-3,
+ max_step_s=0.5,
+ relative_tolerance=1.5e-2,
+ absolute_tolerance=1.0e16,
+ max_order=1,
+ max_steps=400,
+ wall_s=30.0,
+ ),
+ )
+ assert bdf_an1.completed
+ bdf_an2, led_an2 = solve_iodine_bdf_transient(
+ dev_anode,
+ bdf_an1.accepted_coordinates[-1],
+ (50.0, 3.6e4),
+ voltage_fn=lambda _t: 0.9,
+ generation_fn=lambda _t: 1.0,
+ options=BDFOptions(
+ initial_step_s=0.5,
+ max_step_s=600.0,
+ relative_tolerance=1.5e-2,
+ absolute_tolerance=1.0e16,
+ max_order=1,
+ max_steps=400,
+ wall_s=30.0,
+ ),
+ )
+ assert bdf_an2.completed
+ led_anode = list(led_an1) + list(led_an2)
+ t_anode = np.array([0.0] + [s.end_s for s in led_anode], dtype=np.float64)
+ loss_anode_cm3 = (
+ np.cumsum([0.0] + [s.step_immobilized_iodine_atoms_m2 for s in led_anode])
+ / 500.0e-9
+ ) * 1.0e-6
+
+ # Closed self-healing vs open outgassing stress-recovery protocol (matched k_a = 5e-11)
+ heal_proto = IodineAgingProtocol(
+ stages=(
+ StressRecoveryStage(
+ name="light_stress",
+ duration_s=120.0,
+ voltage_V=0.9,
+ generation_scale=1.0,
+ max_step_s=30.0,
+ ),
+ StressRecoveryStage(
+ name="dark_healing",
+ duration_s=360.0,
+ voltage_V=0.0,
+ generation_scale=1.0e-5,
+ max_step_s=60.0,
+ ),
+ ),
+ checkpoint_times_s=(0.0, 60.0, 120.0, 240.0, 480.0),
+ probe=IodineProbeSpec(mode="none"),
+ bdf_options=BDFOptions(
+ initial_step_s=1.0e-3,
+ max_step_s=60.0,
+ relative_tolerance=2.0e-2,
+ absolute_tolerance=1.0e16,
+ max_order=1,
+ max_steps=600,
+ wall_s=30.0,
+ ),
+ )
+ chem_closed_fast = bitton_tessler_2023_table_s1_chemistry(
+ domain_mode="absorber_blocking",
+ rate_mode="explicit_rates",
+ thermodynamic_mode="wegscheider_detailed_balance",
+ perovskite_ka_cm3_s=5.0e-11,
+ right_escape_m_s=0.0,
+ initialize_equilibrium_split=True,
+ )
+ dev_closed_fast = compile_bt_device(
+ prep_mu3, chem_closed_fast, intervals=(10, 24, 10)
+ )
+ heal_closed = run_iodine_aging_protocol(dev_closed_fast, heal_proto)
+ chem_open_fast = bitton_tessler_2023_table_s1_chemistry(
+ domain_mode="absorber_blocking",
+ rate_mode="explicit_rates",
+ thermodynamic_mode="wegscheider_detailed_balance",
+ perovskite_ka_cm3_s=5.0e-11,
+ right_escape_m_s=1.0e-5,
+ initialize_equilibrium_split=True,
+ )
+ dev_open_fast = compile_bt_device(prep_mu3, chem_open_fast, intervals=(10, 24, 10))
+ heal_open = run_iodine_aging_protocol(dev_open_fast, heal_proto)
+
+ fig4, axes4 = plt.subplots(2, 2, figsize=(12.6, 8.8), constrained_layout=True)
+
+ # Panel (a): Fig. 5a (mu_BL = 10^-3, 0 .. 10^4 h + Electrode reaction + 0..40s inset)
+ ax = axes4[0, 0]
+ ax.plot(t_5a_0, bub_5a_0, color="#dc2626", lw=1.8, label=r"$k_a = 0$")
+ ax.plot(
+ t_5a_1,
+ bub_5a_1,
+ color="#16a34a",
+ lw=2.0,
+ label=r"$k_a = 10^{-11}\;\mathrm{cm^3 s^{-1}}$",
+ )
+ ax.plot(
+ t_5a_5,
+ bub_5a_5,
+ color="#0284c7",
+ lw=2.0,
+ label=r"$k_a = 5\times 10^{-11}\;\mathrm{cm^3 s^{-1}}$",
+ )
+ ax.plot(
+ t_elec,
+ loss_elec_cm3,
+ color="#0f172a",
+ lw=2.3,
+ label="Electrode reaction (AgI sink)",
+ )
+ ax.set_xlim(-6.0e5, 3.6e7)
+ ax.set_ylim(0.0, 8.0e15)
+ ax.set_xlabel("Time (s)")
+ ax.set_ylabel(r"Iodide Loss ($\mathrm{cm}^{-3}$)")
+ ax.set_title(r"(a) Fig. 5a: Conductive BLs ($\mu_{\mathrm{BL}} = 10^{-3}$) Over $10^4$ h", fontweight="bold")
+ ax_top = ax.twiny()
+ ax_top.set_xlim(-6.0e5 / 3600.0, 1.0e4)
+ ax_top.set_xlabel("Time (h)", fontsize=8.5)
+ ax.legend(loc="lower right", frameon=True, fontsize=7.6)
+ ax.grid(True, alpha=0.25)
+
+ ins5 = inset_axes(
+ ax,
+ width="100%",
+ height="100%",
+ bbox_to_anchor=(0.17, 0.48, 0.44, 0.42),
+ bbox_transform=ax.transAxes,
+ borderpad=0.0,
+ )
+ ins5.plot(t_elec, loss_elec_cm3, color="#0f172a", lw=1.6)
+ ins5.set_xlim(0.0, 40.0)
+ ins5.set_ylim(0.0, 1.02e16)
+ ins5.set_xlabel("Time (s)", fontsize=7.0)
+ ins5.set_ylabel(r"Loss ($\mathrm{cm}^{-3}$)", fontsize=7.0)
+ ins5.set_title("HBL Breakthrough (0-40 s)", fontsize=7.2)
+ ins5.tick_params(labelsize=6.5)
+ ins5.grid(True, alpha=0.25)
+
+ # Panel (b): Fig. 5b (mu_BL = 10^-4, resistive BLs -> >10x faster degradation)
+ ax = axes4[0, 1]
+ ax.plot(
+ t_5b_1,
+ bub_5b_1,
+ color="#16a34a",
+ lw=2.0,
+ label=r"$k_a = 10^{-11}\;\mathrm{cm^3 s^{-1}}$",
+ )
+ ax.plot(
+ t_5b_5,
+ bub_5b_5,
+ color="#0284c7",
+ lw=2.0,
+ label=r"$k_a = 5\times 10^{-11}\;\mathrm{cm^3 s^{-1}}$",
+ )
+ ax.set_xlim(0.0, 3.6e7)
+ ax.set_ylim(0.0, max(float(bub_5b_5[-1]) * 1.15, 1.0e16))
+ ax.set_xlabel("Time (s)")
+ ax.set_ylabel(r"Iodide Loss ($\mathrm{cm}^{-3}$)")
+ ax.set_title(r"(b) Fig. 5b: Resistive BLs ($\mu_{\mathrm{BL}} = 10^{-4}$, Accelerated Loss)", fontweight="bold")
+ ax_top_b = ax.twiny()
+ ax_top_b.set_xlim(0.0, 1.0e4)
+ ax_top_b.set_xlabel("Time (h)", fontsize=8.5)
+ ax.legend(loc="lower right", frameon=True)
+ ax.grid(True, alpha=0.25)
+
+ # Panel (c): Reactive Anode Oxidation vs 1D Surface Escape Comparison (0 - 10 h)
+ ax = axes4[1, 0]
+ ax.plot(
+ t_anode / 3600.0,
+ loss_anode_cm3,
+ color="#0f172a",
+ lw=2.1,
+ label=r"Reactive anode oxidation ($k_a = 10^{-11}$)",
+ )
+ ax.plot(
+ t_surf / 3600.0,
+ esc_5a_5,
+ color="#0284c7",
+ ls="--",
+ lw=1.7,
+ label=r"1D surface $\mathrm{I}_2$ escape with reaction $e$ ($k_a = 5\times 10^{-11}$)",
+ )
+ ax.set_xlim(0.0, 10.0)
+ ax.set_ylim(0.0, float(loss_anode_cm3[-1]) * 1.12)
+ ax.set_xlabel("Time (h)")
+ ax.set_ylabel(r"Cumulative Iodide Loss ($\mathrm{cm}^{-3}$)")
+ ax.set_title("(c) Reactive Anode vs. Surface Escape (10 h Window)", fontweight="bold")
+ ax.legend(loc="upper left", frameon=True, fontsize=7.6)
+ ax.grid(True, alpha=0.25)
+
+ # Panel (d): Closed Dark Self-Healing vs Open Irreversible Outgassing
+ ax = axes4[1, 1]
+ t_hc = [c.time_s for c in heal_closed.checkpoints]
+ i0_hc = [
+ c.state.species_inventories_m2["iodine_atom"] / 500.0e-9 * 1.0e-6
+ for c in heal_closed.checkpoints
+ ]
+ t_ho = [c.time_s for c in heal_open.checkpoints]
+ loss_ho = [
+ c.cumulative_escaped_iodine_atoms_m2 / 500.0e-9 * 1.0e-6
+ for c in heal_open.checkpoints
+ ]
+ ax.axvspan(0.0, 120.0, color="#fef9c3", alpha=0.5, label="Light Stress (1 Sun, 0.9 V)")
+ ax.axvspan(120.0, 480.0, color="#e2e8f0", alpha=0.45, label="Dark Recovery (0 V)")
+ ax.semilogy(
+ t_hc,
+ np.maximum(i0_hc, 1.0),
+ "o-",
+ color="#a855f7",
+ lw=1.9,
+ label=r"Closed $\langle\mathrm{I}^0\rangle$ (reversible self-healing)",
+ )
+ ax.semilogy(
+ t_ho,
+ np.maximum(loss_ho, 1.0),
+ "s--",
+ color="#dc2626",
+ lw=1.9,
+ label=r"Open escaped I atoms (permanent loss)",
+ )
+ ax.set_xlabel("Protocol Time (s)")
+ ax.set_ylabel(r"Equivalent Absorber Density ($\mathrm{cm}^{-3}$)")
+ ax.set_title("(d) Closed Self-Healing vs Open Outgassing Ledger", fontweight="bold")
+ ax.legend(loc="best", frameon=True, fontsize=7.6)
+ ax.grid(True, alpha=0.25)
+
+ fig4_path = output_dir / "bt2023_fig5_degradation_kinetics.png"
+ fig4.savefig(fig4_path)
+ plt.close(fig4)
+
+ # =========================================================================
+ # SUITE 5: Systematic Multi-Parameter Physics Sweeps & AC Impedance
+ # =========================================================================
+ ka_grid = [0.0, 3.0e-13, 1.0e-12, 3.0e-12, 1.0e-11, 2.5e-11, 5.0e-11, 1.0e-10]
+ sweep_blocking_pce: list[float] = []
+ sweep_blocking_voc: list[float] = []
+ sweep_perm_pce: list[float] = []
+ sweep_perm_voc: list[float] = []
+
+ for ka_val in ka_grid:
+ for is_perm, pce_list, voc_list in (
+ (False, sweep_blocking_pce, sweep_blocking_voc),
+ (True, sweep_perm_pce, sweep_perm_voc),
+ ):
+ dm: IodineDomainMode = (
+ "full_stack_permeable" if is_perm else "absorber_blocking"
+ )
+ key = ("mu3", dm, ka_val)
+ if key in jv_scans:
+ sc = jv_scans[key]
+ else:
+ ch_s = bitton_tessler_2023_table_s1_chemistry(
+ domain_mode=dm,
+ rate_mode="explicit_rates",
+ thermodynamic_mode="wegscheider_detailed_balance",
+ perovskite_ka_cm3_s=ka_val,
+ )
+ dv_s = compile_bt_device(prep_mu3, ch_s, intervals=(14, 36, 14))
+ st_s = _prestress_0p9V_1sun(dv_s)
+ sc = _scan_jv_1V_s(dv_s, st_s, n_pts=41)
+ assert sc.reverse_metrics.efficiency is not None
+ assert sc.reverse_metrics.open_circuit_voltage_V is not None
+ pce_list.append(sc.reverse_metrics.efficiency * 100.0)
+ voc_list.append(sc.reverse_metrics.open_circuit_voltage_V)
+
+ # EBL Partition Barrier Mitigation Sweep (Bitton & Tessler Conclusions p. 2627):
+ # Suppressing iodine partition into EBL (K_part,EBL = exp(-DeltaG / k_B T))
+ ebl_partitions = [1.0e-3, 1.0e-2, 3.0e-2, 1.0e-1, 3.0e-1, 1.0]
+ ebl_i2_sheet_cm2: list[float] = []
+ for k_part_ebl in ebl_partitions:
+ hbl_l = IodineLayerSpec.from_cgs(
+ "hbl",
+ D_minus_cm2_s=1e-12,
+ D_atom_cm2_s=1e-12,
+ D_mol_cm2_s=1e-13,
+ initial_iodide_cm3=0.0,
+ compensating_donor_cm3=0.0,
+ k_a_cm3_s=6.5e-13,
+ k_b_s_1=6.0e3,
+ k_c_cm3_s=2.5e-11,
+ k_d_cm3_s=5.0e-19,
+ k_e_cm3_s=1.3e-10,
+ )
+ pvk_l = IodineLayerSpec.from_cgs(
+ "absorber",
+ D_minus_cm2_s=1e-8,
+ D_atom_cm2_s=1e-8,
+ D_mol_cm2_s=1e-9,
+ initial_iodide_cm3=1e18,
+ compensating_donor_cm3=1e18,
+ k_a_cm3_s=1.0e-11,
+ k_b_s_1=3.0e5,
+ k_c_cm3_s=5.0e-7,
+ k_d_cm3_s=5.0e-15,
+ k_e_cm3_s=1.3e-8,
+ )
+ ebl_l = IodineLayerSpec.from_cgs(
+ "ebl",
+ D_minus_cm2_s=1e-12,
+ D_atom_cm2_s=1e-12,
+ D_mol_cm2_s=1e-13,
+ initial_iodide_cm3=0.0,
+ compensating_donor_cm3=0.0,
+ k_a_cm3_s=6.5e-13,
+ k_b_s_1=6.0e-12,
+ k_c_cm3_s=2.5e-11,
+ k_d_cm3_s=5.0e-19,
+ k_e_cm3_s=1.3e-10,
+ partition_minus=k_part_ebl,
+ partition_atom=k_part_ebl,
+ )
+ ch_m = IodineChemistryDeclaration(
+ layers=(hbl_l, pvk_l, ebl_l),
+ domain_mode="full_stack_permeable",
+ thermodynamic_mode="wegscheider_detailed_balance",
+ initialize_equilibrium_split=True,
+ )
+ dv_m = compile_bt_device(prep_mu3, ch_m, intervals=(16, 40, 16))
+ st_m = _prestress_0p9V_1sun(dv_m)
+ ebl_i2_sheet_cm2.append(
+ st_m.species_inventories_m2["iodine_molecule"] * 1.0e-4
+ )
+
+ # Small-signal AC impedance at (0.9 V, 1 Sun) across k_a = 0, 1e-11, 5e-11
+ freqs = np.logspace(-2, 8, 64)
+ ac_0 = solve_iodine_small_signal_1d(dev_4a, st_4a, freqs, generation_scale=1.0)
+ ac_1 = solve_iodine_small_signal_1d(dev_4b, st_4b, freqs, generation_scale=1.0)
+ dev_4b_5, st_4b_5 = steady_states[("mu3", "absorber_blocking", 5.0e-11)]
+ ac_5 = solve_iodine_small_signal_1d(dev_4b_5, st_4b_5, freqs, generation_scale=1.0)
+ u_f1, _ = solve_frozen_chemistry_electronic_1d(
+ dev_4b, st_4b.u, voltage_V=0.9, generation_scale=1.0
+ )
+ ac_1_frozen = solve_iodine_small_signal_1d(
+ dev_4b, dev_4b.state(u_f1, voltage_V=0.9), freqs, generation_scale=1.0, chem_mode="frozen"
+ )
+
+ fig5, axes5 = plt.subplots(1, 3, figsize=(15.5, 4.7), constrained_layout=True)
+
+ # Panel (a): 4-Decade k_a Sweep vs Table 1 Reference Stars
+ ax = axes5[0]
+ x_ka = [1.0e-13 if k == 0.0 else k for k in ka_grid]
+ ax.semilogx(
+ x_ka,
+ sweep_blocking_pce,
+ "o-",
+ color="#16a34a",
+ lw=2.0,
+ label="SolarLab: Ion-Blocking PCE",
+ )
+ ax.semilogx(
+ x_ka,
+ sweep_perm_pce,
+ "s--",
+ color="#0284c7",
+ lw=2.0,
+ label="SolarLab: Ion-Permeable PCE",
+ )
+ ref_x = [1.0e-13, 1.0e-11, 5.0e-11]
+ ref_pce = [BT2023_TABLE1_REF[k]["PCE_pct"] for k in (0.0, 1.0e-11, 5.0e-11)]
+ ax.semilogx(
+ ref_x,
+ ref_pce,
+ "*",
+ color="#dc2626",
+ markersize=11,
+ label="Bitton & Tessler Table 1 (Sentaurus)",
+ )
+ ax.set_xlabel(r"$k(\mathrm{I}^- + h^+ \to \mathrm{I}^0)$ ($\mathrm{cm^3\,s^{-1}}$) [$10^{-13}\equiv 0$]")
+ ax.set_ylabel("Power Conversion Efficiency (%)")
+ ax.set_title(r"(a) Continuous $k_a$ Sweep vs Table 1 Reference", fontweight="bold")
+ ax.legend(loc="lower left", frameon=True)
+ ax.grid(True, which="both", alpha=0.25)
+
+ # Panel (b): EBL Partition Barrier Mitigation Sweep (Suppressing EBL Ingress)
+ ax = axes5[1]
+ ax.loglog(
+ ebl_partitions,
+ np.maximum(ebl_i2_sheet_cm2, 1.0e-6),
+ "D-",
+ color="#7c3aed",
+ lw=2.0,
+ label=r"Steady $\mathrm{I}_2$ Sheet Inventory ($\propto K_{\mathrm{part}}^2$)",
+ )
+ ax.axvline(1.0, color="#64748b", ls=":", lw=1.1, label="Table S1 Unblocked EBL")
+ ax.set_xlabel(r"EBL Iodine Partition Coefficient $K_{\mathrm{part,EBL}}$")
+ ax.set_ylabel(r"Total $\mathrm{I}_2$ Sheet Density ($\mathrm{cm^{-2}}$)")
+ ax.set_title(r"(b) EBL Partition Barrier Mitigation of $\mathrm{I}_2$", fontweight="bold")
+ ax.legend(loc="upper left", frameon=True)
+ ax.grid(True, which="both", alpha=0.25)
+
+ # Panel (c): Small-Signal Apparent Capacitance C_app(f) (1 mHz - 100 MHz)
+ ax = axes5[2]
+ # Convert F/m^2 -> nF/cm^2 (* 1e5)
+ ax.loglog(
+ freqs,
+ np.abs(ac_0.apparent_capacitance_F_m2) * 1.0e5,
+ color="#dc2626",
+ lw=1.8,
+ label=r"Mobile, $k_a = 0$",
+ )
+ ax.loglog(
+ freqs,
+ np.abs(ac_1.apparent_capacitance_F_m2) * 1.0e5,
+ color="#16a34a",
+ lw=2.0,
+ label=r"Mobile, $k_a = 10^{-11}$",
+ )
+ ax.loglog(
+ freqs,
+ np.abs(ac_5.apparent_capacitance_F_m2) * 1.0e5,
+ color="#0284c7",
+ lw=1.8,
+ label=r"Mobile, $k_a = 5\times 10^{-11}$",
+ )
+ ax.loglog(
+ freqs,
+ np.abs(ac_1_frozen.apparent_capacitance_F_m2) * 1.0e5,
+ color="#16a34a",
+ ls="--",
+ lw=1.5,
+ label=r"Frozen Chemistry, $k_a = 10^{-11}$",
+ )
+ ax.set_xlabel("Frequency (Hz)")
+ ax.set_ylabel(r"$|C_{\mathrm{app}}(f)|$ ($\mathrm{nF\,cm^{-2}}$)")
+ ax.set_title("(c) Small-Signal AC Capacitance Spectrum (0.9 V, 1 Sun)", fontweight="bold")
+ ax.legend(loc="upper right", frameon=True, fontsize=7.5)
+ ax.grid(True, which="both", alpha=0.25)
+
+ fig5_path = output_dir / "bt2023_parameter_sweeps_and_ac.png"
+ fig5.savefig(fig5_path)
+ plt.close(fig5)
+
+ figure_paths = [fig1_path, fig2_path, fig3_path, fig4_path, fig5_path]
+ if artifact_dir is not None:
+ artifact_dir.mkdir(parents=True, exist_ok=True)
+ for fp in figure_paths:
+ (artifact_dir / fp.name).write_bytes(fp.read_bytes())
+
+ # Assemble quantitative Table 1 & Figure S2 comparison summary
+ table1_comparison: list[dict[str, Any]] = []
+ for ka_ref in (0.0, 1.0e-11, 5.0e-11):
+ sc_k = jv_scans[("mu3", "absorber_blocking", ka_ref)]
+ mr = sc_k.reverse_metrics
+ assert (
+ mr.short_circuit_current_A_m2 is not None
+ and mr.open_circuit_voltage_V is not None
+ and mr.fill_factor is not None
+ and mr.efficiency is not None
+ )
+ ref = BT2023_TABLE1_REF[ka_ref]
+ table1_comparison.append(
+ {
+ "ka_cm3_s": ka_ref,
+ "sentaurus_ref": ref,
+ "solarlab": {
+ "Jsc_mA_cm2": round(mr.short_circuit_current_A_m2 / 10.0, 2),
+ "Voc_V": round(mr.open_circuit_voltage_V, 3),
+ "FF_pct": round(mr.fill_factor * 100.0, 1),
+ "PCE_pct": round(mr.efficiency * 100.0, 1),
+ },
+ }
+ )
+
+ sc_s1_perm = jv_scans[("mu3", "full_stack_permeable", 1.0e-11)].reverse_metrics
+ summary: dict[str, Any] = {
+ "schema": "solarlab.bitton_tessler_2023_benchmark.v1",
+ "scientific_qualification": False,
+ "wall_s": round(time.monotonic() - t0, 2),
+ "table1_comparison": table1_comparison,
+ "fig_s1_permeable_ka_1e_11": {
+ "Jsc_mA_cm2": round(float(sc_s1_perm.short_circuit_current_A_m2 or 0.0) / 10.0, 2),
+ "Voc_V": round(float(sc_s1_perm.open_circuit_voltage_V or 0.0), 3),
+ "FF_pct": round(float(sc_s1_perm.fill_factor or 0.0) * 100.0, 1),
+ "PCE_pct": round(float(sc_s1_perm.efficiency or 0.0) * 100.0, 1),
+ },
+ "fig_4_and_s2_key_densities_cm3": {
+ "fig4a_pvk_mid_e": float(st_4a.electronic_state.electron_density_m3[40] * 1e-6),
+ "fig4a_pvk_mid_h": float(st_4a.electronic_state.hole_density_m3[40] * 1e-6),
+ "fig4b_pvk_mid_I0": float(st_4b.iodine_atom_density_m3[22] * 1e-6),
+ "fig4d_s2a_pvk_mid_e": float(st_4d.electronic_state.electron_density_m3[40] * 1e-6),
+ "fig4d_s2a_pvk_mid_I0": float(st_4d.iodine_atom_density_m3[40] * 1e-6),
+ "fig4d_s2a_ebl_max_I2": float(st_4d.iodine_molecule_density_m3[62:].max() * 1e-6),
+ "figs2b_dark_0p9V_ebl_max_I2": float(
+ ss_s2b.state.iodine_molecule_density_m3[62:].max() * 1e-6
+ ),
+ "figs2c_dark_0V_ebl_max_I2": float(
+ st_s2c.iodine_molecule_density_m3[62:].max() * 1e-6
+ ),
+ },
+ "fig_5_10000h_loss_cm3": {
+ "mu_1e_3_ka_1e_11_volumetric_outgas": float(bub_5a_1[-1]),
+ "mu_1e_3_ka_5e_11_volumetric_outgas": float(bub_5a_5[-1]),
+ "mu_1e_3_ka_5e_11_10h_surface_escape": float(esc_5a_5[-1]),
+ "mu_1e_4_ka_1e_11_volumetric_outgas": float(bub_5b_1[-1]),
+ "mu_1e_4_ka_5e_11_volumetric_outgas": float(bub_5b_5[-1]),
+ "ag_cathode_40s_loss_cm3": float(np.interp(40.0, t_elec, loss_elec_cm3)),
+ "ag_cathode_120s_loss_cm3": float(loss_elec_cm3[-1]),
+ "anode_oxidation_10h_loss_cm3": float(loss_anode_cm3[-1]),
+ },
+ "figures": {
+ fp.name: hashlib.sha256(fp.read_bytes()).hexdigest() for fp in figure_paths
+ },
+ }
+ (output_dir / "benchmark_summary.json").write_text(
+ json.dumps(summary, indent=2, sort_keys=True) + "\n", encoding="utf-8"
+ )
+ return summary
+
+
+def main() -> int:
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--output", type=Path, required=True)
+ parser.add_argument("--artifact-dir", type=Path, default=None)
+ args = parser.parse_args()
+ summary = run_full_benchmark(args.output, args.artifact_dir)
+ print(json.dumps(summary, indent=2, sort_keys=True))
+ return 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/examples/research_1d/iodine_aging.py b/examples/research_1d/iodine_aging.py
new file mode 100644
index 00000000..1e8a8c4b
--- /dev/null
+++ b/examples/research_1d/iodine_aging.py
@@ -0,0 +1,264 @@
+"""Bitton & Tessler (2023) 1D iodine aging workflow: stress, recovery, and J-V probes.
+
+Demonstrates coupled 1D ``(phi, n, p, I^-, I^0, I_2)`` reaction-diffusion-aging
+comparing:
+1. Closed-boundary reversible light-induced degradation & dark self-healing
+ (``mol_escape_velocity_m_s = 0``);
+2. Open-boundary irreversible volatile ``I_2`` outgassing degradation
+ (``mol_escape_velocity_m_s > 0``);
+with non-destructive frozen-chemistry J-V probes and checksum-verified bundle
+readback. Every output explicitly retains ``scientific_qualification = False``.
+"""
+
+from __future__ import annotations
+
+import argparse
+import json
+from pathlib import Path
+
+import numpy as np
+
+from solarlab.config.resolve_device import resolve_device
+from solarlab.device.compile_iodine_1d import (
+ bitton_tessler_2023_table_s1_chemistry,
+ compile_iodine_device_1d,
+)
+from solarlab.device.defaults import DefaultCatalog
+from solarlab.device.inputs import DeviceInput
+from solarlab.device.resolved import PreparedDevice
+from solarlab.experiments.iodine_aging import (
+ IodineAgingProtocol,
+ IodineProbeSpec,
+ StressRecoveryStage,
+ load_iodine_aging_bundle,
+ run_iodine_aging_protocol,
+ save_iodine_aging_bundle,
+)
+from solarlab.materials.resources import ResourceLibrary
+from solarlab.materials.source import SourceDocument
+
+REPO_ROOT = Path(__file__).resolve().parents[2]
+
+
+def prepare_bitton_tessler_stack() -> PreparedDevice:
+ """Resolve the 3-layer HBL / Perovskite / EBL stack from SI Table S1."""
+ base_path = REPO_ROOT / "examples" / "research_1d" / "device.json"
+ source = SourceDocument(str(base_path), base_path.read_bytes())
+ doc = json.loads(source.content)
+ catalog = {
+ **doc["default_catalog"],
+ "evidence": [[source.id, source.sha256]],
+ }
+ q_c = 1.602176634e-19
+ kb_j_k = 1.380649e-23
+ vt = (kb_j_k * 300.0) / q_c
+ eps0 = 8.8541878128e-12
+ mu_bl = 1.0e-3 * 1.0e-4
+ b_langevin = q_c * (2.0 * mu_bl) / (eps0 * 3.0)
+ ni_bl = float(np.exp(0.5 * (np.log(1.0e27) + np.log(1.0e27) - 2.5 / vt)))
+ ni_pvk = float(np.exp(0.5 * (np.log(7.0e24) + np.log(2.5e24) - 1.6 / vt)))
+
+ device_dict = {
+ "schema_version": "solarlab.device-preparation.v1",
+ "id": "bitton_tessler_2023_stack",
+ "name": "Bitton & Tessler 2023 HBL/PVK/EBL stack",
+ "source_format": "canonical",
+ "settings": {
+ "built_in_potential_mode": "semiconductor_work_function",
+ "dos_band_potentials": True,
+ "T": 300.0,
+ "Phi": 2.5e21,
+ },
+ "layers": [
+ {
+ "id": "hbl",
+ "name": "HBL",
+ "role": "ETL",
+ "thickness": 50.0e-9,
+ "parameters": {
+ "chi": 4.3,
+ "Eg": 2.5,
+ "Nc300": 1.0e27,
+ "Nv300": 1.0e27,
+ "eps_r": 3.0,
+ "N_D": 2.0e22,
+ "N_A": 0.0,
+ "ni": ni_bl,
+ "n1": ni_bl,
+ "p1": ni_bl,
+ "tau_n": 1.0,
+ "tau_p": 1.0,
+ "B_rad": b_langevin,
+ "C_n": 0.0,
+ "C_p": 0.0,
+ "mu_n": mu_bl,
+ "mu_p": mu_bl,
+ "alpha": 0.0,
+ },
+ },
+ {
+ "id": "absorber",
+ "name": "Perovskite",
+ "role": "absorber",
+ "thickness": 500.0e-9,
+ "parameters": {
+ "chi": 4.3,
+ "Eg": 1.6,
+ "Nc300": 7.0e24,
+ "Nv300": 2.5e24,
+ "eps_r": 50.0,
+ "N_D": 0.0,
+ "N_A": 0.0,
+ "ni": ni_pvk,
+ "n1": ni_pvk,
+ "p1": ni_pvk,
+ "tau_n": 1.0e-5,
+ "tau_p": 1.0e-5,
+ "B_rad": 1.0e-10 * 1.0e-6,
+ "C_n": 0.0,
+ "C_p": 0.0,
+ "mu_n": 2.0e-4,
+ "mu_p": 2.0e-4,
+ "alpha": 1.0e7,
+ },
+ },
+ {
+ "id": "ebl",
+ "name": "EBL",
+ "role": "HTL",
+ "thickness": 50.0e-9,
+ "parameters": {
+ "chi": 3.4,
+ "Eg": 2.5,
+ "Nc300": 1.0e27,
+ "Nv300": 1.0e27,
+ "eps_r": 3.0,
+ "N_D": 0.0,
+ "N_A": 2.0e22,
+ "ni": ni_bl,
+ "n1": ni_bl,
+ "p1": ni_bl,
+ "tau_n": 1.0,
+ "tau_p": 1.0,
+ "B_rad": b_langevin,
+ "C_n": 0.0,
+ "C_p": 0.0,
+ "mu_n": mu_bl,
+ "mu_p": mu_bl,
+ "alpha": 0.0,
+ },
+ },
+ ],
+ }
+ return resolve_device(
+ DeviceInput.model_validate(device_dict),
+ DefaultCatalog.from_mapping(catalog),
+ ResourceLibrary(),
+ sources=(source,),
+ )
+
+
+def run_comparison(output_dir: Path) -> dict[str, object]:
+ """Run closed self-healing vs open I_2 outgassing aging comparison."""
+ if output_dir.exists():
+ raise FileExistsError(f"Choose a fresh output directory: {output_dir}")
+
+ prepared = prepare_bitton_tessler_stack()
+ protocol = IodineAgingProtocol(
+ stages=(
+ StressRecoveryStage(
+ name="light_stress_0p9V",
+ duration_s=100.0,
+ voltage_V=0.9,
+ generation_scale=1.0,
+ max_step_s=25.0,
+ ),
+ StressRecoveryStage(
+ name="dark_recovery_0V",
+ duration_s=300.0,
+ voltage_V=0.0,
+ generation_scale=0.0,
+ max_step_s=50.0,
+ ),
+ ),
+ checkpoint_times_s=(0.0, 100.0, 400.0),
+ probe=IodineProbeSpec(
+ mode="frozen_chemistry_jv",
+ voltages_V=tuple(float(v) for v in np.linspace(0.0, 1.32, 16)),
+ generation_scale=1.0,
+ ),
+ )
+
+ closed_chem = bitton_tessler_2023_table_s1_chemistry(
+ domain_mode="absorber_blocking",
+ rate_mode="smoluchowski_capture_radius",
+ perovskite_ka_cm3_s=5.0e-11,
+ right_escape_m_s=0.0,
+ )
+ open_chem = bitton_tessler_2023_table_s1_chemistry(
+ domain_mode="absorber_blocking",
+ rate_mode="smoluchowski_capture_radius",
+ perovskite_ka_cm3_s=5.0e-11,
+ right_escape_m_s=5.0e-2,
+ )
+ closed_dev = compile_iodine_device_1d(
+ prepared, closed_chem, intervals_per_layer=(6, 20, 6)
+ )
+ open_dev = compile_iodine_device_1d(
+ prepared, open_chem, intervals_per_layer=(6, 20, 6)
+ )
+
+ closed_res = run_iodine_aging_protocol(closed_dev, protocol)
+ open_res = run_iodine_aging_protocol(open_dev, protocol)
+
+ closed_manifest = save_iodine_aging_bundle(output_dir / "closed", closed_res)
+ open_manifest = save_iodine_aging_bundle(output_dir / "open", open_res)
+
+ # Verify checksum-authenticated readback
+ _ = load_iodine_aging_bundle(output_dir / "closed")
+ _ = load_iodine_aging_bundle(output_dir / "open")
+
+ summary: dict[str, object] = {
+ "scientific_qualification": False,
+ "protocol_sha256": protocol.sha256,
+ "closed": {
+ "device_sha256": closed_dev.identity,
+ "max_relative_conservation_error": closed_res.max_relative_conservation_error,
+ "final_in_device_iodine_m2": closed_res.checkpoints[-1].in_device_iodine_m2,
+ "final_escaped_iodine_m2": (
+ closed_res.checkpoints[-1].cumulative_escaped_iodine_atoms_m2
+ ),
+ "arrays_npz_sha256": closed_manifest["arrays_npz_sha256"],
+ },
+ "open": {
+ "device_sha256": open_dev.identity,
+ "max_relative_conservation_error": open_res.max_relative_conservation_error,
+ "final_in_device_iodine_m2": open_res.checkpoints[-1].in_device_iodine_m2,
+ "final_escaped_iodine_m2": (
+ open_res.checkpoints[-1].cumulative_escaped_iodine_atoms_m2
+ ),
+ "arrays_npz_sha256": open_manifest["arrays_npz_sha256"],
+ },
+ }
+ (output_dir / "comparison_summary.json").write_text(
+ json.dumps(summary, indent=2, sort_keys=True) + "\n", encoding="utf-8"
+ )
+ return summary
+
+
+def main() -> int:
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument(
+ "--output",
+ type=Path,
+ required=True,
+ help="Fresh directory to write closed/ and open/ iodine aging bundles.",
+ )
+ args = parser.parse_args()
+ summary = run_comparison(args.output)
+ print(json.dumps(summary, indent=2, sort_keys=True))
+ return 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/src/solarlab/cli.py b/src/solarlab/cli.py
index b016fa6d..d4e4b382 100644
--- a/src/solarlab/cli.py
+++ b/src/solarlab/cli.py
@@ -179,6 +179,173 @@ def _cmd_steady_jv(args: argparse.Namespace) -> int:
return 0
+def _write_or_print_json(payload: dict[str, Any], output: Path | None) -> int:
+ encoded = json.dumps(payload, indent=2, sort_keys=True)
+ if output is not None:
+ output.parent.mkdir(parents=True, exist_ok=True)
+ output.write_text(encoded + "\n", encoding="utf-8")
+ else:
+ print(encoded)
+ return 0
+
+
+def _cli_error_exit(exc: Exception) -> int:
+ err_payload = {
+ "schema": "solarlab.cli.error.v1",
+ "error_type": type(exc).__name__,
+ "message": str(exc),
+ }
+ print(json.dumps(err_payload, sort_keys=True), file=sys.stderr)
+ return 1
+
+
+def _cmd_iodine_presets(args: argparse.Namespace) -> int:
+ from solarlab.experiments.iodine_declarative import export_iodine_deck_schema
+ from solarlab.materials.iodine_presets import list_packaged_iodine_preset_summaries
+
+ if args.schema:
+ return _write_or_print_json(export_iodine_deck_schema(), args.output)
+ summaries = [
+ {k: v for k, v in item.items() if k != "deck"}
+ for item in list_packaged_iodine_preset_summaries()
+ ]
+ return _write_or_print_json(
+ {
+ "schema": "solarlab.cli.iodine-presets.v1",
+ "presets": summaries,
+ "scientific_qualification": False,
+ },
+ args.output,
+ )
+
+
+def _cmd_iodine_steady(args: argparse.Namespace) -> int:
+ from pydantic import ValidationError
+
+ from solarlab.contracts import ContractError
+ from solarlab.equations.dc_1d import CapabilityError
+ from solarlab.experiments.iodine_declarative import (
+ IodineOverridesInput,
+ apply_iodine_deck_overrides,
+ execute_iodine_steady_deck,
+ load_iodine_deck,
+ )
+ from solarlab.solvers.nonlinear.steady_1d import SteadyStateError
+
+ try:
+ target: str | Path = args.config if args.config is not None else args.preset
+ deck, src = load_iodine_deck(target)
+ overrides = IodineOverridesInput(
+ intervals_per_layer=args.intervals_per_layer,
+ k_a_cm3_s=args.k_a,
+ mu_bl_cm2_V_s=args.mu_bl,
+ ebl_partition=args.ebl_partition,
+ voltage_V=args.voltage,
+ generation_scale=args.generation_scale,
+ compute_frozen_jv=(False if args.no_frozen_jv else None),
+ )
+ effective = apply_iodine_deck_overrides(deck, overrides)
+ payload = execute_iodine_steady_deck(effective, source=src)
+ except (
+ CapabilityError,
+ ContractError,
+ FileNotFoundError,
+ KeyError,
+ SteadyStateError,
+ ValidationError,
+ ValueError,
+ ) as exc:
+ return _cli_error_exit(exc)
+ return _write_or_print_json(payload, args.output)
+
+
+def _cmd_iodine_impedance(args: argparse.Namespace) -> int:
+ from pydantic import ValidationError
+
+ from solarlab.contracts import ContractError
+ from solarlab.equations.dc_1d import CapabilityError
+ from solarlab.experiments.iodine_declarative import (
+ IodineOverridesInput,
+ apply_iodine_deck_overrides,
+ execute_iodine_impedance_deck,
+ load_iodine_deck,
+ )
+ from solarlab.solvers.nonlinear.steady_1d import SteadyStateError
+
+ try:
+ target: str | Path = args.config if args.config is not None else args.preset
+ deck, src = load_iodine_deck(target)
+ overrides = IodineOverridesInput(
+ intervals_per_layer=args.intervals_per_layer,
+ k_a_cm3_s=args.k_a,
+ voltage_V=args.voltage,
+ generation_scale=args.generation_scale,
+ f_min_Hz=args.f_min,
+ f_max_Hz=args.f_max,
+ n_frequencies=args.n_frequencies,
+ chem_mode=args.chem_mode,
+ )
+ effective = apply_iodine_deck_overrides(deck, overrides)
+ payload = execute_iodine_impedance_deck(effective, source=src)
+ except (
+ CapabilityError,
+ ContractError,
+ FileNotFoundError,
+ KeyError,
+ SteadyStateError,
+ ValidationError,
+ ValueError,
+ ) as exc:
+ return _cli_error_exit(exc)
+ return _write_or_print_json(payload, args.output)
+
+
+def _cmd_iodine_aging(args: argparse.Namespace) -> int:
+ from pydantic import ValidationError
+
+ from solarlab.contracts import ContractError
+ from solarlab.equations.dc_1d import CapabilityError
+ from solarlab.experiments.iodine_aging import IodineAgingError
+ from solarlab.experiments.iodine_declarative import (
+ IodineOverridesInput,
+ apply_iodine_deck_overrides,
+ execute_iodine_aging_deck,
+ load_iodine_deck,
+ )
+ from solarlab.solvers.nonlinear.steady_1d import SteadyStateError
+
+ try:
+ target: str | Path = args.config if args.config is not None else args.preset
+ deck, src = load_iodine_deck(target)
+ overrides = IodineOverridesInput(
+ intervals_per_layer=args.intervals_per_layer,
+ k_a_cm3_s=args.k_a,
+ volumetric_escape_s_1=args.volumetric_escape,
+ contact_corrosion_m_s=args.contact_corrosion,
+ probe_mode=args.probe_mode,
+ )
+ effective = apply_iodine_deck_overrides(deck, overrides)
+ payload = execute_iodine_aging_deck(
+ effective,
+ source=src,
+ store_dir=args.store_dir,
+ bundle_dir=args.bundle_dir,
+ run_id=args.run_id,
+ )
+ except (
+ CapabilityError,
+ ContractError,
+ FileNotFoundError,
+ IodineAgingError,
+ KeyError,
+ SteadyStateError,
+ ValidationError,
+ ValueError,
+ ) as exc:
+ return _cli_error_exit(exc)
+ return _write_or_print_json(payload, args.output)
+
+
def _delegate_research(module_name: str, extra_args: list[str]) -> int:
module = importlib.import_module(module_name)
entry = getattr(module, "main")
@@ -238,6 +405,86 @@ def main(argv: Sequence[str] | None = None) -> int:
)
p_cbo.add_argument("research_args", nargs=argparse.REMAINDER)
+ from solarlab.materials.iodine_presets import PACKAGED_IODINE_PRESET_NAMES
+
+ p_ipresets = subparsers.add_parser(
+ "iodine-presets",
+ help="List packaged 1D iodine chemistry/aging presets or export the deck JSON Schema.",
+ )
+ p_ipresets.add_argument(
+ "--schema",
+ action="store_true",
+ help="Export the solarlab.iodine-deck.v1 JSON Schema instead of listing presets.",
+ )
+ p_ipresets.add_argument("--output", type=Path, default=None)
+
+ p_isteady = subparsers.add_parser(
+ "iodine-steady",
+ help="Run coupled 1D iodine reaction-diffusion steady state and optional frozen J-V.",
+ )
+ p_isteady.add_argument(
+ "--preset",
+ choices=PACKAGED_IODINE_PRESET_NAMES,
+ default="bitton_tessler_2023_blocking",
+ )
+ p_isteady.add_argument("--config", type=Path, default=None)
+ p_isteady.add_argument("--voltage", type=float, default=None)
+ p_isteady.add_argument("--generation-scale", type=float, default=None)
+ p_isteady.add_argument("--k-a", type=float, default=None, help="Override absorber k_a [cm^3/s].")
+ p_isteady.add_argument("--mu-bl", type=float, default=None, help="Override BL mobility [cm^2/(V s)].")
+ p_isteady.add_argument("--ebl-partition", type=float, default=None)
+ p_isteady.add_argument("--intervals-per-layer", type=int, default=None)
+ p_isteady.add_argument("--no-frozen-jv", action="store_true")
+ p_isteady.add_argument("--output", type=Path, default=None)
+
+ p_iimp = subparsers.add_parser(
+ "iodine-impedance",
+ help="Run 1D small-signal AC impedance and redox capacitance sweep on an iodine deck.",
+ )
+ p_iimp.add_argument(
+ "--preset",
+ choices=PACKAGED_IODINE_PRESET_NAMES,
+ default="bitton_tessler_2023_blocking",
+ )
+ p_iimp.add_argument("--config", type=Path, default=None)
+ p_iimp.add_argument("--voltage", type=float, default=None)
+ p_iimp.add_argument("--generation-scale", type=float, default=None)
+ p_iimp.add_argument("--f-min", type=float, default=None)
+ p_iimp.add_argument("--f-max", type=float, default=None)
+ p_iimp.add_argument("--n-frequencies", type=int, default=None)
+ p_iimp.add_argument(
+ "--chem-mode",
+ choices=("mobile", "frozen", "both"),
+ default=None,
+ )
+ p_iimp.add_argument("--k-a", type=float, default=None)
+ p_iimp.add_argument("--intervals-per-layer", type=int, default=None)
+ p_iimp.add_argument("--output", type=Path, default=None)
+
+ p_iaging = subparsers.add_parser(
+ "iodine-aging",
+ help="Run a multi-stage 1D iodine stress/recovery aging protocol.",
+ )
+ p_iaging.add_argument(
+ "--preset",
+ choices=PACKAGED_IODINE_PRESET_NAMES,
+ default="bitton_tessler_2023_self_healing",
+ )
+ p_iaging.add_argument("--config", type=Path, default=None)
+ p_iaging.add_argument("--k-a", type=float, default=None)
+ p_iaging.add_argument("--volumetric-escape", type=float, default=None)
+ p_iaging.add_argument("--contact-corrosion", type=float, default=None)
+ p_iaging.add_argument(
+ "--probe-mode",
+ choices=("none", "frozen_chemistry_jv", "dynamic_jv_scan", "both"),
+ default=None,
+ )
+ p_iaging.add_argument("--intervals-per-layer", type=int, default=None)
+ p_iaging.add_argument("--store-dir", type=Path, default=None)
+ p_iaging.add_argument("--bundle-dir", type=Path, default=None)
+ p_iaging.add_argument("--run-id", type=str, default=None)
+ p_iaging.add_argument("--output", type=Path, default=None)
+
args = parser.parse_args(list(argv) if argv is not None else None)
if args.command is None:
parser.print_help()
@@ -246,6 +493,14 @@ def main(argv: Sequence[str] | None = None) -> int:
return _cmd_check_install(args)
if args.command == "steady-jv":
return _cmd_steady_jv(args)
+ if args.command == "iodine-presets":
+ return _cmd_iodine_presets(args)
+ if args.command == "iodine-steady":
+ return _cmd_iodine_steady(args)
+ if args.command == "iodine-impedance":
+ return _cmd_iodine_impedance(args)
+ if args.command == "iodine-aging":
+ return _cmd_iodine_aging(args)
if args.command == "cbo-scan":
forwarded = list(args.research_args)
if forwarded and forwarded[0] == "--":
diff --git a/src/solarlab/device/compile_iodine_1d.py b/src/solarlab/device/compile_iodine_1d.py
new file mode 100644
index 00000000..7dcbe3c3
--- /dev/null
+++ b/src/solarlab/device/compile_iodine_1d.py
@@ -0,0 +1,842 @@
+"""Compile a PreparedDevice and IodineChemistryDeclaration into CompiledIodineDevice1D.
+
+Preserves existing :class:`~solarlab.device.inputs.DeviceInput` and frontend
+configuration schemas untouched while binding multi-layer or absorber-confined
+``I^- / I^0 / I_2`` chemistry onto SolarLab's shared 1D geometry and electronic
+component projection.
+"""
+
+from __future__ import annotations
+
+from collections.abc import Sequence
+from dataclasses import dataclass, field
+import hashlib
+import json
+import math
+from typing import Literal, get_args
+
+import numpy as np
+from numpy.typing import NDArray
+
+from solarlab.config.resolve_device import resolve_device
+from solarlab.contracts import ContractError, frozen_array
+from solarlab.device.compile_1d import compile_device_1d
+from solarlab.device.inputs import DeviceInput
+from solarlab.device.resolved import PreparedDevice
+from solarlab.equations.dc_1d import CapabilityError, TERegularizationName
+from solarlab.equations.iodine_1d import (
+ CompiledIodineDevice1D,
+ ContactReactionMode,
+ IodineBoundaryPortSpec,
+ IodineDomainMode,
+)
+from solarlab.mesh.geometry import (
+ PHYSICAL_HALF_ENDPOINT_V2,
+ half_endpoint_geometry,
+ physical_half_endpoint_geometry,
+)
+from solarlab.physics.band_structure.temperature import ion_diffusivity_at_temperature
+from solarlab.physics.chemistry import (
+ BoundedSpeciesMap,
+ IodineKineticsParameters,
+ IodineThermodynamicMode,
+ ReactionEOrder,
+ SoftplusSpeciesMap,
+ SpeciesCoordinateMap,
+ equilibrium_iodine_populations_m3,
+ harmonic_face_diffusivity_m2_s,
+ smoluchowski_rate_m3_s,
+)
+from solarlab.physics.transport.electrochemical_flux import LEGACY_SUMMED_POTENTIAL_V1
+from solarlab.solvers.nonlinear.steady_1d import SteadyOptions, solve_equilibrium
+
+__all__ = [
+ "IodineBoundaryDeclaration",
+ "IodineChemistryDeclaration",
+ "IodineLayerSpec",
+ "IodineRateParameterization",
+ "bitton_tessler_2023_table_s1_chemistry",
+ "compile_iodine_device_1d",
+]
+
+IODINE_COMPILER_SCHEMA = "solarlab.compiled_iodine_device_1d.v1"
+
+IodineRateParameterization = Literal[
+ "explicit_rates",
+ "smoluchowski_capture_radius",
+]
+_RATE_MODES: frozenset[str] = frozenset(get_args(IodineRateParameterization))
+
+
+@dataclass(frozen=True, slots=True)
+class IodineLayerSpec:
+ """Per-layer SI transport, reaction, partition, and initial-population inputs."""
+
+ layer_id: str
+ D_minus_m2_s: float
+ D_atom_m2_s: float
+ D_mol_m2_s: float
+ initial_iodide_m3: float = 0.0
+ initial_atom_m3: float = 0.0
+ initial_mol_m3: float = 0.0
+ compensating_donor_m3: float | None = None
+ E_a_minus_eV: float = 0.0
+ E_a_atom_eV: float = 0.0
+ E_a_mol_eV: float = 0.0
+ rate_mode: IodineRateParameterization = "explicit_rates"
+ k_a_m3_s: float = 0.0
+ k_b_s_1: float = 0.0
+ k_c_m3_s: float = 0.0
+ k_d_m3_s: float = 0.0
+ k_e_m3_s: float = 0.0
+ k_e_3body_m6_s: float = 0.0
+ capture_radius_m: float = 0.2e-9
+ K_diss_m3: float = 1.0e14
+ n_e_star_m3: float = 1.0e14
+ partition_minus: float = 1.0
+ partition_atom: float = 1.0
+ partition_mol: float = 1.0
+ iodide_site_limit_m3: float | None = None
+ volumetric_mol_escape_s_1: float = 0.0
+
+ def __post_init__(self) -> None:
+ if not self.layer_id:
+ raise ContractError("layer_id_must_be_nonempty")
+ if self.rate_mode not in _RATE_MODES:
+ raise ContractError("unknown_iodine_rate_parameterization")
+ for name in (
+ "D_minus_m2_s",
+ "D_atom_m2_s",
+ "D_mol_m2_s",
+ "initial_iodide_m3",
+ "initial_atom_m3",
+ "initial_mol_m3",
+ "E_a_minus_eV",
+ "E_a_atom_eV",
+ "E_a_mol_eV",
+ "k_a_m3_s",
+ "k_b_s_1",
+ "k_c_m3_s",
+ "k_d_m3_s",
+ "k_e_m3_s",
+ "k_e_3body_m6_s",
+ "capture_radius_m",
+ "n_e_star_m3",
+ "volumetric_mol_escape_s_1",
+ ):
+ val = float(getattr(self, name))
+ if not math.isfinite(val) or val < 0.0:
+ raise ContractError(f"{name}_must_be_finite_nonnegative")
+ object.__setattr__(self, name, val)
+
+ for pname in ("K_diss_m3", "partition_minus", "partition_atom", "partition_mol"):
+ pval = float(getattr(self, pname))
+ if not math.isfinite(pval) or pval <= 0.0:
+ raise ContractError(f"{pname}_must_be_strictly_positive")
+ object.__setattr__(self, pname, pval)
+
+ comp_donor = (
+ self.initial_iodide_m3
+ if self.compensating_donor_m3 is None
+ else float(self.compensating_donor_m3)
+ )
+ if not math.isfinite(comp_donor) or comp_donor < 0.0:
+ raise ContractError("compensating_donor_m3_must_be_finite_nonnegative")
+ object.__setattr__(self, "compensating_donor_m3", comp_donor)
+
+ if self.iodide_site_limit_m3 is not None:
+ slim = float(self.iodide_site_limit_m3)
+ if not math.isfinite(slim) or slim <= 0.0 or self.initial_iodide_m3 >= slim:
+ raise ContractError("initial_iodide_must_be_below_positive_site_limit")
+ object.__setattr__(self, "iodide_site_limit_m3", slim)
+
+ @classmethod
+ def from_cgs(
+ cls,
+ layer_id: str,
+ *,
+ D_minus_cm2_s: float,
+ D_atom_cm2_s: float,
+ D_mol_cm2_s: float,
+ initial_iodide_cm3: float = 0.0,
+ initial_atom_cm3: float = 0.0,
+ initial_mol_cm3: float = 0.0,
+ compensating_donor_cm3: float | None = None,
+ rate_mode: IodineRateParameterization = "explicit_rates",
+ k_a_cm3_s: float = 0.0,
+ k_b_s_1: float = 0.0,
+ k_c_cm3_s: float = 0.0,
+ k_d_cm3_s: float = 0.0,
+ k_e_cm3_s: float = 0.0,
+ k_e_3body_cm6_s: float = 0.0,
+ capture_radius_nm: float = 0.2,
+ K_diss_cm3: float = 1.0e8,
+ n_e_star_cm3: float = 1.0e8,
+ partition_minus: float = 1.0,
+ partition_atom: float = 1.0,
+ partition_mol: float = 1.0,
+ iodide_site_limit_cm3: float | None = None,
+ volumetric_mol_escape_s_1: float = 0.0,
+ ) -> IodineLayerSpec:
+ """Construct SI layer specification directly from literature CGS units."""
+ return cls(
+ layer_id=layer_id,
+ D_minus_m2_s=D_minus_cm2_s * 1.0e-4,
+ D_atom_m2_s=D_atom_cm2_s * 1.0e-4,
+ D_mol_m2_s=D_mol_cm2_s * 1.0e-4,
+ initial_iodide_m3=initial_iodide_cm3 * 1.0e6,
+ initial_atom_m3=initial_atom_cm3 * 1.0e6,
+ initial_mol_m3=initial_mol_cm3 * 1.0e6,
+ compensating_donor_m3=(
+ None
+ if compensating_donor_cm3 is None
+ else compensating_donor_cm3 * 1.0e6
+ ),
+ rate_mode=rate_mode,
+ k_a_m3_s=k_a_cm3_s * 1.0e-6,
+ k_b_s_1=k_b_s_1,
+ k_c_m3_s=k_c_cm3_s * 1.0e-6,
+ k_d_m3_s=k_d_cm3_s * 1.0e-6,
+ k_e_m3_s=k_e_cm3_s * 1.0e-6,
+ k_e_3body_m6_s=k_e_3body_cm6_s * 1.0e-12,
+ capture_radius_m=capture_radius_nm * 1.0e-9,
+ K_diss_m3=K_diss_cm3 * 1.0e6,
+ n_e_star_m3=n_e_star_cm3 * 1.0e6,
+ partition_minus=partition_minus,
+ partition_atom=partition_atom,
+ partition_mol=partition_mol,
+ iodide_site_limit_m3=(
+ None
+ if iodide_site_limit_cm3 is None
+ else iodide_site_limit_cm3 * 1.0e6
+ ),
+ volumetric_mol_escape_s_1=volumetric_mol_escape_s_1,
+ )
+
+
+@dataclass(frozen=True, slots=True)
+class IodineBoundaryDeclaration:
+ """User-level boundary closure for volatile ``I_2`` escape and contact oxidation."""
+
+ mol_escape_velocity_m_s: float = 0.0
+ contact_reaction_mode: ContactReactionMode = "none"
+ contact_oxidation_rate_m4_s: float = 0.0
+ contact_corrosion_velocity_m_s: float = 0.0
+
+
+@dataclass(frozen=True, slots=True)
+class IodineChemistryDeclaration:
+ """Complete iodine chemistry configuration bound to a PreparedDevice."""
+
+ layers: tuple[IodineLayerSpec, ...]
+ domain_mode: IodineDomainMode = "absorber_blocking"
+ thermodynamic_mode: IodineThermodynamicMode = "wegscheider_detailed_balance"
+ reaction_e_order: ReactionEOrder = "bimolecular_n"
+ left_boundary: IodineBoundaryDeclaration = field(
+ default_factory=IodineBoundaryDeclaration
+ )
+ right_boundary: IodineBoundaryDeclaration = field(
+ default_factory=IodineBoundaryDeclaration
+ )
+ initialize_equilibrium_split: bool = False
+ enforce_spatial_wegscheider: bool = True
+ steric_diffusion_only: bool = True
+
+ def __post_init__(self) -> None:
+ items = tuple(self.layers)
+ if not items:
+ raise ContractError("iodine_chemistry_requires_at_least_one_layer_spec")
+ ids = [item.layer_id for item in items]
+ if len(set(ids)) != len(ids):
+ raise ContractError("duplicate_iodine_layer_id")
+ object.__setattr__(self, "layers", items)
+
+
+def bitton_tessler_2023_table_s1_chemistry(
+ *,
+ hbl_layer_id: str = "hbl",
+ absorber_layer_id: str = "absorber",
+ ebl_layer_id: str = "ebl",
+ domain_mode: IodineDomainMode = "full_stack_permeable",
+ thermodynamic_mode: IodineThermodynamicMode = "wegscheider_detailed_balance",
+ reaction_e_order: ReactionEOrder = "bimolecular_n",
+ rate_mode: IodineRateParameterization = "explicit_rates",
+ perovskite_ka_cm3_s: float = 1.0e-11,
+ left_escape_m_s: float = 0.0,
+ right_escape_m_s: float = 0.0,
+ hbl_volumetric_mol_escape_s_1: float = 0.0,
+ perovskite_volumetric_mol_escape_s_1: float = 0.0,
+ ebl_volumetric_mol_escape_s_1: float = 0.0,
+ left_boundary: IodineBoundaryDeclaration | None = None,
+ right_boundary: IodineBoundaryDeclaration | None = None,
+ initialize_equilibrium_split: bool = True,
+) -> IodineChemistryDeclaration:
+ """Return Bitton & Tessler (2023) SI Table S1 iodine parameters."""
+ unreactive = float(perovskite_ka_cm3_s) == 0.0
+ eff_rate_mode: IodineRateParameterization = (
+ "explicit_rates" if unreactive else rate_mode
+ )
+ pvk = IodineLayerSpec.from_cgs(
+ absorber_layer_id,
+ D_minus_cm2_s=1.0e-8,
+ D_atom_cm2_s=1.0e-8,
+ D_mol_cm2_s=1.0e-9,
+ initial_iodide_cm3=1.0e18,
+ compensating_donor_cm3=1.0e18,
+ rate_mode=eff_rate_mode,
+ k_a_cm3_s=0.0 if unreactive else perovskite_ka_cm3_s,
+ k_b_s_1=0.0 if unreactive else 3.0e5,
+ k_c_cm3_s=0.0 if unreactive else 5.0e-7,
+ k_d_cm3_s=0.0 if unreactive else 5.0e-15,
+ k_e_cm3_s=0.0 if unreactive else 1.3e-8,
+ capture_radius_nm=0.2,
+ K_diss_cm3=1.0e8,
+ n_e_star_cm3=1.0e8,
+ volumetric_mol_escape_s_1=perovskite_volumetric_mol_escape_s_1,
+ )
+ if domain_mode == "absorber_blocking":
+ layers: tuple[IodineLayerSpec, ...] = (pvk,)
+ else:
+ hbl = IodineLayerSpec.from_cgs(
+ hbl_layer_id,
+ D_minus_cm2_s=1.0e-12,
+ D_atom_cm2_s=1.0e-12,
+ D_mol_cm2_s=1.0e-13,
+ initial_iodide_cm3=0.0,
+ compensating_donor_cm3=0.0,
+ rate_mode=eff_rate_mode,
+ k_a_cm3_s=0.0 if unreactive else 6.5e-13,
+ k_b_s_1=0.0 if unreactive else 6.0e3,
+ k_c_cm3_s=0.0 if unreactive else 2.5e-11,
+ k_d_cm3_s=0.0 if unreactive else 5.0e-19,
+ k_e_cm3_s=0.0 if unreactive else 1.3e-10,
+ capture_radius_nm=0.2,
+ K_diss_cm3=1.0e8,
+ n_e_star_cm3=1.0e6,
+ volumetric_mol_escape_s_1=hbl_volumetric_mol_escape_s_1,
+ )
+ ebl = IodineLayerSpec.from_cgs(
+ ebl_layer_id,
+ D_minus_cm2_s=1.0e-12,
+ D_atom_cm2_s=1.0e-12,
+ D_mol_cm2_s=1.0e-13,
+ initial_iodide_cm3=0.0,
+ compensating_donor_cm3=0.0,
+ rate_mode=eff_rate_mode,
+ k_a_cm3_s=0.0 if unreactive else 6.5e-13,
+ k_b_s_1=0.0 if unreactive else 6.0e-12,
+ k_c_cm3_s=0.0 if unreactive else 2.5e-11,
+ k_d_cm3_s=0.0 if unreactive else 5.0e-19,
+ k_e_cm3_s=0.0 if unreactive else 1.3e-10,
+ capture_radius_nm=0.2,
+ K_diss_cm3=1.0e8,
+ n_e_star_cm3=1.0e6,
+ volumetric_mol_escape_s_1=ebl_volumetric_mol_escape_s_1,
+ )
+ layers = (hbl, pvk, ebl)
+ lb = (
+ IodineBoundaryDeclaration(mol_escape_velocity_m_s=left_escape_m_s)
+ if left_boundary is None
+ else left_boundary
+ )
+ rb = (
+ IodineBoundaryDeclaration(mol_escape_velocity_m_s=right_escape_m_s)
+ if right_boundary is None
+ else right_boundary
+ )
+ return IodineChemistryDeclaration(
+ layers=layers,
+ domain_mode=domain_mode,
+ thermodynamic_mode=thermodynamic_mode,
+ reaction_e_order=reaction_e_order,
+ left_boundary=lb,
+ right_boundary=rb,
+ initialize_equilibrium_split=initialize_equilibrium_split and not unreactive,
+ )
+
+
+def _default_positive_maps(
+ m_count: int,
+ initial_iodide_m3: np.ndarray,
+ site_limit_m3: np.ndarray | None,
+) -> tuple[SpeciesCoordinateMap, SpeciesCoordinateMap, SpeciesCoordinateMap]:
+ max_iodide = max(float(np.max(initial_iodide_m3)), 1.0e20)
+ if site_limit_m3 is not None:
+ eff_init = np.maximum(initial_iodide_m3, 1.0e6)
+ theta = np.clip(eff_init / site_limit_m3, 1.0e-18, 0.999999)
+ logit_ref = np.log(theta) - np.log1p(-theta)
+ iodide_map: SpeciesCoordinateMap = BoundedSpeciesMap(
+ site_limit_m3=site_limit_m3,
+ logit_reference=logit_ref,
+ vacuum_floor_m3=1.0,
+ )
+ else:
+ iodide_map = SoftplusSpeciesMap(
+ scale_m3=np.full(m_count, max_iodide * 0.1),
+ vacuum_floor_m3=1.0,
+ )
+ s_0 = max(max_iodide * 1.0e-5, 1.0e17)
+ atom_map = SoftplusSpeciesMap(
+ scale_m3=np.full(m_count, s_0),
+ vacuum_floor_m3=1.0,
+ )
+ s_2 = max(max_iodide * 1.0e-8, 1.0e14)
+ mol_map = SoftplusSpeciesMap(
+ scale_m3=np.full(m_count, s_2),
+ vacuum_floor_m3=1.0,
+ )
+ return iodide_map, atom_map, mol_map
+
+
+def compile_iodine_device_1d(
+ prepared: PreparedDevice,
+ chemistry: IodineChemistryDeclaration,
+ *,
+ intervals_per_layer: int | Sequence[int] = 40,
+ te_softness: float = 0.02,
+ te_regularization_mode: TERegularizationName = "legacy_logistic",
+ optical_model: Literal["beer_lambert", "beer_lambert_spectral", "tmm"] | None = None,
+ dielectric_rule: str | None = None,
+ geometry_name: str | None = None,
+ band_step_mode: str = LEGACY_SUMMED_POTENTIAL_V1,
+ allow_legacy_benchmark_deck: bool = False,
+) -> CompiledIodineDevice1D:
+ """Compile a PreparedDevice and IodineChemistryDeclaration into a 1D system."""
+ if not isinstance(prepared, PreparedDevice):
+ raise TypeError("compile_iodine_device_1d requires a PreparedDevice")
+ if not isinstance(chemistry, IodineChemistryDeclaration):
+ raise TypeError(
+ "compile_iodine_device_1d requires an IodineChemistryDeclaration"
+ )
+
+ elec_layers = tuple(
+ layer for layer in prepared.layers if layer.role != "substrate"
+ )
+ layer_ids = tuple(layer.id for layer in elec_layers)
+ spec_by_id = {spec.layer_id: spec for spec in chemistry.layers}
+
+ domain_layer_ids: tuple[str, ...]
+ if chemistry.domain_mode == "absorber_blocking":
+ if len(chemistry.layers) != 1:
+ raise CapabilityError(
+ "absorber_blocking mode requires exactly one IodineLayerSpec"
+ )
+ target_id = chemistry.layers[0].layer_id
+ if target_id not in layer_ids:
+ raise CapabilityError(
+ f"absorber_blocking layer {target_id!r} not in electrical stack"
+ )
+ domain_layer_ids = (target_id,)
+ else:
+ if set(spec_by_id) != set(layer_ids):
+ raise CapabilityError(
+ "full_stack_permeable mode requires an IodineLayerSpec for every "
+ f"non-substrate electrical layer {layer_ids}"
+ )
+ domain_layer_ids = layer_ids
+
+ # Project out legacy mobile-ion parameters from the electronic component
+ projection = prepared.to_input().editing_data()
+ for layer_dict in projection["layers"]:
+ for key in ("P0", "P0_neg", "D_ion", "D_ion_neg"):
+ layer_dict.setdefault("parameters", {})[key] = 0.0
+ for key in ("ion_steric_diffusion_only", "ion_steric_shared_site"):
+ projection.setdefault("settings", {})[key] = False
+ component_prepared = resolve_device(
+ DeviceInput.model_validate(projection),
+ prepared.defaults,
+ prepared.resources,
+ sources=prepared.sources,
+ )
+ component = compile_device_1d(
+ component_prepared,
+ intervals_per_layer=intervals_per_layer,
+ te_softness=te_softness,
+ te_regularization_mode=te_regularization_mode,
+ optical_model=optical_model,
+ dielectric_rule=dielectric_rule,
+ geometry_name=geometry_name,
+ band_step_mode=band_step_mode,
+ allow_legacy_benchmark_deck=allow_legacy_benchmark_deck,
+ )
+
+ temp_K = component.parameters.temperature_K
+ n_count = component.node_count
+ planes = component.geometry.interfaces
+
+ # Resolve layer node spans [left_l, right_l] on the shared-node electrical grid
+ layer_spans: list[tuple[str, int, int]] = []
+ for l_idx, l_id in enumerate(layer_ids):
+ left = 0 if l_idx == 0 else planes[l_idx - 1].shared_node
+ right = n_count - 1 if l_idx == len(layer_ids) - 1 else planes[l_idx].shared_node
+ if left is None or right is None:
+ raise CapabilityError(
+ "iodine 1D compiler requires shared electrostatic interface nodes"
+ )
+ layer_spans.append((l_id, int(left), int(right)))
+
+ if chemistry.domain_mode == "absorber_blocking":
+ target_id = domain_layer_ids[0]
+ _, left_idx, right_idx = next(
+ item for item in layer_spans if item[0] == target_id
+ )
+ chem_indices: NDArray[np.intp] = np.arange(left_idx, right_idx + 1, dtype=np.intp)
+ active_spans = [(target_id, 0, int(chem_indices.size) - 1)]
+ else:
+ chem_indices = np.arange(n_count, dtype=np.intp)
+ active_spans = layer_spans
+
+ chem_geometry = (
+ physical_half_endpoint_geometry(component.nodes_m[chem_indices])
+ if component.geometry.name == PHYSICAL_HALF_ENDPOINT_V2
+ else half_endpoint_geometry(component.nodes_m[chem_indices])
+ )
+
+ m_count = chem_geometry.node_count
+ m_faces = m_count - 1
+ chem_nodes_m = chem_geometry.nodes_m
+ chem_dx = np.diff(chem_nodes_m)
+ chem_volumes = chem_geometry.cell_measures_m
+
+ # Accumulate cell-measure-weighted quantities per layer so shared interface
+ # nodes conserve exact layer sheet inventories and reaction integrals!
+ comp_donor: NDArray[np.float64] = np.zeros(m_count, dtype=np.float64)
+ init_cm: NDArray[np.float64] = np.zeros(m_count, dtype=np.float64)
+ init_c0: NDArray[np.float64] = np.zeros(m_count, dtype=np.float64)
+ init_c2: NDArray[np.float64] = np.zeros(m_count, dtype=np.float64)
+ k_a: NDArray[np.float64] = np.zeros(m_count, dtype=np.float64)
+ k_b: NDArray[np.float64] = np.zeros(m_count, dtype=np.float64)
+ k_c: NDArray[np.float64] = np.zeros(m_count, dtype=np.float64)
+ k_d: NDArray[np.float64] = np.zeros(m_count, dtype=np.float64)
+ k_e: NDArray[np.float64] = np.zeros(m_count, dtype=np.float64)
+ k_e3: NDArray[np.float64] = np.zeros(m_count, dtype=np.float64)
+ k_diss: NDArray[np.float64] = np.zeros(m_count, dtype=np.float64)
+ n_star: NDArray[np.float64] = np.zeros(m_count, dtype=np.float64)
+ vol_esc: NDArray[np.float64] = np.zeros(m_count, dtype=np.float64)
+ w_accum: NDArray[np.float64] = np.zeros(m_count, dtype=np.float64)
+
+ d_minus_faces: NDArray[np.float64] = np.zeros(m_faces, dtype=np.float64)
+ d_atom_faces: NDArray[np.float64] = np.zeros(m_faces, dtype=np.float64)
+ d_mol_faces: NDArray[np.float64] = np.zeros(m_faces, dtype=np.float64)
+ part_minus_nodes: NDArray[np.float64] = np.ones(m_count, dtype=np.float64)
+ part_atom_nodes: NDArray[np.float64] = np.ones(m_count, dtype=np.float64)
+ part_mol_nodes: NDArray[np.float64] = np.ones(m_count, dtype=np.float64)
+
+ has_steric = any(spec.iodide_site_limit_m3 is not None for spec in chemistry.layers)
+ if has_steric and not all(
+ spec.iodide_site_limit_m3 is not None for spec in chemistry.layers
+ ):
+ raise CapabilityError(
+ "iodide_site_limit_m3 must be set on all active layers or none"
+ )
+ site_limit: NDArray[np.float64] | None = (
+ np.zeros(m_count, dtype=np.float64) if has_steric else None
+ )
+
+ d_elec_chem = component.parameters.electron_diffusivity_m2_s[chem_indices]
+ d_hole_chem = component.parameters.hole_diffusivity_m2_s[chem_indices]
+
+ for l_id, c_left, c_right in active_spans:
+ spec = spec_by_id[l_id]
+ # Sub-cell half-interval weights inside layer [c_left, c_right]
+ sub_w: NDArray[np.float64] = np.zeros(c_right - c_left + 1, dtype=np.float64)
+ layer_dx = chem_dx[c_left:c_right]
+ sub_w[:-1] += 0.5 * layer_dx
+ sub_w[1:] += 0.5 * layer_dx
+ sl = slice(c_left, c_right + 1)
+
+ dm_T = ion_diffusivity_at_temperature(
+ spec.D_minus_m2_s, temp_K, spec.E_a_minus_eV
+ )
+ d0_T = ion_diffusivity_at_temperature(
+ spec.D_atom_m2_s, temp_K, spec.E_a_atom_eV
+ )
+ d2_T = ion_diffusivity_at_temperature(
+ spec.D_mol_m2_s, temp_K, spec.E_a_mol_eV
+ )
+ d_minus_faces[c_left:c_right] = dm_T
+ d_atom_faces[c_left:c_right] = d0_T
+ d_mol_faces[c_left:c_right] = d2_T
+
+ if spec.rate_mode == "smoluchowski_capture_radius":
+ ka_nodes = (
+ np.full(sub_w.size, spec.k_a_m3_s)
+ if spec.k_a_m3_s > 0.0
+ else smoluchowski_rate_m3_s(
+ dm_T, d_hole_chem[sl], spec.capture_radius_m
+ )
+ )
+ kc_nodes = smoluchowski_rate_m3_s(
+ d0_T, d_elec_chem[sl], spec.capture_radius_m
+ )
+ kd_nodes = smoluchowski_rate_m3_s(d0_T, d0_T, spec.capture_radius_m)
+ ke_nodes = smoluchowski_rate_m3_s(
+ d2_T, d_elec_chem[sl], spec.capture_radius_m
+ )
+ else:
+ ka_nodes = np.full(sub_w.size, spec.k_a_m3_s)
+ kc_nodes = np.full(sub_w.size, spec.k_c_m3_s)
+ kd_nodes = np.full(sub_w.size, spec.k_d_m3_s)
+ ke_nodes = np.full(sub_w.size, spec.k_e_m3_s)
+
+ assert spec.compensating_donor_m3 is not None
+ w_accum[sl] += sub_w
+ comp_donor[sl] += sub_w * spec.compensating_donor_m3
+ init_cm[sl] += sub_w * spec.initial_iodide_m3
+ init_c0[sl] += sub_w * spec.initial_atom_m3
+ init_c2[sl] += sub_w * spec.initial_mol_m3
+ k_a[sl] += sub_w * ka_nodes
+ k_b[sl] += sub_w * spec.k_b_s_1
+ k_c[sl] += sub_w * kc_nodes
+ k_d[sl] += sub_w * kd_nodes
+ k_e[sl] += sub_w * ke_nodes
+ k_e3[sl] += sub_w * spec.k_e_3body_m6_s
+ k_diss[sl] += sub_w * spec.K_diss_m3
+ n_star[sl] += sub_w * spec.n_e_star_m3
+ vol_esc[sl] += sub_w * spec.volumetric_mol_escape_s_1
+ if site_limit is not None:
+ assert spec.iodide_site_limit_m3 is not None
+ site_limit[sl] += sub_w * spec.iodide_site_limit_m3
+
+ # Interior nodes take exact layer partition; shared heterointerface node
+ # takes geometric mean so total chemical step across both adjacent faces
+ # equals ln(K_part_right / K_part_left) identically!
+ part_minus_nodes[c_left + 1 : c_right] = spec.partition_minus
+ part_atom_nodes[c_left + 1 : c_right] = spec.partition_atom
+ part_mol_nodes[c_left + 1 : c_right] = spec.partition_mol
+
+ # Endpoint & shared interface partition geometric means
+ first_spec = spec_by_id[active_spans[0][0]]
+ last_spec = spec_by_id[active_spans[-1][0]]
+ part_minus_nodes[0] = first_spec.partition_minus
+ part_atom_nodes[0] = first_spec.partition_atom
+ part_mol_nodes[0] = first_spec.partition_mol
+ part_minus_nodes[-1] = last_spec.partition_minus
+ part_atom_nodes[-1] = last_spec.partition_atom
+ part_mol_nodes[-1] = last_spec.partition_mol
+ for span_i in range(len(active_spans) - 1):
+ shared_c = active_spans[span_i][2]
+ sp_l = spec_by_id[active_spans[span_i][0]]
+ sp_r = spec_by_id[active_spans[span_i + 1][0]]
+ part_minus_nodes[shared_c] = math.sqrt(
+ sp_l.partition_minus * sp_r.partition_minus
+ )
+ part_atom_nodes[shared_c] = math.sqrt(sp_l.partition_atom * sp_r.partition_atom)
+ part_mol_nodes[shared_c] = math.sqrt(sp_l.partition_mol * sp_r.partition_mol)
+
+ # Normalize accumulated cell integrals by chem_volumes
+ # (note: on physical_half_endpoint_v2 vs half_endpoint_v1 w_accum matches chem_volumes)
+ inv_w = 1.0 / w_accum
+ comp_donor *= inv_w
+ init_cm *= inv_w
+ init_c0 *= inv_w
+ init_c2 *= inv_w
+ k_a *= inv_w
+ k_b *= inv_w
+ k_c *= inv_w
+ k_d *= inv_w
+ k_e *= inv_w
+ k_e3 *= inv_w
+ k_diss *= inv_w
+ n_star *= inv_w
+ vol_esc *= inv_w
+ for span_i in range(len(active_spans) - 1):
+ shared_c = active_spans[span_i][2]
+ sp_l = spec_by_id[active_spans[span_i][0]]
+ sp_r = spec_by_id[active_spans[span_i + 1][0]]
+ if (
+ sp_l.volumetric_mol_escape_s_1 == 0.0
+ or sp_r.volumetric_mol_escape_s_1 == 0.0
+ ):
+ vol_esc[shared_c] = 0.0
+ if site_limit is not None:
+ site_limit *= inv_w
+
+ # Harmonic smoothing at faces adjacent to layer transitions if needed
+ # (each face already lies inside one layer with uniform layer diffusivity;
+ # validate via harmonic_face_diffusivity_m2_s for strict finiteness).
+ d_minus_faces = harmonic_face_diffusivity_m2_s(d_minus_faces, d_minus_faces)
+ d_atom_faces = harmonic_face_diffusivity_m2_s(d_atom_faces, d_atom_faces)
+ d_mol_faces = harmonic_face_diffusivity_m2_s(d_mol_faces, d_mol_faces)
+
+ log_part_minus = np.log(part_minus_nodes[1:] / part_minus_nodes[:-1])
+ log_part_atom = np.log(part_atom_nodes[1:] / part_atom_nodes[:-1])
+ log_part_mol = np.log(part_mol_nodes[1:] / part_mol_nodes[:-1])
+
+ ni_sq_chem = component.parameters.intrinsic_product_m6[chem_indices]
+ n1_override: np.ndarray | None = None
+ if (
+ chemistry.thermodynamic_mode == "wegscheider_detailed_balance"
+ and chemistry.enforce_spatial_wegscheider
+ and np.any((k_a > 0.0) & (k_b > 0.0))
+ ):
+ # Anchor vacuum I^0/I^- redox level and I_2 dissociation free energy to
+ # the primary absorber (or highest initial-iodine layer) so dark thermal
+ # equilibrium satisfies zero net flux AND zero net reaction simultaneously
+ # across all interior and shared heterointerface nodes.
+ ref_span = max(
+ active_spans,
+ key=lambda item: spec_by_id[item[0]].initial_iodide_m3,
+ )
+ ref_mid = (ref_span[1] + ref_span[2]) // 2
+ n1_ref = float((k_a[ref_mid] * ni_sq_chem[ref_mid]) / k_b[ref_mid])
+ kdiss_ref = float(k_diss[ref_mid])
+ n_ref_chem = component.reference_electron_density_m3[chem_indices]
+ phi_ref_chem = component.reference_potential_V[chem_indices]
+ vt_V = component.thermal_voltage_V
+ rel_pm = part_minus_nodes / part_minus_nodes[ref_mid]
+ rel_p0 = part_atom_nodes / part_atom_nodes[ref_mid]
+ rel_p2 = part_mol_nodes / part_mol_nodes[ref_mid]
+ n1_spatial = (
+ n1_ref
+ * (rel_pm / rel_p0)
+ * (n_ref_chem / n_ref_chem[ref_mid])
+ * np.exp(-(phi_ref_chem - phi_ref_chem[ref_mid]) / vt_V)
+ )
+ active_mask = k_a > 0.0
+ k_b = np.where(active_mask, (k_a * ni_sq_chem) / n1_spatial, 0.0)
+ n1_override = np.where(active_mask, n1_spatial, 0.0)
+ k_diss = kdiss_ref * ((rel_p0 * rel_p0) / rel_p2)
+
+ kinetics = IodineKineticsParameters(
+ k_a_m3_s=k_a,
+ k_b_s_1=k_b,
+ k_c_m3_s=k_c,
+ k_d_m3_s=k_d,
+ k_e_m3_s=k_e,
+ k_e_3body_m6_s=k_e3,
+ n_i_sq_m6=ni_sq_chem,
+ K_diss_m3=k_diss,
+ n_e_star_m3=n_star,
+ n_1_iodine_m3=n1_override,
+ thermodynamic_mode=chemistry.thermodynamic_mode,
+ reaction_e_order=chemistry.reaction_e_order,
+ )
+
+ if (
+ chemistry.initialize_equilibrium_split
+ and chemistry.thermodynamic_mode == "wegscheider_detailed_balance"
+ ):
+ eq_res = solve_equilibrium(component, options=SteadyOptions())
+ n_eq = eq_res.state.electron_density_m3[chem_indices]
+ tot_i = init_cm + init_c0 + 2.0 * init_c2
+ init_cm, init_c0, init_c2 = equilibrium_iodine_populations_m3(
+ tot_i, n_eq, kinetics
+ )
+
+ scale_ref = (
+ init_cm + init_c0 + 2.0 * init_c2
+ if chemistry.initialize_equilibrium_split
+ else init_cm
+ )
+ iodide_map, atom_map, mol_map = _default_positive_maps(
+ m_count, np.asarray(scale_ref, dtype=np.float64), site_limit
+ )
+
+ reversible_ct = chemistry.thermodynamic_mode == "wegscheider_detailed_balance"
+ p1_left = (
+ float(k_b[0] / k_a[0]) if k_a[0] > 0.0 and k_b[0] > 0.0 else 0.0
+ )
+ p1_right = (
+ float(k_b[-1] / k_a[-1]) if k_a[-1] > 0.0 and k_b[-1] > 0.0 else 0.0
+ )
+ left_port = IodineBoundaryPortSpec(
+ side="left",
+ chem_node=0,
+ elec_node=int(chem_indices[0]),
+ outward_normal=-1,
+ mol_escape_velocity_m_s=chemistry.left_boundary.mol_escape_velocity_m_s,
+ contact_reaction_mode=chemistry.left_boundary.contact_reaction_mode,
+ contact_oxidation_rate_m4_s=chemistry.left_boundary.contact_oxidation_rate_m4_s,
+ contact_corrosion_velocity_m_s=chemistry.left_boundary.contact_corrosion_velocity_m_s,
+ p1_iodine_m3=p1_left,
+ reversible_contact=reversible_ct
+ and chemistry.left_boundary.contact_reaction_mode == "hole_oxidation_to_I0",
+ )
+ right_port = IodineBoundaryPortSpec(
+ side="right",
+ chem_node=m_count - 1,
+ elec_node=int(chem_indices[-1]),
+ outward_normal=1,
+ mol_escape_velocity_m_s=chemistry.right_boundary.mol_escape_velocity_m_s,
+ contact_reaction_mode=chemistry.right_boundary.contact_reaction_mode,
+ contact_oxidation_rate_m4_s=chemistry.right_boundary.contact_oxidation_rate_m4_s,
+ contact_corrosion_velocity_m_s=chemistry.right_boundary.contact_corrosion_velocity_m_s,
+ p1_iodine_m3=p1_right,
+ reversible_contact=reversible_ct
+ and chemistry.right_boundary.contact_reaction_mode == "hole_oxidation_to_I0",
+ )
+ for bport in (left_port, right_port):
+ if (
+ bport.contact_reaction_mode == "metal_faradaic_corrosion"
+ and bport.elec_node not in (0, n_count - 1)
+ ):
+ raise CapabilityError(
+ "metal_faradaic_corrosion requires an external electrode boundary"
+ )
+
+ manifest = {
+ "schema": IODINE_COMPILER_SCHEMA,
+ "original_prepared_sha256": prepared.content_sha256,
+ "electronic_component_sha256": component.identity,
+ "domain_mode": chemistry.domain_mode,
+ "domain_layer_ids": list(domain_layer_ids),
+ "chem_node_indices": chem_indices.tolist(),
+ "chem_volumes_m": chem_volumes.tolist(),
+ "kinetics_identity": kinetics.identity,
+ "maps": [iodide_map.identity, atom_map.identity, mol_map.identity],
+ "left_boundary": {
+ "escape": left_port.mol_escape_velocity_m_s,
+ "mode": left_port.contact_reaction_mode,
+ "rate": left_port.contact_oxidation_rate_m4_s,
+ },
+ "right_boundary": {
+ "escape": right_port.mol_escape_velocity_m_s,
+ "mode": right_port.contact_reaction_mode,
+ "rate": right_port.contact_oxidation_rate_m4_s,
+ },
+ "scientific_qualification": False,
+ }
+ if left_port.contact_corrosion_velocity_m_s > 0.0:
+ manifest["left_boundary"]["corrosion_velocity"] = (
+ left_port.contact_corrosion_velocity_m_s
+ )
+ if right_port.contact_corrosion_velocity_m_s > 0.0:
+ manifest["right_boundary"]["corrosion_velocity"] = (
+ right_port.contact_corrosion_velocity_m_s
+ )
+ if np.any(vol_esc > 0.0):
+ manifest["volumetric_mol_escape_s_1"] = vol_esc.tolist()
+ manifest_json = json.dumps(manifest, sort_keys=True, separators=(",", ":"))
+ digest = hashlib.sha256(manifest_json.encode()).hexdigest()
+
+ return CompiledIodineDevice1D(
+ device_id=component.device_id,
+ sha256=digest,
+ original_prepared_sha256=prepared.content_sha256,
+ electronic_component=component,
+ domain_mode=chemistry.domain_mode,
+ domain_layer_ids=domain_layer_ids,
+ chem_geometry=chem_geometry,
+ chem_node_indices=chem_indices,
+ compensating_donor_m3=frozen_array(comp_donor),
+ initial_iodide_m3=frozen_array(init_cm),
+ initial_atom_m3=frozen_array(init_c0),
+ initial_mol_m3=frozen_array(init_c2),
+ iodide_map=iodide_map,
+ atom_map=atom_map,
+ mol_map=mol_map,
+ iodide_diffusivity_faces_m2_s=d_minus_faces,
+ atom_diffusivity_faces_m2_s=d_atom_faces,
+ mol_diffusivity_faces_m2_s=d_mol_faces,
+ log_partition_minus_faces=frozen_array(log_part_minus),
+ log_partition_atom_faces=frozen_array(log_part_atom),
+ log_partition_mol_faces=frozen_array(log_part_mol),
+ kinetics=kinetics,
+ left_boundary=left_port,
+ right_boundary=right_port,
+ binding_manifest_json=manifest_json,
+ steric_site_limit_m3=None if site_limit is None else frozen_array(site_limit),
+ steric_diffusion_only=chemistry.steric_diffusion_only,
+ volumetric_mol_escape_s_1=frozen_array(vol_esc),
+ )
diff --git a/src/solarlab/equations/assembly/iodine_1d.py b/src/solarlab/equations/assembly/iodine_1d.py
new file mode 100644
index 00000000..acd23105
--- /dev/null
+++ b/src/solarlab/equations/assembly/iodine_1d.py
@@ -0,0 +1,1383 @@
+"""Unified sparse 1D assembly of coupled ``I^- / I^0 / I_2`` reaction-diffusion.
+
+Builds strictly on :class:`~solarlab.equations.assembly.layout.SystemLayout`,
+:class:`~solarlab.equations.assembly.terms.Term`, and
+:class:`~solarlab.equations.assembly.assembler.Assembler` without modifying core
+assembly infrastructure or duplicating nonlinear/time solvers.
+"""
+
+from __future__ import annotations
+
+from collections.abc import Mapping
+from dataclasses import dataclass, field
+from hashlib import sha256
+import json
+import math
+from typing import Final, Literal
+
+import numpy as np
+from numpy.typing import ArrayLike, NDArray
+from scipy.sparse import csc_matrix
+
+from solarlab.contracts import ContractError, Vector, frozen_array
+from solarlab.contracts.units import (
+ AREA,
+ COULOMB,
+ ELEMENTARY_CHARGE_C,
+ ONE,
+ PARTICLE,
+ SECOND,
+ VOLT,
+ VOLUME,
+ Unit,
+)
+from solarlab.equations.assembly.assembler import (
+ AssembledSystem,
+ Assembler,
+ Mesh,
+ Port,
+ SupportGeometry,
+)
+from solarlab.equations.assembly.classical_1d import (
+ BulkRecombination,
+ CarrierExchange,
+ CarrierGeneration,
+ CarrierReservoirs,
+ CarrierStorage,
+ CarrierTransport,
+ GaussDisplacement,
+ InterfaceCarrierPort,
+ InterfaceGaussPort,
+ PotentialContacts,
+ populate_interface_fields,
+)
+from solarlab.equations.assembly.layout import (
+ Block,
+ ConstraintRows,
+ NodeSet,
+ SystemLayout,
+)
+from solarlab.equations.assembly.quasi_fermi import ELECTRODE_QUASI_FERMI_1D_V1
+from solarlab.equations.assembly.terms import (
+ CELL_SOURCE,
+ CHAIN_DIVERGENCE,
+ CONSTRAINT,
+ FACE_FLUX,
+ PORT_FLUX,
+ STORAGE,
+ Contribution,
+ EvaluationState,
+ FaceValue,
+ FieldValues,
+ LocalValue,
+ OperatingInputs,
+ ReductionValue,
+ Term,
+ TermValue,
+)
+from solarlab.equations.dc_1d import CapabilityError
+from solarlab.equations.iodine_1d import (
+ IODINE_BLOCKS,
+ CompiledIodineDevice1D,
+ IodineBoundaryPortSpec,
+)
+from solarlab.physics.chemistry import (
+ evaluate_iodine_kinetics,
+ species_sg_face_flux,
+)
+from solarlab.physics.contacts.exchange import CarrierExchangeChannel
+from solarlab.physics.electrostatics import contact_displacement
+from solarlab.physics.recombination.bulk import RecombinationRate
+from solarlab.physics.transport.electrochemical_flux import CarrierFaceFluxes
+
+__all__ = [
+ "AssembledConstrainedIodine1DProblem",
+ "AssembledIodine1DProblem",
+ "CHEM_NODES",
+ "IODIDE",
+ "IODINE_ATOM",
+ "IODINE_MOLECULE",
+ "IodineCarrierReactionTerm",
+ "IodineContactReactionPortTerm",
+ "IodineFields",
+ "IodineHoleContactPortTerm",
+ "IodineMoleculeEscapePortTerm",
+ "IodineSpaceChargeTerm",
+ "IodineSpeciesReactionTerm",
+ "IodineSpeciesStorageTerm",
+ "IodineSystem",
+ "IodineTransportTerm",
+ "IodineVolumetricEscapeTerm",
+ "SingleSpeciesInventoryTerm",
+ "TotalIodineInventoryTerm",
+ "iodine_system",
+]
+
+Q = ELEMENTARY_CHARGE_C
+NODES = "nodes"
+CHEM_NODES = "chem"
+POTENTIAL, ELECTRON, HOLE = "potential", "electron", "hole"
+IODIDE: Final = "iodide"
+IODINE_ATOM: Final = "iodine_atom"
+IODINE_MOLECULE: Final = "iodine_molecule"
+CARRIERS = ((ELECTRON, "n", 1.0), (HOLE, "p", -1.0))
+
+DISPLACEMENT_UNIT = COULOMB / AREA
+CHARGE_UNIT = COULOMB / VOLUME
+FLUX_UNIT = PARTICLE / (AREA * SECOND)
+SOURCE_UNIT = PARTICLE / (VOLUME * SECOND)
+DENSITY_UNIT = PARTICLE / VOLUME
+INVENTORY_UNIT = PARTICLE / AREA
+
+TERM_SCHEMA = "solarlab.iodine_1d.terms.v1"
+
+
+def _identity(*parts: object) -> str:
+ return sha256(
+ json.dumps((TERM_SCHEMA, *parts), separators=(",", ":")).encode()
+ ).hexdigest()
+
+
+def _carrier_chain_tangents(
+ dn_coeff: Vector,
+ dp_coeff: Vector,
+ n: Vector,
+ p: Vector,
+ thermal_V: float,
+) -> tuple[Vector, Vector, Vector]:
+ """Chain rule from ``(d/dn, d/dp)`` to ``(d/dphi, d/dzn, d/dzp)``."""
+ t_zn = dn_coeff * n
+ t_zp = -dp_coeff * p
+ t_phi = (t_zn + t_zp) / thermal_V
+ return t_phi, t_zn, t_zp
+
+
+@dataclass(frozen=True)
+class IodineFields:
+ """Single-pass field and bulk-reaction evaluation per trial state."""
+
+ device: CompiledIodineDevice1D
+
+ @property
+ def identity(self) -> str:
+ return _identity("iodine_fields_v1", self.device.identity)
+
+ def evaluate(
+ self, layout: SystemLayout, u: Vector, inputs: OperatingInputs
+ ) -> FieldValues:
+ device = self.device
+ try:
+ (
+ phi,
+ n,
+ p,
+ cm,
+ c0,
+ c2,
+ mm,
+ m0,
+ m2,
+ ) = device.fields_and_tangents(u, voltage_V=inputs.voltage_V)
+ idx = device.chem_node_indices
+ rxn = evaluate_iodine_kinetics(
+ n[idx], p[idx], cm, c0, c2, device.kinetics, derivatives=True
+ )
+ except (ValueError, FloatingPointError, ContractError):
+ return FieldValues({}, False)
+
+ assert rxn.dsources_dstate is not None
+ fields: dict[str, Vector] = {
+ "potential_V": phi,
+ "electron_density_m3": n,
+ "hole_density_m3": p,
+ IODIDE: cm,
+ IODINE_ATOM: c0,
+ IODINE_MOLECULE: c2,
+ "mass:iodide": mm,
+ "mass:iodine_atom": m0,
+ "mass:iodine_molecule": m2,
+ "rxn:rates": rxn.rates_m3_s,
+ "rxn:sources": rxn.sources_m3_s,
+ "rxn:dsources": rxn.dsources_dstate,
+ }
+ component = device.electronic_component
+ if component.interface_model is not None:
+ ok = populate_interface_fields(
+ component, u[: 3 * component.node_count], phi, n, p, fields
+ )
+ return FieldValues(fields, ok)
+ return FieldValues(fields, True)
+
+
+@dataclass(frozen=True)
+class IodineSpaceChargeTerm:
+ """Gauss space-charge cell source coupling ``(n, p, c_-, N_fix^+)``."""
+
+ device: CompiledIodineDevice1D
+ id: str = "potential.iodine_space_charge"
+ kind: str = CELL_SOURCE
+ support: str = NODES
+ equations: tuple[str, ...] = (POTENTIAL,)
+ dependencies: tuple[str, ...] = (POTENTIAL, ELECTRON, HOLE, IODIDE)
+ unit: Unit = CHARGE_UNIT
+ port: str | None = None
+
+ @property
+ def identity(self) -> str:
+ return _identity(
+ self.id, self.device.identity, ELECTRODE_QUASI_FERMI_1D_V1
+ )
+
+ def evaluate(
+ self, state: EvaluationState, *, derivatives: bool
+ ) -> Mapping[str, TermValue]:
+ n = state.field("electron_density_m3")
+ p = state.field("hole_density_m3")
+ cm = state.field(IODIDE)
+ rho = self.device.charge_ledger(n, p, cm).space_charge_C_m3()
+ if not derivatives:
+ return {POTENTIAL: LocalValue(rho)}
+ vt = self.device.electronic_component.thermal_voltage_V
+ idx = self.device.chem_node_indices
+ ratio = state.embedding_ratio(CHEM_NODES)
+ d_iodide = np.zeros(n.size, dtype=np.float64)
+ d_iodide[idx] = -Q * ratio * state.field("mass:iodide")
+ tangents: dict[str, Contribution] = {
+ POTENTIAL: -Q * (n + p) / vt,
+ ELECTRON: -Q * n,
+ HOLE: -Q * p,
+ IODIDE: d_iodide,
+ }
+ return {POTENTIAL: LocalValue(rho, tangents)}
+
+
+@dataclass(frozen=True)
+class IodineSpeciesStorageTerm:
+ """Physical storage ``c_j`` and subtraction-free BDF secants on ``chem``."""
+
+ device: CompiledIodineDevice1D
+ id: str = "chem.storage"
+ kind: str = STORAGE
+ support: str = CHEM_NODES
+ equations: tuple[str, ...] = IODINE_BLOCKS
+ dependencies: tuple[str, ...] = IODINE_BLOCKS
+ unit: Unit = DENSITY_UNIT
+ port: str | None = None
+
+ @property
+ def identity(self) -> str:
+ return _identity(self.id, self.device.identity)
+
+ def evaluate(
+ self, state: EvaluationState, *, derivatives: bool
+ ) -> Mapping[str, TermValue]:
+ out: dict[str, TermValue] = {}
+ for block in IODINE_BLOCKS:
+ dens = state.field(block)
+ if derivatives:
+ out[block] = LocalValue(dens, {block: state.field("mass:" + block)})
+ else:
+ out[block] = LocalValue(dens)
+ return out
+
+ def increment(
+ self, state: EvaluationState, previous: EvaluationState
+ ) -> Mapping[str, Contribution]:
+ dev = self.device
+ return {
+ IODIDE: dev.iodide_map.secant_increment_m3(
+ state.block(IODIDE), previous.block(IODIDE)
+ ),
+ IODINE_ATOM: dev.atom_map.secant_increment_m3(
+ state.block(IODINE_ATOM), previous.block(IODINE_ATOM)
+ ),
+ IODINE_MOLECULE: dev.mol_map.secant_increment_m3(
+ state.block(IODINE_MOLECULE), previous.block(IODINE_MOLECULE)
+ ),
+ }
+
+
+@dataclass(frozen=True)
+class IodineTransportTerm:
+ """SG drift-diffusion of ``I^-`` and Fick/partition diffusion of ``I^0, I_2``."""
+
+ device: CompiledIodineDevice1D
+ species: Literal["iodide", "iodine_atom", "iodine_molecule"]
+ kind: str = FACE_FLUX
+ support: str = CHEM_NODES
+ unit: Unit = FLUX_UNIT
+ port: str | None = None
+ divergence: str = CHAIN_DIVERGENCE
+
+ @property
+ def id(self) -> str:
+ return f"chem.transport.{self.species}"
+
+ @property
+ def equations(self) -> tuple[str, ...]:
+ return (self.species,)
+
+ @property
+ def dependencies(self) -> tuple[str, ...]:
+ if self.species == IODIDE:
+ return (POTENTIAL, IODIDE)
+ return (self.species,)
+
+ @property
+ def identity(self) -> str:
+ return _identity(self.id, self.device.identity)
+
+ def flux_evaluation(
+ self, state: EvaluationState, *, derivatives: bool
+ ) -> tuple[Vector, dict[str, Contribution], dict[str, Contribution]]:
+ dev = self.device
+ phi = state.field("potential_V")[dev.chem_node_indices]
+ dx = np.diff(dev.chem_geometry.nodes_m)
+ vt = dev.electronic_component.thermal_voltage_V
+ dens = state.field(self.species)
+ mass = state.field("mass:" + self.species)
+
+ if self.species == IODIDE:
+ diff = dev.iodide_diffusivity_faces_m2_s
+ log_part = dev.log_partition_minus_faces
+ charge = -1
+ steric = dev.steric_site_limit_m3
+ elif self.species == IODINE_ATOM:
+ diff = dev.atom_diffusivity_faces_m2_s
+ log_part = dev.log_partition_atom_faces
+ charge = 0
+ steric = None
+ else:
+ diff = dev.mol_diffusivity_faces_m2_s
+ log_part = dev.log_partition_mol_faces
+ charge = 0
+ steric = None
+
+ ev = species_sg_face_flux(
+ phi,
+ dens,
+ dx,
+ diff,
+ vt,
+ charge_number=charge,
+ log_partition_step=log_part,
+ steric_site_limit_m3=steric,
+ steric_diffusion_only=dev.steric_diffusion_only,
+ derivatives=derivatives,
+ )
+ if not derivatives:
+ return ev.flux_m2_s, {}, {}
+ assert (
+ ev.dflux_dc_left is not None
+ and ev.dflux_dc_right is not None
+ and ev.dflux_dphi_left is not None
+ and ev.dflux_dphi_right is not None
+ )
+ left: dict[str, Contribution] = {
+ self.species: ev.dflux_dc_left * mass[:-1],
+ }
+ right: dict[str, Contribution] = {
+ self.species: ev.dflux_dc_right * mass[1:],
+ }
+ if self.species == IODIDE:
+ left[POTENTIAL] = ev.dflux_dphi_left
+ right[POTENTIAL] = ev.dflux_dphi_right
+ return ev.flux_m2_s, left, right
+
+ def evaluate(
+ self, state: EvaluationState, *, derivatives: bool
+ ) -> Mapping[str, TermValue]:
+ flux, left, right = self.flux_evaluation(state, derivatives=derivatives)
+ if not derivatives:
+ return {self.species: FaceValue(flux)}
+ return {self.species: FaceValue(flux, left, right)}
+
+
+@dataclass(frozen=True)
+class IodineCarrierReactionTerm:
+ """Embed bulk iodine chemical sources ``(S_n, S_p)`` onto electronic ``nodes``."""
+
+ device: CompiledIodineDevice1D
+ id: str = "carrier.iodine_reactions"
+ kind: str = CELL_SOURCE
+ support: str = NODES
+ equations: tuple[str, ...] = (ELECTRON, HOLE)
+ dependencies: tuple[str, ...] = (
+ POTENTIAL,
+ ELECTRON,
+ HOLE,
+ IODIDE,
+ IODINE_ATOM,
+ IODINE_MOLECULE,
+ )
+ unit: Unit = SOURCE_UNIT
+ port: str | None = None
+
+ @property
+ def identity(self) -> str:
+ return _identity(self.id, self.device.identity)
+
+ def evaluate(
+ self, state: EvaluationState, *, derivatives: bool
+ ) -> Mapping[str, TermValue]:
+ dev = self.device
+ n_total = dev.node_count
+ idx = dev.chem_node_indices
+ ratio = state.embedding_ratio(CHEM_NODES)
+ sources = state.field("rxn:sources")
+
+ s_n: NDArray[np.float64] = np.zeros(n_total, dtype=np.float64)
+ s_p: NDArray[np.float64] = np.zeros(n_total, dtype=np.float64)
+ s_n[idx] = ratio * sources[0]
+ s_p[idx] = ratio * sources[1]
+ if not derivatives:
+ return {ELECTRON: LocalValue(s_n), HOLE: LocalValue(s_p)}
+
+ ds = state.field("rxn:dsources")
+ n_chem = state.field("electron_density_m3")[idx]
+ p_chem = state.field("hole_density_m3")[idx]
+ vt = dev.electronic_component.thermal_voltage_V
+ mm = state.field("mass:iodide")
+ m0 = state.field("mass:iodine_atom")
+ m2 = state.field("mass:iodine_molecule")
+
+ out: dict[str, TermValue] = {}
+ for sp_row, block, val in ((0, ELECTRON, s_n), (1, HOLE, s_p)):
+ t_phi_c, t_zn_c, t_zp_c = _carrier_chain_tangents(
+ ds[sp_row, 0], ds[sp_row, 1], n_chem, p_chem, vt
+ )
+ tangents: dict[str, Contribution] = {}
+ for dep, chem_tan in (
+ (POTENTIAL, t_phi_c),
+ (ELECTRON, t_zn_c),
+ (HOLE, t_zp_c),
+ (IODIDE, ds[sp_row, 2] * mm),
+ (IODINE_ATOM, ds[sp_row, 3] * m0),
+ (IODINE_MOLECULE, ds[sp_row, 4] * m2),
+ ):
+ full: NDArray[np.float64] = np.zeros(n_total, dtype=np.float64)
+ full[idx] = ratio * chem_tan
+ tangents[dep] = full
+ out[block] = LocalValue(val, tangents)
+ return out
+
+
+@dataclass(frozen=True)
+class IodineSpeciesReactionTerm:
+ """Bulk iodine chemical sources ``(S_-, S_0, S_2)`` on ``chem``."""
+
+ device: CompiledIodineDevice1D
+ id: str = "chem.iodine_reactions"
+ kind: str = CELL_SOURCE
+ support: str = CHEM_NODES
+ equations: tuple[str, ...] = IODINE_BLOCKS
+ dependencies: tuple[str, ...] = (
+ POTENTIAL,
+ ELECTRON,
+ HOLE,
+ IODIDE,
+ IODINE_ATOM,
+ IODINE_MOLECULE,
+ )
+ unit: Unit = SOURCE_UNIT
+ port: str | None = None
+
+ @property
+ def identity(self) -> str:
+ return _identity(self.id, self.device.identity)
+
+ def evaluate(
+ self, state: EvaluationState, *, derivatives: bool
+ ) -> Mapping[str, TermValue]:
+ dev = self.device
+ sources = state.field("rxn:sources")
+ if not derivatives:
+ return {
+ IODIDE: LocalValue(sources[2]),
+ IODINE_ATOM: LocalValue(sources[3]),
+ IODINE_MOLECULE: LocalValue(sources[4]),
+ }
+
+ idx = dev.chem_node_indices
+ ds = state.field("rxn:dsources")
+ n_chem = state.field("electron_density_m3")[idx]
+ p_chem = state.field("hole_density_m3")[idx]
+ vt = dev.electronic_component.thermal_voltage_V
+ mm = state.field("mass:iodide")
+ m0 = state.field("mass:iodine_atom")
+ m2 = state.field("mass:iodine_molecule")
+
+ out: dict[str, TermValue] = {}
+ for sp_row, block in (
+ (2, IODIDE),
+ (3, IODINE_ATOM),
+ (4, IODINE_MOLECULE),
+ ):
+ t_phi, t_zn, t_zp = _carrier_chain_tangents(
+ ds[sp_row, 0], ds[sp_row, 1], n_chem, p_chem, vt
+ )
+ tangents: dict[str, Contribution] = {
+ POTENTIAL: t_phi,
+ ELECTRON: t_zn,
+ HOLE: t_zp,
+ IODIDE: ds[sp_row, 2] * mm,
+ IODINE_ATOM: ds[sp_row, 3] * m0,
+ IODINE_MOLECULE: ds[sp_row, 4] * m2,
+ }
+ out[block] = LocalValue(sources[sp_row], tangents)
+ return out
+
+
+@dataclass(frozen=True)
+class IodineMoleculeEscapePortTerm:
+ """Volatile surface ``I_2`` escape ``J_out = k_loss * c_2`` on one port."""
+
+ device: CompiledIodineDevice1D
+ spec: IodineBoundaryPortSpec
+ kind: str = PORT_FLUX
+ support: str = CHEM_NODES
+ equations: tuple[str, ...] = (IODINE_MOLECULE,)
+ dependencies: tuple[str, ...] = (IODINE_MOLECULE,)
+ unit: Unit = FLUX_UNIT
+
+ @property
+ def id(self) -> str:
+ return f"chem.escape.{self.spec.side}"
+
+ @property
+ def port(self) -> str:
+ return self.spec.side
+
+ @property
+ def identity(self) -> str:
+ return _identity(self.id, self.device.identity, self.spec.side)
+
+ def evaluate(
+ self, state: EvaluationState, *, derivatives: bool
+ ) -> Mapping[str, TermValue]:
+ node = self.spec.chem_node
+ n_out = float(self.spec.outward_normal)
+ k_loss = self.spec.mol_escape_velocity_m_s
+ c2 = float(state.field(IODINE_MOLECULE)[node])
+ exchange = np.array([n_out * k_loss * c2], dtype=np.float64)
+ if not derivatives:
+ return {IODINE_MOLECULE: LocalValue(exchange)}
+ m2 = float(state.field("mass:iodine_molecule")[node])
+ return {
+ IODINE_MOLECULE: LocalValue(
+ exchange,
+ {IODINE_MOLECULE: np.array([n_out * k_loss * m2], dtype=np.float64)},
+ )
+ }
+
+
+@dataclass(frozen=True)
+class IodineVolumetricEscapeTerm:
+ """First-order volumetric ``I_2`` outgassing sink ``-k_outgas(x) * c_2``."""
+
+ device: CompiledIodineDevice1D
+ id: str = "chem.volumetric_escape"
+ kind: str = CELL_SOURCE
+ support: str = CHEM_NODES
+ equations: tuple[str, ...] = (IODINE_MOLECULE,)
+ dependencies: tuple[str, ...] = (IODINE_MOLECULE,)
+ unit: Unit = SOURCE_UNIT
+ port: str | None = None
+
+ @property
+ def identity(self) -> str:
+ return _identity(self.id, self.device.identity)
+
+ def evaluate(
+ self, state: EvaluationState, *, derivatives: bool
+ ) -> Mapping[str, TermValue]:
+ k_vol = self.device.volumetric_mol_escape_s_1
+ assert k_vol is not None
+ sink = -k_vol * state.field(IODINE_MOLECULE)
+ if not derivatives:
+ return {IODINE_MOLECULE: LocalValue(sink)}
+ m2 = state.field("mass:iodine_molecule")
+ return {
+ IODINE_MOLECULE: LocalValue(sink, {IODINE_MOLECULE: -k_vol * m2})
+ }
+
+
+def _contact_oxidation_rate_and_partials(
+ device: CompiledIodineDevice1D,
+ spec: IodineBoundaryPortSpec,
+ state: EvaluationState,
+) -> tuple[float, float, float, float]:
+ """Return ``(J_ct, dJ/dp, dJ/dc_-, dJ/dc_0)`` at ``spec``."""
+ cm_val = float(state.field(IODIDE)[spec.chem_node])
+ if spec.contact_reaction_mode == "metal_faradaic_corrosion":
+ v_corr = spec.contact_corrosion_velocity_m_s
+ return v_corr * cm_val, 0.0, v_corr, 0.0
+ k_ct = spec.contact_oxidation_rate_m4_s
+ p_val = float(state.field("hole_density_m3")[spec.elec_node])
+ c0_val = float(state.field(IODINE_ATOM)[spec.chem_node])
+ if spec.reversible_contact:
+ rate = k_ct * (cm_val * p_val - spec.p1_iodine_m3 * c0_val)
+ return rate, k_ct * cm_val, k_ct * p_val, -k_ct * spec.p1_iodine_m3
+ rate = k_ct * cm_val * p_val
+ return rate, k_ct * cm_val, k_ct * p_val, 0.0
+
+
+@dataclass(frozen=True)
+class IodineContactReactionPortTerm:
+ """Surface contact reaction port on ``iodide`` or ``iodine_atom``."""
+
+ device: CompiledIodineDevice1D
+ spec: IodineBoundaryPortSpec
+ species: Literal["iodide", "iodine_atom"]
+ kind: str = PORT_FLUX
+ support: str = CHEM_NODES
+ unit: Unit = FLUX_UNIT
+
+ @property
+ def id(self) -> str:
+ return f"chem.contact_reaction.{self.species}.{self.spec.side}"
+
+ @property
+ def port(self) -> str:
+ return self.spec.side
+
+ @property
+ def equations(self) -> tuple[str, ...]:
+ return (self.species,)
+
+ @property
+ def dependencies(self) -> tuple[str, ...]:
+ return (POTENTIAL, HOLE, IODIDE, IODINE_ATOM)
+
+ @property
+ def identity(self) -> str:
+ return _identity(self.id, self.device.identity)
+
+ def evaluate(
+ self, state: EvaluationState, *, derivatives: bool
+ ) -> Mapping[str, TermValue]:
+ spec = self.spec
+ # Outward loss is +J_ct for iodide (consumed) and -J_ct for iodine_atom (created)
+ sign = 1.0 if self.species == IODIDE else -1.0
+ n_out = float(spec.outward_normal) * sign
+ rate, dj_dp, dj_dcm, dj_dc0 = _contact_oxidation_rate_and_partials(
+ self.device, spec, state
+ )
+ exchange = np.array([n_out * rate], dtype=np.float64)
+ if not derivatives:
+ return {self.species: LocalValue(exchange)}
+ p_val = float(state.field("hole_density_m3")[spec.elec_node])
+ vt = self.device.electronic_component.thermal_voltage_V
+ mm = float(state.field("mass:iodide")[spec.chem_node])
+ m0 = float(state.field("mass:iodine_atom")[spec.chem_node])
+ tangents: dict[str, Contribution] = {
+ POTENTIAL: np.array([n_out * (-dj_dp * p_val / vt)], dtype=np.float64),
+ HOLE: np.array([n_out * (-dj_dp * p_val)], dtype=np.float64),
+ IODIDE: np.array([n_out * dj_dcm * mm], dtype=np.float64),
+ IODINE_ATOM: np.array([n_out * dj_dc0 * m0], dtype=np.float64),
+ }
+ return {self.species: LocalValue(exchange, tangents)}
+
+
+@dataclass(frozen=True)
+class IodineHoleContactPortTerm:
+ """Hole consumption ``-J_ct`` on ``nodes`` from contact oxidation ``I^- + h^+ -> I^0``."""
+
+ device: CompiledIodineDevice1D
+ spec: IodineBoundaryPortSpec
+ kind: str = PORT_FLUX
+ support: str = NODES
+ equations: tuple[str, ...] = (HOLE,)
+ dependencies: tuple[str, ...] = (POTENTIAL, HOLE, IODIDE, IODINE_ATOM)
+ unit: Unit = FLUX_UNIT
+
+ @property
+ def id(self) -> str:
+ return f"hole.iodine_contact_reaction.{self.spec.side}"
+
+ @property
+ def port(self) -> str:
+ return f"chem_{self.spec.side}"
+
+ @property
+ def identity(self) -> str:
+ return _identity(self.id, self.device.identity)
+
+ def evaluate(
+ self, state: EvaluationState, *, derivatives: bool
+ ) -> Mapping[str, TermValue]:
+ spec = self.spec
+ n_out = float(spec.outward_normal)
+ rate, dj_dp, dj_dcm, dj_dc0 = _contact_oxidation_rate_and_partials(
+ self.device, spec, state
+ )
+ exchange = np.array([n_out * rate], dtype=np.float64)
+ if not derivatives:
+ return {HOLE: LocalValue(exchange)}
+ p_val = float(state.field("hole_density_m3")[spec.elec_node])
+ vt = self.device.electronic_component.thermal_voltage_V
+ mm = float(state.field("mass:iodide")[spec.chem_node])
+ m0 = float(state.field("mass:iodine_atom")[spec.chem_node])
+ tangents: dict[str, Contribution] = {
+ POTENTIAL: np.array([n_out * (-dj_dp * p_val / vt)], dtype=np.float64),
+ HOLE: np.array([n_out * (-dj_dp * p_val)], dtype=np.float64),
+ IODIDE: np.array([n_out * dj_dcm * mm], dtype=np.float64),
+ IODINE_ATOM: np.array([n_out * dj_dc0 * m0], dtype=np.float64),
+ }
+ return {HOLE: LocalValue(exchange, tangents)}
+
+
+@dataclass(frozen=True)
+class TotalIodineInventoryTerm:
+ """Closed-domain steady constraint ``sum w (c_- + c_0 + 2 c_2) - M_I,0 = 0``."""
+
+ device: CompiledIodineDevice1D
+ id: str = "chem.total_iodine_inventory"
+ kind: str = CONSTRAINT
+ support: str = CHEM_NODES
+ equations: tuple[str, ...] = (IODIDE,)
+ dependencies: tuple[str, ...] = IODINE_BLOCKS
+ unit: Unit = DENSITY_UNIT
+ port: str | None = None
+ measure: str = "cell"
+
+ @property
+ def identity(self) -> str:
+ return _identity(self.id, self.device.identity)
+
+ def evaluate(
+ self, state: EvaluationState, *, derivatives: bool
+ ) -> Mapping[str, TermValue]:
+ cm = state.field(IODIDE)
+ c0 = state.field(IODINE_ATOM)
+ c2 = state.field(IODINE_MOLECULE)
+ summand = cm + c0 + 2.0 * c2
+ u_ref = self.device.initial_chem_coordinates()
+ m = self.device.chem_node_count
+ ref = (
+ self.device.iodide_map.density_m3(u_ref[:m])
+ + self.device.atom_map.density_m3(u_ref[m : 2 * m])
+ + 2.0 * self.device.mol_map.density_m3(u_ref[2 * m : 3 * m])
+ )
+ if not derivatives:
+ return {IODIDE: ReductionValue(summand, reference=ref)}
+ tangents: dict[str, Contribution] = {
+ IODIDE: state.field("mass:iodide"),
+ IODINE_ATOM: state.field("mass:iodine_atom"),
+ IODINE_MOLECULE: 2.0 * state.field("mass:iodine_molecule"),
+ }
+ return {IODIDE: ReductionValue(summand, tangents=tangents, reference=ref)}
+
+
+@dataclass(frozen=True)
+class SingleSpeciesInventoryTerm:
+ """Closed-domain steady inventory constraint for one unreactive species."""
+
+ device: CompiledIodineDevice1D
+ species: Literal["iodide", "iodine_atom", "iodine_molecule"]
+ kind: str = CONSTRAINT
+ support: str = CHEM_NODES
+ unit: Unit = DENSITY_UNIT
+ port: str | None = None
+ measure: str = "cell"
+
+ @property
+ def id(self) -> str:
+ return f"chem.inventory.{self.species}"
+
+ @property
+ def equations(self) -> tuple[str, ...]:
+ return (self.species,)
+
+ @property
+ def dependencies(self) -> tuple[str, ...]:
+ return (self.species,)
+
+ @property
+ def identity(self) -> str:
+ return _identity(self.id, self.device.identity)
+
+ def evaluate(
+ self, state: EvaluationState, *, derivatives: bool
+ ) -> Mapping[str, TermValue]:
+ dens = state.field(self.species)
+ u_ref = self.device.initial_chem_coordinates()
+ m = self.device.chem_node_count
+ if self.species == IODIDE:
+ ref = self.device.iodide_map.density_m3(u_ref[:m])
+ elif self.species == IODINE_ATOM:
+ ref = self.device.atom_map.density_m3(u_ref[m : 2 * m])
+ else:
+ ref = self.device.mol_map.density_m3(u_ref[2 * m : 3 * m])
+ if not derivatives:
+ return {self.species: ReductionValue(dens, reference=ref)}
+ return {
+ self.species: ReductionValue(
+ dens,
+ tangents={self.species: state.field("mass:" + self.species)},
+ reference=ref,
+ )
+ }
+
+
+def _build_layout_and_terms(
+ device: CompiledIodineDevice1D,
+ *,
+ constrained_steady: bool,
+ inventory_node: int = 0,
+) -> tuple[
+ SystemLayout,
+ Mesh,
+ list[Term],
+ CarrierTransport,
+ BulkRecombination,
+ dict[tuple[str, str], CarrierExchange],
+ dict[str, IodineTransportTerm],
+]:
+ comp = device.electronic_component
+ n_count = comp.node_count
+ m_count = device.chem_node_count
+ if not 0 <= inventory_node < m_count:
+ raise ValueError("inventory_node must index a chemical domain node")
+
+ constraints: list[ConstraintRows] = [
+ ConstraintRows(POTENTIAL, (0, n_count - 1), "potential.contacts", VOLT)
+ ]
+ for block, carrier, _ in CARRIERS:
+ fixed_nodes = tuple(
+ node
+ for side, node in (("left", 0), ("right", n_count - 1))
+ if comp.channel(carrier, side).kind == "fixed_reservoir"
+ )
+ if fixed_nodes:
+ constraints.append(
+ ConstraintRows(block, fixed_nodes, block + ".reservoirs", ONE)
+ )
+
+ if constrained_steady:
+ if device.has_open_iodine_loss:
+ raise CapabilityError(
+ "open-boundary iodine escape or irreversible surface immobilization "
+ "has no non-trivial closed steady inventory; use transient solving"
+ )
+ if device.is_unreactive_limit:
+ for sp in IODINE_BLOCKS:
+ constraints.append(
+ ConstraintRows(
+ sp, (inventory_node,), f"chem.inventory.{sp}", INVENTORY_UNIT
+ )
+ )
+ else:
+ constraints.append(
+ ConstraintRows(
+ IODIDE,
+ (inventory_node,),
+ "chem.total_iodine_inventory",
+ INVENTORY_UNIT,
+ )
+ )
+
+ node_sets = (
+ NodeSet(NODES, n_count),
+ NodeSet(
+ CHEM_NODES,
+ m_count,
+ parent=NODES,
+ parent_indices=tuple(int(i) for i in device.chem_node_indices),
+ ),
+ )
+ blocks = (
+ Block(POTENTIAL, NODES, VOLT, DISPLACEMENT_UNIT),
+ Block(ELECTRON, NODES, ONE, FLUX_UNIT),
+ Block(HOLE, NODES, ONE, FLUX_UNIT),
+ Block(IODIDE, CHEM_NODES, ONE, FLUX_UNIT),
+ Block(IODINE_ATOM, CHEM_NODES, ONE, FLUX_UNIT),
+ Block(IODINE_MOLECULE, CHEM_NODES, ONE, FLUX_UNIT),
+ )
+ layout = SystemLayout(node_sets, blocks, tuple(constraints))
+
+ # Mesh supports & boundary ports
+ elec_geom = comp.geometry.to_contract_geometry(
+ cell_support=NODES, face_support=NODES + ".faces"
+ )
+ elec_ports = [
+ Port(
+ face.id,
+ (face.node,),
+ face.outward_normal,
+ np.array([face.area_m2]),
+ ONE,
+ )
+ for face in comp.geometry.ports
+ ]
+ if comp.interface_model is not None:
+ interior = tuple(range(1, n_count - 1))
+ elec_ports.append(Port("interfaces", interior, -1, np.ones(len(interior)), ONE))
+ for bspec in (device.left_boundary, device.right_boundary):
+ elec_ports.append(
+ Port(
+ f"chem_{bspec.side}",
+ (bspec.elec_node,),
+ bspec.outward_normal,
+ np.array([1.0]),
+ ONE,
+ )
+ )
+
+ chem_geom = device.chem_geometry.to_contract_geometry(
+ cell_support=CHEM_NODES, face_support=CHEM_NODES + ".faces"
+ )
+ chem_ports = (
+ Port(
+ "left",
+ (device.left_boundary.chem_node,),
+ device.left_boundary.outward_normal,
+ np.array([1.0]),
+ ONE,
+ ),
+ Port(
+ "right",
+ (device.right_boundary.chem_node,),
+ device.right_boundary.outward_normal,
+ np.array([1.0]),
+ ONE,
+ ),
+ )
+ mesh = Mesh(
+ (
+ SupportGeometry(NODES, elec_geom, tuple(elec_ports)),
+ SupportGeometry(CHEM_NODES, chem_geom, chem_ports),
+ )
+ )
+
+ carrier_transport = CarrierTransport(comp)
+ recombination = BulkRecombination(comp)
+ chem_transports: dict[str, IodineTransportTerm] = {
+ IODIDE: IodineTransportTerm(device, IODIDE),
+ IODINE_ATOM: IodineTransportTerm(device, IODINE_ATOM),
+ IODINE_MOLECULE: IodineTransportTerm(device, IODINE_MOLECULE),
+ }
+
+ terms: list[Term] = [
+ GaussDisplacement(comp),
+ IodineSpaceChargeTerm(device),
+ PotentialContacts(comp),
+ carrier_transport,
+ CarrierGeneration(comp),
+ recombination,
+ CarrierStorage(comp),
+ IodineCarrierReactionTerm(device),
+ IodineSpeciesStorageTerm(device),
+ chem_transports[IODIDE],
+ chem_transports[IODINE_ATOM],
+ chem_transports[IODINE_MOLECULE],
+ IodineSpeciesReactionTerm(device),
+ ]
+ if comp.interface_model is not None:
+ if comp.interface_model.has_sheet_charge:
+ terms.append(InterfaceGaussPort(comp))
+ if comp.interface_model.has_carrier_port:
+ terms.append(InterfaceCarrierPort(comp, ELECTRON))
+ terms.append(InterfaceCarrierPort(comp, HOLE))
+
+ exchanges: dict[tuple[str, str], CarrierExchange] = {}
+ for block, carrier, _ in CARRIERS:
+ fixed: list[int] = []
+ for side, node in (("left", 0), ("right", n_count - 1)):
+ channel = comp.channel(carrier, side)
+ if channel.kind == "fixed_reservoir":
+ fixed.append(node)
+ else:
+ exchanges[(block, side)] = CarrierExchange(comp, block, channel, node)
+ if fixed:
+ terms.append(CarrierReservoirs(comp, block, tuple(fixed)))
+ terms.extend(exchanges.values())
+
+ # Volumetric outgassing and boundary escape / contact oxidation ports
+ assert device.volumetric_mol_escape_s_1 is not None
+ if np.any(device.volumetric_mol_escape_s_1 > 0.0):
+ terms.append(IodineVolumetricEscapeTerm(device))
+ for bspec in (device.left_boundary, device.right_boundary):
+ if bspec.mol_escape_velocity_m_s > 0.0:
+ terms.append(IodineMoleculeEscapePortTerm(device, bspec))
+ if (
+ bspec.contact_reaction_mode == "metal_faradaic_corrosion"
+ and bspec.contact_corrosion_velocity_m_s > 0.0
+ ):
+ terms.append(IodineContactReactionPortTerm(device, bspec, IODIDE))
+ elif (
+ bspec.contact_reaction_mode != "none"
+ and bspec.contact_oxidation_rate_m4_s > 0.0
+ ):
+ terms.append(IodineHoleContactPortTerm(device, bspec))
+ terms.append(IodineContactReactionPortTerm(device, bspec, IODIDE))
+ if bspec.contact_reaction_mode == "hole_oxidation_to_I0":
+ terms.append(
+ IodineContactReactionPortTerm(device, bspec, IODINE_ATOM)
+ )
+
+ if constrained_steady:
+ if device.is_unreactive_limit:
+ terms.append(SingleSpeciesInventoryTerm(device, IODIDE))
+ terms.append(SingleSpeciesInventoryTerm(device, IODINE_ATOM))
+ terms.append(SingleSpeciesInventoryTerm(device, IODINE_MOLECULE))
+ else:
+ terms.append(TotalIodineInventoryTerm(device))
+
+ return (
+ layout,
+ mesh,
+ terms,
+ carrier_transport,
+ recombination,
+ exchanges,
+ chem_transports,
+ )
+
+
+@dataclass(frozen=True)
+class IodineSystem:
+ """Reusable bound ``Assembler`` for transient or steady iodine systems."""
+
+ device: CompiledIodineDevice1D
+ constrained_steady: bool = False
+ inventory_node: int = 0
+ assembler: Assembler = field(init=False, repr=False)
+ carrier_transport: CarrierTransport = field(init=False, repr=False)
+ recombination: BulkRecombination = field(init=False, repr=False)
+ exchanges: Mapping[tuple[str, str], CarrierExchange] = field(init=False, repr=False)
+ chem_transports: Mapping[str, IodineTransportTerm] = field(init=False, repr=False)
+
+ def __post_init__(self) -> None:
+ (
+ layout,
+ mesh,
+ terms,
+ carrier_transport,
+ recombination,
+ exchanges,
+ chem_transports,
+ ) = _build_layout_and_terms(
+ self.device,
+ constrained_steady=self.constrained_steady,
+ inventory_node=self.inventory_node,
+ )
+ assembler = Assembler(layout, mesh, IodineFields(self.device), terms)
+ object.__setattr__(self, "assembler", assembler)
+ object.__setattr__(self, "carrier_transport", carrier_transport)
+ object.__setattr__(self, "recombination", recombination)
+ object.__setattr__(self, "exchanges", exchanges)
+ object.__setattr__(self, "chem_transports", chem_transports)
+
+ @property
+ def layout(self) -> SystemLayout:
+ return self.assembler.layout
+
+ @property
+ def identity(self) -> str:
+ return self.assembler.identity
+
+
+def iodine_system(
+ device: CompiledIodineDevice1D,
+ *,
+ constrained_steady: bool = False,
+ inventory_node: int = 0,
+) -> IodineSystem:
+ if not isinstance(device, CompiledIodineDevice1D):
+ raise TypeError("iodine_system requires a CompiledIodineDevice1D")
+ return IodineSystem(
+ device=device,
+ constrained_steady=constrained_steady,
+ inventory_node=inventory_node,
+ )
+
+
+@dataclass(frozen=True)
+class AssembledIodine1DProblem:
+ """Unconstrained assembled iodine 1D DAE problem implementing ``StorageProblem``."""
+
+ device: CompiledIodineDevice1D
+ voltage_V: float = 0.0
+ generation_scale: float = 0.0
+ binding: IodineSystem | None = field(default=None, repr=False, compare=False)
+
+ def __post_init__(self) -> None:
+ v = float(self.voltage_V)
+ g = float(self.generation_scale)
+ if not math.isfinite(v):
+ raise ValueError("voltage_V must be finite")
+ if not math.isfinite(g) or g < 0.0:
+ raise ValueError("generation_scale must be finite and nonnegative")
+ object.__setattr__(self, "voltage_V", v)
+ object.__setattr__(self, "generation_scale", g)
+ system = self.binding
+ if system is None:
+ system = iodine_system(self.device, constrained_steady=False)
+ elif system.device is not self.device or system.constrained_steady:
+ raise ValueError("binding must match device with constrained_steady=False")
+ object.__setattr__(self, "binding", system)
+
+ @property
+ def inputs(self) -> OperatingInputs:
+ return OperatingInputs(
+ voltage_V=self.voltage_V,
+ generation_scale=self.generation_scale,
+ )
+
+ def evaluate_system(
+ self, u: ArrayLike, *, derivatives: bool = True, storage: bool = False
+ ) -> AssembledSystem:
+ assert self.binding is not None
+ return self.binding.assembler.evaluate(
+ u, self.inputs, derivatives=derivatives, storage=storage
+ )
+
+ def residual(self, u: Vector) -> Vector:
+ ev = self.evaluate_system(u, derivatives=False, storage=False)
+ if not ev.admissible or not np.all(np.isfinite(ev.F)):
+ raise FloatingPointError("iodine 1D residual is outside finite domain")
+ return ev.F
+
+ def jacobian(self, u: Vector) -> csc_matrix:
+ ev = self.evaluate_system(u, derivatives=True, storage=False)
+ if (
+ not ev.admissible
+ or ev.J is None
+ or (
+ ev.replaced_nonfinite_rows is not None
+ and np.any(ev.replaced_nonfinite_rows)
+ )
+ or not np.all(np.isfinite(ev.J.data))
+ ):
+ raise FloatingPointError("iodine 1D Jacobian is outside finite domain")
+ return ev.J
+
+ def storage(self, u: Vector) -> Vector:
+ assert self.binding is not None
+ s_val, _ = self.binding.assembler.storage(u, self.inputs, derivatives=False)
+ return s_val
+
+ def storage_tangent(self, u: Vector) -> csc_matrix:
+ assert self.binding is not None
+ _, s_tan = self.binding.assembler.storage(u, self.inputs, derivatives=True)
+ assert s_tan is not None
+ return s_tan
+
+ def storage_jacobian(self, u: Vector) -> csc_matrix:
+ """Signed mass matrix ``M = -S_u`` for small-signal AC conventions."""
+ return -self.storage_tangent(u)
+
+ def storage_increment(
+ self, u: Vector, old_problem: object, old_u: Vector
+ ) -> Vector:
+ if not isinstance(old_problem, AssembledIodine1DProblem):
+ raise TypeError("storage_increment requires AssembledIodine1DProblem")
+ assert self.binding is not None and old_problem.binding is not None
+ if old_problem.binding.identity != self.binding.identity:
+ raise ValueError("storage_increment requires identical system binding")
+ return self.binding.assembler.storage_increment(
+ u, self.inputs, old_u, old_problem.inputs, physical=False
+ )
+
+ def physical_storage(self, u: Vector) -> Vector:
+ assert self.binding is not None
+ return self.binding.assembler.physical_storage(u, self.inputs)
+
+ def physical_increment(
+ self, u: Vector, old_problem: AssembledIodine1DProblem, old_u: Vector
+ ) -> Vector:
+ assert self.binding is not None and old_problem.binding is not None
+ if old_problem.binding.identity != self.binding.identity:
+ raise ValueError("physical_increment requires identical system binding")
+ return self.binding.assembler.storage_increment(
+ u, self.inputs, old_u, old_problem.inputs, physical=True
+ )
+
+ def carrier_fluxes(self, u: Vector) -> CarrierFaceFluxes:
+ assert self.binding is not None
+ ev_state = self.binding.assembler.state(u, self.inputs)
+ if ev_state is None:
+ raise FloatingPointError("inadmissible state in carrier_fluxes")
+ return self.binding.carrier_transport.fluxes(ev_state)
+
+ def species_fluxes_m2_s(self, u: Vector) -> dict[str, Vector]:
+ assert self.binding is not None
+ ev_state = self.binding.assembler.state(u, self.inputs)
+ if ev_state is None:
+ raise FloatingPointError("inadmissible state in species_fluxes_m2_s")
+ return {
+ sp: frozen_array(
+ self.binding.chem_transports[sp]
+ .flux_evaluation(ev_state, derivatives=False)[0]
+ )
+ for sp in IODINE_BLOCKS
+ }
+
+ def boundary_rates_m2_s(self, u: Vector) -> dict[str, float]:
+ """Return outward ``I_2`` escape and contact oxidation rates [m^-2 s^-1]."""
+ assert self.binding is not None
+ ev_state = self.binding.assembler.state(u, self.inputs)
+ if ev_state is None:
+ raise FloatingPointError("inadmissible state in boundary_rates_m2_s")
+ c2 = ev_state.field(IODINE_MOLECULE)
+ left_b = self.device.left_boundary
+ right_b = self.device.right_boundary
+ esc_left = left_b.mol_escape_velocity_m_s * float(c2[left_b.chem_node])
+ esc_right = right_b.mol_escape_velocity_m_s * float(c2[right_b.chem_node])
+ k_vol = self.device.volumetric_mol_escape_s_1
+ assert k_vol is not None
+ esc_vol = (
+ float(
+ math.fsum(
+ (self.device.chem_geometry.cell_measures_m * k_vol * c2).tolist()
+ )
+ )
+ if np.any(k_vol > 0.0)
+ else 0.0
+ )
+ ct_left = (
+ _contact_oxidation_rate_and_partials(self.device, left_b, ev_state)[0]
+ if left_b.contact_reaction_mode != "none"
+ and (
+ left_b.contact_oxidation_rate_m4_s > 0.0
+ or left_b.contact_corrosion_velocity_m_s > 0.0
+ )
+ else 0.0
+ )
+ ct_right = (
+ _contact_oxidation_rate_and_partials(self.device, right_b, ev_state)[0]
+ if right_b.contact_reaction_mode != "none"
+ and (
+ right_b.contact_oxidation_rate_m4_s > 0.0
+ or right_b.contact_corrosion_velocity_m_s > 0.0
+ )
+ else 0.0
+ )
+ return {
+ "mol_escape_left_m2_s": esc_left,
+ "mol_escape_right_m2_s": esc_right,
+ "volumetric_mol_escape_m2_s": esc_vol,
+ "contact_oxidation_left_m2_s": ct_left,
+ "contact_oxidation_right_m2_s": ct_right,
+ }
+
+ def face_conduction_current_A_m2(self, u: Vector) -> Vector:
+ """Total particle conduction current ``J_n + J_p + J_I-`` on every face."""
+ cf = self.carrier_fluxes(u)
+ j_face = Q * (cf.hole.flux - cf.electron.flux)
+ j_iodide_chem = -Q * self.species_fluxes_m2_s(u)[IODIDE]
+ if self.device.chem_node_count == self.device.node_count:
+ return frozen_array(j_face + j_iodide_chem)
+ start = int(self.device.chem_node_indices[0])
+ full = j_face.copy()
+ full[start : start + j_iodide_chem.size] += j_iodide_chem
+ return frozen_array(full)
+
+ def steady_current_density_A_m2(self, u: Vector) -> float:
+ """Spatial mean steady conduction current density [A/m^2]."""
+ dx = np.diff(self.device.electronic_component.nodes_m)
+ j_faces = self.face_conduction_current_A_m2(u)
+ return float(math.fsum((dx * j_faces).tolist()) / math.fsum(dx.tolist()))
+
+ def contact_displacement_C_m2(self, u: Vector) -> tuple[float, float]:
+ """Left and right electrode Gauss surface charges [C/m^2]."""
+ phi, n, p, cm, _, _, _, _, _ = self.device.fields_and_tangents(
+ u, voltage_V=self.voltage_V
+ )
+ rho = self.device.charge_ledger(n, p, cm).space_charge_C_m3()
+ comp = self.device.electronic_component
+ d_left, d_right = contact_displacement(
+ comp.poisson.face_displacement(phi),
+ rho,
+ comp.geometry.cell_measures_m,
+ )
+ return float(d_left), float(d_right)
+
+ def recombination_rate(
+ self, n: Vector, p: Vector, *, derivatives: bool = True
+ ) -> RecombinationRate:
+ assert self.binding is not None
+ return self.binding.recombination.rate(n, p, derivatives=derivatives)
+
+ def contact_exchange(
+ self, u: Vector, channel: CarrierExchangeChannel, node: int
+ ) -> tuple[float, float]:
+ assert self.binding is not None
+ block = ELECTRON if channel.carrier == "n" else HOLE
+ term = self.binding.exchanges[(block, channel.side)]
+ n_count = self.device.node_count
+ offset = n_count if block == ELECTRON else 2 * n_count
+ return term.exchange(float(u[node]), float(u[offset + node]), self.voltage_V)
+
+
+@dataclass(frozen=True)
+class AssembledConstrainedIodine1DProblem:
+ """Closed-domain steady iodine 1D system enforcing total iodine inventory."""
+
+ device: CompiledIodineDevice1D
+ voltage_V: float = 0.0
+ generation_scale: float = 0.0
+ inventory_node: int = 0
+ binding: IodineSystem | None = field(default=None, repr=False, compare=False)
+
+ def __post_init__(self) -> None:
+ v = float(self.voltage_V)
+ g = float(self.generation_scale)
+ if not math.isfinite(v):
+ raise ValueError("voltage_V must be finite")
+ if not math.isfinite(g) or g < 0.0:
+ raise ValueError("generation_scale must be finite and nonnegative")
+ object.__setattr__(self, "voltage_V", v)
+ object.__setattr__(self, "generation_scale", g)
+ system = self.binding
+ if system is None:
+ system = iodine_system(
+ self.device,
+ constrained_steady=True,
+ inventory_node=self.inventory_node,
+ )
+ elif (
+ system.device is not self.device
+ or not system.constrained_steady
+ or system.inventory_node != self.inventory_node
+ ):
+ raise ValueError("binding must match constrained steady configuration")
+ object.__setattr__(self, "binding", system)
+
+ @property
+ def inputs(self) -> OperatingInputs:
+ return OperatingInputs(
+ voltage_V=self.voltage_V,
+ generation_scale=self.generation_scale,
+ )
+
+ def evaluate_system(
+ self, u: ArrayLike, *, derivatives: bool = True
+ ) -> AssembledSystem:
+ assert self.binding is not None
+ return self.binding.assembler.evaluate(
+ u, self.inputs, derivatives=derivatives, storage=False
+ )
+
+ def residual(self, u: Vector) -> Vector:
+ ev = self.evaluate_system(u, derivatives=False)
+ if not ev.admissible or not np.all(np.isfinite(ev.F)):
+ raise FloatingPointError("constrained iodine residual outside finite domain")
+ return ev.F
+
+ def jacobian(self, u: Vector) -> csc_matrix:
+ ev = self.evaluate_system(u, derivatives=True)
+ if (
+ not ev.admissible
+ or ev.J is None
+ or (
+ ev.replaced_nonfinite_rows is not None
+ and np.any(ev.replaced_nonfinite_rows)
+ )
+ or not np.all(np.isfinite(ev.J.data))
+ ):
+ raise FloatingPointError(
+ "constrained iodine Jacobian outside finite domain"
+ )
+ return ev.J
diff --git a/src/solarlab/equations/iodine_1d.py b/src/solarlab/equations/iodine_1d.py
new file mode 100644
index 00000000..1b1b46d5
--- /dev/null
+++ b/src/solarlab/equations/iodine_1d.py
@@ -0,0 +1,477 @@
+"""Bound 1D iodine reaction-diffusion-electrostatics device and state contracts.
+
+Separates immutable compiled data (:class:`CompiledIodineDevice1D` and
+:class:`IodineState1D`) from device-input resolution (:mod:`solarlab.device`)
+and nonlinear/time solvers (:mod:`solarlab.solvers`) in strict compliance with
+SolarLab's ``import-linter`` layer hierarchy.
+"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass, field
+import json
+import math
+from typing import Literal, get_args
+
+import numpy as np
+from numpy.typing import ArrayLike, NDArray
+
+from solarlab.contracts import ContractError, Vector, frozen_array, integer_indices
+from solarlab.equations.dc_1d import CompiledDevice1D, State1D
+from solarlab.mesh.geometry import ControlVolumeGeometry1D
+from solarlab.physics.chemistry import (
+ IodineKineticsParameters,
+ SpeciesCoordinateMap,
+)
+from solarlab.physics.electrostatics.charge import ChargeEntry, ChargeLedger
+
+__all__ = [
+ "ContactReactionMode",
+ "CompiledIodineDevice1D",
+ "IODINE_BLOCKS",
+ "IodineBoundaryPortSpec",
+ "IodineDomainMode",
+ "IodineState1D",
+]
+
+IODINE_BLOCKS: tuple[str, str, str] = ("iodide", "iodine_atom", "iodine_molecule")
+
+IodineDomainMode = Literal["absorber_blocking", "full_stack_permeable"]
+ContactReactionMode = Literal[
+ "none",
+ "hole_oxidation_to_I0",
+ "immobilized_product_sheet",
+ "metal_faradaic_corrosion",
+]
+
+_DOMAIN_MODES: frozenset[str] = frozenset(get_args(IodineDomainMode))
+_CONTACT_MODES: frozenset[str] = frozenset(get_args(ContactReactionMode))
+
+
+@dataclass(frozen=True, slots=True)
+class IodineBoundaryPortSpec:
+ """Boundary port closure for outer ``left`` or ``right`` chemical boundary."""
+
+ side: Literal["left", "right"]
+ chem_node: int
+ elec_node: int
+ outward_normal: int
+ mol_escape_velocity_m_s: float = 0.0
+ contact_reaction_mode: ContactReactionMode = "none"
+ contact_oxidation_rate_m4_s: float = 0.0
+ contact_corrosion_velocity_m_s: float = 0.0
+ p1_iodine_m3: float = 0.0
+ reversible_contact: bool = False
+
+ def __post_init__(self) -> None:
+ if self.side not in ("left", "right"):
+ raise ContractError("boundary_side_must_be_left_or_right")
+ if self.outward_normal not in (-1, 1):
+ raise ContractError("boundary_outward_normal_must_be_unit_sign")
+ if self.contact_reaction_mode not in _CONTACT_MODES:
+ raise ContractError("unknown_contact_reaction_mode")
+ for label, val in (
+ ("mol_escape_velocity_m_s", self.mol_escape_velocity_m_s),
+ ("contact_oxidation_rate_m4_s", self.contact_oxidation_rate_m4_s),
+ ("contact_corrosion_velocity_m_s", self.contact_corrosion_velocity_m_s),
+ ("p1_iodine_m3", self.p1_iodine_m3),
+ ):
+ fval = float(val)
+ if not math.isfinite(fval) or fval < 0.0:
+ raise ContractError(f"{label}_must_be_finite_nonnegative")
+ object.__setattr__(self, label, fval)
+ if self.contact_reaction_mode == "none" and (
+ self.contact_oxidation_rate_m4_s > 0.0
+ or self.contact_corrosion_velocity_m_s > 0.0
+ ):
+ raise ContractError(
+ "positive_contact_oxidation_rate_requires_conserving_reaction_mode"
+ )
+
+ @property
+ def removes_device_iodine(self) -> bool:
+ """True if this boundary allows net iodine loss from mobile inventory."""
+ return (
+ self.mol_escape_velocity_m_s > 0.0
+ or (
+ self.contact_reaction_mode == "immobilized_product_sheet"
+ and self.contact_oxidation_rate_m4_s > 0.0
+ )
+ or (
+ self.contact_reaction_mode == "metal_faradaic_corrosion"
+ and self.contact_corrosion_velocity_m_s > 0.0
+ )
+ )
+
+
+@dataclass(frozen=True, slots=True)
+class IodineState1D:
+ """Physical trial/accepted state of a 1D iodine-chemistry device."""
+
+ u: Vector
+ electronic_state: State1D
+ iodide_density_m3: Vector
+ iodine_atom_density_m3: Vector
+ iodine_molecule_density_m3: Vector
+ total_iodine_inventory_m2: float
+ species_inventories_m2: dict[str, float]
+ device_sha256: str
+
+ def __post_init__(self) -> None:
+ object.__setattr__(self, "u", frozen_array(self.u))
+ object.__setattr__(
+ self, "iodide_density_m3", frozen_array(self.iodide_density_m3)
+ )
+ object.__setattr__(
+ self, "iodine_atom_density_m3", frozen_array(self.iodine_atom_density_m3)
+ )
+ object.__setattr__(
+ self,
+ "iodine_molecule_density_m3",
+ frozen_array(self.iodine_molecule_density_m3),
+ )
+ n_elec = self.electronic_state.potential_V.size
+ m_chem = self.iodide_density_m3.size
+ if self.u.shape != (3 * n_elec + 3 * m_chem,):
+ raise ValueError("iodine state vector shape mismatch")
+ if not np.array_equal(self.u[: 3 * n_elec], self.electronic_state.u):
+ raise ValueError("iodine state must match its electronic component state")
+ for arr in (
+ self.iodide_density_m3,
+ self.iodine_atom_density_m3,
+ self.iodine_molecule_density_m3,
+ ):
+ if arr.shape != (m_chem,) or not np.all(np.isfinite(arr)) or np.any(arr <= 0.0):
+ raise ValueError("iodine species densities must be finite and positive")
+
+ @property
+ def voltage_V(self) -> float:
+ return self.electronic_state.voltage_V
+
+
+@dataclass(frozen=True)
+class CompiledIodineDevice1D:
+ """Immutable compiled 1D device with coupled ``I^- / I^0 / I_2`` chemistry."""
+
+ device_id: str
+ sha256: str
+ original_prepared_sha256: str
+ electronic_component: CompiledDevice1D
+ domain_mode: IodineDomainMode
+ domain_layer_ids: tuple[str, ...]
+ chem_geometry: ControlVolumeGeometry1D
+ chem_node_indices: NDArray[np.intp]
+ compensating_donor_m3: Vector
+ initial_iodide_m3: Vector
+ initial_atom_m3: Vector
+ initial_mol_m3: Vector
+ iodide_map: SpeciesCoordinateMap
+ atom_map: SpeciesCoordinateMap
+ mol_map: SpeciesCoordinateMap
+ iodide_diffusivity_faces_m2_s: Vector
+ atom_diffusivity_faces_m2_s: Vector
+ mol_diffusivity_faces_m2_s: Vector
+ log_partition_minus_faces: Vector
+ log_partition_atom_faces: Vector
+ log_partition_mol_faces: Vector
+ kinetics: IodineKineticsParameters
+ left_boundary: IodineBoundaryPortSpec
+ right_boundary: IodineBoundaryPortSpec
+ binding_manifest_json: str
+ steric_site_limit_m3: Vector | None = None
+ steric_diffusion_only: bool = True
+ volumetric_mol_escape_s_1: Vector | None = None
+ capabilities: tuple[str, ...] = field(
+ default=(
+ "classical_1d_electronic_component",
+ "iodine_reaction_diffusion_1d",
+ "physical_iodine_storage",
+ "small_signal_iodine_ac",
+ )
+ )
+
+ def __post_init__(self) -> None:
+ if self.domain_mode not in _DOMAIN_MODES:
+ raise ContractError("unknown_iodine_domain_mode")
+ indices = integer_indices(self.chem_node_indices)
+ m_count = self.chem_geometry.node_count
+ n_count = self.electronic_component.node_count
+ if (
+ indices.shape != (m_count,)
+ or np.any(np.diff(indices) != 1)
+ or indices[0] < 0
+ or indices[-1] >= n_count
+ ):
+ raise ContractError("chem_node_indices_must_be_contiguous_slice_of_nodes")
+ idx_frozen: NDArray[np.intp] = np.frombuffer(indices.tobytes(), dtype=np.intp)
+ object.__setattr__(self, "chem_node_indices", idx_frozen)
+
+ for name in (
+ "compensating_donor_m3",
+ "initial_iodide_m3",
+ "initial_atom_m3",
+ "initial_mol_m3",
+ ):
+ vec = frozen_array(getattr(self, name))
+ if vec.shape != (m_count,) or not np.all(np.isfinite(vec)) or np.any(vec < 0.0):
+ raise ContractError(f"{name}_must_be_finite_nonnegative_chem_vector")
+ object.__setattr__(self, name, vec)
+
+ faces = m_count - 1
+ for name in (
+ "iodide_diffusivity_faces_m2_s",
+ "atom_diffusivity_faces_m2_s",
+ "mol_diffusivity_faces_m2_s",
+ ):
+ fvec = frozen_array(getattr(self, name))
+ if fvec.shape != (faces,) or not np.all(np.isfinite(fvec)) or np.any(fvec < 0.0):
+ raise ContractError(f"{name}_must_be_finite_nonnegative_face_vector")
+ object.__setattr__(self, name, fvec)
+
+ for name in (
+ "log_partition_minus_faces",
+ "log_partition_atom_faces",
+ "log_partition_mol_faces",
+ ):
+ pvec = frozen_array(getattr(self, name))
+ if pvec.shape != (faces,) or not np.all(np.isfinite(pvec)):
+ raise ContractError(f"{name}_must_be_finite_face_vector")
+ object.__setattr__(self, name, pvec)
+
+ if self.steric_site_limit_m3 is not None:
+ slim = frozen_array(self.steric_site_limit_m3)
+ if slim.shape != (m_count,) or np.any(slim <= 0.0):
+ raise ContractError("steric_site_limit_m3_must_be_positive_chem_vector")
+ object.__setattr__(self, "steric_site_limit_m3", slim)
+
+ vol_esc = (
+ frozen_array(np.zeros(m_count, dtype=np.float64))
+ if self.volumetric_mol_escape_s_1 is None
+ else frozen_array(self.volumetric_mol_escape_s_1)
+ )
+ if (
+ vol_esc.shape != (m_count,)
+ or not np.all(np.isfinite(vol_esc))
+ or np.any(vol_esc < 0.0)
+ ):
+ raise ContractError(
+ "volumetric_mol_escape_s_1_must_be_finite_nonnegative_chem_vector"
+ )
+ object.__setattr__(self, "volumetric_mol_escape_s_1", vol_esc)
+
+ if (
+ self.iodide_map.size != m_count
+ or self.atom_map.size != m_count
+ or self.mol_map.size != m_count
+ or self.kinetics.size != m_count
+ ):
+ raise ContractError("chem_maps_and_kinetics_must_match_chem_node_count")
+
+ @property
+ def identity(self) -> str:
+ return self.sha256
+
+ @property
+ def node_count(self) -> int:
+ return self.electronic_component.node_count
+
+ @property
+ def chem_node_count(self) -> int:
+ return self.chem_geometry.node_count
+
+ @property
+ def state_size(self) -> int:
+ return 3 * self.node_count + 3 * self.chem_node_count
+
+ @property
+ def chem_slices(self) -> dict[str, slice]:
+ base = 3 * self.node_count
+ m = self.chem_node_count
+ return {
+ "iodide": slice(base, base + m),
+ "iodine_atom": slice(base + m, base + 2 * m),
+ "iodine_molecule": slice(base + 2 * m, base + 3 * m),
+ }
+
+ @property
+ def chem_weight_ratio(self) -> Vector:
+ """Cell-volume embedding ratio ``w_chem / w_elec[chem_node_indices]``."""
+ return frozen_array(
+ self.chem_geometry.cell_measures_m
+ / self.electronic_component.geometry.cell_measures_m[self.chem_node_indices]
+ )
+
+ @property
+ def initial_total_iodine_atoms_m3(self) -> Vector:
+ """Node-wise initial elemental iodine concentration ``c_- + c_0 + 2 c_2``."""
+ return frozen_array(
+ self.initial_iodide_m3 + self.initial_atom_m3 + 2.0 * self.initial_mol_m3
+ )
+
+ @property
+ def reference_iodine_inventory_m2(self) -> float:
+ """Initial represented total iodine sheet inventory on the coordinate maps."""
+ u_init = self.initial_chem_coordinates()
+ m = self.chem_node_count
+ cm = self.iodide_map.density_m3(u_init[:m])
+ c0 = self.atom_map.density_m3(u_init[m : 2 * m])
+ c2 = self.mol_map.density_m3(u_init[2 * m : 3 * m])
+ weights = self.chem_geometry.cell_measures_m
+ return math.fsum((weights * (cm + c0 + 2.0 * c2)).tolist())
+
+ @property
+ def reference_species_inventories_m2(self) -> dict[str, float]:
+ u_init = self.initial_chem_coordinates()
+ m = self.chem_node_count
+ weights = self.chem_geometry.cell_measures_m
+ return {
+ "iodide": math.fsum(
+ (weights * self.iodide_map.density_m3(u_init[:m])).tolist()
+ ),
+ "iodine_atom": math.fsum(
+ (weights * self.atom_map.density_m3(u_init[m : 2 * m])).tolist()
+ ),
+ "iodine_molecule": math.fsum(
+ (weights * self.mol_map.density_m3(u_init[2 * m : 3 * m])).tolist()
+ ),
+ }
+
+ @property
+ def has_open_iodine_loss(self) -> bool:
+ assert self.volumetric_mol_escape_s_1 is not None
+ return (
+ self.left_boundary.removes_device_iodine
+ or self.right_boundary.removes_device_iodine
+ or bool(np.any(self.volumetric_mol_escape_s_1 > 0.0))
+ )
+
+ @property
+ def is_unreactive_limit(self) -> bool:
+ k = self.kinetics
+ assert k.k_e_3body_m6_s is not None and self.volumetric_mol_escape_s_1 is not None
+ bulk_zero = bool(
+ np.all(k.k_a_m3_s == 0.0)
+ and np.all(k.k_b_s_1 == 0.0)
+ and np.all(k.k_c_m3_s == 0.0)
+ and np.all(k.k_d_m3_s == 0.0)
+ and np.all(k.k_e_m3_s == 0.0)
+ and np.all(k.k_e_3body_m6_s == 0.0)
+ and np.all(self.volumetric_mol_escape_s_1 == 0.0)
+ )
+ contact_zero = (
+ self.left_boundary.contact_oxidation_rate_m4_s == 0.0
+ and self.right_boundary.contact_oxidation_rate_m4_s == 0.0
+ and self.left_boundary.contact_corrosion_velocity_m_s == 0.0
+ and self.right_boundary.contact_corrosion_velocity_m_s == 0.0
+ )
+ return bulk_zero and contact_zero
+
+ @property
+ def binding_manifest(self) -> dict[str, object]:
+ return dict(json.loads(self.binding_manifest_json))
+
+ def project_chem_density(self, chem_density_m3: ArrayLike) -> Vector:
+ """Embed a ``chem`` cell density onto ``nodes`` scaled by ``w_chem / w_nodes``."""
+ arr = np.asarray(chem_density_m3, dtype=np.float64)
+ if arr.shape != (self.chem_node_count,) or not np.all(np.isfinite(arr)):
+ raise ValueError("chem density must be finite with shape (chem_node_count,)")
+ out: NDArray[np.float64] = np.zeros(self.node_count, dtype=np.float64)
+ out[self.chem_node_indices] = self.chem_weight_ratio * arr
+ return frozen_array(out)
+
+ def initial_chem_coordinates(self) -> Vector:
+ u_minus = self.iodide_map.coordinate_from_density(self.initial_iodide_m3)
+ u_atom = self.atom_map.coordinate_from_density(self.initial_atom_m3)
+ u_mol = self.mol_map.coordinate_from_density(self.initial_mol_m3)
+ return frozen_array(np.concatenate((u_minus, u_atom, u_mol)))
+
+ def initial_coordinates(
+ self,
+ *,
+ voltage_V: float = 0.0,
+ electronic_u: ArrayLike | None = None,
+ ) -> Vector:
+ if electronic_u is None:
+ left, right = self.electronic_component.contact_potentials(voltage_V)
+ pos = (
+ self.electronic_component.nodes_m
+ - self.electronic_component.nodes_m[0]
+ ) / self.electronic_component.geometry.extent_m
+ phi = left + (right - left) * pos
+ elec = np.concatenate((phi, np.zeros(2 * self.node_count)))
+ else:
+ elec = np.asarray(electronic_u, dtype=np.float64)
+ if elec.shape != (3 * self.node_count,):
+ raise ValueError("electronic_u must have shape (3 * node_count,)")
+ return frozen_array(np.concatenate((elec, self.initial_chem_coordinates())))
+
+ def fields_and_tangents(
+ self,
+ u: ArrayLike,
+ *,
+ voltage_V: float = 0.0,
+ ) -> tuple[
+ Vector,
+ Vector,
+ Vector,
+ Vector,
+ Vector,
+ Vector,
+ Vector,
+ Vector,
+ Vector,
+ ]:
+ """Return ``(phi, n, p, c_-, c_0, c_2, dc_-/du_-, dc_0/du_0, dc_2/du_2)``."""
+ vec = np.asarray(u, dtype=np.float64)
+ if vec.shape != (self.state_size,) or not np.all(np.isfinite(vec)):
+ raise ValueError("iodine coordinates must be finite of shape (state_size,)")
+ n_elec = 3 * self.node_count
+ phi, n, p = self.electronic_component.fields(vec[:n_elec], voltage_V=voltage_V)
+ slices = self.chem_slices
+ cm, mm = self.iodide_map.density_and_tangent_m3(vec[slices["iodide"]])
+ c0, m0 = self.atom_map.density_and_tangent_m3(vec[slices["iodine_atom"]])
+ c2, m2 = self.mol_map.density_and_tangent_m3(vec[slices["iodine_molecule"]])
+ if any(
+ not np.all(np.isfinite(arr)) or np.any(arr <= 0.0)
+ for arr in (n, p, cm, c0, c2)
+ ):
+ raise FloatingPointError("trial densities outside positive finite domain")
+ return phi, n, p, cm, c0, c2, mm, m0, m2
+
+ def charge_ledger(self, n: Vector, p: Vector, c_minus_m3: Vector) -> ChargeLedger:
+ component = self.electronic_component.charge_ledger(n, p)
+ iodide_entry = ChargeEntry(
+ "iodide",
+ "iodine_chemistry",
+ -1,
+ self.project_chem_density(c_minus_m3),
+ self.project_chem_density(self.compensating_donor_m3),
+ group="iodine_space_charge",
+ )
+ return component.with_entry(iodide_entry)
+
+ def state(self, u: ArrayLike, *, voltage_V: float = 0.0) -> IodineState1D:
+ vec = np.asarray(u, dtype=np.float64)
+ _, _, _, cm, c0, c2, _, _, _ = self.fields_and_tangents(vec, voltage_V=voltage_V)
+ elec_state = self.electronic_component.state(
+ vec[: 3 * self.node_count], voltage_V=voltage_V
+ )
+ w = self.chem_geometry.cell_measures_m
+ inv_minus = math.fsum((w * cm).tolist())
+ inv_atom = math.fsum((w * c0).tolist())
+ inv_mol = math.fsum((w * c2).tolist())
+ total_inv = math.fsum((w * (cm + c0 + 2.0 * c2)).tolist())
+ return IodineState1D(
+ u=vec,
+ electronic_state=elec_state,
+ iodide_density_m3=cm,
+ iodine_atom_density_m3=c0,
+ iodine_molecule_density_m3=c2,
+ total_iodine_inventory_m2=total_inv,
+ species_inventories_m2={
+ "iodide": inv_minus,
+ "iodine_atom": inv_atom,
+ "iodine_molecule": inv_mol,
+ },
+ device_sha256=self.sha256,
+ )
diff --git a/src/solarlab/experiments/iodine_aging.py b/src/solarlab/experiments/iodine_aging.py
new file mode 100644
index 00000000..4a36ac18
--- /dev/null
+++ b/src/solarlab/experiments/iodine_aging.py
@@ -0,0 +1,796 @@
+"""Multi-stage iodine stress/recovery aging protocols, J-V probes, and persistence.
+
+Orchestrates coupled 1D ``(phi, n, p, I^-, I^0, I_2)`` reaction-diffusion-aging
+trajectories across arbitrary sequences of illumination/bias stress and dark
+recovery stages, non-destructive frozen-chemistry vs dynamic-scan ``J-V``
+checkpoint probes, checksum-bound bundle I/O, and SQLite :class:`RunStore`
+recording. Every result explicitly carries ``scientific_qualification = False``.
+"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass, field, replace
+import hashlib
+import json
+import math
+from pathlib import Path
+import time
+from typing import Any, Literal
+
+import numpy as np
+from numpy.typing import ArrayLike, NDArray
+
+from solarlab.contracts import ContractError, Vector, frozen_array
+from solarlab.equations.assembly.iodine_1d import AssembledIodine1DProblem, iodine_system
+from solarlab.equations.iodine_1d import CompiledIodineDevice1D, IodineState1D
+from solarlab.experiments.jv.steady import SteadyJVMetrics, steady_jv_metrics
+from solarlab.io.artifacts import array_artifact, bytes_artifact
+from solarlab.io.run_store import RunStore
+from solarlab.solvers.nonlinear.iodine_1d import (
+ IodineStepAccounting,
+ solve_frozen_chemistry_electronic_1d,
+ solve_iodine_bdf_transient,
+ solve_iodine_steady_state,
+)
+from solarlab.solvers.time.bdf import BDFOptions
+
+__all__ = [
+ "DynamicJVScanProbeResult",
+ "FrozenChemistryJVProbeResult",
+ "IODINE_AGING_SCHEMA",
+ "IodineAgingError",
+ "IodineAgingProtocol",
+ "IodineAgingResult",
+ "IodineCheckpointSnapshot",
+ "IodineProbeMode",
+ "IodineProbeSpec",
+ "StressRecoveryStage",
+ "load_iodine_aging_bundle",
+ "measure_dynamic_jv_scan",
+ "measure_frozen_chemistry_jv",
+ "record_iodine_aging_in_run_store",
+ "run_iodine_aging_protocol",
+ "save_iodine_aging_bundle",
+]
+
+IODINE_AGING_SCHEMA = "solarlab.iodine_aging.v1"
+IodineProbeMode = Literal["none", "frozen_chemistry_jv", "dynamic_jv_scan", "both"]
+
+
+class IodineAgingError(RuntimeError):
+ """Raised when an aging trajectory stage or probe fails physical/solver gates."""
+
+
+def _default_aging_bdf_options() -> BDFOptions:
+ return BDFOptions(
+ initial_step_s=1.0e-6,
+ min_step_s=1.0e-14,
+ max_step_s=200.0,
+ relative_tolerance=1.0e-3,
+ absolute_tolerance=1.0e11,
+ max_steps=800,
+ )
+
+
+def _default_probe_voltages() -> tuple[float, ...]:
+ return tuple(float(v) for v in np.linspace(0.0, 1.25, 26))
+
+
+@dataclass(frozen=True, slots=True)
+class StressRecoveryStage:
+ """One constant-bias, constant-illumination stress or recovery stage."""
+
+ name: str
+ duration_s: float
+ voltage_V: float
+ generation_scale: float
+ max_step_s: float = 200.0
+
+ def __post_init__(self) -> None:
+ if not self.name or not self.name.strip():
+ raise ContractError("stage_name_must_be_nonempty")
+ for attr in ("duration_s", "max_step_s"):
+ val = float(getattr(self, attr))
+ if not math.isfinite(val) or val <= 0.0:
+ raise ContractError(f"{attr}_must_be_finite_positive")
+ object.__setattr__(self, attr, val)
+ v = float(self.voltage_V)
+ g = float(self.generation_scale)
+ if not math.isfinite(v):
+ raise ContractError("voltage_V_must_be_finite")
+ if not math.isfinite(g) or g < 0.0:
+ raise ContractError("generation_scale_must_be_finite_nonnegative")
+ object.__setattr__(self, "voltage_V", v)
+ object.__setattr__(self, "generation_scale", g)
+
+
+@dataclass(frozen=True, slots=True)
+class IodineProbeSpec:
+ """Non-destructive J-V characterization specification at aging checkpoints."""
+
+ mode: IodineProbeMode = "frozen_chemistry_jv"
+ voltages_V: tuple[float, ...] = field(default_factory=_default_probe_voltages)
+ scan_rate_V_s: float = 1.0
+ generation_scale: float = 1.0
+ incident_power_W_m2: float = 1000.0
+
+ def __post_init__(self) -> None:
+ if self.mode not in ("none", "frozen_chemistry_jv", "dynamic_jv_scan", "both"):
+ raise ContractError("invalid_iodine_probe_mode")
+ v_tuple = tuple(float(v) for v in self.voltages_V)
+ if self.mode != "none":
+ if len(v_tuple) < 2 or not all(math.isfinite(v) for v in v_tuple):
+ raise ContractError("probe_voltages_V_requires_at_least_two_finite_points")
+ if len(set(v_tuple)) != len(v_tuple):
+ raise ContractError("probe_voltages_V_must_be_distinct")
+ rate = float(self.scan_rate_V_s)
+ g = float(self.generation_scale)
+ p_in = float(self.incident_power_W_m2)
+ if not math.isfinite(rate) or rate <= 0.0:
+ raise ContractError("scan_rate_V_s_must_be_finite_positive")
+ if not math.isfinite(g) or g < 0.0:
+ raise ContractError("probe_generation_scale_must_be_finite_nonnegative")
+ if not math.isfinite(p_in) or p_in <= 0.0:
+ raise ContractError("incident_power_W_m2_must_be_finite_positive")
+ object.__setattr__(self, "voltages_V", tuple(sorted(v_tuple)))
+ object.__setattr__(self, "scan_rate_V_s", rate)
+ object.__setattr__(self, "generation_scale", g)
+ object.__setattr__(self, "incident_power_W_m2", p_in)
+
+
+@dataclass(frozen=True, slots=True)
+class IodineAgingProtocol:
+ """Multi-stage iodine stress/recovery schedule and checkpoint probe spec."""
+
+ stages: tuple[StressRecoveryStage, ...]
+ checkpoint_times_s: tuple[float, ...] = ()
+ probe: IodineProbeSpec = field(default_factory=IodineProbeSpec)
+ bdf_options: BDFOptions = field(default_factory=_default_aging_bdf_options)
+
+ def __post_init__(self) -> None:
+ st = tuple(self.stages)
+ if not st:
+ raise ContractError("aging_protocol_requires_at_least_one_stage")
+ total_dur = sum(s.duration_s for s in st)
+ ckpts = tuple(sorted({float(t) for t in self.checkpoint_times_s}))
+ for t in ckpts:
+ if not math.isfinite(t) or t < 0.0 or t > total_dur * (1.0 + 1.0e-12):
+ raise ContractError("checkpoint_time_s_outside_protocol_horizon")
+ object.__setattr__(self, "stages", st)
+ object.__setattr__(self, "checkpoint_times_s", ckpts)
+
+ @property
+ def total_duration_s(self) -> float:
+ return float(sum(s.duration_s for s in self.stages))
+
+ @property
+ def sha256(self) -> str:
+ doc = {
+ "schema": IODINE_AGING_SCHEMA,
+ "stages": [
+ {
+ "name": s.name,
+ "duration_s": s.duration_s,
+ "voltage_V": s.voltage_V,
+ "generation_scale": s.generation_scale,
+ "max_step_s": s.max_step_s,
+ }
+ for s in self.stages
+ ],
+ "checkpoint_times_s": list(self.checkpoint_times_s),
+ "probe": {
+ "mode": self.probe.mode,
+ "voltages_V": list(self.probe.voltages_V),
+ "scan_rate_V_s": self.probe.scan_rate_V_s,
+ "generation_scale": self.probe.generation_scale,
+ "incident_power_W_m2": self.probe.incident_power_W_m2,
+ },
+ }
+ encoded = json.dumps(doc, sort_keys=True, separators=(",", ":")).encode("utf-8")
+ return hashlib.sha256(encoded).hexdigest()
+
+
+@dataclass(frozen=True, slots=True)
+class FrozenChemistryJVProbeResult:
+ """Stationary electronic J-V curve with frozen spatial iodine profiles."""
+
+ voltages_V: Vector
+ output_current_A_m2: Vector
+ metrics: SteadyJVMetrics
+
+
+@dataclass(frozen=True, slots=True)
+class DynamicJVScanProbeResult:
+ """Transient reverse (V_max -> V_min) and forward (V_min -> V_max) J-V scan."""
+
+ voltages_V: Vector
+ scan_rate_V_s: float
+ reverse_output_current_A_m2: Vector
+ forward_output_current_A_m2: Vector
+ reverse_metrics: SteadyJVMetrics
+ forward_metrics: SteadyJVMetrics
+ hysteresis_index: float | None
+
+
+@dataclass(frozen=True, slots=True)
+class IodineCheckpointSnapshot:
+ """Recorded physical state, conservation accounting, and probes at ``time_s``."""
+
+ time_s: float
+ stage_name: str
+ state: IodineState1D
+ in_device_iodine_m2: float
+ cumulative_escaped_iodine_atoms_m2: float
+ cumulative_immobilized_iodine_atoms_m2: float
+ conservation_residual_m2: float
+ frozen_jv: FrozenChemistryJVProbeResult | None = None
+ dynamic_jv: DynamicJVScanProbeResult | None = None
+
+
+@dataclass(frozen=True, slots=True)
+class IodineAgingResult:
+ """Complete trajectory, checkpoint probes, and conservation ledger."""
+
+ protocol_sha256: str
+ device_sha256: str
+ reference_iodine_inventory_m2: float
+ checkpoints: tuple[IodineCheckpointSnapshot, ...]
+ step_ledger: tuple[IodineStepAccounting, ...]
+ max_relative_conservation_error: float
+ completed: bool
+ wall_s: float
+ scientific_qualification: bool = False
+
+
+def measure_frozen_chemistry_jv(
+ device: CompiledIodineDevice1D,
+ state: IodineState1D,
+ voltages_V: ArrayLike,
+ *,
+ generation_scale: float = 1.0,
+ incident_power_W_m2: float = 1000.0,
+) -> FrozenChemistryJVProbeResult:
+ """Sweep stationary electronic J-V at exact 0-ULP frozen chemical species."""
+ if state.device_sha256 != device.identity:
+ raise ContractError("state_device_mismatch")
+ v_grid = np.sort(np.asarray(voltages_V, dtype=np.float64))
+ if v_grid.ndim != 1 or v_grid.size < 2 or np.unique(v_grid).size != v_grid.size:
+ raise ContractError("voltages_V_must_be_1d_distinct_sorted_array")
+
+ binding = iodine_system(device, constrained_steady=False)
+ n_elec = 3 * device.node_count
+ chem_ref = state.u[n_elec:].copy()
+ polarity = float(device.electronic_component.voltage_polarity)
+
+ u_cur = state.u
+ prev_v = state.electronic_state.voltage_V
+ j_out = np.empty(v_grid.size, dtype=np.float64)
+ for idx, v_val in enumerate(v_grid):
+ u_cur, j_mean = solve_frozen_chemistry_electronic_1d(
+ device,
+ u_cur,
+ voltage_V=float(v_val),
+ generation_scale=generation_scale,
+ prev_voltage_V=prev_v,
+ binding=binding,
+ )
+ if not np.array_equal(u_cur[n_elec:], chem_ref):
+ raise IodineAgingError("frozen-chemistry J-V mutated chemical coordinates")
+ j_out[idx] = -polarity * j_mean
+ prev_v = float(v_val)
+
+ metrics = steady_jv_metrics(
+ v_grid, j_out, incident_power_W_m2=incident_power_W_m2
+ )
+ return FrozenChemistryJVProbeResult(
+ voltages_V=frozen_array(v_grid),
+ output_current_A_m2=frozen_array(j_out),
+ metrics=metrics,
+ )
+
+
+def measure_dynamic_jv_scan(
+ device: CompiledIodineDevice1D,
+ state: IodineState1D,
+ voltages_V: ArrayLike,
+ *,
+ scan_rate_V_s: float = 1.0,
+ generation_scale: float = 1.0,
+ incident_power_W_m2: float = 1000.0,
+ bdf_options: BDFOptions | None = None,
+) -> DynamicJVScanProbeResult:
+ """Execute non-destructive coupled reverse + forward transient J-V scan."""
+ if state.device_sha256 != device.identity:
+ raise ContractError("state_device_mismatch")
+ v_sorted = np.sort(np.asarray(voltages_V, dtype=np.float64))
+ if v_sorted.ndim != 1 or v_sorted.size < 2:
+ raise ContractError("voltages_V_requires_at_least_two_points")
+ rate = float(scan_rate_V_s)
+ v_min = float(v_sorted[0])
+ v_max = float(v_sorted[-1])
+ span_v = v_max - v_min
+ leg_dur_s = span_v / rate
+ min_dv_s = float(np.min(np.diff(v_sorted))) / rate
+
+ binding = iodine_system(device, constrained_steady=False)
+ # Pre-position electronics cleanly at v_max without altering chemical inventory
+ u_start_rev, _ = solve_frozen_chemistry_electronic_1d(
+ device,
+ state.u,
+ voltage_V=v_max,
+ generation_scale=generation_scale,
+ prev_voltage_V=state.electronic_state.voltage_V,
+ binding=binding,
+ )
+
+ base_opts = _default_aging_bdf_options() if bdf_options is None else bdf_options
+ scan_opts = replace(
+ base_opts,
+ initial_step_s=min(base_opts.initial_step_s, max(leg_dur_s * 1.0e-3, 1.0e-9)),
+ max_step_s=min(
+ base_opts.max_step_s, min_dv_s, max(leg_dur_s / 40.0, 1.0e-6)
+ ),
+ )
+
+ rev_bdf, rev_ledger = solve_iodine_bdf_transient(
+ device,
+ u_start_rev,
+ (0.0, leg_dur_s),
+ voltage_fn=lambda t: v_max - rate * t,
+ generation_fn=lambda _t: generation_scale,
+ options=scan_opts,
+ )
+ if not rev_bdf.completed or not rev_ledger:
+ raise IodineAgingError(
+ f"Dynamic reverse J-V scan failed: {rev_bdf.termination}"
+ )
+
+ u_turn = rev_bdf.accepted_coordinates[-1]
+ fwd_bdf, fwd_ledger = solve_iodine_bdf_transient(
+ device,
+ u_turn,
+ (0.0, leg_dur_s),
+ voltage_fn=lambda t: v_min + rate * t,
+ generation_fn=lambda _t: generation_scale,
+ options=scan_opts,
+ )
+ if not fwd_bdf.completed or not fwd_ledger:
+ raise IodineAgingError(
+ f"Dynamic forward J-V scan failed: {fwd_bdf.termination}"
+ )
+
+ pol = device.electronic_component.voltage_polarity
+ # Reverse leg trajectory ordered in ascending voltage (end of leg = v_min -> start = v_max)
+ prob_vmax = AssembledIodine1DProblem(
+ device=device,
+ voltage_V=v_max,
+ generation_scale=generation_scale,
+ binding=binding,
+ )
+ j0_rev = float(-pol * prob_vmax.steady_current_density_A_m2(rev_bdf.initial_u))
+ t_rev_traj = np.array([0.0] + [s.end_s for s in rev_ledger], dtype=np.float64)
+ v_rev_desc = v_max - rate * t_rev_traj
+ j_rev_desc = np.array(
+ [j0_rev] + [float(-pol * s.terminal_current_A_m2) for s in rev_ledger],
+ dtype=np.float64,
+ )
+ rev_j_asc = np.interp(v_sorted, v_rev_desc[::-1], j_rev_desc[::-1])
+
+ prob_vmin = AssembledIodine1DProblem(
+ device=device,
+ voltage_V=v_min,
+ generation_scale=generation_scale,
+ binding=binding,
+ )
+ j0_fwd = float(-pol * prob_vmin.steady_current_density_A_m2(fwd_bdf.initial_u))
+ t_fwd_traj = np.array([0.0] + [s.end_s for s in fwd_ledger], dtype=np.float64)
+ v_fwd_asc = v_min + rate * t_fwd_traj
+ j_fwd_asc = np.array(
+ [j0_fwd] + [float(-pol * s.terminal_current_A_m2) for s in fwd_ledger],
+ dtype=np.float64,
+ )
+ fwd_j_asc = np.interp(v_sorted, v_fwd_asc, j_fwd_asc)
+
+ rev_metrics = steady_jv_metrics(
+ v_sorted, rev_j_asc, incident_power_W_m2=incident_power_W_m2
+ )
+ fwd_metrics = steady_jv_metrics(
+ v_sorted, fwd_j_asc, incident_power_W_m2=incident_power_W_m2
+ )
+ hi: float | None = None
+ if (
+ rev_metrics.maximum_power_W_m2 is not None
+ and fwd_metrics.maximum_power_W_m2 is not None
+ and rev_metrics.maximum_power_W_m2 > 0.0
+ ):
+ hi = float(
+ (rev_metrics.maximum_power_W_m2 - fwd_metrics.maximum_power_W_m2)
+ / rev_metrics.maximum_power_W_m2
+ )
+
+ return DynamicJVScanProbeResult(
+ voltages_V=frozen_array(v_sorted),
+ scan_rate_V_s=rate,
+ reverse_output_current_A_m2=frozen_array(rev_j_asc),
+ forward_output_current_A_m2=frozen_array(fwd_j_asc),
+ reverse_metrics=rev_metrics,
+ forward_metrics=fwd_metrics,
+ hysteresis_index=hi,
+ )
+
+
+def _evaluate_checkpoint_probes(
+ device: CompiledIodineDevice1D,
+ state: IodineState1D,
+ probe: IodineProbeSpec,
+ bdf_options: BDFOptions,
+) -> tuple[FrozenChemistryJVProbeResult | None, DynamicJVScanProbeResult | None]:
+ frozen_res: FrozenChemistryJVProbeResult | None = None
+ dyn_res: DynamicJVScanProbeResult | None = None
+ if probe.mode in ("frozen_chemistry_jv", "both"):
+ frozen_res = measure_frozen_chemistry_jv(
+ device,
+ state,
+ probe.voltages_V,
+ generation_scale=probe.generation_scale,
+ incident_power_W_m2=probe.incident_power_W_m2,
+ )
+ if probe.mode in ("dynamic_jv_scan", "both"):
+ dyn_res = measure_dynamic_jv_scan(
+ device,
+ state,
+ probe.voltages_V,
+ scan_rate_V_s=probe.scan_rate_V_s,
+ generation_scale=probe.generation_scale,
+ incident_power_W_m2=probe.incident_power_W_m2,
+ bdf_options=bdf_options,
+ )
+ return frozen_res, dyn_res
+
+
+def run_iodine_aging_protocol(
+ device: CompiledIodineDevice1D,
+ protocol: IodineAgingProtocol,
+ *,
+ initial_u: Vector | None = None,
+) -> IodineAgingResult:
+ """Execute a multi-stage stress/recovery protocol with conservation auditing."""
+ t_wall_start = time.monotonic()
+ if initial_u is None:
+ if not device.has_open_iodine_loss:
+ eq = solve_iodine_steady_state(device, voltage_V=0.0, generation_scale=0.0)
+ if not eq.converged or eq.state is None:
+ raise IodineAgingError(
+ f"Initial dark equilibrium failed: {eq.termination}"
+ )
+ u_curr = eq.state.u
+ v_curr = 0.0
+ else:
+ u_base = device.initial_coordinates(voltage_V=0.0)
+ u_curr, _ = solve_frozen_chemistry_electronic_1d(
+ device, u_base, voltage_V=0.0, generation_scale=0.0, prev_voltage_V=0.0
+ )
+ v_curr = 0.0
+ else:
+ u_curr = frozen_array(initial_u)
+ v_curr = 0.0
+
+ state_0 = device.state(u_curr, voltage_V=v_curr)
+ inv_0 = state_0.total_iodine_inventory_m2
+ inv_scale = max(inv_0, 1.0)
+
+ # Collect stage-end times + user checkpoint times
+ stage_bounds: list[tuple[float, float, StressRecoveryStage]] = []
+ t_cursor = 0.0
+ for stg in protocol.stages:
+ stage_bounds.append((t_cursor, t_cursor + stg.duration_s, stg))
+ t_cursor += stg.duration_s
+
+ all_ckpts = sorted(
+ {0.0, *(b[1] for b in stage_bounds), *protocol.checkpoint_times_s}
+ )
+
+ checkpoints: list[IodineCheckpointSnapshot] = []
+ all_steps: list[IodineStepAccounting] = []
+ cum_escaped = 0.0
+ cum_immob = 0.0
+ max_rel_err = 0.0
+
+ if 0.0 in all_ckpts:
+ f_jv0, d_jv0 = _evaluate_checkpoint_probes(
+ device, state_0, protocol.probe, protocol.bdf_options
+ )
+ checkpoints.append(
+ IodineCheckpointSnapshot(
+ time_s=0.0,
+ stage_name="initial",
+ state=state_0,
+ in_device_iodine_m2=inv_0,
+ cumulative_escaped_iodine_atoms_m2=0.0,
+ cumulative_immobilized_iodine_atoms_m2=0.0,
+ conservation_residual_m2=0.0,
+ frozen_jv=f_jv0,
+ dynamic_jv=d_jv0,
+ )
+ )
+
+ for t_start, t_end, stg in stage_bounds:
+ # Sub-intervals broken at any requested checkpoint inside (t_start, t_end]
+ sub_targets = [
+ t for t in all_ckpts if t_start + 1.0e-14 < t <= t_end + 1.0e-14
+ ]
+ if not sub_targets or abs(sub_targets[-1] - t_end) > 1.0e-12:
+ sub_targets.append(t_end)
+
+ sub_a = t_start
+ for sub_b in sub_targets:
+ dt_span = sub_b - sub_a
+ stg_opts = replace(
+ protocol.bdf_options,
+ initial_step_s=min(protocol.bdf_options.initial_step_s, dt_span * 0.5),
+ max_step_s=min(protocol.bdf_options.max_step_s, stg.max_step_s, dt_span),
+ )
+ v_const = float(stg.voltage_V)
+ g_const = float(stg.generation_scale)
+
+ def _stg_v(_t: float, _v: float = v_const) -> float:
+ return _v
+
+ def _stg_g(_t: float, _g: float = g_const) -> float:
+ return _g
+
+ bdf_res, sub_ledger = solve_iodine_bdf_transient(
+ device,
+ u_curr,
+ (sub_a, sub_b),
+ voltage_fn=_stg_v,
+ generation_fn=_stg_g,
+ options=stg_opts,
+ )
+ if not bdf_res.completed:
+ raise IodineAgingError(
+ f"Aging stage {stg.name!r} failed on [{sub_a:.3g}, {sub_b:.3g}] s: "
+ f"{bdf_res.termination}"
+ )
+ for acc in sub_ledger:
+ cum_escaped += acc.step_escaped_iodine_atoms_m2
+ cum_immob += acc.step_immobilized_iodine_atoms_m2
+ tot_res = (acc.in_device_iodine_m2 + cum_escaped + cum_immob) - inv_0
+ max_rel_err = max(
+ max_rel_err,
+ abs(tot_res) / inv_scale,
+ abs(acc.step_conservation_residual_m2) / inv_scale,
+ )
+ all_steps.append(acc)
+
+ u_curr = bdf_res.accepted_coordinates[-1]
+ st_ckpt = device.state(u_curr, voltage_V=stg.voltage_V)
+ cons_res = (st_ckpt.total_iodine_inventory_m2 + cum_escaped + cum_immob) - inv_0
+ max_rel_err = max(max_rel_err, abs(cons_res) / inv_scale)
+
+ f_jv, d_jv = _evaluate_checkpoint_probes(
+ device, st_ckpt, protocol.probe, protocol.bdf_options
+ )
+ checkpoints.append(
+ IodineCheckpointSnapshot(
+ time_s=float(sub_b),
+ stage_name=stg.name,
+ state=st_ckpt,
+ in_device_iodine_m2=st_ckpt.total_iodine_inventory_m2,
+ cumulative_escaped_iodine_atoms_m2=cum_escaped,
+ cumulative_immobilized_iodine_atoms_m2=cum_immob,
+ conservation_residual_m2=cons_res,
+ frozen_jv=f_jv,
+ dynamic_jv=d_jv,
+ )
+ )
+ sub_a = sub_b
+
+ return IodineAgingResult(
+ protocol_sha256=protocol.sha256,
+ device_sha256=device.identity,
+ reference_iodine_inventory_m2=inv_0,
+ checkpoints=tuple(checkpoints),
+ step_ledger=tuple(all_steps),
+ max_relative_conservation_error=max_rel_err,
+ completed=True,
+ wall_s=time.monotonic() - t_wall_start,
+ scientific_qualification=False,
+ )
+
+
+def _metrics_dict(m: SteadyJVMetrics) -> dict[str, Any]:
+ return {
+ "short_circuit_current_A_m2": m.short_circuit_current_A_m2,
+ "open_circuit_voltage_V": m.open_circuit_voltage_V,
+ "maximum_power_W_m2": m.maximum_power_W_m2,
+ "fill_factor": m.fill_factor,
+ "efficiency": m.efficiency,
+ "limitation": m.limitation,
+ }
+
+
+def save_iodine_aging_bundle(
+ directory: Path,
+ result: IodineAgingResult,
+) -> dict[str, Any]:
+ """Persist checksum-verified ``manifest.json`` and ``arrays.npz`` without overwrite."""
+ target = Path(directory)
+ manifest_path = target / "manifest.json"
+ npz_path = target / "arrays.npz"
+ if manifest_path.exists() or npz_path.exists():
+ raise FileExistsError(f"Refusing to overwrite existing aging bundle at {target}")
+ target.mkdir(parents=True, exist_ok=True)
+
+ npz_dict: dict[str, NDArray[np.float64]] = {
+ "checkpoint_times_s": np.array(
+ [c.time_s for c in result.checkpoints], dtype=np.float64
+ ),
+ "checkpoint_in_device_iodine_m2": np.array(
+ [c.in_device_iodine_m2 for c in result.checkpoints], dtype=np.float64
+ ),
+ "checkpoint_escaped_iodine_m2": np.array(
+ [c.cumulative_escaped_iodine_atoms_m2 for c in result.checkpoints],
+ dtype=np.float64,
+ ),
+ "checkpoint_immobilized_iodine_m2": np.array(
+ [c.cumulative_immobilized_iodine_atoms_m2 for c in result.checkpoints],
+ dtype=np.float64,
+ ),
+ "checkpoint_coordinates": np.stack(
+ [c.state.u for c in result.checkpoints], axis=0
+ ),
+ "step_end_s": np.array([s.end_s for s in result.step_ledger], dtype=np.float64),
+ "step_conservation_residual_m2": np.array(
+ [s.step_conservation_residual_m2 for s in result.step_ledger],
+ dtype=np.float64,
+ ),
+ }
+ for idx, ck in enumerate(result.checkpoints):
+ if ck.frozen_jv is not None:
+ npz_dict[f"ckpt_{idx}_frozen_v"] = ck.frozen_jv.voltages_V
+ npz_dict[f"ckpt_{idx}_frozen_j"] = ck.frozen_jv.output_current_A_m2
+ if ck.dynamic_jv is not None:
+ npz_dict[f"ckpt_{idx}_dyn_v"] = ck.dynamic_jv.voltages_V
+ npz_dict[f"ckpt_{idx}_dyn_j_rev"] = ck.dynamic_jv.reverse_output_current_A_m2
+ npz_dict[f"ckpt_{idx}_dyn_j_fwd"] = ck.dynamic_jv.forward_output_current_A_m2
+
+ with npz_path.open("wb") as fh:
+ np.savez_compressed(fh, allow_pickle=False, **npz_dict)
+ npz_bytes = npz_path.read_bytes()
+ npz_sha256 = hashlib.sha256(npz_bytes).hexdigest()
+
+ manifest: dict[str, Any] = {
+ "schema": IODINE_AGING_SCHEMA,
+ "scientific_qualification": False,
+ "completed": result.completed,
+ "protocol_sha256": result.protocol_sha256,
+ "device_sha256": result.device_sha256,
+ "reference_iodine_inventory_m2": result.reference_iodine_inventory_m2,
+ "max_relative_conservation_error": result.max_relative_conservation_error,
+ "step_count": len(result.step_ledger),
+ "wall_s": result.wall_s,
+ "arrays_npz_sha256": npz_sha256,
+ "checkpoints": [
+ {
+ "index": i,
+ "time_s": c.time_s,
+ "stage_name": c.stage_name,
+ "in_device_iodine_m2": c.in_device_iodine_m2,
+ "cumulative_escaped_iodine_atoms_m2": c.cumulative_escaped_iodine_atoms_m2,
+ "cumulative_immobilized_iodine_atoms_m2": c.cumulative_immobilized_iodine_atoms_m2,
+ "conservation_residual_m2": c.conservation_residual_m2,
+ "species_inventories_m2": dict(c.state.species_inventories_m2),
+ "frozen_jv_metrics": (
+ None if c.frozen_jv is None else _metrics_dict(c.frozen_jv.metrics)
+ ),
+ "dynamic_jv": (
+ None
+ if c.dynamic_jv is None
+ else {
+ "scan_rate_V_s": c.dynamic_jv.scan_rate_V_s,
+ "hysteresis_index": c.dynamic_jv.hysteresis_index,
+ "reverse_metrics": _metrics_dict(c.dynamic_jv.reverse_metrics),
+ "forward_metrics": _metrics_dict(c.dynamic_jv.forward_metrics),
+ }
+ ),
+ }
+ for i, c in enumerate(result.checkpoints)
+ ],
+ }
+ manifest_text = json.dumps(manifest, indent=2, sort_keys=True, allow_nan=False)
+ manifest_path.write_text(manifest_text + "\n", encoding="utf-8")
+ return manifest
+
+
+def load_iodine_aging_bundle(directory: Path) -> dict[str, Any]:
+ """Load and checksum-verify a saved iodine aging bundle."""
+ target = Path(directory)
+ manifest = json.loads((target / "manifest.json").read_text(encoding="utf-8"))
+ if manifest.get("schema") != IODINE_AGING_SCHEMA:
+ raise ContractError("unexpected_iodine_aging_bundle_schema")
+ npz_path = target / "arrays.npz"
+ actual_sha = hashlib.sha256(npz_path.read_bytes()).hexdigest()
+ if actual_sha != manifest.get("arrays_npz_sha256"):
+ raise ContractError("iodine_aging_bundle_arrays_sha256_mismatch")
+ with np.load(npz_path, allow_pickle=False) as data:
+ arrays = {k: frozen_array(data[k]) for k in data.files}
+ return {"manifest": manifest, "arrays": arrays}
+
+
+def record_iodine_aging_in_run_store(
+ store: RunStore,
+ run_id: str,
+ device: CompiledIodineDevice1D,
+ protocol: IodineAgingProtocol,
+ result: IodineAgingResult,
+ *,
+ owner_id: str = "iodine_aging_worker",
+) -> dict[str, Any]:
+ """Commit an executed :class:`IodineAgingResult` into SolarLab's SQLite RunStore."""
+ queued = store.enqueue(
+ run_id,
+ opaque_identity={
+ "H_input": device.original_prepared_sha256,
+ "H_physics": device.identity,
+ "H_execution": protocol.sha256,
+ },
+ input_metadata={
+ "schema": IODINE_AGING_SCHEMA,
+ "scientific_qualification": False,
+ "total_duration_s": protocol.total_duration_s,
+ "stage_count": len(protocol.stages),
+ },
+ )
+ token = store.claim(
+ run_id,
+ expected_attempt_id=queued["current_attempt_id"],
+ expected_generation=queued["generation"],
+ owner_id=owner_id,
+ )
+ coords_stack = np.stack([c.state.u for c in result.checkpoints], axis=0)
+ coords_art = store.publish(
+ token,
+ "checkpoint_coordinates",
+ array_artifact(
+ coords_stack,
+ unit="1",
+ metadata={"description": "checkpoint_state_coordinates"},
+ ),
+ )
+ summary_doc = {
+ "schema": IODINE_AGING_SCHEMA,
+ "scientific_qualification": False,
+ "protocol_sha256": result.protocol_sha256,
+ "device_sha256": result.device_sha256,
+ "reference_iodine_inventory_m2": result.reference_iodine_inventory_m2,
+ "max_relative_conservation_error": result.max_relative_conservation_error,
+ "checkpoint_times_s": [c.time_s for c in result.checkpoints],
+ "in_device_iodine_m2": [c.in_device_iodine_m2 for c in result.checkpoints],
+ "escaped_iodine_m2": [
+ c.cumulative_escaped_iodine_atoms_m2 for c in result.checkpoints
+ ],
+ }
+ summary_bytes = json.dumps(
+ summary_doc, sort_keys=True, separators=(",", ":"), allow_nan=False
+ ).encode("utf-8")
+ summary_art = store.publish(
+ token,
+ "aging_summary",
+ bytes_artifact(
+ summary_bytes,
+ metadata={"content_type": "application/json", "schema": IODINE_AGING_SCHEMA},
+ ),
+ )
+ store.complete(
+ token,
+ state="succeeded" if result.completed else "failed",
+ result={
+ "scientific_qualification": False,
+ "completed": result.completed,
+ "max_relative_conservation_error": result.max_relative_conservation_error,
+ "checkpoint_count": len(result.checkpoints),
+ },
+ artifacts=(coords_art["artifact_id"], summary_art["artifact_id"]),
+ )
+ return store.get_run(run_id)
diff --git a/src/solarlab/experiments/iodine_declarative.py b/src/solarlab/experiments/iodine_declarative.py
new file mode 100644
index 00000000..1b8b058f
--- /dev/null
+++ b/src/solarlab/experiments/iodine_declarative.py
@@ -0,0 +1,968 @@
+"""Declarative YAML/JSON schema, preset loader, and execution runners for 1D iodine aging.
+
+Provides Pydantic-validated declarative decks (``solarlab.iodine-deck.v1``) that
+researchers, CLI commands, and HTTP routes can load from packaged presets or
+user YAML/JSON files without modifying SolarLab's frozen 20-DTO V2 frontend
+configuration schema. Every execution payload explicitly carries
+``scientific_qualification = False`` and ``scientific_acceptance = "not_evaluated"``.
+"""
+
+from __future__ import annotations
+
+from collections.abc import Mapping, Sequence
+from dataclasses import asdict
+import hashlib
+import json
+from pathlib import Path
+import time
+from typing import Any, Literal
+
+import numpy as np
+from numpy.typing import NDArray
+from pydantic import BaseModel, ConfigDict, Field, model_validator
+import yaml
+
+from solarlab.config.resolve_device import resolve_device
+from solarlab.contracts import ContractError
+from solarlab.contracts.units import ELEMENTARY_CHARGE_C as Q
+from solarlab.device.compile_iodine_1d import (
+ IodineBoundaryDeclaration,
+ IodineChemistryDeclaration,
+ IodineLayerSpec,
+ IodineRateParameterization,
+ compile_iodine_device_1d,
+)
+from solarlab.device.defaults import DefaultCatalog
+from solarlab.device.inputs import DeviceInput
+from solarlab.device.resolved import PreparedDevice
+from solarlab.equations.iodine_1d import (
+ CompiledIodineDevice1D,
+ ContactReactionMode,
+ IodineDomainMode,
+ IodineState1D,
+)
+from solarlab.experiments.iodine_aging import (
+ IodineAgingProtocol,
+ IodineProbeMode,
+ IodineProbeSpec,
+ StressRecoveryStage,
+ measure_frozen_chemistry_jv,
+ record_iodine_aging_in_run_store,
+ run_iodine_aging_protocol,
+ save_iodine_aging_bundle,
+)
+from solarlab.io.run_store import RunStore
+from solarlab.materials import (
+ PACKAGED_PRESET_NAMES,
+ load_packaged_default_catalog,
+ load_packaged_preset_device_mapping,
+ load_packaged_preset_sources,
+ load_packaged_resource_library,
+)
+from solarlab.materials.iodine_presets import (
+ PACKAGED_IODINE_PRESET_NAMES,
+ load_packaged_iodine_preset_mapping,
+ load_packaged_iodine_preset_source,
+)
+from solarlab.materials.source import SourceDocument
+from solarlab.physics.chemistry import IodineThermodynamicMode, ReactionEOrder
+from solarlab.solvers.linear.iodine_impedance import (
+ ChemResponseMode,
+ IodineImpedanceResult,
+ solve_iodine_small_signal_1d,
+)
+from solarlab.solvers.nonlinear.iodine_1d import (
+ solve_frozen_chemistry_electronic_1d,
+ solve_iodine_bdf_transient,
+ solve_iodine_steady_state,
+)
+from solarlab.solvers.time.bdf import BDFOptions
+
+__all__ = [
+ "IODINE_DECK_SCHEMA_VERSION",
+ "IodineAgingSpecInput",
+ "IodineBDFOptionsInput",
+ "IodineBoundaryInput",
+ "IodineChemistryInput",
+ "IodineDeckInput",
+ "IodineElectronicStackInput",
+ "IodineImpedanceSpecInput",
+ "IodineLayerInput",
+ "IodineOverridesInput",
+ "IodineProbeInput",
+ "IodineStageInput",
+ "IodineSteadySpecInput",
+ "apply_iodine_deck_overrides",
+ "compile_iodine_deck",
+ "execute_iodine_aging_deck",
+ "execute_iodine_impedance_deck",
+ "execute_iodine_steady_deck",
+ "export_iodine_deck_schema",
+ "load_iodine_deck",
+ "resolve_iodine_operating_state",
+]
+
+IODINE_DECK_SCHEMA_VERSION = "solarlab.iodine-deck.v1"
+_EPS0_F_M = 8.8541878128e-12
+
+
+class IodineLayerInput(BaseModel):
+ """Declarative per-layer iodine transport, reaction, partition, and outgassing spec."""
+
+ model_config = ConfigDict(extra="forbid", allow_inf_nan=False)
+
+ layer_id: str = Field(min_length=1, max_length=128)
+ units: Literal["cgs", "si"] = "cgs"
+ D_minus: float = Field(ge=0.0)
+ D_atom: float = Field(ge=0.0)
+ D_mol: float = Field(ge=0.0)
+ initial_iodide: float = Field(default=0.0, ge=0.0)
+ initial_atom: float = Field(default=0.0, ge=0.0)
+ initial_mol: float = Field(default=0.0, ge=0.0)
+ compensating_donor: float | None = Field(default=None, ge=0.0)
+ E_a_minus_eV: float = Field(default=0.0, ge=0.0)
+ E_a_atom_eV: float = Field(default=0.0, ge=0.0)
+ E_a_mol_eV: float = Field(default=0.0, ge=0.0)
+ rate_mode: IodineRateParameterization = "explicit_rates"
+ k_a: float = Field(default=0.0, ge=0.0)
+ k_b: float = Field(default=0.0, ge=0.0)
+ k_c: float = Field(default=0.0, ge=0.0)
+ k_d: float = Field(default=0.0, ge=0.0)
+ k_e: float = Field(default=0.0, ge=0.0)
+ k_e_3body: float = Field(default=0.0, ge=0.0)
+ capture_radius_nm: float = Field(default=0.2, ge=0.0)
+ K_diss: float = Field(default=1.0e8, gt=0.0)
+ n_e_star: float = Field(default=1.0e8, ge=0.0)
+ partition_minus: float = Field(default=1.0, gt=0.0)
+ partition_atom: float = Field(default=1.0, gt=0.0)
+ partition_mol: float = Field(default=1.0, gt=0.0)
+ iodide_site_limit: float | None = Field(default=None, gt=0.0)
+ volumetric_mol_escape_s_1: float = Field(default=0.0, ge=0.0)
+
+ def to_layer_spec(self) -> IodineLayerSpec:
+ if self.units == "cgs":
+ spec = IodineLayerSpec.from_cgs(
+ self.layer_id,
+ D_minus_cm2_s=self.D_minus,
+ D_atom_cm2_s=self.D_atom,
+ D_mol_cm2_s=self.D_mol,
+ initial_iodide_cm3=self.initial_iodide,
+ initial_atom_cm3=self.initial_atom,
+ initial_mol_cm3=self.initial_mol,
+ compensating_donor_cm3=self.compensating_donor,
+ rate_mode=self.rate_mode,
+ k_a_cm3_s=self.k_a,
+ k_b_s_1=self.k_b,
+ k_c_cm3_s=self.k_c,
+ k_d_cm3_s=self.k_d,
+ k_e_cm3_s=self.k_e,
+ k_e_3body_cm6_s=self.k_e_3body,
+ capture_radius_nm=self.capture_radius_nm,
+ K_diss_cm3=self.K_diss,
+ n_e_star_cm3=self.n_e_star,
+ partition_minus=self.partition_minus,
+ partition_atom=self.partition_atom,
+ partition_mol=self.partition_mol,
+ iodide_site_limit_cm3=self.iodide_site_limit,
+ volumetric_mol_escape_s_1=self.volumetric_mol_escape_s_1,
+ )
+ if (
+ self.E_a_minus_eV != 0.0
+ or self.E_a_atom_eV != 0.0
+ or self.E_a_mol_eV != 0.0
+ ):
+ return IodineLayerSpec(
+ **{
+ **asdict(spec),
+ "E_a_minus_eV": self.E_a_minus_eV,
+ "E_a_atom_eV": self.E_a_atom_eV,
+ "E_a_mol_eV": self.E_a_mol_eV,
+ }
+ )
+ return spec
+ return IodineLayerSpec(
+ layer_id=self.layer_id,
+ D_minus_m2_s=self.D_minus,
+ D_atom_m2_s=self.D_atom,
+ D_mol_m2_s=self.D_mol,
+ initial_iodide_m3=self.initial_iodide,
+ initial_atom_m3=self.initial_atom,
+ initial_mol_m3=self.initial_mol,
+ compensating_donor_m3=self.compensating_donor,
+ E_a_minus_eV=self.E_a_minus_eV,
+ E_a_atom_eV=self.E_a_atom_eV,
+ E_a_mol_eV=self.E_a_mol_eV,
+ rate_mode=self.rate_mode,
+ k_a_m3_s=self.k_a,
+ k_b_s_1=self.k_b,
+ k_c_m3_s=self.k_c,
+ k_d_m3_s=self.k_d,
+ k_e_m3_s=self.k_e,
+ k_e_3body_m6_s=self.k_e_3body,
+ capture_radius_m=self.capture_radius_nm * 1.0e-9,
+ K_diss_m3=self.K_diss,
+ n_e_star_m3=self.n_e_star,
+ partition_minus=self.partition_minus,
+ partition_atom=self.partition_atom,
+ partition_mol=self.partition_mol,
+ iodide_site_limit_m3=self.iodide_site_limit,
+ volumetric_mol_escape_s_1=self.volumetric_mol_escape_s_1,
+ )
+
+
+class IodineBoundaryInput(BaseModel):
+ """Outer contact boundary reaction and volatile I2 escape specification."""
+
+ model_config = ConfigDict(extra="forbid", allow_inf_nan=False)
+
+ mol_escape_velocity_m_s: float = Field(default=0.0, ge=0.0)
+ contact_reaction_mode: ContactReactionMode = "none"
+ contact_oxidation_rate_m4_s: float = Field(default=0.0, ge=0.0)
+ contact_corrosion_velocity_m_s: float = Field(default=0.0, ge=0.0)
+
+ def to_declaration(self) -> IodineBoundaryDeclaration:
+ return IodineBoundaryDeclaration(
+ mol_escape_velocity_m_s=self.mol_escape_velocity_m_s,
+ contact_reaction_mode=self.contact_reaction_mode,
+ contact_oxidation_rate_m4_s=self.contact_oxidation_rate_m4_s,
+ contact_corrosion_velocity_m_s=self.contact_corrosion_velocity_m_s,
+ )
+
+
+class IodineChemistryInput(BaseModel):
+ """Complete declarative 5-reaction I-/I0/I2 chemistry configuration."""
+
+ model_config = ConfigDict(extra="forbid", allow_inf_nan=False)
+
+ domain_mode: IodineDomainMode = "absorber_blocking"
+ thermodynamic_mode: IodineThermodynamicMode = "wegscheider_detailed_balance"
+ reaction_e_order: ReactionEOrder = "bimolecular_n"
+ initialize_equilibrium_split: bool = False
+ enforce_spatial_wegscheider: bool = True
+ steric_diffusion_only: bool = True
+ left_boundary: IodineBoundaryInput = Field(default_factory=IodineBoundaryInput)
+ right_boundary: IodineBoundaryInput = Field(default_factory=IodineBoundaryInput)
+ layers: list[IodineLayerInput] = Field(min_length=1, max_length=16)
+
+ def to_declaration(self) -> IodineChemistryDeclaration:
+ return IodineChemistryDeclaration(
+ layers=tuple(layer.to_layer_spec() for layer in self.layers),
+ domain_mode=self.domain_mode,
+ thermodynamic_mode=self.thermodynamic_mode,
+ reaction_e_order=self.reaction_e_order,
+ left_boundary=self.left_boundary.to_declaration(),
+ right_boundary=self.right_boundary.to_declaration(),
+ initialize_equilibrium_split=self.initialize_equilibrium_split,
+ enforce_spatial_wegscheider=self.enforce_spatial_wegscheider,
+ steric_diffusion_only=self.steric_diffusion_only,
+ )
+
+
+class IodineElectronicStackInput(BaseModel):
+ """Electronic stack reference: packaged preset name or inline DeviceInput mapping."""
+
+ model_config = ConfigDict(extra="forbid", allow_inf_nan=False)
+
+ preset: str | None = None
+ device: dict[str, Any] | None = None
+ allow_legacy_benchmark_deck: bool = False
+ intervals_per_layer: int | list[int] = 18
+
+ @model_validator(mode="after")
+ def _validate_source_and_intervals(self) -> IodineElectronicStackInput:
+ if (self.preset is None) == (self.device is None):
+ raise ValueError(
+ "electronic_stack must specify exactly one of 'preset' or 'device'"
+ )
+ if self.preset is not None and self.preset not in PACKAGED_PRESET_NAMES:
+ raise ValueError(
+ f"unknown electronic device preset {self.preset!r}; "
+ f"expected one of {list(PACKAGED_PRESET_NAMES)}"
+ )
+ if isinstance(self.intervals_per_layer, int):
+ if not 2 <= self.intervals_per_layer <= 256:
+ raise ValueError("intervals_per_layer must lie in [2, 256]")
+ else:
+ if not self.intervals_per_layer or any(
+ not 2 <= int(n) <= 256 for n in self.intervals_per_layer
+ ):
+ raise ValueError("each intervals_per_layer entry must lie in [2, 256]")
+ return self
+
+
+class IodineSteadySpecInput(BaseModel):
+ """Default operating point and optional frozen-chemistry J-V sweep for steady runs."""
+
+ model_config = ConfigDict(extra="forbid", allow_inf_nan=False)
+
+ voltage_V: float = Field(default=0.9, ge=-2.0, le=3.0)
+ generation_scale: float = Field(default=1.0, ge=0.0, le=100.0)
+ open_loss_precondition_s: float = Field(default=20.0, gt=0.0, le=3600.0)
+ compute_frozen_jv: bool = True
+ jv_v_min_V: float = Field(default=0.0, ge=-2.0, le=3.0)
+ jv_v_max_V: float = Field(default=1.25, ge=-2.0, le=3.0)
+ jv_n_points: int = Field(default=26, ge=2, le=201)
+
+
+class IodineImpedanceSpecInput(BaseModel):
+ """Default small-signal AC impedance and redox capacitance sweep parameters."""
+
+ model_config = ConfigDict(extra="forbid", allow_inf_nan=False)
+
+ voltage_V: float = Field(default=0.9, ge=-2.0, le=3.0)
+ generation_scale: float = Field(default=1.0, ge=0.0, le=100.0)
+ f_min_Hz: float = Field(default=1.0e-2, gt=0.0, le=1.0e9)
+ f_max_Hz: float = Field(default=1.0e6, gt=0.0, le=1.0e10)
+ n_frequencies: int = Field(default=25, ge=2, le=201)
+ chem_mode: Literal["mobile", "frozen", "both"] = "both"
+
+ @model_validator(mode="after")
+ def _check_freq_order(self) -> IodineImpedanceSpecInput:
+ if self.f_max_Hz <= self.f_min_Hz:
+ raise ValueError("f_max_Hz must exceed f_min_Hz")
+ return self
+
+
+class IodineStageInput(BaseModel):
+ """One constant-bias, constant-illumination stress or recovery stage."""
+
+ model_config = ConfigDict(extra="forbid", allow_inf_nan=False)
+
+ name: str = Field(min_length=1, max_length=128)
+ duration_s: float = Field(gt=0.0, le=1.0e9)
+ voltage_V: float = Field(ge=-2.0, le=3.0)
+ generation_scale: float = Field(ge=0.0, le=100.0)
+ max_step_s: float = Field(default=200.0, gt=0.0, le=1.0e8)
+
+ def to_stage(self) -> StressRecoveryStage:
+ return StressRecoveryStage(
+ name=self.name,
+ duration_s=self.duration_s,
+ voltage_V=self.voltage_V,
+ generation_scale=self.generation_scale,
+ max_step_s=self.max_step_s,
+ )
+
+
+class IodineProbeInput(BaseModel):
+ """Non-destructive J-V characterization probe at aging checkpoints."""
+
+ model_config = ConfigDict(extra="forbid", allow_inf_nan=False)
+
+ mode: IodineProbeMode = "frozen_chemistry_jv"
+ v_min_V: float = Field(default=0.0, ge=-2.0, le=3.0)
+ v_max_V: float = Field(default=1.25, ge=-2.0, le=3.0)
+ n_points: int = Field(default=26, ge=2, le=201)
+ scan_rate_V_s: float = Field(default=1.0, gt=0.0, le=1.0e4)
+ generation_scale: float = Field(default=1.0, ge=0.0, le=100.0)
+ incident_power_W_m2: float = Field(default=1000.0, gt=0.0, le=1.0e6)
+
+ def to_probe_spec(self) -> IodineProbeSpec:
+ voltages = tuple(
+ float(v) for v in np.linspace(self.v_min_V, self.v_max_V, self.n_points)
+ )
+ return IodineProbeSpec(
+ mode=self.mode,
+ voltages_V=voltages,
+ scan_rate_V_s=self.scan_rate_V_s,
+ generation_scale=self.generation_scale,
+ incident_power_W_m2=self.incident_power_W_m2,
+ )
+
+
+class IodineBDFOptionsInput(BaseModel):
+ """Variable-step BDF-1/BDF-2 time-integration tolerances and limits."""
+
+ model_config = ConfigDict(extra="forbid", allow_inf_nan=False)
+
+ initial_step_s: float = Field(default=1.0e-5, gt=0.0)
+ min_step_s: float = Field(default=1.0e-14, gt=0.0)
+ max_step_s: float = Field(default=200.0, gt=0.0)
+ relative_tolerance: float = Field(default=1.0e-2, gt=0.0, le=0.1)
+ absolute_tolerance: float = Field(default=1.0e15, gt=0.0)
+ max_order: Literal[1, 2] = 1
+ max_steps: int = Field(default=800, ge=4, le=10000)
+
+ def to_bdf_options(self) -> BDFOptions:
+ return BDFOptions(
+ initial_step_s=self.initial_step_s,
+ min_step_s=self.min_step_s,
+ max_step_s=self.max_step_s,
+ relative_tolerance=self.relative_tolerance,
+ absolute_tolerance=self.absolute_tolerance,
+ max_order=self.max_order,
+ max_steps=self.max_steps,
+ )
+
+
+class IodineAgingSpecInput(BaseModel):
+ """Complete multi-stage aging protocol specification."""
+
+ model_config = ConfigDict(extra="forbid", allow_inf_nan=False)
+
+ stages: list[IodineStageInput] = Field(min_length=1, max_length=32)
+ checkpoint_times_s: list[float] = Field(default_factory=list)
+ probe: IodineProbeInput = Field(default_factory=IodineProbeInput)
+ bdf: IodineBDFOptionsInput = Field(default_factory=IodineBDFOptionsInput)
+
+ def to_protocol(self) -> IodineAgingProtocol:
+ stages = tuple(s.to_stage() for s in self.stages)
+ max_stage_step = max(s.max_step_s for s in stages)
+ bdf_opts = self.bdf.to_bdf_options()
+ if max_stage_step > bdf_opts.max_step_s:
+ bdf_opts = BDFOptions(
+ initial_step_s=bdf_opts.initial_step_s,
+ min_step_s=bdf_opts.min_step_s,
+ max_step_s=max_stage_step,
+ relative_tolerance=bdf_opts.relative_tolerance,
+ absolute_tolerance=bdf_opts.absolute_tolerance,
+ max_order=bdf_opts.max_order,
+ max_steps=bdf_opts.max_steps,
+ )
+ return IodineAgingProtocol(
+ stages=stages,
+ checkpoint_times_s=tuple(self.checkpoint_times_s),
+ probe=self.probe.to_probe_spec(),
+ bdf_options=bdf_opts,
+ )
+
+
+class IodineDeckInput(BaseModel):
+ """Top-level ``solarlab.iodine-deck.v1`` declarative configuration."""
+
+ model_config = ConfigDict(extra="forbid", allow_inf_nan=False)
+
+ schema_version: Literal["solarlab.iodine-deck.v1"] = "solarlab.iodine-deck.v1"
+ id: str = Field(min_length=1, max_length=128)
+ name: str = Field(default="Iodine Chemistry & Aging Deck", max_length=256)
+ description: str = Field(default="", max_length=2048)
+ reference: str = Field(default="", max_length=512)
+ electronic_stack: IodineElectronicStackInput
+ chemistry: IodineChemistryInput
+ steady: IodineSteadySpecInput = Field(default_factory=IodineSteadySpecInput)
+ impedance: IodineImpedanceSpecInput = Field(
+ default_factory=IodineImpedanceSpecInput
+ )
+ aging: IodineAgingSpecInput | None = None
+
+
+class IodineOverridesInput(BaseModel):
+ """Bounded interactive parameter overrides for CLI and HTTP workstation runs."""
+
+ model_config = ConfigDict(extra="forbid", allow_inf_nan=False)
+
+ intervals_per_layer: int | list[int] | None = None
+ k_a_cm3_s: float | None = Field(default=None, ge=0.0, le=1.0e-5)
+ mu_bl_cm2_V_s: float | None = Field(default=None, gt=0.0, le=100.0)
+ ebl_partition: float | None = Field(default=None, gt=0.0, le=1.0e3)
+ volumetric_escape_s_1: float | None = Field(default=None, ge=0.0, le=1.0e3)
+ contact_corrosion_m_s: float | None = Field(default=None, ge=0.0, le=1.0)
+ voltage_V: float | None = Field(default=None, ge=-2.0, le=3.0)
+ generation_scale: float | None = Field(default=None, ge=0.0, le=100.0)
+ compute_frozen_jv: bool | None = None
+ f_min_Hz: float | None = Field(default=None, gt=0.0, le=1.0e9)
+ f_max_Hz: float | None = Field(default=None, gt=0.0, le=1.0e10)
+ n_frequencies: int | None = Field(default=None, ge=2, le=101)
+ chem_mode: Literal["mobile", "frozen", "both"] | None = None
+ probe_mode: IodineProbeMode | None = None
+ stages: list[IodineStageInput] | None = Field(default=None, max_length=12)
+ checkpoint_times_s: list[float] | None = None
+
+
+def export_iodine_deck_schema() -> dict[str, Any]:
+ """Export deterministic JSON Schema and SHA-256 digest for ``IodineDeckInput``."""
+ schema = IodineDeckInput.model_json_schema()
+ canonical = json.dumps(schema, sort_keys=True, separators=(",", ":")).encode("utf-8")
+ return {
+ "schema": "solarlab.iodine-deck-schema.v1",
+ "deck_schema_version": IODINE_DECK_SCHEMA_VERSION,
+ "sha256": hashlib.sha256(canonical).hexdigest(),
+ "packaged_presets": list(PACKAGED_IODINE_PRESET_NAMES),
+ "json_schema": schema,
+ "scientific_qualification": False,
+ }
+
+
+def load_iodine_deck(
+ source: str | Path | Mapping[str, Any],
+) -> tuple[IodineDeckInput, SourceDocument]:
+ """Load and validate an ``IodineDeckInput`` from preset name, YAML/JSON path, or dict."""
+ if isinstance(source, Mapping):
+ raw_bytes = json.dumps(dict(source), sort_keys=True).encode("utf-8")
+ doc = SourceDocument("inline-iodine-deck.json", raw_bytes)
+ return IodineDeckInput.model_validate(dict(source)), doc
+ if isinstance(source, str) and not Path(source).is_file():
+ preset_doc = load_packaged_iodine_preset_source(source)
+ mapping = load_packaged_iodine_preset_mapping(source)
+ return IodineDeckInput.model_validate(mapping), preset_doc
+ path = Path(source)
+ raw = path.read_bytes()
+ src_doc = SourceDocument(path.name, raw)
+ text = raw.decode("utf-8")
+ if path.suffix.lower() in {".yaml", ".yml"}:
+ parsed = yaml.safe_load(text)
+ else:
+ parsed = json.loads(text)
+ if not isinstance(parsed, dict):
+ raise ValueError(f"iodine deck file {path} must contain a mapping/object")
+ return IodineDeckInput.model_validate(parsed), src_doc
+
+
+def apply_iodine_deck_overrides(
+ deck: IodineDeckInput,
+ overrides: IodineOverridesInput | None,
+) -> IodineDeckInput:
+ """Return a validated copy of ``deck`` with optional interactive overrides applied."""
+ if overrides is None:
+ return deck
+ data = deck.model_dump(mode="python")
+
+ if overrides.intervals_per_layer is not None:
+ data["electronic_stack"]["intervals_per_layer"] = overrides.intervals_per_layer
+
+ if overrides.mu_bl_cm2_V_s is not None and data["electronic_stack"].get("device"):
+ mu_si = float(overrides.mu_bl_cm2_V_s) * 1.0e-4
+ for layer in data["electronic_stack"]["device"].get("layers", []):
+ if layer.get("role") in {"ETL", "HTL"}:
+ params = layer.setdefault("parameters", {})
+ eps_r = float(params.get("eps_r", 3.0))
+ params["mu_n"] = mu_si
+ params["mu_p"] = mu_si
+ params["B_rad"] = float(Q * (2.0 * mu_si) / (_EPS0_F_M * eps_r))
+
+ for layer_spec in data["chemistry"]["layers"]:
+ lid = layer_spec["layer_id"]
+ is_cgs = layer_spec.get("units", "cgs") == "cgs"
+ if overrides.k_a_cm3_s is not None and lid == "absorber":
+ layer_spec["rate_mode"] = "explicit_rates"
+ layer_spec["k_a"] = (
+ float(overrides.k_a_cm3_s)
+ if is_cgs
+ else float(overrides.k_a_cm3_s) * 1.0e-6
+ )
+ if overrides.ebl_partition is not None and lid in {"ebl", "htl"}:
+ part = float(overrides.ebl_partition)
+ layer_spec["partition_minus"] = part
+ layer_spec["partition_atom"] = part
+ layer_spec["partition_mol"] = part
+ if overrides.volumetric_escape_s_1 is not None:
+ target = (
+ "ebl"
+ if data["chemistry"]["domain_mode"] == "full_stack_permeable"
+ else "absorber"
+ )
+ if lid == target:
+ layer_spec["volumetric_mol_escape_s_1"] = float(
+ overrides.volumetric_escape_s_1
+ )
+
+ if overrides.contact_corrosion_m_s is not None:
+ v_corr = float(overrides.contact_corrosion_m_s)
+ if v_corr > 0.0:
+ data["chemistry"]["left_boundary"]["contact_reaction_mode"] = (
+ "metal_faradaic_corrosion"
+ )
+ data["chemistry"]["left_boundary"]["contact_corrosion_velocity_m_s"] = (
+ v_corr
+ )
+ else:
+ data["chemistry"]["left_boundary"]["contact_reaction_mode"] = "none"
+ data["chemistry"]["left_boundary"]["contact_corrosion_velocity_m_s"] = 0.0
+
+ if overrides.voltage_V is not None:
+ data["steady"]["voltage_V"] = float(overrides.voltage_V)
+ data["impedance"]["voltage_V"] = float(overrides.voltage_V)
+ if overrides.generation_scale is not None:
+ data["steady"]["generation_scale"] = float(overrides.generation_scale)
+ data["impedance"]["generation_scale"] = float(overrides.generation_scale)
+ if overrides.compute_frozen_jv is not None:
+ data["steady"]["compute_frozen_jv"] = bool(overrides.compute_frozen_jv)
+ if overrides.f_min_Hz is not None:
+ data["impedance"]["f_min_Hz"] = float(overrides.f_min_Hz)
+ if overrides.f_max_Hz is not None:
+ data["impedance"]["f_max_Hz"] = float(overrides.f_max_Hz)
+ if overrides.n_frequencies is not None:
+ data["impedance"]["n_frequencies"] = int(overrides.n_frequencies)
+ if overrides.chem_mode is not None:
+ data["impedance"]["chem_mode"] = overrides.chem_mode
+
+ if data.get("aging") is not None:
+ if overrides.probe_mode is not None:
+ data["aging"]["probe"]["mode"] = overrides.probe_mode
+ if overrides.stages is not None:
+ data["aging"]["stages"] = [s.model_dump(mode="python") for s in overrides.stages]
+ total_s = sum(float(s.duration_s) for s in overrides.stages)
+ if overrides.checkpoint_times_s is None:
+ data["aging"]["checkpoint_times_s"] = [0.0, total_s]
+ if overrides.checkpoint_times_s is not None:
+ data["aging"]["checkpoint_times_s"] = list(overrides.checkpoint_times_s)
+
+ return IodineDeckInput.model_validate(data)
+
+
+def compile_iodine_deck(
+ deck: IodineDeckInput,
+ *,
+ source: SourceDocument | None = None,
+ intervals_override: int | Sequence[int] | None = None,
+) -> tuple[PreparedDevice, CompiledIodineDevice1D]:
+ """Resolve the electronic stack and compile ``CompiledIodineDevice1D``."""
+ defaults: DefaultCatalog = load_packaged_default_catalog()
+ resources = load_packaged_resource_library()
+ src_tuple = (
+ (*load_packaged_preset_sources(),)
+ if source is None
+ else (source, *load_packaged_preset_sources())
+ )
+ if deck.electronic_stack.preset is not None:
+ dev_map = load_packaged_preset_device_mapping(deck.electronic_stack.preset)
+ else:
+ assert deck.electronic_stack.device is not None
+ dev_map = json.loads(json.dumps(deck.electronic_stack.device))
+ settings_map = dev_map.setdefault("settings", {})
+ if settings_map.get("built_in_potential_mode") == "metal_work_function":
+ settings_map.setdefault("V_bi", 0.0)
+ for layer_entry in dev_map.get("layers", []):
+ if isinstance(layer_entry, dict) and isinstance(
+ layer_entry.get("parameters"), dict
+ ):
+ p = layer_entry["parameters"]
+ p.setdefault("A_star_n", 0.0)
+ p.setdefault("A_star_p", 0.0)
+ p.setdefault("D_ion", 0.0)
+ p.setdefault("P0", 0.0)
+ p.setdefault("P_lim", 1.0e28)
+
+ prepared = resolve_device(
+ DeviceInput.model_validate(dev_map),
+ defaults,
+ resources,
+ sources=src_tuple,
+ )
+ chem_decl = deck.chemistry.to_declaration()
+ intervals = (
+ deck.electronic_stack.intervals_per_layer
+ if intervals_override is None
+ else intervals_override
+ )
+ compiled = compile_iodine_device_1d(
+ prepared,
+ chem_decl,
+ intervals_per_layer=intervals,
+ allow_legacy_benchmark_deck=deck.electronic_stack.allow_legacy_benchmark_deck,
+ )
+ return prepared, compiled
+
+
+def resolve_iodine_operating_state(
+ device: CompiledIodineDevice1D,
+ *,
+ voltage_V: float,
+ generation_scale: float,
+ open_loss_precondition_s: float = 20.0,
+) -> tuple[IodineState1D, str]:
+ """Resolve closed-inventory steady state or open-loss quasi-steady operating state."""
+ if not device.has_open_iodine_loss:
+ ss = solve_iodine_steady_state(
+ device,
+ voltage_V=voltage_V,
+ generation_scale=generation_scale,
+ )
+ if ss.converged and ss.state is not None:
+ return ss.state, "closed_inventory_steady"
+
+ u0, _ = solve_frozen_chemistry_electronic_1d(
+ device,
+ device.initial_coordinates(voltage_V=0.0),
+ voltage_V=voltage_V,
+ generation_scale=generation_scale,
+ prev_voltage_V=0.0,
+ )
+ horizon_s = open_loss_precondition_s if device.has_open_iodine_loss else 600.0
+ bdf_res, _ = solve_iodine_bdf_transient(
+ device,
+ u0,
+ (0.0, horizon_s),
+ voltage_fn=lambda _t: voltage_V,
+ generation_fn=lambda _t: generation_scale,
+ options=BDFOptions(
+ initial_step_s=1.0e-5,
+ min_step_s=1.0e-14,
+ max_step_s=max(horizon_s * 0.25, 1.0),
+ relative_tolerance=1.0e-2,
+ absolute_tolerance=1.0e15,
+ max_order=1,
+ max_steps=400,
+ ),
+ )
+ if len(bdf_res.accepted_coordinates) == 0:
+ raise ContractError("failed_to_resolve_iodine_operating_state")
+ state = device.state(bdf_res.accepted_coordinates[-1], voltage_V=voltage_V)
+ mode = (
+ f"open_loss_quasi_steady_{horizon_s:g}s"
+ if device.has_open_iodine_loss
+ else "bdf_relaxed_steady"
+ )
+ return state, mode
+
+
+def _serialize_state_profiles(
+ device: CompiledIodineDevice1D,
+ state: IodineState1D,
+) -> dict[str, Any]:
+ e_nodes_nm = [float(x * 1.0e9) for x in device.electronic_component.nodes_m]
+ c_nodes_nm = [float(x * 1.0e9) for x in device.chem_geometry.nodes_m]
+ e_state = state.electronic_state
+ return {
+ "electrical_nodes_nm": e_nodes_nm,
+ "chem_nodes_nm": c_nodes_nm,
+ "potential_V": [float(v) for v in e_state.potential_V],
+ "electron_density_m3": [float(v) for v in e_state.electron_density_m3],
+ "hole_density_m3": [float(v) for v in e_state.hole_density_m3],
+ "iodide_m3": [float(v) for v in state.iodide_density_m3],
+ "iodine_atom_m3": [float(v) for v in state.iodine_atom_density_m3],
+ "iodine_molecule_m3": [float(v) for v in state.iodine_molecule_density_m3],
+ "species_inventories_m2": {
+ k: float(v) for k, v in state.species_inventories_m2.items()
+ },
+ "total_iodine_atoms_m2": float(state.total_iodine_inventory_m2),
+ }
+
+
+def execute_iodine_steady_deck(
+ deck: IodineDeckInput,
+ *,
+ source: SourceDocument | None = None,
+) -> dict[str, Any]:
+ """Run coupled steady/quasi-steady state and optional frozen-chemistry J-V probe."""
+ t0 = time.perf_counter()
+ _, compiled = compile_iodine_deck(deck, source=source)
+ spec = deck.steady
+ state, state_mode = resolve_iodine_operating_state(
+ compiled,
+ voltage_V=spec.voltage_V,
+ generation_scale=spec.generation_scale,
+ open_loss_precondition_s=spec.open_loss_precondition_s,
+ )
+ frozen_jv_payload: dict[str, Any] | None = None
+ if spec.compute_frozen_jv:
+ v_grid = np.linspace(spec.jv_v_min_V, spec.jv_v_max_V, spec.jv_n_points)
+ probe = measure_frozen_chemistry_jv(
+ compiled,
+ state,
+ v_grid,
+ generation_scale=spec.generation_scale,
+ )
+ frozen_jv_payload = {
+ "voltages_V": [float(v) for v in probe.voltages_V],
+ "output_current_A_m2": [float(j) for j in probe.output_current_A_m2],
+ "metrics": asdict(probe.metrics),
+ }
+
+ return {
+ "schema": "solarlab.iodine-steady-result.v1",
+ "deck_id": deck.id,
+ "deck_name": deck.name,
+ "device_sha256": compiled.identity,
+ "domain_mode": compiled.domain_mode,
+ "operating_state_mode": state_mode,
+ "voltage_V": spec.voltage_V,
+ "generation_scale": spec.generation_scale,
+ "profiles": _serialize_state_profiles(compiled, state),
+ "frozen_jv": frozen_jv_payload,
+ "wall_s": float(time.perf_counter() - t0),
+ "scientific_acceptance": "not_evaluated",
+ "scientific_qualification": False,
+ }
+
+
+def _serialize_impedance_sweep(res: IodineImpedanceResult) -> dict[str, Any]:
+ return {
+ "chem_mode": res.chem_mode,
+ "frequencies_Hz": [float(f) for f in res.frequencies_Hz],
+ "admittance_real_S_m2": [float(y.real) for y in res.admittance_S_m2],
+ "admittance_imag_S_m2": [float(y.imag) for y in res.admittance_S_m2],
+ "impedance_real_Ohm_m2": [float(z.real) for z in res.impedance_Ohm_m2],
+ "impedance_imag_Ohm_m2": [float(z.imag) for z in res.impedance_Ohm_m2],
+ "apparent_capacitance_F_m2": [float(c) for c in res.apparent_capacitance_F_m2],
+ "max_maxwell_spread_A_m2_V": float(res.max_maxwell_spread_A_m2_V),
+ "max_backward_error": float(res.max_backward_error),
+ }
+
+
+def execute_iodine_impedance_deck(
+ deck: IodineDeckInput,
+ *,
+ source: SourceDocument | None = None,
+) -> dict[str, Any]:
+ """Run coupled operating-point solve and small-signal AC impedance / capacitance sweep."""
+ t0 = time.perf_counter()
+ _, compiled = compile_iodine_deck(deck, source=source)
+ spec = deck.impedance
+ state, state_mode = resolve_iodine_operating_state(
+ compiled,
+ voltage_V=spec.voltage_V,
+ generation_scale=spec.generation_scale,
+ open_loss_precondition_s=deck.steady.open_loss_precondition_s,
+ )
+ freqs: NDArray[np.float64] = np.geomspace(
+ spec.f_min_Hz, spec.f_max_Hz, spec.n_frequencies
+ )
+ modes: tuple[ChemResponseMode, ...] = (
+ ("mobile", "frozen") if spec.chem_mode == "both" else (spec.chem_mode,)
+ )
+ sweeps: dict[str, Any] = {}
+ for m in modes:
+ res = solve_iodine_small_signal_1d(
+ compiled,
+ state,
+ freqs,
+ generation_scale=spec.generation_scale,
+ chem_mode=m,
+ )
+ sweeps[m] = _serialize_impedance_sweep(res)
+
+ redox_excess_cap: list[float] | None = None
+ if "mobile" in sweeps and "frozen" in sweeps:
+ c_mob = sweeps["mobile"]["apparent_capacitance_F_m2"]
+ c_frz = sweeps["frozen"]["apparent_capacitance_F_m2"]
+ redox_excess_cap = [float(cm - cf) for cm, cf in zip(c_mob, c_frz, strict=True)]
+
+ return {
+ "schema": "solarlab.iodine-impedance-result.v1",
+ "deck_id": deck.id,
+ "deck_name": deck.name,
+ "device_sha256": compiled.identity,
+ "domain_mode": compiled.domain_mode,
+ "operating_state_mode": state_mode,
+ "voltage_V": spec.voltage_V,
+ "generation_scale": spec.generation_scale,
+ "frequencies_Hz": [float(f) for f in freqs],
+ "sweeps": sweeps,
+ "redox_excess_capacitance_F_m2": redox_excess_cap,
+ "profiles": _serialize_state_profiles(compiled, state),
+ "wall_s": float(time.perf_counter() - t0),
+ "scientific_acceptance": "not_evaluated",
+ "scientific_qualification": False,
+ }
+
+
+def execute_iodine_aging_deck(
+ deck: IodineDeckInput,
+ *,
+ source: SourceDocument | None = None,
+ store_dir: Path | None = None,
+ bundle_dir: Path | None = None,
+ run_id: str | None = None,
+) -> dict[str, Any]:
+ """Run multi-stage iodine stress/recovery aging protocol and optional persistence."""
+ if deck.aging is None:
+ raise ValueError(f"iodine deck {deck.id!r} does not define an 'aging' section")
+ _, compiled = compile_iodine_deck(deck, source=source)
+ protocol = deck.aging.to_protocol()
+ result = run_iodine_aging_protocol(compiled, protocol)
+
+ persisted_store: dict[str, str] | None = None
+ if store_dir is not None:
+ store_root = Path(store_dir).resolve()
+ actual_run_id = run_id or f"iodine-aging-{deck.id}-{int(time.time() * 1000)}"
+ with RunStore(store_root) as store:
+ run_rec = record_iodine_aging_in_run_store(
+ store,
+ actual_run_id,
+ compiled,
+ protocol,
+ result,
+ )
+ persisted_store = {
+ "store_id": store.store_id,
+ "run_id": str(run_rec["run_id"]),
+ "attempt_id": str(run_rec["current_attempt_id"]),
+ }
+
+ if bundle_dir is not None:
+ save_iodine_aging_bundle(bundle_dir, result)
+
+ checkpoints_out: list[dict[str, Any]] = []
+ for ckpt in result.checkpoints:
+ frozen_dict: dict[str, Any] | None = None
+ if ckpt.frozen_jv is not None:
+ frozen_dict = {
+ "voltages_V": [float(v) for v in ckpt.frozen_jv.voltages_V],
+ "output_current_A_m2": [
+ float(j) for j in ckpt.frozen_jv.output_current_A_m2
+ ],
+ "metrics": asdict(ckpt.frozen_jv.metrics),
+ }
+ dyn_dict: dict[str, Any] | None = None
+ if ckpt.dynamic_jv is not None:
+ dyn_dict = {
+ "voltages_V": [float(v) for v in ckpt.dynamic_jv.voltages_V],
+ "scan_rate_V_s": float(ckpt.dynamic_jv.scan_rate_V_s),
+ "reverse_output_current_A_m2": [
+ float(j) for j in ckpt.dynamic_jv.reverse_output_current_A_m2
+ ],
+ "forward_output_current_A_m2": [
+ float(j) for j in ckpt.dynamic_jv.forward_output_current_A_m2
+ ],
+ "reverse_metrics": asdict(ckpt.dynamic_jv.reverse_metrics),
+ "forward_metrics": asdict(ckpt.dynamic_jv.forward_metrics),
+ "hysteresis_index": ckpt.dynamic_jv.hysteresis_index,
+ }
+ checkpoints_out.append(
+ {
+ "time_s": float(ckpt.time_s),
+ "stage_name": ckpt.stage_name,
+ "in_device_iodine_m2": float(ckpt.in_device_iodine_m2),
+ "cumulative_escaped_iodine_atoms_m2": float(
+ ckpt.cumulative_escaped_iodine_atoms_m2
+ ),
+ "cumulative_immobilized_iodine_atoms_m2": float(
+ ckpt.cumulative_immobilized_iodine_atoms_m2
+ ),
+ "conservation_residual_m2": float(ckpt.conservation_residual_m2),
+ "profiles": _serialize_state_profiles(compiled, ckpt.state),
+ "frozen_jv": frozen_dict,
+ "dynamic_jv": dyn_dict,
+ }
+ )
+
+ step_times = [0.0] + [float(step.end_s) for step in result.step_ledger]
+ step_in_device = [float(result.reference_iodine_inventory_m2)] + [
+ float(step.in_device_iodine_m2) for step in result.step_ledger
+ ]
+ cum_esc = 0.0
+ cum_imm = 0.0
+ step_escaped = [0.0]
+ step_immobilized = [0.0]
+ for step in result.step_ledger:
+ cum_esc += float(step.step_escaped_iodine_atoms_m2)
+ cum_imm += float(step.step_immobilized_iodine_atoms_m2)
+ step_escaped.append(cum_esc)
+ step_immobilized.append(cum_imm)
+
+ return {
+ "schema": "solarlab.iodine-aging-result.v1",
+ "deck_id": deck.id,
+ "deck_name": deck.name,
+ "protocol_sha256": result.protocol_sha256,
+ "device_sha256": result.device_sha256,
+ "domain_mode": compiled.domain_mode,
+ "reference_iodine_inventory_m2": float(result.reference_iodine_inventory_m2),
+ "max_relative_conservation_error": float(
+ result.max_relative_conservation_error
+ ),
+ "accepted_bdf_steps": len(result.step_ledger),
+ "completed": bool(result.completed),
+ "wall_s": float(result.wall_s),
+ "trajectory": {
+ "times_s": step_times,
+ "in_device_iodine_m2": step_in_device,
+ "cumulative_escaped_iodine_atoms_m2": step_escaped,
+ "cumulative_immobilized_iodine_atoms_m2": step_immobilized,
+ },
+ "checkpoints": checkpoints_out,
+ "persisted_run_store": persisted_store,
+ "scientific_acceptance": "not_evaluated",
+ "scientific_qualification": False,
+ }
diff --git a/src/solarlab/materials/data/iodine_presets/__init__.py b/src/solarlab/materials/data/iodine_presets/__init__.py
new file mode 100644
index 00000000..de69eccd
--- /dev/null
+++ b/src/solarlab/materials/data/iodine_presets/__init__.py
@@ -0,0 +1 @@
+"""Packaged YAML presets for 1D iodine reaction-diffusion-aging simulations."""
diff --git a/src/solarlab/materials/data/iodine_presets/bitton_tessler_2023_ag_corrosion.yaml b/src/solarlab/materials/data/iodine_presets/bitton_tessler_2023_ag_corrosion.yaml
new file mode 100644
index 00000000..dc8f3cf1
--- /dev/null
+++ b/src/solarlab/materials/data/iodine_presets/bitton_tessler_2023_ag_corrosion.yaml
@@ -0,0 +1,197 @@
+schema_version: solarlab.iodine-deck.v1
+id: bitton_tessler_2023_ag_corrosion
+name: Bitton & Tessler (2023) HBL Ag Cathode Corrosion
+description: >-
+ Open-boundary full-stack deck with Faradaic metal corrosion at the left HBL
+ cathode (Ag + I- -> AgI + e-_metal, v_corr = 1e-5 m/s) resolving the ~2 s
+ transport breakthrough lag and steady corrosion flux under forward bias.
+reference: Bitton & Tessler, Energy Environ. Sci. 16, 2621-2628 (2023), Fig. 5a & Inset
+
+electronic_stack:
+ allow_legacy_benchmark_deck: true
+ intervals_per_layer: [14, 36, 14]
+ device:
+ schema_version: solarlab.device-preparation.v1
+ id: bt2023_ag_corrosion_stack
+ name: Bitton & Tessler 2023 Ag Corrosion Stack
+ source_format: canonical
+ settings:
+ built_in_potential_mode: metal_work_function
+ V_bi: 0.0
+ work_function_left_eV: 4.44
+ work_function_right_eV: 5.76
+ flat_band_metal_contacts: true
+ contact_phi_B_eV: 0.14
+ dos_band_potentials: true
+ T: 300.0
+ Phi: 1.623603893899371e24
+ layers:
+ - id: hbl
+ name: HBL
+ role: ETL
+ thickness: 50.0e-9
+ parameters:
+ chi: 4.3
+ Eg: 2.5
+ Nc300: 1.0e27
+ Nv300: 1.0e27
+ eps_r: 3.0
+ N_D: 1.0
+ N_A: 0.0
+ ni: 1002130.379122778
+ n1: 1002130.379122778
+ p1: 1002130.379122778
+ tau_n: 1.0e6
+ tau_p: 1.0e6
+ B_rad: 1.206341838923508e-15
+ C_n: 0.0
+ C_p: 0.0
+ mu_n: 1.0e-7
+ mu_p: 1.0e-7
+ alpha: 0.0
+ A_star_n: 0.0
+ A_star_p: 0.0
+ D_ion: 0.0
+ P0: 0.0
+ P_lim: 1.0e28
+ - id: absorber
+ name: Perovskite
+ role: absorber
+ thickness: 500.0e-9
+ parameters:
+ chi: 4.3
+ Eg: 1.6
+ Nc300: 7.0e24
+ Nv300: 2.5e24
+ eps_r: 50.0
+ N_D: 0.0
+ N_A: 0.0
+ ni: 152093456592.39743
+ n1: 152093456592.39743
+ p1: 152093456592.39743
+ tau_n: 1.0e6
+ tau_p: 1.0e6
+ B_rad: 1.0e-16
+ C_n: 0.0
+ C_p: 0.0
+ mu_n: 2.0e-4
+ mu_p: 2.0e-4
+ alpha: 2000.0
+ A_star_n: 0.0
+ A_star_p: 0.0
+ D_ion: 0.0
+ P0: 0.0
+ P_lim: 1.0e28
+ - id: ebl
+ name: EBL
+ role: HTL
+ thickness: 50.0e-9
+ parameters:
+ chi: 3.4
+ Eg: 2.5
+ Nc300: 1.0e27
+ Nv300: 1.0e27
+ eps_r: 3.0
+ N_D: 0.0
+ N_A: 1.0
+ ni: 1002130.379122778
+ n1: 1002130.379122778
+ p1: 1002130.379122778
+ tau_n: 1.0e6
+ tau_p: 1.0e6
+ B_rad: 1.206341838923508e-15
+ C_n: 0.0
+ C_p: 0.0
+ mu_n: 1.0e-7
+ mu_p: 1.0e-7
+ alpha: 0.0
+ A_star_n: 0.0
+ A_star_p: 0.0
+ D_ion: 0.0
+ P0: 0.0
+ P_lim: 1.0e28
+
+chemistry:
+ domain_mode: full_stack_permeable
+ thermodynamic_mode: wegscheider_detailed_balance
+ reaction_e_order: bimolecular_n
+ initialize_equilibrium_split: false
+ enforce_spatial_wegscheider: true
+ left_boundary:
+ contact_reaction_mode: metal_faradaic_corrosion
+ contact_corrosion_velocity_m_s: 1.0e-5
+ layers:
+ - layer_id: hbl
+ units: cgs
+ D_minus: 1.0e-8
+ D_atom: 1.0e-8
+ D_mol: 1.0e-8
+ initial_iodide: 0.0
+ rate_mode: smoluchowski_capture_radius
+ capture_radius_nm: 0.2
+ k_b: 1.0e-6
+ K_diss: 1.0e8
+ n_e_star: 1.0e8
+ - layer_id: absorber
+ units: cgs
+ D_minus: 1.0e-9
+ D_atom: 1.0e-9
+ D_mol: 1.0e-9
+ initial_iodide: 1.0e18
+ rate_mode: explicit_rates
+ k_a: 1.0e-11
+ k_b: 1.0e-3
+ k_c: 5.0e-11
+ k_d: 3.0e-16
+ k_e: 3.0e-16
+ K_diss: 1.0e8
+ n_e_star: 1.0e8
+ - layer_id: ebl
+ units: cgs
+ D_minus: 1.0e-8
+ D_atom: 1.0e-8
+ D_mol: 1.0e-8
+ initial_iodide: 0.0
+ rate_mode: smoluchowski_capture_radius
+ capture_radius_nm: 0.2
+ k_b: 1.0e-6
+ K_diss: 1.0e8
+ n_e_star: 1.0e8
+
+steady:
+ voltage_V: 0.9
+ generation_scale: 1.0
+ compute_frozen_jv: false
+ jv_v_min_V: 0.0
+ jv_v_max_V: 1.25
+ jv_n_points: 26
+
+impedance:
+ voltage_V: 0.9
+ generation_scale: 1.0
+ f_min_Hz: 1.0e-2
+ f_max_Hz: 1.0e6
+ n_frequencies: 25
+ chem_mode: mobile
+
+aging:
+ stages:
+ - name: ag_cathode_breakthrough
+ duration_s: 40.0
+ voltage_V: 0.9
+ generation_scale: 1.0
+ max_step_s: 2.0
+ - name: ag_cathode_steady_corrosion
+ duration_s: 80.0
+ voltage_V: 0.9
+ generation_scale: 1.0
+ max_step_s: 10.0
+ checkpoint_times_s: [0.0, 2.0, 10.0, 40.0, 120.0]
+ probe:
+ mode: none
+ v_min_V: 0.0
+ v_max_V: 1.25
+ n_points: 26
+ scan_rate_V_s: 1.0
+ generation_scale: 1.0
+ incident_power_W_m2: 1000.0
diff --git a/src/solarlab/materials/data/iodine_presets/bitton_tessler_2023_blocking.yaml b/src/solarlab/materials/data/iodine_presets/bitton_tessler_2023_blocking.yaml
new file mode 100644
index 00000000..04b13496
--- /dev/null
+++ b/src/solarlab/materials/data/iodine_presets/bitton_tessler_2023_blocking.yaml
@@ -0,0 +1,167 @@
+schema_version: solarlab.iodine-deck.v1
+id: bitton_tessler_2023_blocking
+name: Bitton & Tessler (2023) Blocking Absorber Stack
+description: >-
+ Symmetric HBL(50 nm)/Perovskite(500 nm)/EBL(50 nm) p-i-n stack with
+ ion-blocking transport layers and coupled 5-reaction I-/I0/I2 chemistry
+ (Table S1, k_a = 1e-11 cm^3/s, mu_BL = 1e-3 cm^2/(V s)).
+reference: Bitton & Tessler, Energy Environ. Sci. 16, 2621-2628 (2023), Table 1 & Fig. 4a-b
+
+electronic_stack:
+ allow_legacy_benchmark_deck: true
+ intervals_per_layer: [14, 36, 14]
+ device:
+ schema_version: solarlab.device-preparation.v1
+ id: bt2023_blocking_stack
+ name: Bitton & Tessler 2023 Sentaurus Stack
+ source_format: canonical
+ settings:
+ built_in_potential_mode: metal_work_function
+ V_bi: 0.0
+ work_function_left_eV: 4.44
+ work_function_right_eV: 5.76
+ flat_band_metal_contacts: true
+ contact_phi_B_eV: 0.14
+ dos_band_potentials: true
+ T: 300.0
+ Phi: 1.623603893899371e24
+ layers:
+ - id: hbl
+ name: HBL
+ role: ETL
+ thickness: 50.0e-9
+ parameters:
+ chi: 4.3
+ Eg: 2.5
+ Nc300: 1.0e27
+ Nv300: 1.0e27
+ eps_r: 3.0
+ N_D: 1.0
+ N_A: 0.0
+ ni: 1002130.379122778
+ n1: 1002130.379122778
+ p1: 1002130.379122778
+ tau_n: 1.0e6
+ tau_p: 1.0e6
+ B_rad: 1.206341838923508e-15
+ C_n: 0.0
+ C_p: 0.0
+ mu_n: 1.0e-7
+ mu_p: 1.0e-7
+ alpha: 0.0
+ A_star_n: 0.0
+ A_star_p: 0.0
+ D_ion: 0.0
+ P0: 0.0
+ P_lim: 1.0e28
+ - id: absorber
+ name: Perovskite
+ role: absorber
+ thickness: 500.0e-9
+ parameters:
+ chi: 4.3
+ Eg: 1.6
+ Nc300: 7.0e24
+ Nv300: 2.5e24
+ eps_r: 50.0
+ N_D: 0.0
+ N_A: 0.0
+ ni: 152093456592.39743
+ n1: 152093456592.39743
+ p1: 152093456592.39743
+ tau_n: 1.0e6
+ tau_p: 1.0e6
+ B_rad: 1.0e-16
+ C_n: 0.0
+ C_p: 0.0
+ mu_n: 2.0e-4
+ mu_p: 2.0e-4
+ alpha: 2000.0
+ A_star_n: 0.0
+ A_star_p: 0.0
+ D_ion: 0.0
+ P0: 0.0
+ P_lim: 1.0e28
+ - id: ebl
+ name: EBL
+ role: HTL
+ thickness: 50.0e-9
+ parameters:
+ chi: 3.4
+ Eg: 2.5
+ Nc300: 1.0e27
+ Nv300: 1.0e27
+ eps_r: 3.0
+ N_D: 0.0
+ N_A: 1.0
+ ni: 1002130.379122778
+ n1: 1002130.379122778
+ p1: 1002130.379122778
+ tau_n: 1.0e6
+ tau_p: 1.0e6
+ B_rad: 1.206341838923508e-15
+ C_n: 0.0
+ C_p: 0.0
+ mu_n: 1.0e-7
+ mu_p: 1.0e-7
+ alpha: 0.0
+ A_star_n: 0.0
+ A_star_p: 0.0
+ D_ion: 0.0
+ P0: 0.0
+ P_lim: 1.0e28
+
+chemistry:
+ domain_mode: absorber_blocking
+ thermodynamic_mode: wegscheider_detailed_balance
+ reaction_e_order: bimolecular_n
+ initialize_equilibrium_split: false
+ enforce_spatial_wegscheider: true
+ layers:
+ - layer_id: absorber
+ units: cgs
+ D_minus: 1.0e-9
+ D_atom: 1.0e-9
+ D_mol: 1.0e-9
+ initial_iodide: 1.0e18
+ rate_mode: explicit_rates
+ k_a: 1.0e-11
+ k_b: 1.0e-3
+ k_c: 5.0e-11
+ k_d: 3.0e-16
+ k_e: 3.0e-16
+ K_diss: 1.0e8
+ n_e_star: 1.0e8
+
+steady:
+ voltage_V: 0.9
+ generation_scale: 1.0
+ compute_frozen_jv: true
+ jv_v_min_V: 0.0
+ jv_v_max_V: 1.25
+ jv_n_points: 26
+
+impedance:
+ voltage_V: 0.9
+ generation_scale: 1.0
+ f_min_Hz: 1.0e-2
+ f_max_Hz: 1.0e6
+ n_frequencies: 25
+ chem_mode: both
+
+aging:
+ stages:
+ - name: light_stress_0p9V
+ duration_s: 120.0
+ voltage_V: 0.9
+ generation_scale: 1.0
+ max_step_s: 20.0
+ checkpoint_times_s: [0.0, 30.0, 120.0]
+ probe:
+ mode: frozen_chemistry_jv
+ v_min_V: 0.0
+ v_max_V: 1.25
+ n_points: 26
+ scan_rate_V_s: 1.0
+ generation_scale: 1.0
+ incident_power_W_m2: 1000.0
diff --git a/src/solarlab/materials/data/iodine_presets/bitton_tessler_2023_outgassing.yaml b/src/solarlab/materials/data/iodine_presets/bitton_tessler_2023_outgassing.yaml
new file mode 100644
index 00000000..257f6f6d
--- /dev/null
+++ b/src/solarlab/materials/data/iodine_presets/bitton_tessler_2023_outgassing.yaml
@@ -0,0 +1,190 @@
+schema_version: solarlab.iodine-deck.v1
+id: bitton_tessler_2023_outgassing
+name: Bitton & Tessler (2023) EBL Volatile I2 Outgassing
+description: >-
+ Open-boundary full-stack deck with online volumetric EBL I2 escape
+ (volumetric_mol_escape_s_1 = 1e-3 s^-1, k_a = 5e-11 cm^3/s) capturing
+ multi-thousand-hour mobile iodide depletion curvature.
+reference: Bitton & Tessler, Energy Environ. Sci. 16, 2621-2628 (2023), Fig. 5b
+
+electronic_stack:
+ allow_legacy_benchmark_deck: true
+ intervals_per_layer: [14, 36, 14]
+ device:
+ schema_version: solarlab.device-preparation.v1
+ id: bt2023_outgassing_stack
+ name: Bitton & Tessler 2023 Volatile Outgassing Stack
+ source_format: canonical
+ settings:
+ built_in_potential_mode: metal_work_function
+ V_bi: 0.0
+ work_function_left_eV: 4.44
+ work_function_right_eV: 5.76
+ flat_band_metal_contacts: true
+ contact_phi_B_eV: 0.14
+ dos_band_potentials: true
+ T: 300.0
+ Phi: 1.623603893899371e24
+ layers:
+ - id: hbl
+ name: HBL
+ role: ETL
+ thickness: 50.0e-9
+ parameters:
+ chi: 4.3
+ Eg: 2.5
+ Nc300: 1.0e27
+ Nv300: 1.0e27
+ eps_r: 3.0
+ N_D: 1.0
+ N_A: 0.0
+ ni: 1002130.379122778
+ n1: 1002130.379122778
+ p1: 1002130.379122778
+ tau_n: 1.0e6
+ tau_p: 1.0e6
+ B_rad: 1.206341838923508e-15
+ C_n: 0.0
+ C_p: 0.0
+ mu_n: 1.0e-7
+ mu_p: 1.0e-7
+ alpha: 0.0
+ A_star_n: 0.0
+ A_star_p: 0.0
+ D_ion: 0.0
+ P0: 0.0
+ P_lim: 1.0e28
+ - id: absorber
+ name: Perovskite
+ role: absorber
+ thickness: 500.0e-9
+ parameters:
+ chi: 4.3
+ Eg: 1.6
+ Nc300: 7.0e24
+ Nv300: 2.5e24
+ eps_r: 50.0
+ N_D: 0.0
+ N_A: 0.0
+ ni: 152093456592.39743
+ n1: 152093456592.39743
+ p1: 152093456592.39743
+ tau_n: 1.0e6
+ tau_p: 1.0e6
+ B_rad: 1.0e-16
+ C_n: 0.0
+ C_p: 0.0
+ mu_n: 2.0e-4
+ mu_p: 2.0e-4
+ alpha: 2000.0
+ A_star_n: 0.0
+ A_star_p: 0.0
+ D_ion: 0.0
+ P0: 0.0
+ P_lim: 1.0e28
+ - id: ebl
+ name: EBL
+ role: HTL
+ thickness: 50.0e-9
+ parameters:
+ chi: 3.4
+ Eg: 2.5
+ Nc300: 1.0e27
+ Nv300: 1.0e27
+ eps_r: 3.0
+ N_D: 0.0
+ N_A: 1.0
+ ni: 1002130.379122778
+ n1: 1002130.379122778
+ p1: 1002130.379122778
+ tau_n: 1.0e6
+ tau_p: 1.0e6
+ B_rad: 1.206341838923508e-15
+ C_n: 0.0
+ C_p: 0.0
+ mu_n: 1.0e-7
+ mu_p: 1.0e-7
+ alpha: 0.0
+ A_star_n: 0.0
+ A_star_p: 0.0
+ D_ion: 0.0
+ P0: 0.0
+ P_lim: 1.0e28
+
+chemistry:
+ domain_mode: full_stack_permeable
+ thermodynamic_mode: wegscheider_detailed_balance
+ reaction_e_order: bimolecular_n
+ initialize_equilibrium_split: false
+ enforce_spatial_wegscheider: true
+ layers:
+ - layer_id: hbl
+ units: cgs
+ D_minus: 1.0e-8
+ D_atom: 1.0e-8
+ D_mol: 1.0e-8
+ initial_iodide: 0.0
+ rate_mode: smoluchowski_capture_radius
+ capture_radius_nm: 0.2
+ k_b: 1.0e-6
+ K_diss: 1.0e8
+ n_e_star: 1.0e8
+ - layer_id: absorber
+ units: cgs
+ D_minus: 1.0e-9
+ D_atom: 1.0e-9
+ D_mol: 1.0e-9
+ initial_iodide: 1.0e18
+ rate_mode: explicit_rates
+ k_a: 5.0e-11
+ k_b: 1.0e-3
+ k_c: 5.0e-11
+ k_d: 3.0e-16
+ k_e: 3.0e-16
+ K_diss: 1.0e8
+ n_e_star: 1.0e8
+ - layer_id: ebl
+ units: cgs
+ D_minus: 1.0e-8
+ D_atom: 1.0e-8
+ D_mol: 1.0e-8
+ initial_iodide: 0.0
+ rate_mode: smoluchowski_capture_radius
+ capture_radius_nm: 0.2
+ k_b: 1.0e-6
+ K_diss: 1.0e8
+ n_e_star: 1.0e8
+ volumetric_mol_escape_s_1: 1.0e-3
+
+steady:
+ voltage_V: 0.9
+ generation_scale: 1.0
+ compute_frozen_jv: false
+ jv_v_min_V: 0.0
+ jv_v_max_V: 1.25
+ jv_n_points: 26
+
+impedance:
+ voltage_V: 0.9
+ generation_scale: 1.0
+ f_min_Hz: 1.0e-2
+ f_max_Hz: 1.0e6
+ n_frequencies: 25
+ chem_mode: both
+
+aging:
+ stages:
+ - name: outgassing_1000h_stress
+ duration_s: 3600000.0
+ voltage_V: 0.9
+ generation_scale: 1.0
+ max_step_s: 200000.0
+ checkpoint_times_s: [0.0, 360000.0, 1800000.0, 3600000.0]
+ probe:
+ mode: none
+ v_min_V: 0.0
+ v_max_V: 1.25
+ n_points: 26
+ scan_rate_V_s: 1.0
+ generation_scale: 1.0
+ incident_power_W_m2: 1000.0
diff --git a/src/solarlab/materials/data/iodine_presets/bitton_tessler_2023_permeable.yaml b/src/solarlab/materials/data/iodine_presets/bitton_tessler_2023_permeable.yaml
new file mode 100644
index 00000000..e97e3c6d
--- /dev/null
+++ b/src/solarlab/materials/data/iodine_presets/bitton_tessler_2023_permeable.yaml
@@ -0,0 +1,189 @@
+schema_version: solarlab.iodine-deck.v1
+id: bitton_tessler_2023_permeable
+name: Bitton & Tessler (2023) Permeable Full Stack
+description: >-
+ Full-stack permeable HBL/Perovskite/EBL iodine reaction-diffusion deck
+ allowing I-, I0, and I2 penetration into both charge transport layers
+ (D_BL = 1e-8 cm^2/s, D_PVK = 1e-9 cm^2/s, k_a = 1e-11 cm^3/s).
+reference: Bitton & Tessler, Energy Environ. Sci. 16, 2621-2628 (2023), Fig. 4c-d & Fig. S2
+
+electronic_stack:
+ allow_legacy_benchmark_deck: true
+ intervals_per_layer: [14, 36, 14]
+ device:
+ schema_version: solarlab.device-preparation.v1
+ id: bt2023_permeable_stack
+ name: Bitton & Tessler 2023 Permeable Stack
+ source_format: canonical
+ settings:
+ built_in_potential_mode: metal_work_function
+ V_bi: 0.0
+ work_function_left_eV: 4.44
+ work_function_right_eV: 5.76
+ flat_band_metal_contacts: true
+ contact_phi_B_eV: 0.14
+ dos_band_potentials: true
+ T: 300.0
+ Phi: 1.623603893899371e24
+ layers:
+ - id: hbl
+ name: HBL
+ role: ETL
+ thickness: 50.0e-9
+ parameters:
+ chi: 4.3
+ Eg: 2.5
+ Nc300: 1.0e27
+ Nv300: 1.0e27
+ eps_r: 3.0
+ N_D: 1.0
+ N_A: 0.0
+ ni: 1002130.379122778
+ n1: 1002130.379122778
+ p1: 1002130.379122778
+ tau_n: 1.0e6
+ tau_p: 1.0e6
+ B_rad: 1.206341838923508e-15
+ C_n: 0.0
+ C_p: 0.0
+ mu_n: 1.0e-7
+ mu_p: 1.0e-7
+ alpha: 0.0
+ A_star_n: 0.0
+ A_star_p: 0.0
+ D_ion: 0.0
+ P0: 0.0
+ P_lim: 1.0e28
+ - id: absorber
+ name: Perovskite
+ role: absorber
+ thickness: 500.0e-9
+ parameters:
+ chi: 4.3
+ Eg: 1.6
+ Nc300: 7.0e24
+ Nv300: 2.5e24
+ eps_r: 50.0
+ N_D: 0.0
+ N_A: 0.0
+ ni: 152093456592.39743
+ n1: 152093456592.39743
+ p1: 152093456592.39743
+ tau_n: 1.0e6
+ tau_p: 1.0e6
+ B_rad: 1.0e-16
+ C_n: 0.0
+ C_p: 0.0
+ mu_n: 2.0e-4
+ mu_p: 2.0e-4
+ alpha: 2000.0
+ A_star_n: 0.0
+ A_star_p: 0.0
+ D_ion: 0.0
+ P0: 0.0
+ P_lim: 1.0e28
+ - id: ebl
+ name: EBL
+ role: HTL
+ thickness: 50.0e-9
+ parameters:
+ chi: 3.4
+ Eg: 2.5
+ Nc300: 1.0e27
+ Nv300: 1.0e27
+ eps_r: 3.0
+ N_D: 0.0
+ N_A: 1.0
+ ni: 1002130.379122778
+ n1: 1002130.379122778
+ p1: 1002130.379122778
+ tau_n: 1.0e6
+ tau_p: 1.0e6
+ B_rad: 1.206341838923508e-15
+ C_n: 0.0
+ C_p: 0.0
+ mu_n: 1.0e-7
+ mu_p: 1.0e-7
+ alpha: 0.0
+ A_star_n: 0.0
+ A_star_p: 0.0
+ D_ion: 0.0
+ P0: 0.0
+ P_lim: 1.0e28
+
+chemistry:
+ domain_mode: full_stack_permeable
+ thermodynamic_mode: wegscheider_detailed_balance
+ reaction_e_order: bimolecular_n
+ initialize_equilibrium_split: false
+ enforce_spatial_wegscheider: true
+ layers:
+ - layer_id: hbl
+ units: cgs
+ D_minus: 1.0e-8
+ D_atom: 1.0e-8
+ D_mol: 1.0e-8
+ initial_iodide: 0.0
+ rate_mode: smoluchowski_capture_radius
+ capture_radius_nm: 0.2
+ k_b: 1.0e-6
+ K_diss: 1.0e8
+ n_e_star: 1.0e8
+ - layer_id: absorber
+ units: cgs
+ D_minus: 1.0e-9
+ D_atom: 1.0e-9
+ D_mol: 1.0e-9
+ initial_iodide: 1.0e18
+ rate_mode: explicit_rates
+ k_a: 1.0e-11
+ k_b: 1.0e-3
+ k_c: 5.0e-11
+ k_d: 3.0e-16
+ k_e: 3.0e-16
+ K_diss: 1.0e8
+ n_e_star: 1.0e8
+ - layer_id: ebl
+ units: cgs
+ D_minus: 1.0e-8
+ D_atom: 1.0e-8
+ D_mol: 1.0e-8
+ initial_iodide: 0.0
+ rate_mode: smoluchowski_capture_radius
+ capture_radius_nm: 0.2
+ k_b: 1.0e-6
+ K_diss: 1.0e8
+ n_e_star: 1.0e8
+
+steady:
+ voltage_V: 0.9
+ generation_scale: 1.0
+ compute_frozen_jv: true
+ jv_v_min_V: 0.0
+ jv_v_max_V: 1.25
+ jv_n_points: 26
+
+impedance:
+ voltage_V: 0.9
+ generation_scale: 1.0
+ f_min_Hz: 1.0e-2
+ f_max_Hz: 1.0e6
+ n_frequencies: 25
+ chem_mode: both
+
+aging:
+ stages:
+ - name: permeable_light_stress
+ duration_s: 300.0
+ voltage_V: 0.9
+ generation_scale: 1.0
+ max_step_s: 50.0
+ checkpoint_times_s: [0.0, 60.0, 300.0]
+ probe:
+ mode: frozen_chemistry_jv
+ v_min_V: 0.0
+ v_max_V: 1.25
+ n_points: 26
+ scan_rate_V_s: 1.0
+ generation_scale: 1.0
+ incident_power_W_m2: 1000.0
diff --git a/src/solarlab/materials/data/iodine_presets/bitton_tessler_2023_self_healing.yaml b/src/solarlab/materials/data/iodine_presets/bitton_tessler_2023_self_healing.yaml
new file mode 100644
index 00000000..7745c509
--- /dev/null
+++ b/src/solarlab/materials/data/iodine_presets/bitton_tessler_2023_self_healing.yaml
@@ -0,0 +1,172 @@
+schema_version: solarlab.iodine-deck.v1
+id: bitton_tessler_2023_self_healing
+name: Bitton & Tessler (2023) Light Stress & Dark Self-Healing
+description: >-
+ Two-stage closed-system protocol combining 1 Sun / 0.9 V forward-bias light
+ stress (oxidizing I- into neutral I0/I2 recombination centers) followed by
+ dark 0 V resting recovery demonstrating reversible PV metric self-healing.
+reference: Bitton & Tessler, Energy Environ. Sci. 16, 2621-2628 (2023), Table 1 & Fig. S2c
+
+electronic_stack:
+ allow_legacy_benchmark_deck: true
+ intervals_per_layer: [14, 36, 14]
+ device:
+ schema_version: solarlab.device-preparation.v1
+ id: bt2023_self_healing_stack
+ name: Bitton & Tessler 2023 Self-Healing Stack
+ source_format: canonical
+ settings:
+ built_in_potential_mode: metal_work_function
+ V_bi: 0.0
+ work_function_left_eV: 4.44
+ work_function_right_eV: 5.76
+ flat_band_metal_contacts: true
+ contact_phi_B_eV: 0.14
+ dos_band_potentials: true
+ T: 300.0
+ Phi: 1.623603893899371e24
+ layers:
+ - id: hbl
+ name: HBL
+ role: ETL
+ thickness: 50.0e-9
+ parameters:
+ chi: 4.3
+ Eg: 2.5
+ Nc300: 1.0e27
+ Nv300: 1.0e27
+ eps_r: 3.0
+ N_D: 1.0
+ N_A: 0.0
+ ni: 1002130.379122778
+ n1: 1002130.379122778
+ p1: 1002130.379122778
+ tau_n: 1.0e6
+ tau_p: 1.0e6
+ B_rad: 1.206341838923508e-15
+ C_n: 0.0
+ C_p: 0.0
+ mu_n: 1.0e-7
+ mu_p: 1.0e-7
+ alpha: 0.0
+ A_star_n: 0.0
+ A_star_p: 0.0
+ D_ion: 0.0
+ P0: 0.0
+ P_lim: 1.0e28
+ - id: absorber
+ name: Perovskite
+ role: absorber
+ thickness: 500.0e-9
+ parameters:
+ chi: 4.3
+ Eg: 1.6
+ Nc300: 7.0e24
+ Nv300: 2.5e24
+ eps_r: 50.0
+ N_D: 0.0
+ N_A: 0.0
+ ni: 152093456592.39743
+ n1: 152093456592.39743
+ p1: 152093456592.39743
+ tau_n: 1.0e6
+ tau_p: 1.0e6
+ B_rad: 1.0e-16
+ C_n: 0.0
+ C_p: 0.0
+ mu_n: 2.0e-4
+ mu_p: 2.0e-4
+ alpha: 2000.0
+ A_star_n: 0.0
+ A_star_p: 0.0
+ D_ion: 0.0
+ P0: 0.0
+ P_lim: 1.0e28
+ - id: ebl
+ name: EBL
+ role: HTL
+ thickness: 50.0e-9
+ parameters:
+ chi: 3.4
+ Eg: 2.5
+ Nc300: 1.0e27
+ Nv300: 1.0e27
+ eps_r: 3.0
+ N_D: 0.0
+ N_A: 1.0
+ ni: 1002130.379122778
+ n1: 1002130.379122778
+ p1: 1002130.379122778
+ tau_n: 1.0e6
+ tau_p: 1.0e6
+ B_rad: 1.206341838923508e-15
+ C_n: 0.0
+ C_p: 0.0
+ mu_n: 1.0e-7
+ mu_p: 1.0e-7
+ alpha: 0.0
+ A_star_n: 0.0
+ A_star_p: 0.0
+ D_ion: 0.0
+ P0: 0.0
+ P_lim: 1.0e28
+
+chemistry:
+ domain_mode: absorber_blocking
+ thermodynamic_mode: wegscheider_detailed_balance
+ reaction_e_order: bimolecular_n
+ initialize_equilibrium_split: false
+ enforce_spatial_wegscheider: true
+ layers:
+ - layer_id: absorber
+ units: cgs
+ D_minus: 1.0e-9
+ D_atom: 1.0e-9
+ D_mol: 1.0e-9
+ initial_iodide: 1.0e18
+ rate_mode: explicit_rates
+ k_a: 1.0e-11
+ k_b: 1.0e-3
+ k_c: 5.0e-11
+ k_d: 3.0e-16
+ k_e: 3.0e-16
+ K_diss: 1.0e8
+ n_e_star: 1.0e8
+
+steady:
+ voltage_V: 0.9
+ generation_scale: 1.0
+ compute_frozen_jv: true
+ jv_v_min_V: 0.0
+ jv_v_max_V: 1.25
+ jv_n_points: 26
+
+impedance:
+ voltage_V: 0.9
+ generation_scale: 1.0
+ f_min_Hz: 1.0e-2
+ f_max_Hz: 1.0e6
+ n_frequencies: 25
+ chem_mode: both
+
+aging:
+ stages:
+ - name: light_stress_0p9V
+ duration_s: 300.0
+ voltage_V: 0.9
+ generation_scale: 1.0
+ max_step_s: 50.0
+ - name: dark_self_healing_0V
+ duration_s: 1800.0
+ voltage_V: 0.0
+ generation_scale: 0.0
+ max_step_s: 200.0
+ checkpoint_times_s: [0.0, 300.0, 900.0, 2100.0]
+ probe:
+ mode: frozen_chemistry_jv
+ v_min_V: 0.0
+ v_max_V: 1.25
+ n_points: 26
+ scan_rate_V_s: 1.0
+ generation_scale: 1.0
+ incident_power_W_m2: 1000.0
diff --git a/src/solarlab/materials/iodine_presets.py b/src/solarlab/materials/iodine_presets.py
new file mode 100644
index 00000000..444b8fb5
--- /dev/null
+++ b/src/solarlab/materials/iodine_presets.py
@@ -0,0 +1,113 @@
+"""Packaged immutable YAML presets for 1D iodine chemistry & aging studies.
+
+Reads exclusively from ``importlib.resources`` under
+``solarlab.materials.data.iodine_presets`` without importing higher
+configuration, device, physics, or experiment packages.
+"""
+
+from __future__ import annotations
+
+from importlib import resources
+from typing import Any
+
+import yaml
+
+from solarlab.materials.source import SourceDocument
+
+__all__ = [
+ "PACKAGED_IODINE_PRESET_NAMES",
+ "list_packaged_iodine_preset_summaries",
+ "load_packaged_iodine_preset_bytes",
+ "load_packaged_iodine_preset_mapping",
+ "load_packaged_iodine_preset_source",
+]
+
+_IODINE_PRESET_PACKAGE = "solarlab.materials.data.iodine_presets"
+
+PACKAGED_IODINE_PRESET_NAMES: tuple[str, ...] = (
+ "bitton_tessler_2023_blocking",
+ "bitton_tessler_2023_permeable",
+ "bitton_tessler_2023_outgassing",
+ "bitton_tessler_2023_ag_corrosion",
+ "bitton_tessler_2023_self_healing",
+)
+
+
+class _UniqueKeyYamlLoader(yaml.SafeLoader):
+ """YAML SafeLoader rejecting duplicate mapping keys."""
+
+
+def _construct_unique_mapping(
+ loader: _UniqueKeyYamlLoader, node: yaml.MappingNode
+) -> dict[str, Any]:
+ mapping: dict[str, Any] = {}
+ for key_node, value_node in node.value:
+ key = loader.construct_object(key_node, deep=True)
+ if not isinstance(key, str) or key in mapping:
+ raise ValueError("packaged iodine YAML mapping keys must be unique strings")
+ mapping[key] = loader.construct_object(value_node, deep=True)
+ return mapping
+
+
+_UniqueKeyYamlLoader.add_constructor(
+ "tag:yaml.org,2002:map", _construct_unique_mapping
+)
+
+
+def _normalize_preset_stem(name: str) -> str:
+ stem = name.strip().removesuffix(".yaml").removesuffix(".yml")
+ if stem not in PACKAGED_IODINE_PRESET_NAMES:
+ raise KeyError(
+ f"unknown packaged iodine preset {name!r}; "
+ f"available: {list(PACKAGED_IODINE_PRESET_NAMES)}"
+ )
+ return stem
+
+
+def load_packaged_iodine_preset_bytes(name: str) -> bytes:
+ """Return raw UTF-8 YAML bytes for a packaged iodine deck preset."""
+ stem = _normalize_preset_stem(name)
+ filename = f"{stem}.yaml"
+ node = resources.files(_IODINE_PRESET_PACKAGE).joinpath(filename)
+ if not node.is_file():
+ raise FileNotFoundError(f"missing packaged iodine preset asset: {filename}")
+ return node.read_bytes()
+
+
+def load_packaged_iodine_preset_source(name: str) -> SourceDocument:
+ """Return a checksummed ``SourceDocument`` for a packaged iodine preset."""
+ stem = _normalize_preset_stem(name)
+ raw = load_packaged_iodine_preset_bytes(stem)
+ return SourceDocument(
+ f"solarlab/materials/data/iodine_presets/{stem}.yaml",
+ raw,
+ )
+
+
+def load_packaged_iodine_preset_mapping(name: str) -> dict[str, Any]:
+ """Parse and return a packaged iodine preset YAML document as a dict."""
+ raw = load_packaged_iodine_preset_bytes(name)
+ doc = yaml.load(raw.decode("utf-8"), Loader=_UniqueKeyYamlLoader)
+ if not isinstance(doc, dict):
+ raise ValueError(f"packaged iodine preset {name!r} must decode to a mapping")
+ return doc
+
+
+def list_packaged_iodine_preset_summaries() -> list[dict[str, Any]]:
+ """Return metadata summaries and parsed decks for all packaged iodine presets."""
+ items: list[dict[str, Any]] = []
+ for stem in PACKAGED_IODINE_PRESET_NAMES:
+ source = load_packaged_iodine_preset_source(stem)
+ doc = load_packaged_iodine_preset_mapping(stem)
+ items.append(
+ {
+ "id": stem,
+ "name": str(doc.get("name", stem)),
+ "description": str(doc.get("description", "")),
+ "reference": str(doc.get("reference", "")),
+ "source_id": source.id,
+ "sha256": source.sha256,
+ "deck": doc,
+ }
+ )
+ return items
diff --git a/src/solarlab/physics/chemistry/__init__.py b/src/solarlab/physics/chemistry/__init__.py
new file mode 100644
index 00000000..fc48b66d
--- /dev/null
+++ b/src/solarlab/physics/chemistry/__init__.py
@@ -0,0 +1,57 @@
+"""Constitutive iodine reaction-diffusion physics kernels (SI units)."""
+
+from __future__ import annotations
+
+from solarlab.physics.chemistry.iodine_kinetics import (
+ IODINE_KINETICS_SCHEMA,
+ IodineKineticsParameters,
+ IodineReactionEvaluation,
+ IodineThermodynamicMode,
+ ReactionEOrder,
+ equilibrium_iodine_populations_m3,
+ evaluate_iodine_kinetics,
+ smoluchowski_rate_m3_s,
+)
+from solarlab.physics.chemistry.iodine_transport import (
+ BoundedSpeciesMap,
+ IODINE_TRANSPORT_SCHEMA,
+ PositiveSpeciesMap,
+ SoftplusSpeciesMap,
+ SpeciesCoordinateMap,
+ SpeciesFaceFluxEvaluation,
+ harmonic_face_diffusivity_m2_s,
+ species_sg_face_flux,
+)
+from solarlab.physics.chemistry.stoichiometry import (
+ CANONICAL_IODINE_NETWORK,
+ IODINE_REACTIONS,
+ IODINE_SPECIES,
+ STOICHIOMETRY_SCHEMA,
+ StoichiometricNetwork,
+ canonical_iodine_network,
+)
+
+__all__ = [
+ "BoundedSpeciesMap",
+ "CANONICAL_IODINE_NETWORK",
+ "IODINE_KINETICS_SCHEMA",
+ "IODINE_REACTIONS",
+ "IODINE_SPECIES",
+ "IODINE_TRANSPORT_SCHEMA",
+ "IodineKineticsParameters",
+ "IodineReactionEvaluation",
+ "IodineThermodynamicMode",
+ "PositiveSpeciesMap",
+ "ReactionEOrder",
+ "STOICHIOMETRY_SCHEMA",
+ "SoftplusSpeciesMap",
+ "SpeciesCoordinateMap",
+ "SpeciesFaceFluxEvaluation",
+ "StoichiometricNetwork",
+ "canonical_iodine_network",
+ "equilibrium_iodine_populations_m3",
+ "evaluate_iodine_kinetics",
+ "harmonic_face_diffusivity_m2_s",
+ "smoluchowski_rate_m3_s",
+ "species_sg_face_flux",
+]
diff --git a/src/solarlab/physics/chemistry/iodine_kinetics.py b/src/solarlab/physics/chemistry/iodine_kinetics.py
new file mode 100644
index 00000000..e3fca32d
--- /dev/null
+++ b/src/solarlab/physics/chemistry/iodine_kinetics.py
@@ -0,0 +1,391 @@
+"""Constitutive kinetics, Wegscheider detailed balance, and exact derivatives.
+
+Implements the five iodine reaction channels of Bitton & Tessler (Energy &
+Environmental Science, 16, 2621-2628, 2023, SI Table S1 & Eqs. 3-4) in strict
+SI units (m, s, m^-3) with both Wegscheider cyclic detailed balance (default)
+and irreversible mass-action closures, plus exact analytical state Jacobians.
+"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass
+from hashlib import sha256
+import json
+import math
+from typing import Literal, get_args
+
+import numpy as np
+from numpy.typing import ArrayLike, NDArray
+
+from solarlab.contracts import ContractError, Vector, frozen_array
+from solarlab.physics.chemistry.stoichiometry import (
+ CANONICAL_IODINE_NETWORK,
+ StoichiometricNetwork,
+)
+
+__all__ = [
+ "IODINE_KINETICS_SCHEMA",
+ "IodineKineticsParameters",
+ "IodineReactionEvaluation",
+ "IodineThermodynamicMode",
+ "ReactionEOrder",
+ "equilibrium_iodine_populations_m3",
+ "evaluate_iodine_kinetics",
+ "smoluchowski_rate_m3_s",
+]
+
+IODINE_KINETICS_SCHEMA = "solarlab.iodine_kinetics.v1"
+
+IodineThermodynamicMode = Literal[
+ "wegscheider_detailed_balance",
+ "irreversible_mass_action",
+]
+ReactionEOrder = Literal["bimolecular_n", "termolecular_n2"]
+
+_THERMODYNAMIC_MODES: frozenset[str] = frozenset(get_args(IodineThermodynamicMode))
+_REACTION_E_ORDERS: frozenset[str] = frozenset(get_args(ReactionEOrder))
+
+
+def _vector(values: ArrayLike, size: int, name: str) -> Vector:
+ arr = np.asarray(values, dtype=np.float64)
+ if arr.ndim == 0:
+ arr = np.full(size, float(arr), dtype=np.float64)
+ if arr.shape != (size,) or not np.all(np.isfinite(arr)):
+ raise ContractError(f"{name}_must_be_finite_1d_vector_of_length_{size}")
+ return frozen_array(arr)
+
+
+def smoluchowski_rate_m3_s(
+ diffusivity_a_m2_s: ArrayLike,
+ diffusivity_b_m2_s: ArrayLike,
+ capture_radius_m: float,
+) -> Vector:
+ """Diffusion-limited bimolecular rate ``4 * pi * (D_A + D_B) * R_AB`` [m^3/s].
+
+ For homodimerization ``2 I^0 -> I_2`` pass ``D_A = D_0`` and ``D_B = D_0``
+ so ``D_A + D_B = 2 D_0``, matching Bitton & Tessler SI Table S1.
+ """
+ radius = float(capture_radius_m)
+ if not math.isfinite(radius) or radius < 0.0:
+ raise ContractError("capture_radius_m_must_be_finite_nonnegative")
+ da = np.asarray(diffusivity_a_m2_s, dtype=np.float64)
+ db = np.asarray(diffusivity_b_m2_s, dtype=np.float64)
+ if not (np.all(np.isfinite(da)) and np.all(np.isfinite(db))):
+ raise ContractError("diffusivities_must_be_finite")
+ if np.any(da < 0.0) or np.any(db < 0.0):
+ raise ContractError("diffusivities_must_be_nonnegative")
+ rate = 4.0 * math.pi * (da + db) * radius
+ return frozen_array(np.atleast_1d(np.asarray(rate, dtype=np.float64)))
+
+
+@dataclass(frozen=True, slots=True)
+class IodineKineticsParameters:
+ """Node-aligned SI kinetic arrays on the chemical NodeSet (size ``M``)."""
+
+ k_a_m3_s: Vector
+ k_b_s_1: Vector
+ k_c_m3_s: Vector
+ k_d_m3_s: Vector
+ k_e_m3_s: Vector
+ n_i_sq_m6: Vector
+ K_diss_m3: Vector
+ n_e_star_m3: Vector
+ k_e_3body_m6_s: Vector | None = None
+ n_1_iodine_m3: Vector | None = None
+ thermodynamic_mode: IodineThermodynamicMode = "wegscheider_detailed_balance"
+ reaction_e_order: ReactionEOrder = "bimolecular_n"
+ network: StoichiometricNetwork = CANONICAL_IODINE_NETWORK
+
+ def __post_init__(self) -> None:
+ if self.thermodynamic_mode not in _THERMODYNAMIC_MODES:
+ raise ContractError("unknown_iodine_thermodynamic_mode")
+ if self.reaction_e_order not in _REACTION_E_ORDERS:
+ raise ContractError("unknown_reaction_e_order")
+ raw_ka = np.atleast_1d(np.asarray(self.k_a_m3_s, dtype=np.float64))
+ if raw_ka.ndim != 1 or raw_ka.size < 1:
+ raise ContractError("k_a_m3_s_must_be_nonempty_1d_vector")
+ size = int(raw_ka.size)
+
+ k_a = _vector(self.k_a_m3_s, size, "k_a_m3_s")
+ k_b = _vector(self.k_b_s_1, size, "k_b_s_1")
+ k_c = _vector(self.k_c_m3_s, size, "k_c_m3_s")
+ k_d = _vector(self.k_d_m3_s, size, "k_d_m3_s")
+ k_e = _vector(self.k_e_m3_s, size, "k_e_m3_s")
+ n_i_sq = _vector(self.n_i_sq_m6, size, "n_i_sq_m6")
+ k_diss = _vector(self.K_diss_m3, size, "K_diss_m3")
+ n_star = _vector(self.n_e_star_m3, size, "n_e_star_m3")
+ k_e_3 = (
+ _vector(0.0, size, "k_e_3body_m6_s")
+ if self.k_e_3body_m6_s is None
+ else _vector(self.k_e_3body_m6_s, size, "k_e_3body_m6_s")
+ )
+
+ for label, arr in (
+ ("k_a_m3_s", k_a),
+ ("k_b_s_1", k_b),
+ ("k_c_m3_s", k_c),
+ ("k_d_m3_s", k_d),
+ ("k_e_m3_s", k_e),
+ ("k_e_3body_m6_s", k_e_3),
+ ):
+ if np.any(arr < 0.0):
+ raise ContractError(f"{label}_must_be_nonnegative")
+ if np.any(n_i_sq <= 0.0):
+ raise ContractError("n_i_sq_m6_must_be_strictly_positive")
+ if np.any(k_diss <= 0.0):
+ raise ContractError("K_diss_m3_must_be_strictly_positive")
+
+ if self.thermodynamic_mode == "wegscheider_detailed_balance":
+ if (
+ self.reaction_e_order == "bimolecular_n"
+ and np.any((k_e > 0.0) & (n_star <= 0.0))
+ ):
+ raise ContractError("wegscheider_bimolecular_e_requires_positive_n_e_star")
+ if self.n_1_iodine_m3 is None:
+ if np.any((k_a > 0.0) & (k_b <= 0.0)):
+ raise ContractError(
+ "wegscheider_detailed_balance_requires_positive_k_b_where_k_a_positive"
+ )
+ with np.errstate(divide="ignore", invalid="ignore"):
+ derived_n1 = np.where(k_b > 0.0, (k_a * n_i_sq) / k_b, 0.0)
+ if not np.all(np.isfinite(derived_n1)):
+ raise ContractError("nonfinite_derived_n_1_iodine_m3")
+ n_1 = frozen_array(derived_n1)
+ else:
+ n_1 = _vector(self.n_1_iodine_m3, size, "n_1_iodine_m3")
+ if np.any(n_1 < 0.0):
+ raise ContractError("n_1_iodine_m3_must_be_nonnegative")
+ else:
+ if np.any(n_star < 0.0):
+ raise ContractError("n_e_star_m3_must_be_nonnegative")
+ n_1 = (
+ _vector(0.0, size, "n_1_iodine_m3")
+ if self.n_1_iodine_m3 is None
+ else _vector(self.n_1_iodine_m3, size, "n_1_iodine_m3")
+ )
+
+ object.__setattr__(self, "k_a_m3_s", k_a)
+ object.__setattr__(self, "k_b_s_1", k_b)
+ object.__setattr__(self, "k_c_m3_s", k_c)
+ object.__setattr__(self, "k_d_m3_s", k_d)
+ object.__setattr__(self, "k_e_m3_s", k_e)
+ object.__setattr__(self, "k_e_3body_m6_s", k_e_3)
+ object.__setattr__(self, "n_i_sq_m6", n_i_sq)
+ object.__setattr__(self, "K_diss_m3", k_diss)
+ object.__setattr__(self, "n_e_star_m3", n_star)
+ object.__setattr__(self, "n_1_iodine_m3", n_1)
+
+ @property
+ def size(self) -> int:
+ return int(self.k_a_m3_s.size)
+
+ @property
+ def identity(self) -> str:
+ digest = sha256(IODINE_KINETICS_SCHEMA.encode())
+ digest.update(self.network.identity.encode())
+ digest.update(
+ json.dumps(
+ [self.thermodynamic_mode, self.reaction_e_order, self.size],
+ separators=(",", ":"),
+ ).encode()
+ )
+ assert self.k_e_3body_m6_s is not None and self.n_1_iodine_m3 is not None
+ for arr in (
+ self.k_a_m3_s,
+ self.k_b_s_1,
+ self.k_c_m3_s,
+ self.k_d_m3_s,
+ self.k_e_m3_s,
+ self.k_e_3body_m6_s,
+ self.n_i_sq_m6,
+ self.K_diss_m3,
+ self.n_e_star_m3,
+ self.n_1_iodine_m3,
+ ):
+ digest.update(np.ascontiguousarray(arr, dtype=np.float64).tobytes())
+ return digest.hexdigest()
+
+
+@dataclass(frozen=True, slots=True)
+class IodineReactionEvaluation:
+ """Evaluated reaction rates, projected species sources, and exact Jacobians."""
+
+ rates_m3_s: NDArray[np.float64]
+ sources_m3_s: NDArray[np.float64]
+ dsources_dstate: NDArray[np.float64] | None = None
+
+
+def evaluate_iodine_kinetics(
+ n_m3: ArrayLike,
+ p_m3: ArrayLike,
+ c_minus_m3: ArrayLike,
+ c_atom_m3: ArrayLike,
+ c_mol_m3: ArrayLike,
+ params: IodineKineticsParameters,
+ *,
+ derivatives: bool = True,
+) -> IodineReactionEvaluation:
+ """Evaluate all five iodine reactions, net sources, and exact partials.
+
+ State ordering in ``sources_m3_s`` (shape ``(5, M)``) and ``dsources_dstate``
+ (shape ``(5, 5, M)``) follows :data:`IODINE_SPECIES`:
+ ``(electron, hole, iodide, iodine_atom, iodine_molecule)``.
+ """
+ size = params.size
+ n = np.asarray(n_m3, dtype=np.float64)
+ p = np.asarray(p_m3, dtype=np.float64)
+ cm = np.asarray(c_minus_m3, dtype=np.float64)
+ c0 = np.asarray(c_atom_m3, dtype=np.float64)
+ c2 = np.asarray(c_mol_m3, dtype=np.float64)
+ for label, arr in (
+ ("n_m3", n),
+ ("p_m3", p),
+ ("c_minus_m3", cm),
+ ("c_atom_m3", c0),
+ ("c_mol_m3", c2),
+ ):
+ if arr.shape != (size,) or not np.all(np.isfinite(arr)) or np.any(arr < 0.0):
+ raise ContractError(f"{label}_must_be_finite_nonnegative_vector")
+
+ k_a = params.k_a_m3_s
+ k_b = params.k_b_s_1
+ k_c = params.k_c_m3_s
+ k_d = params.k_d_m3_s
+ k_e = params.k_e_m3_s
+ assert params.k_e_3body_m6_s is not None and params.n_1_iodine_m3 is not None
+ k_e3 = params.k_e_3body_m6_s
+ n1 = params.n_1_iodine_m3
+ k_diss = params.K_diss_m3
+ n_star = params.n_e_star_m3
+ reversible = params.thermodynamic_mode == "wegscheider_detailed_balance"
+
+ # R_a = k_a * c_- * p, R_b = k_b * c_0
+ r_a = k_a * cm * p
+ r_b = k_b * c0
+
+ # R_c and R_d
+ if reversible:
+ r_c = k_c * (c0 * n - n1 * cm)
+ r_d = k_d * (c0 * c0 - k_diss * c2)
+ alpha_e = (n1 * n1) / k_diss
+ else:
+ r_c = k_c * c0 * n
+ r_d = k_d * (c0 * c0)
+ alpha_e = np.zeros(size, dtype=np.float64)
+
+ # R_e
+ if params.reaction_e_order == "bimolecular_n":
+ if reversible:
+ denom = n + n_star
+ # Safe where k_e == 0 and n == n_star == 0.
+ safe_denom = np.where(denom > 0.0, denom, 1.0)
+ pref = np.where(k_e > 0.0, k_e / safe_denom, 0.0)
+ r_e = pref * (c2 * (n * n) - alpha_e * (cm * cm))
+ else:
+ r_e = k_e * c2 * n
+ else:
+ if reversible:
+ r_e = k_e3 * (c2 * (n * n) - alpha_e * (cm * cm))
+ else:
+ r_e = k_e3 * c2 * (n * n)
+
+ rates = np.stack((r_a, r_b, r_c, r_d, r_e), axis=0)
+ if not np.all(np.isfinite(rates)):
+ raise ContractError("nonfinite_iodine_reaction_rates")
+ sources = params.network.project_sources(rates)
+
+ if not derivatives:
+ return IodineReactionEvaluation(
+ rates_m3_s=frozen_array(rates),
+ sources_m3_s=frozen_array(sources),
+ dsources_dstate=None,
+ )
+
+ # Exact drates_dstate of shape (5 reactions, 5 state vars, M nodes)
+ dr: NDArray[np.float64] = np.zeros((5, 5, size), dtype=np.float64)
+
+ # dR_a / d(p, c_-)
+ dr[0, 1] = k_a * cm
+ dr[0, 2] = k_a * p
+
+ # dR_b / dc_0
+ dr[1, 3] = k_b
+
+ # dR_c / d(n, c_-, c_0)
+ dr[2, 0] = k_c * c0
+ if reversible:
+ dr[2, 2] = -k_c * n1
+ dr[2, 3] = k_c * n
+
+ # dR_d / d(c_0, c_2)
+ dr[3, 3] = 2.0 * k_d * c0
+ if reversible:
+ dr[3, 4] = -k_d * k_diss
+
+ # dR_e / d(n, c_-, c_2)
+ if params.reaction_e_order == "bimolecular_n":
+ if reversible:
+ denom = n + n_star
+ safe_denom = np.where(denom > 0.0, denom, 1.0)
+ inv_d = np.where(k_e > 0.0, 1.0 / safe_denom, 0.0)
+ # Cancellation-free positive form:
+ # d/dn [k_e (c2 n^2 - alpha cm^2)/(n + n*)]
+ # = k_e [c2 n (n + 2 n*) + alpha cm^2] / (n + n*)^2
+ dr[4, 0] = (
+ k_e
+ * (c2 * n * (n + 2.0 * n_star) + alpha_e * (cm * cm))
+ * (inv_d * inv_d)
+ )
+ dr[4, 2] = -2.0 * k_e * alpha_e * cm * inv_d
+ dr[4, 4] = k_e * (n * n) * inv_d
+ else:
+ dr[4, 0] = k_e * c2
+ dr[4, 4] = k_e * n
+ else:
+ dr[4, 0] = 2.0 * k_e3 * c2 * n
+ if reversible:
+ dr[4, 2] = -2.0 * k_e3 * alpha_e * cm
+ dr[4, 4] = k_e3 * (n * n)
+
+ nu_float = params.network.nu.astype(np.float64)
+ dsources = np.einsum("sr,rjm->sjm", nu_float, dr)
+ if not np.all(np.isfinite(dsources)):
+ raise ContractError("nonfinite_iodine_reaction_jacobian")
+
+ return IodineReactionEvaluation(
+ rates_m3_s=frozen_array(rates),
+ sources_m3_s=frozen_array(sources),
+ dsources_dstate=frozen_array(dsources),
+ )
+
+
+def equilibrium_iodine_populations_m3(
+ total_iodine_atoms_m3: ArrayLike,
+ n_eq_m3: ArrayLike,
+ params: IodineKineticsParameters,
+) -> tuple[Vector, Vector, Vector]:
+ """Solve exact local thermal equilibrium ``(c_-, c_0, c_2)`` conserving iodine.
+
+ Given local elemental iodine density ``c_tot = c_- + c_0 + 2 c_2 >= 0`` and
+ equilibrium electron density ``n_eq > 0`` (with ``n_eq * p_eq = n_i^2``),
+ detailed balance fixes ``c_0 = r_0 * c_-`` (``r_0 = n_1 / n_eq``) and
+ ``c_2 = (r_0^2 / K_diss) * c_-^2``. Solving the monotone quadratic
+ ``(2 r_0^2 / K_diss) c_-^2 + (1 + r_0) c_- - c_tot = 0`` via the
+ cancellation-free Citardauq root gives exact machine-precision equilibrium.
+ """
+ size = params.size
+ c_tot = _vector(total_iodine_atoms_m3, size, "total_iodine_atoms_m3")
+ n_eq = _vector(n_eq_m3, size, "n_eq_m3")
+ if np.any(c_tot < 0.0):
+ raise ContractError("total_iodine_atoms_m3_must_be_nonnegative")
+ if np.any(n_eq <= 0.0):
+ raise ContractError("n_eq_m3_must_be_strictly_positive")
+ assert params.n_1_iodine_m3 is not None
+ r0 = params.n_1_iodine_m3 / n_eq
+ quad_a = 2.0 * (r0 * r0) / params.K_diss_m3
+ lin_b = 1.0 + r0
+ disc = np.sqrt(lin_b * lin_b + 4.0 * quad_a * c_tot)
+ c_minus = (2.0 * c_tot) / (lin_b + disc)
+ c_atom = r0 * c_minus
+ c_mol = (c_atom * c_atom) / params.K_diss_m3
+ return frozen_array(c_minus), frozen_array(c_atom), frozen_array(c_mol)
diff --git a/src/solarlab/physics/chemistry/iodine_transport.py b/src/solarlab/physics/chemistry/iodine_transport.py
new file mode 100644
index 00000000..2a020f6a
--- /dev/null
+++ b/src/solarlab/physics/chemistry/iodine_transport.py
@@ -0,0 +1,525 @@
+"""Coordinate maps and exponential-fitted Scharfetter-Gummel face fluxes.
+
+Provides:
+1. :class:`PositiveSpeciesMap` -- overflow-free dimensionless Fischer-Burmeister
+ coordinate map ``c(u) = scale * psi(u; eta) > 0`` with exact subtraction-free
+ tangent and BDF storage secant, preserving ``O(1)`` coordinates and nonsingular
+ linear diffusion slopes when invading initially empty blocking layers.
+2. :class:`BoundedSpeciesMap` -- smooth finite-site logistic map ``c in (0, c_lim)``
+ for optional steric exclusion on mobile iodide ``I^-``.
+3. :func:`species_sg_face_flux` -- unified Scharfetter-Gummel face flux for
+ charged (``z = -1``) and neutral (``z = 0``) species with harmonic face
+ diffusivity and optional heterointerface partition ratios ``K_part``.
+"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass
+from hashlib import sha256
+import json
+import math
+
+import numpy as np
+from numpy.typing import ArrayLike
+
+from solarlab.contracts import ContractError, Vector, frozen_array
+from solarlab.discretization.bernoulli import bernoulli, bernoulli_derivative
+from solarlab.physics.ions import ion_face_flux, ion_face_flux_jacobian
+
+__all__ = [
+ "BoundedSpeciesMap",
+ "IODINE_TRANSPORT_SCHEMA",
+ "PositiveSpeciesMap",
+ "SoftplusSpeciesMap",
+ "SpeciesCoordinateMap",
+ "SpeciesFaceFluxEvaluation",
+ "harmonic_face_diffusivity_m2_s",
+ "species_sg_face_flux",
+]
+
+IODINE_TRANSPORT_SCHEMA = "solarlab.iodine_transport.v1"
+
+
+def _positive_vector(values: ArrayLike, size: int, name: str) -> Vector:
+ arr = np.asarray(values, dtype=np.float64)
+ if arr.ndim == 0:
+ arr = np.full(size, float(arr), dtype=np.float64)
+ if arr.shape != (size,) or not np.all(np.isfinite(arr)) or np.any(arr <= 0.0):
+ raise ContractError(f"{name}_must_be_strictly_positive_vector_of_length_{size}")
+ return frozen_array(arr)
+
+
+def _psi_and_radius(u: np.ndarray, eta: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
+ radius = np.hypot(u, 2.0 * eta)
+ two_eta_sq = 2.0 * (eta * eta)
+ nonneg = u >= 0.0
+ safe_denom = np.where(nonneg, 1.0, radius - u)
+ psi = np.where(nonneg, 0.5 * (u + radius), two_eta_sq / safe_denom)
+ return psi, radius
+
+
+@dataclass(frozen=True, slots=True)
+class PositiveSpeciesMap:
+ """Dimensionless Fischer-Burmeister positive map ``c(u) = scale * psi(u; eta)``."""
+
+ scale_m3: Vector
+ eta: Vector | ArrayLike = 1.0e-6
+ vacuum_floor_m3: float = 1.0
+
+ def __post_init__(self) -> None:
+ raw = np.atleast_1d(np.asarray(self.scale_m3, dtype=np.float64))
+ if raw.ndim != 1 or raw.size < 1:
+ raise ContractError("scale_m3_must_be_nonempty_1d_vector")
+ size = int(raw.size)
+ scale = _positive_vector(self.scale_m3, size, "scale_m3")
+ eta = _positive_vector(self.eta, size, "eta")
+ if np.any(eta > 1.0):
+ raise ContractError("eta_must_not_exceed_unity")
+ floor = float(self.vacuum_floor_m3)
+ if not math.isfinite(floor) or floor <= 0.0:
+ raise ContractError("vacuum_floor_m3_must_be_strictly_positive")
+ object.__setattr__(self, "scale_m3", scale)
+ object.__setattr__(self, "eta", eta)
+ object.__setattr__(self, "vacuum_floor_m3", floor)
+
+ @property
+ def size(self) -> int:
+ return int(self.scale_m3.size)
+
+ @property
+ def identity(self) -> str:
+ eta_arr = np.ascontiguousarray(self.eta, dtype=np.float64)
+ digest = sha256(
+ json.dumps(
+ [IODINE_TRANSPORT_SCHEMA, "positive_fb_v1", self.vacuum_floor_m3],
+ separators=(",", ":"),
+ ).encode()
+ )
+ digest.update(np.ascontiguousarray(self.scale_m3, dtype=np.float64).tobytes())
+ digest.update(eta_arr.tobytes())
+ return digest.hexdigest()
+
+ def density_and_tangent_m3(self, u: ArrayLike) -> tuple[Vector, Vector]:
+ coord = np.asarray(u, dtype=np.float64)
+ if coord.shape != (self.size,) or not np.all(np.isfinite(coord)):
+ raise ContractError("coordinate_must_be_finite_vector")
+ eta_arr = np.asarray(self.eta, dtype=np.float64)
+ psi, radius = _psi_and_radius(coord, eta_arr)
+ density = self.scale_m3 * psi
+ tangent = self.scale_m3 * (psi / radius)
+ if not (np.all(np.isfinite(density)) and np.all(np.isfinite(tangent))):
+ raise ContractError("nonfinite_positive_species_map_evaluation")
+ if np.any(density <= 0.0) or np.any(tangent <= 0.0):
+ raise FloatingPointError("positive_species_map_underflow")
+ return frozen_array(density), frozen_array(tangent)
+
+ def density_m3(self, u: ArrayLike) -> Vector:
+ density, _ = self.density_and_tangent_m3(u)
+ return density
+
+ def coordinate_from_density(self, density_m3: ArrayLike) -> Vector:
+ """Exact inverse ``u(c)``; maps ``c == 0`` cleanly to ``vacuum_floor_m3``."""
+ raw = np.asarray(density_m3, dtype=np.float64)
+ if raw.ndim == 0:
+ raw = np.full(self.size, float(raw), dtype=np.float64)
+ if raw.shape != (self.size,) or not np.all(np.isfinite(raw)) or np.any(raw < 0.0):
+ raise ContractError("density_m3_must_be_finite_nonnegative_vector")
+ eta_arr = np.asarray(self.eta, dtype=np.float64)
+ eff = np.where(raw > 0.0, raw, self.vacuum_floor_m3)
+ psi = eff / self.scale_m3
+ coord = psi - (eta_arr * eta_arr) / psi
+ return frozen_array(coord)
+
+ def secant_increment_m3(self, u_new: ArrayLike, u_old: ArrayLike) -> Vector:
+ """Cancellation-free ``c(u_new) - c(u_old)`` valid for all ``u in R``."""
+ u2 = np.asarray(u_new, dtype=np.float64)
+ u1 = np.asarray(u_old, dtype=np.float64)
+ if (
+ u2.shape != (self.size,)
+ or u1.shape != (self.size,)
+ or not (np.all(np.isfinite(u2)) and np.all(np.isfinite(u1)))
+ ):
+ raise ContractError("secant_coordinates_must_be_finite_vectors")
+ eta_arr = np.asarray(self.eta, dtype=np.float64)
+ psi1, r1 = _psi_and_radius(u1, eta_arr)
+ psi2, r2 = _psi_and_radius(u2, eta_arr)
+ delta = self.scale_m3 * (u2 - u1) * ((psi1 + psi2) / (r1 + r2))
+ return frozen_array(delta)
+
+
+@dataclass(frozen=True, slots=True)
+class BoundedSpeciesMap:
+ """Smooth logistic map ``c(u) = c_lim / (1 + exp(-(u + u_ref)))``."""
+
+ site_limit_m3: Vector
+ logit_reference: Vector
+ vacuum_floor_m3: float = 1.0
+
+ def __post_init__(self) -> None:
+ raw = np.atleast_1d(np.asarray(self.site_limit_m3, dtype=np.float64))
+ if raw.ndim != 1 or raw.size < 1:
+ raise ContractError("site_limit_m3_must_be_nonempty_1d_vector")
+ size = int(raw.size)
+ limit = _positive_vector(self.site_limit_m3, size, "site_limit_m3")
+ ref = np.asarray(self.logit_reference, dtype=np.float64)
+ if ref.ndim == 0:
+ ref = np.full(size, float(ref), dtype=np.float64)
+ if ref.shape != (size,) or not np.all(np.isfinite(ref)):
+ raise ContractError("logit_reference_must_be_finite_vector")
+ floor = float(self.vacuum_floor_m3)
+ if not math.isfinite(floor) or floor <= 0.0 or np.any(floor >= limit):
+ raise ContractError("vacuum_floor_m3_must_be_below_site_limit")
+ object.__setattr__(self, "site_limit_m3", limit)
+ object.__setattr__(self, "logit_reference", frozen_array(ref))
+ object.__setattr__(self, "vacuum_floor_m3", floor)
+
+ @property
+ def size(self) -> int:
+ return int(self.site_limit_m3.size)
+
+ @property
+ def identity(self) -> str:
+ digest = sha256(
+ json.dumps(
+ [IODINE_TRANSPORT_SCHEMA, "bounded_logistic_v1", self.vacuum_floor_m3],
+ separators=(",", ":"),
+ ).encode()
+ )
+ digest.update(
+ np.ascontiguousarray(self.site_limit_m3, dtype=np.float64).tobytes()
+ )
+ digest.update(
+ np.ascontiguousarray(self.logit_reference, dtype=np.float64).tobytes()
+ )
+ return digest.hexdigest()
+
+ @staticmethod
+ def _sigmoid(z: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
+ pos = z >= 0.0
+ exp_neg = np.exp(np.where(pos, -z, z))
+ denom = 1.0 + exp_neg
+ theta = np.where(pos, 1.0 / denom, exp_neg / denom)
+ one_minus = np.where(pos, exp_neg / denom, 1.0 / denom)
+ return theta, one_minus
+
+ def density_and_tangent_m3(self, u: ArrayLike) -> tuple[Vector, Vector]:
+ coord = np.asarray(u, dtype=np.float64)
+ if coord.shape != (self.size,) or not np.all(np.isfinite(coord)):
+ raise ContractError("coordinate_must_be_finite_vector")
+ theta, one_minus = self._sigmoid(coord + self.logit_reference)
+ density = self.site_limit_m3 * theta
+ tangent = density * one_minus
+ return frozen_array(density), frozen_array(tangent)
+
+ def density_m3(self, u: ArrayLike) -> Vector:
+ density, _ = self.density_and_tangent_m3(u)
+ return density
+
+ def coordinate_from_density(self, density_m3: ArrayLike) -> Vector:
+ raw = np.asarray(density_m3, dtype=np.float64)
+ if raw.ndim == 0:
+ raw = np.full(self.size, float(raw), dtype=np.float64)
+ if raw.shape != (self.size,) or not np.all(np.isfinite(raw)) or np.any(raw < 0.0):
+ raise ContractError("density_m3_must_be_finite_nonnegative_vector")
+ if np.any(raw >= self.site_limit_m3):
+ raise ContractError("density_exceeds_finite_site_limit")
+ eff = np.maximum(raw, self.vacuum_floor_m3)
+ theta = eff / self.site_limit_m3
+ logit = np.log(theta) - np.log1p(-theta)
+ return frozen_array(logit - self.logit_reference)
+
+ def secant_increment_m3(self, u_new: ArrayLike, u_old: ArrayLike) -> Vector:
+ """Cancellation-free logistic difference ``c(u_new) - c(u_old)``."""
+ u2 = np.asarray(u_new, dtype=np.float64)
+ u1 = np.asarray(u_old, dtype=np.float64)
+ if (
+ u2.shape != (self.size,)
+ or u1.shape != (self.size,)
+ or not (np.all(np.isfinite(u2)) and np.all(np.isfinite(u1)))
+ ):
+ raise ContractError("secant_coordinates_must_be_finite_vectors")
+ du = u2 - u1
+ theta1, om1 = self._sigmoid(u1 + self.logit_reference)
+ theta2, om2 = self._sigmoid(u2 + self.logit_reference)
+ neg_expm1 = -np.expm1(-np.abs(du))
+ factor = np.where(du >= 0.0, theta2 * om1, -theta1 * om2)
+ return frozen_array(self.site_limit_m3 * factor * neg_expm1)
+
+
+@dataclass(frozen=True, slots=True)
+class SoftplusSpeciesMap:
+ """Smooth log-linear map ``c(u) = scale * ln(1 + exp(u))`` on ``(-inf, +inf)``.
+
+ Behaves exponentially (``scale * exp(u)``) in trace regimes ``u << 0`` and
+ linearly (``scale * u``) in concentrated regimes ``u >> 0``, maintaining
+ smoothness radius ``|c'/c''| = 1 + exp(u) > 1`` everywhere with zero kinks
+ and zero positive overflow.
+ """
+
+ scale_m3: Vector
+ vacuum_floor_m3: float = 1.0
+
+ def __post_init__(self) -> None:
+ raw = np.atleast_1d(np.asarray(self.scale_m3, dtype=np.float64))
+ if raw.ndim != 1 or raw.size < 1:
+ raise ContractError("scale_m3_must_be_nonempty_1d_vector")
+ scale = _positive_vector(self.scale_m3, int(raw.size), "scale_m3")
+ floor = float(self.vacuum_floor_m3)
+ if not math.isfinite(floor) or floor <= 0.0:
+ raise ContractError("vacuum_floor_m3_must_be_strictly_positive")
+ object.__setattr__(self, "scale_m3", scale)
+ object.__setattr__(self, "vacuum_floor_m3", floor)
+
+ @property
+ def size(self) -> int:
+ return int(self.scale_m3.size)
+
+ @property
+ def identity(self) -> str:
+ digest = sha256(
+ json.dumps(
+ [IODINE_TRANSPORT_SCHEMA, "softplus_v1", self.vacuum_floor_m3],
+ separators=(",", ":"),
+ ).encode()
+ )
+ digest.update(np.ascontiguousarray(self.scale_m3, dtype=np.float64).tobytes())
+ return digest.hexdigest()
+
+ @staticmethod
+ def _softplus_and_sigmoid(u: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
+ pos = u >= 0.0
+ exp_neg = np.exp(np.where(pos, -u, u))
+ sp = np.where(pos, u + np.log1p(exp_neg), np.log1p(exp_neg))
+ sig = np.where(pos, 1.0 / (1.0 + exp_neg), exp_neg / (1.0 + exp_neg))
+ return sp, sig
+
+ def density_and_tangent_m3(self, u: ArrayLike) -> tuple[Vector, Vector]:
+ coord = np.asarray(u, dtype=np.float64)
+ if coord.shape != (self.size,) or not np.all(np.isfinite(coord)):
+ raise ContractError("coordinate_must_be_finite_vector")
+ sp, sig = self._softplus_and_sigmoid(coord)
+ density = self.scale_m3 * sp
+ tangent = self.scale_m3 * sig
+ if not (np.all(np.isfinite(density)) and np.all(np.isfinite(tangent))):
+ raise ContractError("nonfinite_softplus_species_map_evaluation")
+ if np.any(density <= 0.0) or np.any(tangent <= 0.0):
+ raise FloatingPointError("softplus_species_map_underflow")
+ return frozen_array(density), frozen_array(tangent)
+
+ def density_m3(self, u: ArrayLike) -> Vector:
+ density, _ = self.density_and_tangent_m3(u)
+ return density
+
+ def coordinate_from_density(self, density_m3: ArrayLike) -> Vector:
+ raw = np.asarray(density_m3, dtype=np.float64)
+ if raw.ndim == 0:
+ raw = np.full(self.size, float(raw), dtype=np.float64)
+ if raw.shape != (self.size,) or not np.all(np.isfinite(raw)) or np.any(raw < 0.0):
+ raise ContractError("density_m3_must_be_finite_nonnegative_vector")
+ eff = np.where(raw > 0.0, raw, self.vacuum_floor_m3)
+ y = eff / self.scale_m3
+ large = y > 1.0
+ safe_small = np.where(large, 1.0, y)
+ safe_large = np.where(large, y, 1.0)
+ coord = np.where(
+ large,
+ safe_large + np.log(-np.expm1(-safe_large)),
+ np.log(np.expm1(safe_small)),
+ )
+ return frozen_array(coord)
+
+ def secant_increment_m3(self, u_new: ArrayLike, u_old: ArrayLike) -> Vector:
+ """Subtraction-free ``c(u_new) - c(u_old)`` accurate across all regimes."""
+ u2 = np.asarray(u_new, dtype=np.float64)
+ u1 = np.asarray(u_old, dtype=np.float64)
+ if (
+ u2.shape != (self.size,)
+ or u1.shape != (self.size,)
+ or not (np.all(np.isfinite(u2)) and np.all(np.isfinite(u1)))
+ ):
+ raise ContractError("secant_coordinates_must_be_finite_vectors")
+ du = u2 - u1
+ close = np.abs(du) <= 0.5
+ sp1, sig1 = self._softplus_and_sigmoid(u1)
+ sp2, _ = self._softplus_and_sigmoid(u2)
+ safe_du = np.where(close, du, 0.0)
+ near_inc = np.log1p(sig1 * np.expm1(safe_du))
+ both_pos = (u1 > 0.0) & (u2 > 0.0)
+ far_pos_inc = du + np.log1p(np.exp(-np.maximum(u2, 0.0))) - np.log1p(
+ np.exp(-np.maximum(u1, 0.0))
+ )
+ far_inc = np.where(both_pos, far_pos_inc, sp2 - sp1)
+ return frozen_array(self.scale_m3 * np.where(close, near_inc, far_inc))
+
+
+SpeciesCoordinateMap = PositiveSpeciesMap | SoftplusSpeciesMap | BoundedSpeciesMap
+
+
+def harmonic_face_diffusivity_m2_s(
+ left_diffusivity_m2_s: ArrayLike,
+ right_diffusivity_m2_s: ArrayLike,
+) -> Vector:
+ """Harmonic average ``2 D_L D_R / (D_L + D_R)`` returning exact ``0`` at blocking faces."""
+ dl = np.asarray(left_diffusivity_m2_s, dtype=np.float64)
+ dr = np.asarray(right_diffusivity_m2_s, dtype=np.float64)
+ if dl.shape != dr.shape or dl.ndim != 1:
+ raise ContractError("face_diffusivity_inputs_must_match_1d_shape")
+ if not (np.all(np.isfinite(dl)) and np.all(np.isfinite(dr))):
+ raise ContractError("face_diffusivity_inputs_must_be_finite")
+ if np.any(dl < 0.0) or np.any(dr < 0.0):
+ raise ContractError("face_diffusivity_inputs_must_be_nonnegative")
+ denom = dl + dr
+ positive = (dl > 0.0) & (dr > 0.0) & (denom > 0.0)
+ safe_denom = np.where(positive, denom, 1.0)
+ harmonic = np.where(positive, (2.0 * dl * dr) / safe_denom, 0.0)
+ return frozen_array(harmonic)
+
+
+@dataclass(frozen=True, slots=True)
+class SpeciesFaceFluxEvaluation:
+ """Particle face flux ``[1 / (m^2 s)]`` and exact node-density/potential tangents."""
+
+ flux_m2_s: Vector
+ dflux_dc_left: Vector | None = None
+ dflux_dc_right: Vector | None = None
+ dflux_dphi_left: Vector | None = None
+ dflux_dphi_right: Vector | None = None
+
+
+def species_sg_face_flux(
+ phi_V: ArrayLike,
+ density_m3: ArrayLike,
+ dx_m: ArrayLike,
+ face_diffusivity_m2_s: ArrayLike,
+ thermal_voltage_V: float,
+ *,
+ charge_number: int = 0,
+ log_partition_step: ArrayLike | None = None,
+ steric_site_limit_m3: ArrayLike | None = None,
+ steric_diffusion_only: bool = True,
+ derivatives: bool = True,
+) -> SpeciesFaceFluxEvaluation:
+ """Evaluate 1D Scharfetter-Gummel face flux for charged or neutral species.
+
+ With ``xi_f = z * (phi_R - phi_L) / V_T - ln(K_part_R / K_part_L)``:
+ ``Gamma_f = (D_f / dx_f) * [B(xi_f) * c_L - B(-xi_f) * c_R]``.
+ """
+ phi = np.asarray(phi_V, dtype=np.float64)
+ c = np.asarray(density_m3, dtype=np.float64)
+ dx = np.asarray(dx_m, dtype=np.float64)
+ diff = np.asarray(face_diffusivity_m2_s, dtype=np.float64)
+ vt = float(thermal_voltage_V)
+ if phi.ndim != 1 or phi.size < 2 or c.shape != phi.shape:
+ raise ContractError("species_flux_requires_matching_1d_node_vectors")
+ faces = phi.size - 1
+ if dx.shape != (faces,) or diff.shape != (faces,):
+ raise ContractError("species_flux_requires_matching_face_vectors")
+ if not (
+ np.all(np.isfinite(phi))
+ and np.all(np.isfinite(c))
+ and np.all(np.isfinite(dx))
+ and np.all(np.isfinite(diff))
+ and math.isfinite(vt)
+ ):
+ raise ContractError("species_flux_inputs_must_be_finite")
+ if vt <= 0.0 or np.any(dx <= 0.0) or np.any(diff < 0.0) or np.any(c < 0.0):
+ raise ContractError("species_flux_invalid_physical_domain")
+
+ log_part = (
+ np.zeros(faces, dtype=np.float64)
+ if log_partition_step is None
+ else np.asarray(log_partition_step, dtype=np.float64)
+ )
+ if log_part.shape != (faces,) or not np.all(np.isfinite(log_part)):
+ raise ContractError("log_partition_step_must_be_finite_face_vector")
+
+ if steric_site_limit_m3 is not None:
+ if charge_number not in (-1, 1):
+ raise ContractError("steric_ion_kernel_requires_unit_charge_species")
+ if np.any(log_part != 0.0):
+ raise ContractError("steric_ion_kernel_does_not_combine_partition_step")
+ limit = np.asarray(steric_site_limit_m3, dtype=np.float64)
+ if limit.shape != phi.shape:
+ raise ContractError("steric_site_limit_must_match_node_count")
+ sign = float(charge_number)
+ flux = ion_face_flux(
+ phi,
+ c,
+ dx,
+ diff,
+ vt,
+ limit[:-1],
+ steric_diffusion_only=steric_diffusion_only,
+ P_lim_node=limit,
+ drift_sign=sign,
+ )
+ if not derivatives:
+ return SpeciesFaceFluxEvaluation(flux_m2_s=frozen_array(flux))
+ jac = ion_face_flux_jacobian(
+ phi,
+ c,
+ dx,
+ diff,
+ vt,
+ limit[:-1],
+ steric_diffusion_only=steric_diffusion_only,
+ P_lim_node=limit,
+ drift_sign=sign,
+ )
+ if not np.all(jac.differentiable_faces):
+ raise ContractError("steric_ion_flux_hit_nondifferentiable_kink")
+ return SpeciesFaceFluxEvaluation(
+ flux_m2_s=frozen_array(jac.flux),
+ dflux_dc_left=frozen_array(jac.density_left_derivative),
+ dflux_dc_right=frozen_array(jac.density_right_derivative),
+ dflux_dphi_left=frozen_array(jac.potential_left_derivative),
+ dflux_dphi_right=frozen_array(jac.potential_right_derivative),
+ )
+
+ conductance = diff / dx
+ if charge_number == 0 and log_partition_step is None:
+ flux = conductance * (c[:-1] - c[1:])
+ if not derivatives:
+ return SpeciesFaceFluxEvaluation(flux_m2_s=frozen_array(flux))
+ zeros = np.zeros(faces, dtype=np.float64)
+ return SpeciesFaceFluxEvaluation(
+ flux_m2_s=frozen_array(flux),
+ dflux_dc_left=frozen_array(conductance),
+ dflux_dc_right=frozen_array(-conductance),
+ dflux_dphi_left=frozen_array(zeros),
+ dflux_dphi_right=frozen_array(zeros),
+ )
+
+ z_float = float(charge_number)
+ xi = (z_float * np.diff(phi) / vt) - log_part
+ bp = bernoulli(xi)
+ bm = bernoulli(-xi)
+ flux = conductance * (bp * c[:-1] - bm * c[1:])
+ if not derivatives:
+ return SpeciesFaceFluxEvaluation(flux_m2_s=frozen_array(flux))
+
+ dc_left = conductance * bp
+ dc_right = -conductance * bm
+ if charge_number == 0:
+ zeros = np.zeros(faces, dtype=np.float64)
+ return SpeciesFaceFluxEvaluation(
+ flux_m2_s=frozen_array(flux),
+ dflux_dc_left=frozen_array(dc_left),
+ dflux_dc_right=frozen_array(dc_right),
+ dflux_dphi_left=frozen_array(zeros),
+ dflux_dphi_right=frozen_array(zeros),
+ )
+
+ dbp = bernoulli_derivative(xi)
+ dbm = bernoulli_derivative(-xi)
+ dflux_dxi = conductance * (dbp * c[:-1] + dbm * c[1:])
+ scale_phi = z_float / vt
+ dphi_left = -scale_phi * dflux_dxi
+ dphi_right = scale_phi * dflux_dxi
+ return SpeciesFaceFluxEvaluation(
+ flux_m2_s=frozen_array(flux),
+ dflux_dc_left=frozen_array(dc_left),
+ dflux_dc_right=frozen_array(dc_right),
+ dflux_dphi_left=frozen_array(dphi_left),
+ dflux_dphi_right=frozen_array(dphi_right),
+ )
diff --git a/src/solarlab/physics/chemistry/stoichiometry.py b/src/solarlab/physics/chemistry/stoichiometry.py
new file mode 100644
index 00000000..437088ea
--- /dev/null
+++ b/src/solarlab/physics/chemistry/stoichiometry.py
@@ -0,0 +1,144 @@
+"""Stoichiometric network contracts and exact nullspace conservation invariants.
+
+Enforces microscopic charge neutrality ``z^T @ nu == 0`` and elemental iodine
+atom conservation ``m_I^T @ nu == 0`` at construction time on every reaction
+column before any ODE or PDE evaluation can proceed.
+"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass
+from hashlib import sha256
+import json
+
+import numpy as np
+from numpy.typing import ArrayLike, NDArray
+
+from solarlab.contracts import ContractError
+
+__all__ = [
+ "CANONICAL_IODINE_NETWORK",
+ "IODINE_REACTIONS",
+ "IODINE_SPECIES",
+ "STOICHIOMETRY_SCHEMA",
+ "StoichiometricNetwork",
+ "canonical_iodine_network",
+]
+
+STOICHIOMETRY_SCHEMA = "solarlab.iodine_stoichiometry.v1"
+
+IODINE_SPECIES: tuple[str, ...] = (
+ "electron",
+ "hole",
+ "iodide",
+ "iodine_atom",
+ "iodine_molecule",
+)
+IODINE_REACTIONS: tuple[str, ...] = ("R_a", "R_b", "R_c", "R_d", "R_e")
+
+
+def _frozen_int_array(values: ArrayLike, *, ndim: int, name: str) -> NDArray[np.int64]:
+ raw = np.asarray(values)
+ if raw.ndim != ndim or raw.dtype.kind not in ("i", "u"):
+ raise ContractError(f"{name}_must_be_{ndim}d_integer_array")
+ arr = np.array(raw, dtype=np.int64, copy=True)
+ arr.setflags(write=False)
+ return arr
+
+
+@dataclass(frozen=True, slots=True)
+class StoichiometricNetwork:
+ """Immutable stoichiometric network enforcing charge and atom conservation."""
+
+ species_ids: tuple[str, ...]
+ reaction_ids: tuple[str, ...]
+ nu: NDArray[np.int64]
+ charge_numbers: NDArray[np.int64]
+ iodine_atom_counts: NDArray[np.int64]
+
+ def __post_init__(self) -> None:
+ species = tuple(str(item) for item in self.species_ids)
+ reactions = tuple(str(item) for item in self.reaction_ids)
+ if not species or len(set(species)) != len(species):
+ raise ContractError("stoichiometry_requires_distinct_species_ids")
+ if not reactions or len(set(reactions)) != len(reactions):
+ raise ContractError("stoichiometry_requires_distinct_reaction_ids")
+ nu = _frozen_int_array(self.nu, ndim=2, name="nu")
+ charges = _frozen_int_array(
+ self.charge_numbers, ndim=1, name="charge_numbers"
+ )
+ atoms = _frozen_int_array(
+ self.iodine_atom_counts, ndim=1, name="iodine_atom_counts"
+ )
+ if nu.shape != (len(species), len(reactions)):
+ raise ContractError("stoichiometric_matrix_shape_mismatch")
+ if charges.shape != (len(species),) or atoms.shape != (len(species),):
+ raise ContractError("conservation_vector_shape_mismatch")
+ if np.any(atoms < 0):
+ raise ContractError("iodine_atom_counts_must_be_nonnegative")
+ charge_defect = charges @ nu
+ if not np.all(charge_defect == 0):
+ raise ContractError("stoichiometric_charge_conservation_violated")
+ atom_defect = atoms @ nu
+ if not np.all(atom_defect == 0):
+ raise ContractError("stoichiometric_iodine_conservation_violated")
+ object.__setattr__(self, "species_ids", species)
+ object.__setattr__(self, "reaction_ids", reactions)
+ object.__setattr__(self, "nu", nu)
+ object.__setattr__(self, "charge_numbers", charges)
+ object.__setattr__(self, "iodine_atom_counts", atoms)
+
+ @property
+ def identity(self) -> str:
+ payload = [
+ STOICHIOMETRY_SCHEMA,
+ list(self.species_ids),
+ list(self.reaction_ids),
+ self.nu.tolist(),
+ self.charge_numbers.tolist(),
+ self.iodine_atom_counts.tolist(),
+ ]
+ return sha256(
+ json.dumps(payload, separators=(",", ":")).encode()
+ ).hexdigest()
+
+ def project_sources(self, rates: NDArray[np.float64]) -> NDArray[np.float64]:
+ """Map reaction rates ``(R, M)`` or ``(R,)`` to species sources ``nu @ rates``."""
+ arr = np.asarray(rates, dtype=np.float64)
+ if arr.shape[0] != len(self.reaction_ids):
+ raise ContractError("reaction_rate_dimension_mismatch")
+ return np.asarray(self.nu.astype(np.float64) @ arr, dtype=np.float64)
+
+
+def canonical_iodine_network() -> StoichiometricNetwork:
+ """Return the 5-species, 5-reaction Bitton & Tessler (2023) iodine network.
+
+ Columns correspond to ``[R_a, R_b, R_c, R_d, R_e]``:
+ * ``R_a``: ``I^- + h^+ -> I^0``
+ * ``R_b``: ``I^0 -> I^- + h^+``
+ * ``R_c``: ``I^0 + e^- <-> I^-``
+ * ``R_d``: ``2 I^0 <-> I_2``
+ * ``R_e``: ``I_2 + 2 e^- <-> 2 I^-``
+ """
+ nu = np.array(
+ [
+ [0, 0, -1, 0, -2], # electron (n)
+ [-1, 1, 0, 0, 0], # hole (p)
+ [-1, 1, 1, 0, 2], # iodide (c_-)
+ [1, -1, -1, -2, 0], # iodine_atom (c_0)
+ [0, 0, 0, 1, -1], # iodine_molecule (c_2)
+ ],
+ dtype=np.int64,
+ )
+ charges = np.array([-1, 1, -1, 0, 0], dtype=np.int64)
+ atoms = np.array([0, 0, 1, 1, 2], dtype=np.int64)
+ return StoichiometricNetwork(
+ species_ids=IODINE_SPECIES,
+ reaction_ids=IODINE_REACTIONS,
+ nu=nu,
+ charge_numbers=charges,
+ iodine_atom_counts=atoms,
+ )
+
+
+CANONICAL_IODINE_NETWORK: StoichiometricNetwork = canonical_iodine_network()
diff --git a/src/solarlab/reproducibility/PublicAPI.json b/src/solarlab/reproducibility/PublicAPI.json
index a2e727ce..94656d07 100644
--- a/src/solarlab/reproducibility/PublicAPI.json
+++ b/src/solarlab/reproducibility/PublicAPI.json
@@ -1390,6 +1390,135 @@
"solve_frozen_metastable_jv",
"solve_frozen_metastable_steady",
"solve_metastable_transient"
+ ],
+ "solarlab.physics.chemistry": [
+ "BoundedSpeciesMap",
+ "CANONICAL_IODINE_NETWORK",
+ "IODINE_KINETICS_SCHEMA",
+ "IODINE_REACTIONS",
+ "IODINE_SPECIES",
+ "IODINE_TRANSPORT_SCHEMA",
+ "IodineKineticsParameters",
+ "IodineReactionEvaluation",
+ "IodineThermodynamicMode",
+ "PositiveSpeciesMap",
+ "ReactionEOrder",
+ "STOICHIOMETRY_SCHEMA",
+ "SoftplusSpeciesMap",
+ "SpeciesCoordinateMap",
+ "SpeciesFaceFluxEvaluation",
+ "StoichiometricNetwork",
+ "canonical_iodine_network",
+ "equilibrium_iodine_populations_m3",
+ "evaluate_iodine_kinetics",
+ "harmonic_face_diffusivity_m2_s",
+ "smoluchowski_rate_m3_s",
+ "species_sg_face_flux"
+ ],
+ "solarlab.equations.iodine_1d": [
+ "ContactReactionMode",
+ "CompiledIodineDevice1D",
+ "IODINE_BLOCKS",
+ "IodineBoundaryPortSpec",
+ "IodineDomainMode",
+ "IodineState1D"
+ ],
+ "solarlab.device.compile_iodine_1d": [
+ "IodineBoundaryDeclaration",
+ "IodineChemistryDeclaration",
+ "IodineLayerSpec",
+ "IodineRateParameterization",
+ "bitton_tessler_2023_table_s1_chemistry",
+ "compile_iodine_device_1d"
+ ],
+ "solarlab.equations.assembly.iodine_1d": [
+ "AssembledConstrainedIodine1DProblem",
+ "AssembledIodine1DProblem",
+ "CHEM_NODES",
+ "IODIDE",
+ "IODINE_ATOM",
+ "IODINE_MOLECULE",
+ "IodineCarrierReactionTerm",
+ "IodineContactReactionPortTerm",
+ "IodineFields",
+ "IodineHoleContactPortTerm",
+ "IodineMoleculeEscapePortTerm",
+ "IodineSpaceChargeTerm",
+ "IodineSpeciesReactionTerm",
+ "IodineSpeciesStorageTerm",
+ "IodineSystem",
+ "IodineTransportTerm",
+ "IodineVolumetricEscapeTerm",
+ "SingleSpeciesInventoryTerm",
+ "TotalIodineInventoryTerm",
+ "iodine_system"
+ ],
+ "solarlab.solvers.nonlinear.iodine_1d": [
+ "IodineSteadyOptions",
+ "IodineSteadyResult",
+ "IodineStepAccounting",
+ "iodine_bdf_newton_settings",
+ "iodine_bdf_seed",
+ "iodine_convergence_norm",
+ "iodine_steady_newton_settings",
+ "iodine_step_accounting",
+ "solve_frozen_chemistry_electronic_1d",
+ "solve_iodine_bdf_transient",
+ "solve_iodine_steady_state"
+ ],
+ "solarlab.solvers.linear.iodine_impedance": [
+ "ChemResponseMode",
+ "IodineFrequencyResponse",
+ "IodineImpedanceResult",
+ "solve_iodine_small_signal_1d"
+ ],
+ "solarlab.experiments.iodine_aging": [
+ "DynamicJVScanProbeResult",
+ "FrozenChemistryJVProbeResult",
+ "IODINE_AGING_SCHEMA",
+ "IodineAgingError",
+ "IodineAgingProtocol",
+ "IodineAgingResult",
+ "IodineCheckpointSnapshot",
+ "IodineProbeMode",
+ "IodineProbeSpec",
+ "StressRecoveryStage",
+ "load_iodine_aging_bundle",
+ "measure_dynamic_jv_scan",
+ "measure_frozen_chemistry_jv",
+ "record_iodine_aging_in_run_store",
+ "run_iodine_aging_protocol",
+ "save_iodine_aging_bundle"
+ ],
+ "solarlab.experiments.iodine_declarative": [
+ "IODINE_DECK_SCHEMA_VERSION",
+ "IodineAgingSpecInput",
+ "IodineBDFOptionsInput",
+ "IodineBoundaryInput",
+ "IodineChemistryInput",
+ "IodineDeckInput",
+ "IodineElectronicStackInput",
+ "IodineImpedanceSpecInput",
+ "IodineLayerInput",
+ "IodineOverridesInput",
+ "IodineProbeInput",
+ "IodineStageInput",
+ "IodineSteadySpecInput",
+ "apply_iodine_deck_overrides",
+ "compile_iodine_deck",
+ "execute_iodine_aging_deck",
+ "execute_iodine_impedance_deck",
+ "execute_iodine_steady_deck",
+ "export_iodine_deck_schema",
+ "load_iodine_deck",
+ "resolve_iodine_operating_state"
+ ],
+ "solarlab.materials.iodine_presets": [
+ "PACKAGED_IODINE_PRESET_NAMES",
+ "list_packaged_iodine_preset_summaries",
+ "load_packaged_iodine_preset_bytes",
+ "load_packaged_iodine_preset_mapping",
+ "load_packaged_iodine_preset_source"
]
},
"public_imports": {
@@ -2781,6 +2910,135 @@
"solve_frozen_metastable_jv",
"solve_frozen_metastable_steady",
"solve_metastable_transient"
+ ],
+ "solarlab.physics.chemistry": [
+ "BoundedSpeciesMap",
+ "CANONICAL_IODINE_NETWORK",
+ "IODINE_KINETICS_SCHEMA",
+ "IODINE_REACTIONS",
+ "IODINE_SPECIES",
+ "IODINE_TRANSPORT_SCHEMA",
+ "IodineKineticsParameters",
+ "IodineReactionEvaluation",
+ "IodineThermodynamicMode",
+ "PositiveSpeciesMap",
+ "ReactionEOrder",
+ "STOICHIOMETRY_SCHEMA",
+ "SoftplusSpeciesMap",
+ "SpeciesCoordinateMap",
+ "SpeciesFaceFluxEvaluation",
+ "StoichiometricNetwork",
+ "canonical_iodine_network",
+ "equilibrium_iodine_populations_m3",
+ "evaluate_iodine_kinetics",
+ "harmonic_face_diffusivity_m2_s",
+ "smoluchowski_rate_m3_s",
+ "species_sg_face_flux"
+ ],
+ "solarlab.equations.iodine_1d": [
+ "CompiledIodineDevice1D",
+ "ContactReactionMode",
+ "IODINE_BLOCKS",
+ "IodineBoundaryPortSpec",
+ "IodineDomainMode",
+ "IodineState1D"
+ ],
+ "solarlab.device.compile_iodine_1d": [
+ "IodineBoundaryDeclaration",
+ "IodineChemistryDeclaration",
+ "IodineLayerSpec",
+ "IodineRateParameterization",
+ "bitton_tessler_2023_table_s1_chemistry",
+ "compile_iodine_device_1d"
+ ],
+ "solarlab.equations.assembly.iodine_1d": [
+ "AssembledConstrainedIodine1DProblem",
+ "AssembledIodine1DProblem",
+ "CHEM_NODES",
+ "IODIDE",
+ "IODINE_ATOM",
+ "IODINE_MOLECULE",
+ "IodineCarrierReactionTerm",
+ "IodineContactReactionPortTerm",
+ "IodineFields",
+ "IodineHoleContactPortTerm",
+ "IodineMoleculeEscapePortTerm",
+ "IodineSpaceChargeTerm",
+ "IodineSpeciesReactionTerm",
+ "IodineSpeciesStorageTerm",
+ "IodineSystem",
+ "IodineTransportTerm",
+ "IodineVolumetricEscapeTerm",
+ "SingleSpeciesInventoryTerm",
+ "TotalIodineInventoryTerm",
+ "iodine_system"
+ ],
+ "solarlab.solvers.nonlinear.iodine_1d": [
+ "IodineSteadyOptions",
+ "IodineSteadyResult",
+ "IodineStepAccounting",
+ "iodine_bdf_newton_settings",
+ "iodine_bdf_seed",
+ "iodine_convergence_norm",
+ "iodine_steady_newton_settings",
+ "iodine_step_accounting",
+ "solve_frozen_chemistry_electronic_1d",
+ "solve_iodine_bdf_transient",
+ "solve_iodine_steady_state"
+ ],
+ "solarlab.solvers.linear.iodine_impedance": [
+ "ChemResponseMode",
+ "IodineFrequencyResponse",
+ "IodineImpedanceResult",
+ "solve_iodine_small_signal_1d"
+ ],
+ "solarlab.experiments.iodine_aging": [
+ "DynamicJVScanProbeResult",
+ "FrozenChemistryJVProbeResult",
+ "IODINE_AGING_SCHEMA",
+ "IodineAgingError",
+ "IodineAgingProtocol",
+ "IodineAgingResult",
+ "IodineCheckpointSnapshot",
+ "IodineProbeMode",
+ "IodineProbeSpec",
+ "StressRecoveryStage",
+ "load_iodine_aging_bundle",
+ "measure_dynamic_jv_scan",
+ "measure_frozen_chemistry_jv",
+ "record_iodine_aging_in_run_store",
+ "run_iodine_aging_protocol",
+ "save_iodine_aging_bundle"
+ ],
+ "solarlab.experiments.iodine_declarative": [
+ "IODINE_DECK_SCHEMA_VERSION",
+ "IodineAgingSpecInput",
+ "IodineBDFOptionsInput",
+ "IodineBoundaryInput",
+ "IodineChemistryInput",
+ "IodineDeckInput",
+ "IodineElectronicStackInput",
+ "IodineImpedanceSpecInput",
+ "IodineLayerInput",
+ "IodineOverridesInput",
+ "IodineProbeInput",
+ "IodineStageInput",
+ "IodineSteadySpecInput",
+ "apply_iodine_deck_overrides",
+ "compile_iodine_deck",
+ "execute_iodine_aging_deck",
+ "execute_iodine_impedance_deck",
+ "execute_iodine_steady_deck",
+ "export_iodine_deck_schema",
+ "load_iodine_deck",
+ "resolve_iodine_operating_state"
+ ],
+ "solarlab.materials.iodine_presets": [
+ "PACKAGED_IODINE_PRESET_NAMES",
+ "list_packaged_iodine_preset_summaries",
+ "load_packaged_iodine_preset_bytes",
+ "load_packaged_iodine_preset_mapping",
+ "load_packaged_iodine_preset_source"
]
},
"checked_consumers": [
diff --git a/src/solarlab/solvers/linear/iodine_impedance.py b/src/solarlab/solvers/linear/iodine_impedance.py
new file mode 100644
index 00000000..95d3a182
--- /dev/null
+++ b/src/solarlab/solvers/linear/iodine_impedance.py
@@ -0,0 +1,429 @@
+"""Small-signal AC impedance solver for 1D iodine reaction-diffusion systems.
+
+Linearizes the assembled 1D ``(phi, n, p, I^-, I^0, I_2)`` DAE operator around
+any admitted steady or transient snapshot state using the ``exp(+i * omega * t)``
+phasor convention and reuses SolarLab's shared
+:func:`~solarlab.solvers.linear.frequency_domain.solve_frequency_systems`
+without duplicating linear solver infrastructure.
+"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass
+import math
+from typing import Literal, TypeAlias
+
+import numpy as np
+from numpy.typing import ArrayLike, NDArray
+from scipy.sparse import lil_matrix
+
+from solarlab.contracts import ContractError, Vector, frozen_array
+from solarlab.contracts.units import ELEMENTARY_CHARGE_C as Q
+from solarlab.equations.assembly.iodine_1d import (
+ IODIDE,
+ IODINE_BLOCKS,
+ POTENTIAL,
+ AssembledConstrainedIodine1DProblem,
+ AssembledIodine1DProblem,
+ iodine_system,
+)
+from solarlab.equations.assembly.quasi_fermi import quasi_fermi_potential_tangents
+from solarlab.equations.dc_1d import CapabilityError, DC1DProblem
+from solarlab.equations.iodine_1d import CompiledIodineDevice1D, IodineState1D
+from solarlab.solvers.linear.frequency_domain import (
+ FrequencyOptions,
+ FrequencySolution,
+ solve_frequency_systems,
+)
+
+__all__ = [
+ "ChemResponseMode",
+ "IodineFrequencyResponse",
+ "IodineImpedanceResult",
+ "solve_iodine_small_signal_1d",
+]
+
+ComplexVector: TypeAlias = NDArray[np.complex128]
+ChemResponseMode: TypeAlias = Literal["mobile", "frozen"]
+
+
+def _frozen_complex(values: ArrayLike) -> ComplexVector:
+ arr = np.array(values, dtype=np.complex128, copy=True)
+ arr.setflags(write=False)
+ return arr
+
+
+@dataclass(frozen=True, slots=True)
+class IodineFrequencyResponse:
+ """Complex small-signal response at one frequency ``f`` [Hz]."""
+
+ frequency_Hz: float
+ omega_rad_s: float
+ voltage_phasor_V: complex
+ current_density_phasor_A_m2: complex
+ admittance_S_m2: complex
+ impedance_Ohm_m2: complex
+ apparent_capacitance_F_m2: float
+ maxwell_spread_A_m2_V: float
+ backward_error: float
+ perturbation_u: ComplexVector
+ species_inventory_perturbation_m2: dict[str, complex]
+
+
+@dataclass(frozen=True, slots=True)
+class IodineImpedanceResult:
+ """Bounded AC impedance sweep across a distinct frequency grid."""
+
+ frequencies_Hz: Vector
+ voltage_phasor_V: complex
+ chem_mode: ChemResponseMode
+ operating_voltage_V: float
+ generation_scale: float
+ responses: tuple[IodineFrequencyResponse, ...]
+ admittance_S_m2: ComplexVector
+ impedance_Ohm_m2: ComplexVector
+ apparent_capacitance_F_m2: Vector
+ max_maxwell_spread_A_m2_V: float
+ max_backward_error: float
+ device_sha256: str
+ scientific_qualification: bool = False
+
+
+def _carrier_flux_perturbation_m2_s(
+ problem: AssembledIodine1DProblem,
+ state: IodineState1D,
+ fixed_x: ComplexVector,
+) -> tuple[ComplexVector, ComplexVector]:
+ """Perturbed interior electron and hole particle fluxes [m^-2 s^-1]."""
+ comp = problem.device.electronic_component
+ n_c = problem.device.node_count
+ u_0 = state.u[: 3 * n_c]
+ cf = problem.carrier_fluxes(state.u)
+ vt = comp.thermal_voltage_V
+ e_state = state.electronic_state
+ ft = None if comp.field_transport is None else comp.field_transport.evaluate(u_0[:n_c])
+
+ out: list[ComplexVector] = []
+ for offset, dens, flux_obj, sign in (
+ (n_c, e_state.electron_density_m3, cf.electron, 1.0),
+ (2 * n_c, e_state.hole_density_m3, cf.hole, -1.0),
+ ):
+ drive = sign * np.diff(u_0[offset : offset + n_c])
+ left_phi, _ = quasi_fermi_potential_tangents(flux_obj, drive, sign, vt)
+ if ft is not None:
+ diff = (
+ ft.electron_diffusivity_m2_s
+ if offset == n_c
+ else ft.hole_diffusivity_m2_s
+ )
+ ddiff = (
+ ft.electron_d_diffusivity_d_field
+ if offset == n_c
+ else ft.hole_d_diffusivity_d_field
+ )
+ left_phi = left_phi + (flux_obj.flux / diff) * ddiff / np.diff(comp.nodes_m)
+ left_z = sign * flux_obj.left_density_derivative * dens[:-1]
+ df = (
+ left_phi * (fixed_x[: n_c - 1] - fixed_x[1:n_c])
+ + left_z
+ * (fixed_x[offset : offset + n_c - 1] - fixed_x[offset + 1 : offset + n_c])
+ + sign
+ * flux_obj.flux
+ * (fixed_x[offset + 1 : offset + n_c] + fixed_x[1:n_c] / vt)
+ )
+ out.append(np.asarray(df, dtype=np.complex128))
+ return out[0], out[1]
+
+
+def _iodide_flux_perturbation_m2_s(
+ problem: AssembledIodine1DProblem,
+ state: IodineState1D,
+ fixed_x: ComplexVector,
+ chem_mode: ChemResponseMode,
+) -> ComplexVector:
+ """Perturbed interior iodide particle flux embedded on all ``N - 1`` faces."""
+ dev = problem.device
+ n_c = dev.node_count
+ out: NDArray[np.complex128] = np.zeros(n_c - 1, dtype=np.complex128)
+ if chem_mode == "frozen":
+ return out
+ assert problem.binding is not None
+ ev_state = problem.binding.assembler.state(state.u, problem.inputs)
+ if ev_state is None:
+ raise FloatingPointError("inadmissible operating state in iodide AC flux")
+ _, left, right = problem.binding.chem_transports[IODIDE].flux_evaluation(
+ ev_state, derivatives=True
+ )
+ idx = dev.chem_node_indices
+ x_phi_chem = fixed_x[idx]
+ x_iodide = fixed_x[dev.chem_slices[IODIDE]]
+ d_flux_chem = (
+ np.asarray(left[POTENTIAL], dtype=np.float64) * x_phi_chem[:-1]
+ + np.asarray(right[POTENTIAL], dtype=np.float64) * x_phi_chem[1:]
+ + np.asarray(left[IODIDE], dtype=np.float64) * x_iodide[:-1]
+ + np.asarray(right[IODIDE], dtype=np.float64) * x_iodide[1:]
+ )
+ start = int(idx[0])
+ out[start : start + d_flux_chem.size] = d_flux_chem
+ return out
+
+
+def solve_iodine_small_signal_1d(
+ device: CompiledIodineDevice1D,
+ state: IodineState1D,
+ frequencies_Hz: ArrayLike,
+ *,
+ generation_scale: float = 0.0,
+ voltage_phasor_V: complex = 1.0,
+ chem_mode: ChemResponseMode = "mobile",
+ inventory_node: int = 0,
+ options: FrequencyOptions | None = None,
+) -> IodineImpedanceResult:
+ """Solve small-signal AC impedance ``Z(omega)`` on a 1D iodine aging stack.
+
+ Parameters
+ ----------
+ device:
+ Compiled 1D iodine-coupled device.
+ state:
+ Operating state ``(u_0, V_0)`` around which ``J`` and ``K = -S_u`` are
+ linearized.
+ frequencies_Hz:
+ 1D array of distinct nonnegative frequencies ``f`` [Hz].
+ generation_scale:
+ Operating optical generation scale ``G`` matching ``state``.
+ voltage_phasor_V:
+ Complex terminal voltage perturbation amplitude ``V_tilde`` [V].
+ chem_mode:
+ ``"mobile"`` includes full coupled ``I^- / I^0 / I_2`` reaction-diffusion
+ perturbations; ``"frozen"`` locks all three chemical species at ``0`` AC
+ perturbation to isolate pure electronic impedance.
+ inventory_node:
+ Cell index used if ``0 Hz`` is requested on a closed-domain stack.
+ options:
+ Linear frequency solver tolerances and iteration controls.
+ """
+ if state.device_sha256 != device.identity:
+ raise ContractError("iodine_ac_state_device_mismatch")
+ if chem_mode not in ("mobile", "frozen"):
+ raise ContractError("invalid_chem_mode")
+ voltage = complex(voltage_phasor_V)
+ if not (math.isfinite(voltage.real) and math.isfinite(voltage.imag)) or voltage == 0.0j:
+ raise ContractError("voltage_phasor_V_must_be_finite_nonzero")
+ g_scale = float(generation_scale)
+ if not math.isfinite(g_scale) or g_scale < 0.0:
+ raise ContractError("generation_scale_must_be_finite_nonnegative")
+
+ comp = device.electronic_component
+ if any(ch.kind != "fixed_reservoir" for ch in comp.channels):
+ raise CapabilityError(
+ "iodine small-signal AC currently requires fixed_reservoir carrier contacts"
+ )
+
+ controls = FrequencyOptions() if options is None else options
+ raw_freqs = np.asarray(frequencies_Hz)
+ if np.iscomplexobj(raw_freqs):
+ raise ValueError("frequencies_Hz must be real")
+ freqs = np.asarray(raw_freqs, dtype=np.float64)
+ if (
+ freqs.ndim != 1
+ or freqs.size == 0
+ or freqs.size > controls.max_frequencies
+ or not np.all(np.isfinite(freqs))
+ or np.any(freqs < 0.0)
+ or np.unique(freqs).size != freqs.size
+ ):
+ raise ValueError("frequencies_Hz must be a 1D array of distinct nonnegative Hz")
+
+ v_op = state.electronic_state.voltage_V
+ unconstrained_sys = iodine_system(device, constrained_steady=False)
+ problem = AssembledIodine1DProblem(
+ device=device,
+ voltage_V=v_op,
+ generation_scale=g_scale,
+ binding=unconstrained_sys,
+ )
+ j_base = problem.jacobian(state.u)
+ k_base = problem.storage_jacobian(state.u)
+
+ n_c = device.node_count
+ vt = comp.thermal_voltage_V
+ phi_right = complex(-comp.voltage_polarity * voltage)
+ known_base: dict[int, complex] = {
+ 0: 0.0j,
+ n_c - 1: phi_right,
+ n_c: 0.0j,
+ 2 * n_c - 1: -phi_right / vt,
+ 2 * n_c: 0.0j,
+ 3 * n_c - 1: -phi_right / vt,
+ }
+
+ j_work = lil_matrix(j_base, dtype=np.float64)
+ k_work = lil_matrix(k_base, dtype=np.float64)
+ known = dict(known_base)
+ if chem_mode == "frozen":
+ # Pure electronic response against frozen static iodide space charge:
+ # chemical reactions & ionic motion are frozen out, preserving exact
+ # Kirchhoff electronic current continuity div(J_n + J_p + i*w*D) == 0.
+ dc_prob = DC1DProblem(comp, v_op, g_scale)
+ j_dc = dc_prob.jacobian(state.u[: 3 * n_c])
+ k_dc = dc_prob.storage_jacobian(state.u[: 3 * n_c])
+ j_work[: 3 * n_c, :] = 0.0
+ k_work[: 3 * n_c, :] = 0.0
+ j_work[: 3 * n_c, : 3 * n_c] = j_dc
+ k_work[: 3 * n_c, : 3 * n_c] = k_dc
+ for row_idx in range(3 * n_c, device.state_size):
+ j_work.rows[row_idx] = [row_idx]
+ j_work.data[row_idx] = [1.0]
+ k_work.rows[row_idx] = []
+ k_work.data[row_idx] = []
+ known[row_idx] = 0.0j
+
+ j_csc = j_work.tocsc()
+ k_csc = k_work.tocsc()
+ prescribed_vec: NDArray[np.complex128] = np.zeros(
+ device.state_size, dtype=np.complex128
+ )
+ for k_idx, k_val in known.items():
+ prescribed_vec[k_idx] = k_val
+ rhs: NDArray[np.complex128] = np.zeros(device.state_size, dtype=np.complex128)
+ fixed_sorted = sorted(known)
+ rhs[fixed_sorted] = (j_csc[fixed_sorted, :] @ prescribed_vec)
+
+ # Separate 0 Hz on closed mobile domains (which requires the inventory constraint row)
+ zero_mask = freqs == 0.0
+ pos_freqs = freqs[~zero_mask]
+ sol_by_freq: dict[float, FrequencySolution] = {}
+
+ if pos_freqs.size > 0:
+ pos_sols = solve_frequency_systems(
+ j_csc,
+ k_csc,
+ rhs,
+ pos_freqs,
+ options=controls,
+ fixed_coordinates=known,
+ )
+ for sol in pos_sols:
+ sol_by_freq[sol.frequency_Hz] = sol
+
+ if np.any(zero_mask):
+ if chem_mode == "mobile" and not device.has_open_iodine_loss:
+ c_prob = AssembledConstrainedIodine1DProblem(
+ device=device,
+ voltage_V=v_op,
+ generation_scale=g_scale,
+ inventory_node=inventory_node,
+ )
+ j_zero = c_prob.jacobian(state.u)
+ k_zero = lil_matrix(k_csc.shape, dtype=np.float64).tocsc()
+ rhs_zero: NDArray[np.complex128] = np.zeros(
+ device.state_size, dtype=np.complex128
+ )
+ rhs_zero[fixed_sorted] = j_zero[fixed_sorted, :] @ prescribed_vec
+ zero_sol = solve_frequency_systems(
+ j_zero,
+ k_zero,
+ rhs_zero,
+ np.array([0.0]),
+ options=controls,
+ fixed_coordinates=known,
+ )[0]
+ else:
+ zero_sol = solve_frequency_systems(
+ j_csc,
+ k_csc,
+ rhs,
+ np.array([0.0]),
+ options=controls,
+ fixed_coordinates=known,
+ )[0]
+ sol_by_freq[0.0] = zero_sol
+
+ # Tangents dc_j / du_j at operating point for species inventory readout
+ _, _, _, _, _, _, mm, m0, m2 = device.fields_and_tangents(state.u, voltage_V=v_op)
+ tangents_map = {
+ "iodide": mm,
+ "iodine_atom": m0,
+ "iodine_molecule": m2,
+ }
+ w_chem = device.chem_geometry.cell_measures_m
+ cap_faces = comp.poisson.face_capacitance_F_m2
+ dx_faces = np.diff(comp.nodes_m)
+ total_len = float(math.fsum(dx_faces.tolist()))
+ slices = device.chem_slices
+
+ responses: list[IodineFrequencyResponse] = []
+ y_list: list[complex] = []
+ z_list: list[complex] = []
+ c_list: list[float] = []
+
+ for f_hz in freqs:
+ sol = sol_by_freq[float(f_hz)]
+ omega = 2.0 * math.pi * float(f_hz)
+ x_fixed = np.asarray(sol.solution, dtype=np.complex128)
+
+ dfn, dfp = _carrier_flux_perturbation_m2_s(problem, state, x_fixed)
+ df_iodide = _iodide_flux_perturbation_m2_s(problem, state, x_fixed, chem_mode)
+ j_cond_faces = Q * (dfp - dfn - df_iodide)
+ j_disp_faces = 1j * omega * (-cap_faces * np.diff(x_fixed[:n_c]))
+ j_tot_faces = j_cond_faces + j_disp_faces
+
+ # Spatial mean & all-face Maxwell uniformity spread
+ j_mean = complex(
+ math.fsum((dx_faces * j_tot_faces.real).tolist()) / total_len,
+ math.fsum((dx_faces * j_tot_faces.imag).tolist()) / total_len,
+ )
+ j_in = complex(comp.voltage_polarity * j_mean)
+ admittance = j_in / voltage
+ impedance = (1.0 / admittance) if admittance != 0.0j else complex(math.nan, math.nan)
+ c_app = float(admittance.imag / omega) if omega > 0.0 else math.nan
+ spread = float(np.max(np.abs(j_tot_faces - j_tot_faces[0]))) / abs(voltage)
+
+ sp_inv: dict[str, complex] = {}
+ for sp in IODINE_BLOCKS:
+ if chem_mode == "frozen":
+ sp_inv[sp] = 0.0j
+ else:
+ dc = tangents_map[sp] * x_fixed[slices[sp]]
+ sp_inv[sp] = complex(
+ math.fsum((w_chem * dc.real).tolist()),
+ math.fsum((w_chem * dc.imag).tolist()),
+ )
+
+ responses.append(
+ IodineFrequencyResponse(
+ frequency_Hz=float(f_hz),
+ omega_rad_s=omega,
+ voltage_phasor_V=voltage,
+ current_density_phasor_A_m2=j_in,
+ admittance_S_m2=admittance,
+ impedance_Ohm_m2=impedance,
+ apparent_capacitance_F_m2=c_app,
+ maxwell_spread_A_m2_V=spread,
+ backward_error=sol.componentwise_backward_error,
+ perturbation_u=_frozen_complex(x_fixed),
+ species_inventory_perturbation_m2=sp_inv,
+ )
+ )
+ y_list.append(admittance)
+ z_list.append(impedance)
+ c_list.append(c_app)
+
+ c_arr = np.array(c_list, dtype=np.float64, copy=True)
+ c_arr.setflags(write=False)
+ return IodineImpedanceResult(
+ frequencies_Hz=frozen_array(freqs),
+ voltage_phasor_V=voltage,
+ chem_mode=chem_mode,
+ operating_voltage_V=v_op,
+ generation_scale=g_scale,
+ responses=tuple(responses),
+ admittance_S_m2=_frozen_complex(y_list),
+ impedance_Ohm_m2=_frozen_complex(z_list),
+ apparent_capacitance_F_m2=c_arr,
+ max_maxwell_spread_A_m2_V=max(r.maxwell_spread_A_m2_V for r in responses),
+ max_backward_error=max(r.backward_error for r in responses),
+ device_sha256=device.identity,
+ scientific_qualification=False,
+ )
diff --git a/src/solarlab/solvers/nonlinear/iodine_1d.py b/src/solarlab/solvers/nonlinear/iodine_1d.py
new file mode 100644
index 00000000..5419209e
--- /dev/null
+++ b/src/solarlab/solvers/nonlinear/iodine_1d.py
@@ -0,0 +1,1460 @@
+"""Steady-state and physical-storage BDF adapters for 1D iodine aging systems.
+
+Reuses SolarLab's shared :func:`~solarlab.solvers.nonlinear.newton.solve_newton`
+and :func:`~solarlab.solvers.time.bdf.solve_bdf` drivers without duplicating
+any linear, nonlinear, or multistep time-integration solver logic.
+"""
+
+from __future__ import annotations
+
+from collections.abc import Callable, Sequence
+from dataclasses import dataclass
+import math
+
+import numpy as np
+from numpy.typing import NDArray
+from scipy.sparse import csc_matrix, diags
+
+from solarlab.contracts import Vector, frozen_array
+from solarlab.contracts.units import ELEMENTARY_CHARGE_C as Q
+from solarlab.equations.assembly.iodine_1d import (
+ AssembledConstrainedIodine1DProblem,
+ AssembledIodine1DProblem,
+ IodineSystem,
+ iodine_system,
+)
+from solarlab.equations.dc_1d import DC1DProblem
+from solarlab.equations.iodine_1d import CompiledIodineDevice1D, IodineState1D
+from solarlab.solvers.nonlinear.newton import (
+ NewtonResult,
+ NewtonSettings,
+ Termination,
+ factorize,
+ solve_newton,
+)
+from solarlab.solvers.nonlinear.problem import (
+ CallableProblem,
+ GateOutcome,
+ PhysicalGate,
+ ResidualScaling,
+ SolveBudget,
+ SteadyProblem,
+ StepControl,
+)
+from solarlab.solvers.nonlinear.production import (
+ POISSON_CONTACT_BALANCE_V1,
+ production_convergence_norm,
+ production_coordinates,
+ production_residual_scaling,
+)
+from solarlab.solvers.nonlinear.steady_1d import (
+ SteadyOptions,
+ SteadyStateError,
+ solve_equilibrium,
+)
+from solarlab.solvers.time.bdf import (
+ Assessment,
+ BDFEvent,
+ BDFOptions,
+ BDFResult,
+ BDFStep,
+ solve_bdf,
+)
+
+__all__ = [
+ "IodineSteadyOptions",
+ "IodineSteadyResult",
+ "IodineStepAccounting",
+ "iodine_bdf_newton_settings",
+ "iodine_bdf_seed",
+ "iodine_convergence_norm",
+ "iodine_steady_newton_settings",
+ "iodine_step_accounting",
+ "solve_frozen_chemistry_electronic_1d",
+ "solve_iodine_bdf_transient",
+ "solve_iodine_steady_state",
+]
+
+
+@dataclass(frozen=True, slots=True)
+class IodineSteadyOptions:
+ """Controls for closed-domain 1D iodine steady-state solves."""
+
+ poisson_tolerance: float = 5.0e-9
+ continuity_tolerance_A_m2: float = 2.0e-6
+ chem_flux_tolerance_A_m2: float = 5.0e-9
+ inventory_relative_tolerance: float = 1.0e-12
+ contact_log_tolerance: float = 1.0e-11
+ potential_step_V: float = 0.15
+ quasi_fermi_step: float = 2.5
+ chem_coordinate_step: float = 40.0
+ max_iterations: int = 120
+ max_backtracks: int = 16
+ wall_s: float = 30.0
+ continuation_steps: int = 6
+
+
+@dataclass(frozen=True, slots=True)
+class IodineSteadyResult:
+ """Converged or failed closed-domain 1D iodine steady-state result."""
+
+ converged: bool
+ state: IodineState1D | None
+ current_density_A_m2: float
+ termination: str
+ scaled_residual: float
+ iterations: int
+ newton: NewtonResult
+
+
+@dataclass(frozen=True, slots=True)
+class IodineStepAccounting:
+ """Per-step conservation and Maxwell current diagnostics."""
+
+ start_s: float
+ end_s: float
+ dt_s: float
+ in_device_iodine_m2: float
+ step_escaped_iodine_atoms_m2: float
+ step_immobilized_iodine_atoms_m2: float
+ step_conservation_residual_m2: float
+ terminal_current_A_m2: float
+ max_total_current_spread_A_m2: float
+
+
+def _poisson_weights_with_ions(device: CompiledIodineDevice1D) -> np.ndarray:
+ comp = device.electronic_component
+ count = comp.node_count
+ v_ref = max(abs(comp.built_in_potential_V), comp.thermal_voltage_V)
+ ion_bg = device.project_chem_density(device.compensating_donor_m3)
+ ion_peak = float(np.max(device.initial_iodide_m3)) * 0.1
+ d_ref = np.maximum(
+ np.maximum(
+ comp.parameters.acceptor_density_m3[1:-1],
+ comp.parameters.donor_density_m3[1:-1],
+ ),
+ np.maximum(ion_bg[1:-1], max(ion_peak, 1.0)),
+ )
+ cap = comp.poisson.face_capacitance_F_m2
+ scale = (
+ Q * d_ref * comp.poisson.interior_widths_m
+ + (cap[:-1] + cap[1:]) * v_ref
+ )
+ weights: NDArray[np.float64] = np.full(count, 1.0 / v_ref, dtype=np.float64)
+ weights[1:-1] = 1.0 / scale
+ return weights
+
+
+def iodine_convergence_norm(
+ device: CompiledIodineDevice1D,
+ *,
+ constrained_steady: bool = False,
+ inventory_node: int = 0,
+) -> Callable[[NDArray[np.float64]], float]:
+ """L1-integrated balance norm matching POISSON_CONTACT_BALANCE_V1."""
+ comp = device.electronic_component
+ n_count = device.node_count
+ m_count = device.chem_node_count
+ pointwise: NDArray[np.bool_] = np.zeros(device.state_size, dtype=bool)
+ pointwise[:n_count] = True
+ for carrier, offset in (("n", n_count), ("p", 2 * n_count)):
+ for side, node in (("left", 0), ("right", n_count - 1)):
+ if comp.channel(carrier, side).kind == "fixed_reservoir":
+ pointwise[offset + node] = True
+ if constrained_steady:
+ slices = device.chem_slices
+ if device.is_unreactive_limit:
+ for sp in ("iodide", "iodine_atom", "iodine_molecule"):
+ pointwise[slices[sp].start + inventory_node] = True
+ else:
+ pointwise[slices["iodide"].start + inventory_node] = True
+
+ def norm(scaled_residual: NDArray[np.float64]) -> float:
+ vals = np.asarray(scaled_residual, dtype=np.float64)
+ if not np.all(np.isfinite(vals)):
+ return math.inf
+ abs_v = np.abs(vals)
+ max_fixed = float(np.max(abs_v[pointwise]))
+ carrier_rows = abs_v[n_count : 3 * n_count].copy()
+ carrier_rows[pointwise[n_count : 3 * n_count]] = 0.0
+ carrier_bal = float(np.sum(carrier_rows)) / (2.0 * n_count)
+ chem_rows = abs_v[3 * n_count :].copy()
+ chem_rows[pointwise[3 * n_count :]] = 0.0
+ chem_bal = float(np.sum(chem_rows)) / (3.0 * m_count)
+ return max(max_fixed, carrier_bal, chem_bal)
+
+ return norm
+
+
+def _positive_species_gate(device: CompiledIodineDevice1D, voltage_V: float) -> PhysicalGate:
+ def check(u: Vector) -> GateOutcome:
+ try:
+ phi, n, p, cm, c0, c2, _, _, _ = device.fields_and_tangents(
+ u, voltage_V=voltage_V
+ )
+ except (ValueError, FloatingPointError):
+ return GateOutcome("positive_finite_densities", False, math.inf, 0.5)
+ ok = bool(
+ np.all(np.isfinite(phi))
+ and np.all(n > 0.0)
+ and np.all(p > 0.0)
+ and np.all(cm > 0.0)
+ and np.all(c0 > 0.0)
+ and np.all(c2 > 0.0)
+ )
+ return GateOutcome("positive_finite_densities", ok, 0.0 if ok else 1.0, 0.5)
+
+ return check
+
+
+def iodine_steady_newton_settings(
+ device: CompiledIodineDevice1D,
+ *,
+ voltage_V: float,
+ inventory_node: int = 0,
+ options: IodineSteadyOptions = IodineSteadyOptions(),
+) -> NewtonSettings:
+ comp = device.electronic_component
+ n_count = device.node_count
+ m_count = device.chem_node_count
+ weights: NDArray[np.float64] = np.empty(device.state_size, dtype=np.float64)
+
+ weights[:n_count] = _poisson_weights_with_ions(device) / options.poisson_tolerance
+ weights[n_count : 3 * n_count] = (
+ 2.0 * n_count * Q / options.continuity_tolerance_A_m2
+ )
+ for carrier, offset in (("n", n_count), ("p", 2 * n_count)):
+ for side, node in (("left", 0), ("right", n_count - 1)):
+ if comp.channel(carrier, side).kind == "fixed_reservoir":
+ weights[offset + node] = 1.0 / options.contact_log_tolerance
+
+ chem_w = m_count * Q / options.chem_flux_tolerance_A_m2
+ weights[3 * n_count :] = chem_w
+
+ inv_ref = max(device.reference_iodine_inventory_m2, 1.0)
+ inv_weight = 1.0 / (options.inventory_relative_tolerance * inv_ref)
+ slices = device.chem_slices
+ if device.is_unreactive_limit:
+ sp_refs = device.reference_species_inventories_m2
+ for sp in ("iodide", "iodine_atom", "iodine_molecule"):
+ ref_sp = max(sp_refs[sp], 1.0)
+ weights[slices[sp].start + inventory_node] = 1.0 / (
+ options.inventory_relative_tolerance * ref_sp
+ )
+ else:
+ weights[slices["iodide"].start + inventory_node] = inv_weight
+
+ iodide_step = (
+ 10.0 if device.steric_site_limit_m3 is not None else options.chem_coordinate_step
+ )
+ max_step = np.concatenate(
+ (
+ np.full(n_count, options.potential_step_V),
+ np.full(2 * n_count, options.quasi_fermi_step),
+ np.full(m_count, iodide_step),
+ np.full(2 * m_count, options.chem_coordinate_step),
+ )
+ )
+ budget = SolveBudget(
+ max_iterations=options.max_iterations,
+ max_residual_evaluations=options.max_iterations * (options.max_backtracks + 2),
+ max_jacobian_evaluations=options.max_iterations + 2,
+ max_backtracks=options.max_backtracks,
+ )
+ lower = np.concatenate(
+ (
+ np.full(3 * n_count, -math.inf),
+ np.full(3 * m_count, -220.0),
+ )
+ )
+ return NewtonSettings(
+ scaling=ResidualScaling(weights),
+ tolerance=1.0,
+ step_control=StepControl(max_step, lower=lower),
+ budget=budget,
+ gates=(_positive_species_gate(device, voltage_V),),
+ reuse_jacobian=False,
+ )
+
+
+def iodine_bdf_newton_settings(
+ step: BDFStep,
+ *,
+ poisson_tolerance: float = 5.0e-9,
+ continuity_tolerance_A_m2: float = 2.0e-6,
+ chem_flux_tolerance_A_m2: float = 2.0e-8,
+ inventory_relative_tolerance: float = 1.0e-10,
+ potential_step_V: float = 0.15,
+ quasi_fermi_step: float = 2.5,
+ chem_coordinate_step: float = 40.0,
+ max_iterations: int = 80,
+) -> NewtonSettings:
+ if not isinstance(step.endpoint, AssembledIodine1DProblem):
+ raise TypeError("iodine_bdf_newton_settings requires AssembledIodine1DProblem")
+ device = step.endpoint.device
+ comp = device.electronic_component
+ n_count = device.node_count
+ m_count = device.chem_node_count
+ dt_s = max(step.dt_s, 1.0e-30)
+
+ weights: NDArray[np.float64] = np.empty(device.state_size, dtype=np.float64)
+ weights[:n_count] = _poisson_weights_with_ions(device) / poisson_tolerance
+ w_cont = 2.0 * n_count * Q / continuity_tolerance_A_m2
+ old_c_s = float(
+ np.sum(np.abs(step.history[0].storage_value[n_count : 3 * n_count]))
+ )
+ carrier_s_ref = max(old_c_s, 1.0e14)
+ w_c_step = (2.0 * n_count * dt_s) / (1.0e-9 * carrier_s_ref)
+ weights[n_count : 3 * n_count] = min(w_cont, max(w_c_step, 1.0e-20))
+ for carrier, offset in (("n", n_count), ("p", 2 * n_count)):
+ for side, node in (("left", 0), ("right", n_count - 1)):
+ if comp.channel(carrier, side).kind == "fixed_reservoir":
+ weights[offset + node] = 1.0e11
+
+ inv_ref = max(device.reference_iodine_inventory_m2, 1.0)
+ # Per-species diagonal flux scaling aligned with merit = 0.5 * ||scaled||_2^2:
+ # monomer rows stay >=20x above PVK fast-redox ULP (~1.6e-12 A/m^2), while trace I_2
+ # enforces 1e-13 A/m^2 (~75x above I_2 ULP) so outgassing equilibrates at every step.
+ if step.endpoint.generation_scale > 0.0:
+ w_flux = m_count * Q / chem_flux_tolerance_A_m2
+ w_step = (m_count * dt_s) / (inventory_relative_tolerance * inv_ref)
+ weights[3 * n_count :] = min(w_flux, max(w_step, 1.0e-20))
+ assert device.volumetric_mol_escape_s_1 is not None
+ vol_mask = device.volumetric_mol_escape_s_1 > 0.0
+ if np.any(vol_mask):
+ w_vol = min(
+ 3.0 * m_count * Q / min(chem_flux_tolerance_A_m2, 5.0e-13),
+ max(w_step * 4.0e3, 1.0e-20),
+ )
+ weights[3 * n_count + 2 * m_count :][vol_mask] = np.maximum(
+ weights[3 * n_count + 2 * m_count :][vol_mask], w_vol
+ )
+ else:
+ w_flux = 3.0 * m_count * Q / 1.0e-12
+ w_step = (6.0 * m_count * dt_s) / (inventory_relative_tolerance * inv_ref)
+ weights[3 * n_count :] = min(w_flux, max(w_step, 1.0e-20))
+
+ iodide_step = (
+ 10.0 if device.steric_site_limit_m3 is not None else chem_coordinate_step
+ )
+ max_step = np.concatenate(
+ (
+ np.full(n_count, potential_step_V),
+ np.full(2 * n_count, quasi_fermi_step),
+ np.full(m_count, iodide_step),
+ np.full(2 * m_count, chem_coordinate_step),
+ )
+ )
+ lower = np.concatenate(
+ (
+ np.full(3 * n_count, -math.inf),
+ np.full(3 * m_count, -220.0),
+ )
+ )
+ return NewtonSettings(
+ scaling=ResidualScaling(weights),
+ tolerance=1.0,
+ step_control=StepControl(max_step, lower=lower),
+ budget=SolveBudget(
+ max_iterations=max_iterations,
+ max_residual_evaluations=max_iterations * 18,
+ max_jacobian_evaluations=max_iterations + 2,
+ max_backtracks=16,
+ ),
+ gates=(_positive_species_gate(device, step.endpoint.voltage_V),),
+ reuse_jacobian=False,
+ )
+
+
+def _carrier_density_basin_lift(
+ problem: SteadyProblem,
+ device: CompiledIodineDevice1D,
+ u: Vector,
+ voltage_V: float,
+) -> Vector:
+ """Linear-density carrier seed eliminating wide-gap log-coordinate stagnation."""
+ n_count = device.node_count
+ comp = device.electronic_component
+ u_cur = np.array(u, dtype=np.float64, copy=True)
+ fixed_local: list[int] = []
+ for carrier, offset in (("n", 0), ("p", n_count)):
+ for side, node in (("left", 0), ("right", n_count - 1)):
+ if comp.channel(carrier, side).kind == "fixed_reservoir":
+ fixed_local.append(offset + node)
+
+ for _ in range(4):
+ _, n, p = comp.fields(u_cur[: 3 * n_count], voltage_V=voltage_V)
+ f_all = problem.residual(u_cur)
+ if float(np.max(np.abs(f_all[n_count : 3 * n_count]))) * Q < 1.0e-6:
+ break
+ j_all = problem.jacobian(u_cur)
+ f_np = np.array(f_all[n_count : 3 * n_count], dtype=np.float64, copy=True)
+ inv_scale = np.concatenate((1.0 / n, -1.0 / p))
+ j_np = (
+ j_all[n_count : 3 * n_count, n_count : 3 * n_count] @ diags(inv_scale)
+ ).tolil()
+ for r_idx in fixed_local:
+ j_np.rows[r_idx] = [r_idx]
+ j_np.data[r_idx] = [1.0]
+ f_np[r_idx] = 0.0
+ try:
+ inc = factorize(j_np.tocsc()).solve(-f_np)
+ except Exception:
+ break
+ if not np.all(np.isfinite(inc)):
+ break
+ trial_n = np.maximum(n + inc[:n_count], 0.1 * n)
+ trial_p = np.maximum(p + inc[n_count:], 0.1 * p)
+ u_cur[n_count : 2 * n_count] += np.log(trial_n) - np.log(n)
+ u_cur[2 * n_count : 3 * n_count] -= np.log(trial_p) - np.log(p)
+ return frozen_array(u_cur)
+
+
+def _chem_density_basin_lift(
+ problem: SteadyProblem,
+ device: CompiledIodineDevice1D,
+ u: Vector,
+ voltage_V: float,
+ *,
+ freeze_iodide: bool = False,
+) -> Vector:
+ """Linear-density chemical seed eliminating trace-species Softplus stagnation."""
+ n_elec = 3 * device.node_count
+ m = device.chem_node_count
+ u_cur = np.array(u, dtype=np.float64, copy=True)
+ for _ in range(8):
+ try:
+ _, _, _, cm, c0, c2, mm, m0, m2 = device.fields_and_tangents(
+ u_cur, voltage_V=voltage_V
+ )
+ f_chem = problem.residual(u_cur)[n_elec:]
+ if float(np.max(np.abs(f_chem))) * Q < 1.0e-8:
+ break
+ if freeze_iodide:
+ inv_tan_n = 1.0 / np.concatenate((m0, m2))
+ j_neut = problem.jacobian(u_cur)[n_elec + m :, n_elec + m :] @ diags(
+ inv_tan_n
+ )
+ dc_neut = factorize(j_neut.tocsc()).solve(-f_chem[m:])
+ dc = np.concatenate((np.zeros(m, dtype=np.float64), dc_neut))
+ else:
+ inv_tan = 1.0 / np.concatenate((mm, m0, m2))
+ j_chem = problem.jacobian(u_cur)[n_elec:, n_elec:] @ diags(inv_tan)
+ dc = factorize(j_chem.tocsc()).solve(-f_chem)
+ except Exception:
+ break
+ if not np.all(np.isfinite(dc)):
+ break
+ cm_n = cm if freeze_iodide else np.maximum(cm + dc[:m], 0.1 * cm)
+ c0_n = np.maximum(c0 + dc[m : 2 * m], 0.1 * c0)
+ c2_n = np.maximum(c2 + dc[2 * m :], 0.1 * c2)
+ if device.steric_site_limit_m3 is not None:
+ cm_n = np.minimum(cm_n, 0.999999 * device.steric_site_limit_m3)
+ u_cur[n_elec:] = np.maximum(
+ np.concatenate(
+ (
+ device.iodide_map.coordinate_from_density(cm_n),
+ device.atom_map.coordinate_from_density(c0_n),
+ device.mol_map.coordinate_from_density(c2_n),
+ )
+ ),
+ -115.0,
+ )
+ return frozen_array(u_cur)
+
+
+def _inferred_voltage_V(device: CompiledIodineDevice1D, u: Vector) -> float:
+ comp = device.electronic_component
+ n_c = comp.node_count
+ dphi_contacts = float(u[n_c - 1] - u[0])
+ return float((comp.built_in_potential_V - dphi_contacts) / comp.voltage_polarity)
+
+
+def iodine_bdf_seed(step: BDFStep) -> Vector:
+ """Harmonic potential & BDF-step homotopy lift across voltage/light jumps."""
+ if not isinstance(step.endpoint, AssembledIodine1DProblem):
+ raise TypeError("iodine_bdf_seed requires AssembledIodine1DProblem")
+ prev = step.history[0]
+ u_cur = np.array(prev.u, dtype=np.float64, copy=True)
+ dev = step.endpoint.device
+ u_cur[3 * dev.node_count :] = np.maximum(u_cur[3 * dev.node_count :], -115.0)
+ v_prev = _inferred_voltage_V(dev, u_cur)
+ v_next = step.endpoint.voltage_V
+ if abs(v_next - v_prev) > 1.0e-13:
+ u_cur = np.array(
+ _harmonic_voltage_lift(dev, u_cur, v_prev, v_next),
+ dtype=np.float64,
+ copy=True,
+ )
+
+ bdf_norm = iodine_convergence_norm(dev, constrained_steady=False)
+ base_settings = iodine_bdf_newton_settings(step)
+ f_try = step.residual(u_cur)
+ scaled_try = base_settings.scaling.scaled(f_try)
+ if float(np.max(np.abs(scaled_try[3 * dev.node_count :]))) > 10.0:
+ p_comp = dev.electronic_component.parameters
+ undoped_bl = (
+ max(float(p_comp.donor_density_m3[0]), float(p_comp.acceptor_density_m3[0]))
+ < 1.0e22
+ and max(
+ float(p_comp.donor_density_m3[-1]),
+ float(p_comp.acceptor_density_m3[-1]),
+ )
+ < 1.0e22
+ )
+ u_cur = np.array(
+ _chem_density_basin_lift(
+ CallableProblem(step.residual, step.jacobian),
+ dev,
+ u_cur,
+ v_next,
+ freeze_iodide=undoped_bl and abs(v_next - v_prev) <= 1.0e-12,
+ ),
+ dtype=np.float64,
+ copy=True,
+ )
+ f_try = step.residual(u_cur)
+ scaled_try = base_settings.scaling.scaled(f_try)
+
+ # Full-Jacobian elemental conservation polish when long BDF steps accumulate
+ # open outgassing / contact oxidation below the per-row monomer ULP flux cap.
+ if dev.has_open_iodine_loss and step.dt_s >= 1.0 and bdf_norm(scaled_try) <= 1.2:
+ m_c = dev.chem_node_count
+ n_e = 3 * dev.node_count
+ inv_ref = max(dev.reference_iodine_inventory_m2, 1.0)
+ tot_imb = abs(
+ math.fsum(
+ (
+ f_try[n_e : n_e + m_c]
+ + f_try[n_e + m_c : n_e + 2 * m_c]
+ + 2.0 * f_try[n_e + 2 * m_c :]
+ ).tolist()
+ )
+ )
+ if tot_imb * step.dt_s > 5.0e-11 * inv_ref:
+ for _ in range(2):
+ try:
+ du_p = factorize(step.jacobian(u_cur).tocsc()).solve(-f_try)
+ except Exception:
+ break
+ if not np.all(np.isfinite(du_p)):
+ break
+ alpha_p = base_settings.step_control.step_fraction(u_cur, du_p)
+ u_next = u_cur + alpha_p * du_p
+ if not base_settings.step_control.feasible(u_next):
+ break
+ try:
+ f_next = step.residual(u_next)
+ except Exception:
+ break
+ if not np.all(np.isfinite(f_next)):
+ break
+ u_cur = u_next
+ f_try = f_next
+ tot_imb = abs(
+ math.fsum(
+ (
+ f_try[n_e : n_e + m_c]
+ + f_try[n_e + m_c : n_e + 2 * m_c]
+ + 2.0 * f_try[n_e + 2 * m_c :]
+ ).tolist()
+ )
+ )
+ if tot_imb * step.dt_s <= 1.0e-11 * inv_ref:
+ break
+ scaled_try = base_settings.scaling.scaled(f_try)
+ scaled_norm = bdf_norm(scaled_try)
+ if len(step.history) > 1 or abs(v_next - v_prev) <= 0.05 or scaled_norm <= 1.0e4:
+ return frozen_array(u_cur)
+
+ # Discontinuous drive step: homotopy from (0 V, 0 Sun) -> (0 V, g_next) -> (v_next, g_next)
+ # on the exact BDFStep while keeping step.history completely untouched!
+ g_next = step.endpoint.generation_scale
+ cur_v = v_next
+ if abs(cur_v) > 1.0e-13:
+ u_cur = np.array(
+ _harmonic_voltage_lift(dev, u_cur, cur_v, 0.0),
+ dtype=np.float64,
+ copy=True,
+ )
+ cur_v = 0.0
+ cur_g = 0.0
+ stages: list[tuple[float, float]] = [(0.0, 0.0)]
+ if g_next > 0.0:
+ for frac in (1.0e-5, 1.0e-3, 0.03, 0.25, 1.0):
+ stages.append((0.0, g_next * frac))
+ if abs(v_next) > 1.0e-13:
+ n_v = max(1, int(math.ceil(abs(v_next) / 0.08)))
+ for k in range(1, n_v + 1):
+ stages.append((v_next * (k / n_v), g_next))
+
+ queue: list[tuple[float, float, int]] = [
+ (v_s, g_s, 0) for v_s, g_s in reversed(stages)
+ ]
+ while queue:
+ v_s, g_s, depth = queue.pop()
+ sub_end = AssembledIodine1DProblem(
+ device=dev,
+ voltage_V=v_s,
+ generation_scale=g_s,
+ binding=step.endpoint.binding,
+ )
+ sub_step = BDFStep(sub_end, step.history, step.end_s, step.order)
+ u_try = u_cur
+ if abs(v_s - cur_v) > 1.0e-13:
+ u_try = np.array(
+ _harmonic_voltage_lift(dev, u_try, cur_v, v_s),
+ dtype=np.float64,
+ copy=True,
+ )
+ if g_s > cur_g:
+ u_try = np.array(
+ _carrier_density_basin_lift(
+ CallableProblem(sub_step.residual, sub_step.jacobian),
+ dev,
+ u_try,
+ v_s,
+ ),
+ dtype=np.float64,
+ copy=True,
+ )
+ sub_res = solve_newton(
+ CallableProblem(sub_step.residual, sub_step.jacobian),
+ u_try,
+ iodine_bdf_newton_settings(sub_step),
+ convergence_norm=bdf_norm,
+ )
+ if sub_res.accepted:
+ u_cur = np.array(sub_res.state, dtype=np.float64, copy=True)
+ cur_v, cur_g = v_s, g_s
+ elif depth < 6 and (
+ abs(v_s - cur_v) > 2.0e-3 or abs(g_s - cur_g) > 1.0e-8
+ ):
+ v_mid = 0.5 * (cur_v + v_s)
+ g_mid = (
+ math.sqrt(cur_g * g_s)
+ if (cur_g > 0.0 and g_s / cur_g > 4.0)
+ else 0.5 * (cur_g + g_s)
+ )
+ queue.append((v_s, g_s, depth + 1))
+ queue.append((v_mid, g_mid, depth + 1))
+ else:
+ break
+ if abs(v_next - cur_v) > 1.0e-13:
+ u_cur = np.array(
+ _harmonic_voltage_lift(dev, u_cur, cur_v, v_next),
+ dtype=np.float64,
+ copy=True,
+ )
+ return frozen_array(u_cur)
+
+
+def iodine_step_accounting(step: BDFStep, u: Vector) -> IodineStepAccounting:
+ """Compute exact BDF step iodine inventory balance and Maxwell current spread."""
+ if not isinstance(step.endpoint, AssembledIodine1DProblem):
+ raise TypeError("iodine_step_accounting requires AssembledIodine1DProblem")
+ endpoint = step.endpoint
+ device = endpoint.device
+ old = step.history[0]
+ if not isinstance(old.problem, AssembledIodine1DProblem):
+ raise TypeError("history problem must be AssembledIodine1DProblem")
+
+ phys_rate = (
+ step.coefficients[0] * endpoint.physical_increment(u, old.problem, old.u) / step.dt_s
+ )
+ if step.order == 2:
+ older = step.history[1]
+ assert isinstance(older.problem, AssembledIodine1DProblem)
+ phys_rate -= (
+ step.coefficients[2]
+ * old.problem.physical_increment(old.u, older.problem, older.u)
+ / step.dt_s
+ )
+
+ slices = device.chem_slices
+ d_cm_dt = phys_rate[slices["iodide"]]
+ d_c0_dt = phys_rate[slices["iodine_atom"]]
+ d_c2_dt = phys_rate[slices["iodine_molecule"]]
+ d_iodine_rate_m2_s = math.fsum((d_cm_dt + d_c0_dt + 2.0 * d_c2_dt).tolist())
+
+ brates = endpoint.boundary_rates_m2_s(u)
+ esc_atoms_rate = 2.0 * (
+ brates["mol_escape_left_m2_s"]
+ + brates["mol_escape_right_m2_s"]
+ + brates["volumetric_mol_escape_m2_s"]
+ )
+ immob_rate = 0.0
+ if device.left_boundary.contact_reaction_mode in (
+ "immobilized_product_sheet",
+ "metal_faradaic_corrosion",
+ ):
+ immob_rate += brates["contact_oxidation_left_m2_s"]
+ if device.right_boundary.contact_reaction_mode in (
+ "immobilized_product_sheet",
+ "metal_faradaic_corrosion",
+ ):
+ immob_rate += brates["contact_oxidation_right_m2_s"]
+
+ # Discrete BDF balance: dM_I/dt + esc_atoms_rate + immob_rate == 0
+ step_cons_res_m2 = (d_iodine_rate_m2_s + esc_atoms_rate + immob_rate) * step.dt_s
+
+ # Maxwell total current across every interior face: J_cond + dD_face/dt
+ j_cond = endpoint.face_conduction_current_A_m2(u)
+ cap = device.electronic_component.poisson.face_capacitance_F_m2
+ n_count = device.node_count
+ dphi_new = np.diff(u[:n_count])
+ dphi_old = np.diff(old.u[:n_count])
+ dd_dt = step.coefficients[0] * (-cap * (dphi_new - dphi_old)) / step.dt_s
+ if step.order == 2:
+ dphi_older = np.diff(step.history[1].u[:n_count])
+ dd_dt -= step.coefficients[2] * (-cap * (dphi_old - dphi_older)) / step.dt_s
+ j_total_faces = j_cond + dd_dt
+ dx = np.diff(device.electronic_component.nodes_m)
+ j_term = float(math.fsum((dx * j_total_faces).tolist()) / math.fsum(dx.tolist()))
+ spread = float(np.max(j_total_faces) - np.min(j_total_faces))
+
+ state = device.state(u, voltage_V=endpoint.voltage_V)
+ return IodineStepAccounting(
+ start_s=old.time_s,
+ end_s=step.end_s,
+ dt_s=step.dt_s,
+ in_device_iodine_m2=state.total_iodine_inventory_m2,
+ step_escaped_iodine_atoms_m2=esc_atoms_rate * step.dt_s,
+ step_immobilized_iodine_atoms_m2=immob_rate * step.dt_s,
+ step_conservation_residual_m2=step_cons_res_m2,
+ terminal_current_A_m2=j_term,
+ max_total_current_spread_A_m2=spread,
+ )
+
+
+def _harmonic_voltage_lift(
+ device: CompiledIodineDevice1D, u: Vector, v_from: float, v_to: float
+) -> Vector:
+ if v_to == v_from:
+ return u
+ comp = device.electronic_component
+ n_c = comp.node_count
+ u_mut = np.array(u, dtype=np.float64, copy=True)
+ values = comp.rebase_coordinates(u_mut[: 3 * n_c], v_from, v_to)
+ resistance = 1.0 / comp.poisson.face_capacitance_F_m2
+ profile = np.r_[0.0, np.cumsum(resistance)]
+ profile /= profile[-1]
+ change = -comp.voltage_polarity * (v_to - v_from)
+ before = values[:n_c].copy()
+ values[:n_c] += change * profile
+ shift = (values[:n_c] - before) / comp.thermal_voltage_V
+ values[n_c : 2 * n_c] -= shift
+ values[2 * n_c : 3 * n_c] -= shift
+ u_mut[: 3 * n_c] = values
+ return frozen_array(u_mut)
+
+
+def _local_steady_iodine_coordinates(
+ device: CompiledIodineDevice1D,
+ elec_u: Vector,
+ voltage_V: float,
+ *,
+ cell_total_iodine_m3: Vector | None = None,
+) -> Vector:
+ """Closed-form local photochemical steady seed conserving cell iodine."""
+ if device.is_unreactive_limit:
+ return device.initial_coordinates(voltage_V=voltage_V, electronic_u=elec_u)
+ _, n_full, p_full = device.electronic_component.fields(elec_u, voltage_V=voltage_V)
+ idx = device.chem_node_indices
+ n = n_full[idx]
+ p = p_full[idx]
+ kin = device.kinetics
+ assert kin.n_1_iodine_m3 is not None and kin.k_e_3body_m6_s is not None
+ reversible = kin.thermodynamic_mode == "wegscheider_detailed_balance"
+ n1 = kin.n_1_iodine_m3 if reversible else np.zeros_like(n)
+ k_diss = kin.K_diss_m3
+
+ # Monomer quasi-steady ratio r0 = c_0 / c_-
+ denom_0 = kin.k_b_s_1 + kin.k_c_m3_s * n
+ r0 = np.where(
+ denom_0 > 0.0,
+ (kin.k_a_m3_s * p + kin.k_c_m3_s * n1) / np.maximum(denom_0, 1.0e-30),
+ 0.0,
+ )
+
+ # Dimer quasi-steady quadratic coefficient q2 = c_2 / c_-^2
+ if kin.reaction_e_order == "bimolecular_n":
+ if reversible:
+ ke_eff = kin.k_e_m3_s / np.maximum(n + kin.n_e_star_m3, 1.0e-30)
+ ke_fwd = ke_eff * (n * n)
+ else:
+ ke_eff = np.zeros_like(n)
+ ke_fwd = kin.k_e_m3_s * n
+ else:
+ ke_eff = kin.k_e_3body_m6_s if reversible else np.zeros_like(n)
+ ke_fwd = kin.k_e_3body_m6_s * (n * n)
+
+ assert device.volumetric_mol_escape_s_1 is not None
+ alpha_e = (n1 * n1) / k_diss if reversible else np.zeros_like(n)
+ num_2 = kin.k_d_m3_s * (r0 * r0) + ke_eff * alpha_e
+ den_2 = (
+ (kin.k_d_m3_s * k_diss if reversible else 0.0)
+ + ke_fwd
+ + device.volumetric_mol_escape_s_1
+ )
+ q2 = np.where(den_2 > 0.0, num_2 / np.maximum(den_2, 1.0e-30), 0.0)
+
+ c_tot = (
+ device.initial_total_iodine_atoms_m3
+ if cell_total_iodine_m3 is None
+ else cell_total_iodine_m3
+ )
+ lin_b = 1.0 + r0
+ disc = np.sqrt(lin_b * lin_b + 8.0 * q2 * c_tot)
+ cm = (2.0 * c_tot) / (lin_b + disc)
+ # Clamp trace c0, c2 at vacuum_floor_m3 so coordinates stay O(1) while
+ # keeping residual << 1.0 and adjusting cm to conserve c_tot!
+ floor_0 = getattr(device.atom_map, "vacuum_floor_m3", 1.0)
+ floor_2 = getattr(device.mol_map, "vacuum_floor_m3", 1.0)
+ c0 = np.maximum(r0 * cm, floor_0 * 1.0e-3)
+ c2 = np.maximum(q2 * (cm * cm), floor_2 * 1.0e-3)
+ cm = np.maximum(c_tot - c0 - 2.0 * c2, c_tot * 0.5)
+
+ u_chem = np.concatenate(
+ (
+ device.iodide_map.coordinate_from_density(cm),
+ device.atom_map.coordinate_from_density(c0),
+ device.mol_map.coordinate_from_density(c2),
+ )
+ )
+ return frozen_array(np.concatenate((elec_u, u_chem)))
+
+
+def _poisson_boltzmann_dark_seed(device: CompiledIodineDevice1D) -> Vector:
+ """Grand-canonical 1D Poisson-Boltzmann + Wegscheider dark equilibrium seed."""
+ comp = device.electronic_component
+ n_count = device.node_count
+ idx = device.chem_node_indices
+ w_chem = device.chem_geometry.cell_measures_m
+ w_e = comp.geometry.cell_measures_m
+ vt = comp.thermal_voltage_V
+ l_pot, r_pot = comp.contact_potentials(0.0)
+ phi = l_pot + (r_pot - l_pot) * (
+ (comp.nodes_m - comp.nodes_m[0]) / comp.geometry.extent_m
+ )
+ k_part_m = np.exp(
+ np.concatenate(([0.0], np.cumsum(device.log_partition_minus_faces)))
+ )
+ k_part_0 = np.exp(
+ np.concatenate(([0.0], np.cumsum(device.log_partition_atom_faces)))
+ )
+ k_part_2 = np.exp(
+ np.concatenate(([0.0], np.cumsum(device.log_partition_mol_faces)))
+ )
+ m_tot = device.reference_iodine_inventory_m2
+ m_minus_only = device.reference_species_inventories_m2["iodide"]
+ j_disp = comp.poisson.jacobian().toarray()
+ ratio = device.chem_weight_ratio
+ kin = device.kinetics
+ use_weg = (
+ kin.thermodynamic_mode == "wegscheider_detailed_balance"
+ and not device.is_unreactive_limit
+ and kin.n_1_iodine_m3 is not None
+ and bool(np.any(kin.n_1_iodine_m3 > 0.0))
+ )
+
+ for _ in range(120):
+ u_e = np.concatenate((phi, np.zeros(2 * n_count)))
+ _, n, p = comp.fields(u_e, voltage_V=0.0)
+ phi_ref_max = float(np.max(phi[idx]))
+ bm = k_part_m * np.exp((phi[idx] - phi_ref_max) / vt)
+ if use_weg:
+ assert kin.n_1_iodine_m3 is not None
+ act = kin.n_1_iodine_m3 > 0.0
+ first_act = int(np.flatnonzero(act)[0])
+ b0_unit = float(
+ (bm[first_act] * kin.n_1_iodine_m3[first_act])
+ / (n[idx[first_act]] * k_part_0[first_act])
+ )
+ b0 = b0_unit * k_part_0
+ kdiss_0 = float(kin.K_diss_m3[first_act]) / (
+ (k_part_0[first_act] ** 2) / k_part_2[first_act]
+ )
+ b2 = ((b0_unit * b0_unit) / kdiss_0) * k_part_2
+ a1 = float(np.sum(w_chem * (bm + b0)))
+ q2 = float(np.sum(2.0 * w_chem * b2))
+ disc = math.sqrt(a1 * a1 + 4.0 * q2 * m_tot)
+ alpha = (2.0 * m_tot) / (a1 + disc) if (a1 + disc) > 0.0 else 0.0
+ d_alpha_dphi = -(alpha / max(a1 + 2.0 * q2 * alpha, 1.0e-30)) * (
+ w_chem * bm / vt
+ )
+ else:
+ z_norm = max(float(np.sum(w_chem * bm)), 1.0e-30)
+ alpha = m_minus_only / z_norm
+ d_alpha_dphi = -(alpha / z_norm) * (w_chem * bm / vt)
+ cm = alpha * bm
+ rho = device.charge_ledger(n, p, cm).space_charge_C_m3()
+ f_phi = comp.poisson.residual(phi, rho, l_pot, r_pot)
+ if float(np.max(np.abs(f_phi[1:-1]))) < 1.0e-13:
+ break
+ j_pb = j_disp.copy()
+ diag_sc = -Q * w_e * (n + p) / vt
+ diag_sc[idx] -= Q * w_e[idx] * ratio * cm / vt
+ diag_sc[0] = 0.0
+ diag_sc[-1] = 0.0
+ j_pb += np.diag(diag_sc)
+ row_vec = -Q * w_e[idx] * ratio * bm
+ if int(idx[0]) == 0:
+ row_vec[0] = 0.0
+ if int(idx[-1]) == n_count - 1:
+ row_vec[-1] = 0.0
+ j_pb[np.ix_(idx, idx)] += np.outer(row_vec, d_alpha_dphi)
+ dphi = -np.linalg.solve(j_pb, f_phi)
+ step = min(1.0, 0.15 / max(float(np.max(np.abs(dphi))), 1.0e-30))
+ phi = phi + step * dphi
+
+ u_e = np.concatenate((phi, np.zeros(2 * n_count)))
+ _, n, _ = comp.fields(u_e, voltage_V=0.0)
+ bm = k_part_m * np.exp((phi[idx] - float(np.max(phi[idx]))) / vt)
+ if use_weg:
+ assert kin.n_1_iodine_m3 is not None
+ act = kin.n_1_iodine_m3 > 0.0
+ first_act = int(np.flatnonzero(act)[0])
+ b0_unit = float(
+ (bm[first_act] * kin.n_1_iodine_m3[first_act])
+ / (n[idx[first_act]] * k_part_0[first_act])
+ )
+ b0 = b0_unit * k_part_0
+ kdiss_0 = float(kin.K_diss_m3[first_act]) / (
+ (k_part_0[first_act] ** 2) / k_part_2[first_act]
+ )
+ b2 = ((b0_unit * b0_unit) / kdiss_0) * k_part_2
+ a1 = float(np.sum(w_chem * (bm + b0)))
+ q2 = float(np.sum(2.0 * w_chem * b2))
+ disc = math.sqrt(a1 * a1 + 4.0 * q2 * m_tot)
+ alpha = (2.0 * m_tot) / (a1 + disc)
+ cm = alpha * bm
+ c0 = np.maximum(alpha * b0, 1.0)
+ c2 = np.maximum((alpha * alpha) * b2, 1.0)
+ else:
+ z_norm = max(float(np.sum(w_chem * bm)), 1.0e-30)
+ cm = np.maximum((m_minus_only / z_norm) * bm, 1.0)
+ c0 = np.maximum(device.initial_atom_m3, 1.0)
+ c2 = np.maximum(device.initial_mol_m3, 1.0)
+ return frozen_array(
+ np.concatenate(
+ (
+ u_e,
+ device.iodide_map.coordinate_from_density(cm),
+ device.atom_map.coordinate_from_density(c0),
+ device.mol_map.coordinate_from_density(c2),
+ )
+ )
+ )
+
+
+def solve_iodine_steady_state(
+ device: CompiledIodineDevice1D,
+ *,
+ voltage_V: float = 0.0,
+ generation_scale: float = 0.0,
+ initial_u: Vector | None = None,
+ inventory_node: int = 0,
+ options: IodineSteadyOptions = IodineSteadyOptions(),
+) -> IodineSteadyResult:
+ """Solve closed-domain coupled steady state from exact PB dark equilibrium."""
+ system = iodine_system(
+ device, constrained_steady=True, inventory_node=inventory_node
+ )
+ unconstrained = iodine_system(device, constrained_steady=False)
+
+ if initial_u is None:
+ if device.steric_site_limit_m3 is None:
+ u_curr = _poisson_boltzmann_dark_seed(device)
+ else:
+ eq_seed = solve_equilibrium(
+ device.electronic_component,
+ options=SteadyOptions(convergence_policy=POISSON_CONTACT_BALANCE_V1),
+ )
+ u_curr = _local_steady_iodine_coordinates(device, eq_seed.state.u, 0.0)
+ prev_v = 0.0
+ stages: list[tuple[float, float]] = [(0.0, 0.0)]
+ comp_p = device.electronic_component.parameters
+ undoped_contacts = bool(
+ (comp_p.donor_density_m3[0] + comp_p.acceptor_density_m3[0]) < 1.0e15
+ or (comp_p.donor_density_m3[-1] + comp_p.acceptor_density_m3[-1]) < 1.0e15
+ )
+ if undoped_contacts and voltage_V > 0.3 and generation_scale > 0.0:
+ # Ramp forward bias in the dark first to reduce junction barrier and
+ # avoid SCLC extraction bottlenecks in undoped low-mobility blocking layers.
+ n_v = max(1, int(math.ceil(abs(voltage_V) / 0.10)))
+ for k in range(1, n_v + 1):
+ stages.append((voltage_V * (k / n_v), 0.0))
+ for frac in (1.0e-5, 1.0e-3, 0.03, 0.15, 0.45, 0.75, 1.0):
+ stages.append((voltage_V, generation_scale * frac))
+ else:
+ if generation_scale > 0.0:
+ for frac in (1.0e-5, 1.0e-3, 0.03, 0.25, 1.0):
+ stages.append((0.0, generation_scale * frac))
+ if voltage_V != 0.0:
+ n_v = max(1, int(math.ceil(abs(voltage_V) / 0.10)))
+ for k in range(1, n_v + 1):
+ stages.append((voltage_V * (k / n_v), generation_scale))
+ else:
+ u_curr = frozen_array(initial_u)
+ prev_v = voltage_V
+ stages = [(voltage_V, generation_scale)]
+
+ last_newton: NewtonResult | None = None
+ total_iters = 0
+ prev_g = 0.0 if initial_u is None else generation_scale
+
+ steady_norm = iodine_convergence_norm(
+ device, constrained_steady=True, inventory_node=inventory_node
+ )
+ bdf_norm = iodine_convergence_norm(device, constrained_steady=False)
+ stage_stack: list[tuple[float, float, int]] = [
+ (v_s, g_s, 0) for v_s, g_s in reversed(stages)
+ ]
+ while stage_stack:
+ v_step, g_step, depth = stage_stack.pop()
+ u_trial = _harmonic_voltage_lift(device, u_curr, prev_v, v_step)
+ prob = AssembledConstrainedIodine1DProblem(
+ device=device,
+ voltage_V=v_step,
+ generation_scale=g_step,
+ inventory_node=inventory_node,
+ binding=system,
+ )
+ if g_step > prev_g:
+ u_trial = _carrier_density_basin_lift(
+ CallableProblem(prob.residual, prob.jacobian),
+ device,
+ u_trial,
+ v_step,
+ )
+ settings = iodine_steady_newton_settings(
+ device,
+ voltage_V=v_step,
+ inventory_node=inventory_node,
+ options=options,
+ )
+ res = solve_newton(
+ CallableProblem(prob.residual, prob.jacobian),
+ u_trial,
+ settings,
+ convergence_norm=steady_norm,
+ )
+ total_iters += res.iteration_count
+ if (
+ (not res.accepted or res.termination != Termination.CONVERGED)
+ and depth < 6
+ and (abs(v_step - prev_v) > 2.0e-3 or abs(g_step - prev_g) > 1.0e-8)
+ ):
+ v_mid = 0.5 * (prev_v + v_step)
+ g_mid = (
+ math.sqrt(prev_g * g_step)
+ if (prev_g > 0.0 and g_step / prev_g > 4.0)
+ else 0.5 * (prev_g + g_step)
+ )
+ stage_stack.append((v_step, g_step, depth + 1))
+ stage_stack.append((v_mid, g_mid, depth + 1))
+ continue
+ if not res.accepted or res.termination != Termination.CONVERGED:
+ # Mass-regularized BDF relaxation into steady basin followed by exact polish
+ ptc_opts = BDFOptions(
+ initial_step_s=1.0e-6,
+ min_step_s=1.0e-14,
+ max_step_s=200.0,
+ relative_tolerance=5.0e-3,
+ absolute_tolerance=1.0e14,
+ max_order=1,
+ max_factor=2.0,
+ max_steps=250,
+ wall_s=options.wall_s,
+ )
+
+ def _ptc_factory(_t: float, _side: str) -> AssembledIodine1DProblem:
+ return AssembledIodine1DProblem(
+ device=device,
+ voltage_V=v_step,
+ generation_scale=g_step,
+ binding=unconstrained,
+ )
+
+ ptc_bdf = solve_bdf(
+ _ptc_factory,
+ u_trial,
+ (0.0, 200.0),
+ options=ptc_opts,
+ settings=iodine_bdf_newton_settings,
+ seed=iodine_bdf_seed,
+ convergence_norm=bdf_norm,
+ )
+ total_iters += ptc_bdf.nonlinear_calls
+ if ptc_bdf.accepted_coordinates:
+ u_warm = ptc_bdf.accepted_coordinates[-1]
+ res = solve_newton(
+ CallableProblem(prob.residual, prob.jacobian),
+ u_warm,
+ settings,
+ convergence_norm=steady_norm,
+ )
+ total_iters += res.iteration_count
+
+ last_newton = res
+ if not res.accepted or res.termination != Termination.CONVERGED:
+ return IodineSteadyResult(
+ converged=False,
+ state=None,
+ current_density_A_m2=math.nan,
+ termination=res.termination.value,
+ scaled_residual=res.scaled_residual,
+ iterations=total_iters,
+ newton=res,
+ )
+ u_curr = res.state
+ prev_v = v_step
+ prev_g = g_step
+
+ assert last_newton is not None
+ state = device.state(u_curr, voltage_V=voltage_V)
+ obs = AssembledIodine1DProblem(
+ device=device,
+ voltage_V=voltage_V,
+ generation_scale=generation_scale,
+ binding=unconstrained,
+ )
+ j_steady = obs.steady_current_density_A_m2(u_curr)
+ return IodineSteadyResult(
+ converged=True,
+ state=state,
+ current_density_A_m2=j_steady,
+ termination=last_newton.termination.value,
+ scaled_residual=last_newton.scaled_residual,
+ iterations=total_iters,
+ newton=last_newton,
+ )
+
+
+def solve_frozen_chemistry_electronic_1d(
+ device: CompiledIodineDevice1D,
+ u: Vector,
+ *,
+ voltage_V: float,
+ generation_scale: float,
+ prev_voltage_V: float | None = None,
+ binding: IodineSystem | None = None,
+) -> tuple[Vector, float]:
+ """Solve stationary ``3 * N`` electronic rows with frozen chemical coordinates.
+
+ Preserves ``u[3 * N :]`` bit-for-bit (0-ULP iodine species invariance) while
+ relaxing ``(phi, z_n, z_p)`` to ``(voltage_V, generation_scale)``. Returns
+ ``(u_relaxed, electronic_current_density_A_m2)``.
+ """
+ comp = device.electronic_component
+ n_c = device.node_count
+ n_elec = 3 * n_c
+ u_chem = np.array(u[n_elec:], dtype=np.float64, copy=True)
+ v_from = _inferred_voltage_V(device, u) if prev_voltage_V is None else float(prev_voltage_V)
+ v_target = float(voltage_V)
+ g_target = float(generation_scale)
+ _ = binding
+
+ weights = production_residual_scaling(
+ comp,
+ poisson_tolerance=5.0e-9,
+ continuity_tolerance_A_m2=2.0e-6,
+ contact_log_tolerance=1.0e-11,
+ ).row_weights.copy()
+ weights[:n_c] = _poisson_weights_with_ions(device) / 5.0e-9
+ steps = production_coordinates(
+ comp,
+ potential_step_V=0.15,
+ quasi_fermi_step=2.5,
+ ).max_step
+ settings = NewtonSettings(
+ scaling=ResidualScaling(weights),
+ tolerance=1.0,
+ step_control=StepControl(steps),
+ budget=SolveBudget(80, 1400, 82, 16),
+ gates=(),
+ reuse_jacobian=False,
+ )
+ elec_norm = production_convergence_norm(
+ comp, convergence_policy=POISSON_CONTACT_BALANCE_V1
+ )
+
+ # Static space-charge contribution of frozen iodide profile in interior Gauss cells
+ _, _, _, cm_frozen, _, _, _, _, _ = device.fields_and_tangents(u, voltage_V=v_from)
+ w_e = comp.geometry.cell_measures_m
+ net_ion_m3 = device.project_chem_density(cm_frozen) - device.project_chem_density(
+ device.compensating_donor_m3
+ )
+ static_ion_gauss: NDArray[np.float64] = np.zeros(n_c, dtype=np.float64)
+ static_ion_gauss[1:-1] = -Q * w_e[1:-1] * net_ion_m3[1:-1]
+
+ def _f_dc_frozen(ue: Vector, dc_p: DC1DProblem) -> Vector:
+ res_v = dc_p.residual(ue).copy()
+ res_v[:n_c] += static_ion_gauss
+ return res_v
+
+ u_cur = np.array(u, dtype=np.float64, copy=True)
+ p_check = DC1DProblem(comp, v_from, g_target)
+ need_light_ramp = (
+ float(np.max(np.abs(_f_dc_frozen(u_cur[:n_elec], p_check)[n_c:n_elec]))) * Q
+ > 1.0e-2
+ )
+ stages: list[tuple[float, float]] = []
+ if need_light_ramp:
+ if g_target > 0.0:
+ for frac in (1.0e-5, 1.0e-3, 0.03, 0.25, 1.0):
+ stages.append((v_from, g_target * frac))
+ else:
+ for frac in (0.2, 0.02, 1.0e-3, 1.0e-5, 0.0):
+ stages.append((v_from, frac))
+ if abs(v_target - v_from) > 1.0e-13:
+ n_v = max(1, int(math.ceil(abs(v_target - v_from) / 0.10)))
+ for k in range(1, n_v + 1):
+ stages.append((v_from + (v_target - v_from) * (k / n_v), g_target))
+ if not stages:
+ stages.append((v_target, g_target))
+
+ cur_v = v_from
+ cur_g = (0.0 if g_target > 0.0 else 1.0) if need_light_ramp else g_target
+ stack: list[tuple[float, float, int]] = [
+ (vs, gs, 0) for vs, gs in reversed(stages)
+ ]
+ while stack:
+ vs, gs, depth = stack.pop()
+ u_try = _harmonic_voltage_lift(device, u_cur, cur_v, vs)
+ dc_prob = DC1DProblem(comp, vs, gs)
+
+ def _f_e(ue: Vector, _dp: DC1DProblem = dc_prob) -> Vector:
+ return _f_dc_frozen(ue, _dp)
+
+ def _j_e(ue: Vector, _dp: DC1DProblem = dc_prob) -> csc_matrix:
+ return _dp.jacobian(ue)
+
+ if gs > cur_g:
+ # Lift 3N carriers in linear density space against frozen iodide field
+ def _f_full(uf: Vector, _dp: DC1DProblem = dc_prob) -> Vector:
+ out = np.zeros_like(uf)
+ out[:n_elec] = _f_dc_frozen(uf[:n_elec], _dp)
+ return out
+
+ def _j_full(uf: Vector, _dp: DC1DProblem = dc_prob) -> csc_matrix:
+ from scipy.sparse import block_diag, eye
+
+ return csc_matrix(
+ block_diag(
+ (_dp.jacobian(uf[:n_elec]), eye(uf.size - n_elec, format="csc")),
+ format="csc",
+ )
+ )
+
+ u_try = _carrier_density_basin_lift(
+ CallableProblem(_f_full, _j_full), device, u_try, vs
+ )
+
+ res = solve_newton(
+ CallableProblem(_f_e, _j_e),
+ u_try[:n_elec],
+ settings,
+ convergence_norm=elec_norm,
+ )
+ if res.accepted:
+ u_cur = np.concatenate((res.state, u_chem))
+ cur_v, cur_g = vs, gs
+ elif depth < 6 and (abs(vs - cur_v) > 2.0e-3 or abs(gs - cur_g) > 1.0e-8):
+ stack.append((vs, gs, depth + 1))
+ stack.append((0.5 * (cur_v + vs), 0.5 * (cur_g + gs), depth + 1))
+ else:
+ raise SteadyStateError(
+ f"Frozen-chemistry electronic solve failed at V={vs:.4f} V: {res.termination.value}",
+ res,
+ )
+
+ final_dc = DC1DProblem(comp, v_target, g_target)
+ j_elec_faces = final_dc.current_density(u_cur[:n_elec])
+ dx = np.diff(comp.nodes_m)
+ j_mean = float(math.fsum((dx * j_elec_faces).tolist()) / math.fsum(dx.tolist()))
+ return frozen_array(u_cur), j_mean
+
+
+def solve_iodine_bdf_transient(
+ device: CompiledIodineDevice1D,
+ initial_u: Vector,
+ interval_s: tuple[float, float],
+ *,
+ voltage_fn: Callable[[float], float],
+ generation_fn: Callable[[float], float],
+ options: BDFOptions,
+ output_times_s: Sequence[float] | Vector | None = None,
+ breakpoints_s: tuple[float, ...] = (),
+ events: tuple[BDFEvent, ...] = (),
+) -> tuple[BDFResult, tuple[IodineStepAccounting, ...]]:
+ """Integrate the assembled 1D iodine system via adaptive BDF1/2."""
+ binding = iodine_system(device, constrained_steady=False)
+ step_ledger: list[IodineStepAccounting] = []
+
+ start_s = float(interval_s[0])
+ v_u0 = _inferred_voltage_V(device, initial_u)
+ v_start_target = float(voltage_fn(start_s))
+ g_start_target = float(generation_fn(start_s))
+ all_events = list(events)
+ has_start_event = any(ev.time_s == start_s for ev in all_events)
+ n_c = device.node_count
+ probe_right = AssembledIodine1DProblem(
+ device=device,
+ voltage_V=v_start_target,
+ generation_scale=g_start_target,
+ binding=binding,
+ )
+ elec_jump = False
+ if abs(v_u0 - v_start_target) > 1.0e-12:
+ elec_jump = True
+ else:
+ f_e0 = probe_right.residual(initial_u)[n_c : 3 * n_c]
+ if float(np.max(np.abs(f_e0))) * Q > 1.0e-3:
+ elec_jump = True
+ use_auto_start_jump = not has_start_event and elec_jump
+
+ def factory(t_s: float, side: str) -> AssembledIodine1DProblem:
+ if use_auto_start_jump and t_s == start_s and side == "left":
+ return AssembledIodine1DProblem(
+ device=device,
+ voltage_V=v_u0,
+ generation_scale=0.0,
+ binding=binding,
+ )
+ return AssembledIodine1DProblem(
+ device=device,
+ voltage_V=float(voltage_fn(t_s)),
+ generation_scale=float(generation_fn(t_s)),
+ binding=binding,
+ )
+
+ if use_auto_start_jump:
+ def _start_restart(
+ _old_p: object, _new_p: object, left_u: Vector
+ ) -> tuple[Vector, Assessment]:
+ relaxed_u, _ = solve_frozen_chemistry_electronic_1d(
+ device,
+ left_u,
+ voltage_V=v_start_target,
+ generation_scale=g_start_target,
+ prev_voltage_V=v_u0,
+ binding=binding,
+ )
+ chem_unchanged = bool(np.array_equal(relaxed_u[3 * n_c :], left_u[3 * n_c :]))
+ return relaxed_u, Assessment(
+ accounting={
+ "voltage_jump_V": v_start_target - v_u0,
+ "g_jump": g_start_target,
+ },
+ checks=(
+ GateOutcome(
+ "frozen_chemistry_start_relaxation",
+ chem_unchanged,
+ 0.0 if chem_unchanged else 1.0,
+ 0.5,
+ ),
+ ),
+ )
+
+ all_events.insert(
+ 0, BDFEvent(time_s=start_s, restart=_start_restart, name="initial_drive_step")
+ )
+
+ def assess(step: BDFStep, u: Vector) -> Assessment:
+ acct = iodine_step_accounting(step, u)
+ inv_ref = max(device.reference_iodine_inventory_m2, 1.0)
+ rel_err = abs(acct.step_conservation_residual_m2) / inv_ref
+ step_lim = 1.0e-9
+ if (
+ isinstance(step.endpoint, AssembledIodine1DProblem)
+ and step.endpoint.generation_scale > 0.0
+ ):
+ step_lim = max(1.0e-9, (6.0e-8 / Q) * step.dt_s / inv_ref)
+ gate = GateOutcome(
+ "step_iodine_conservation", rel_err <= step_lim, rel_err, step_lim
+ )
+ return Assessment(
+ accounting={
+ "in_device_iodine_m2": acct.in_device_iodine_m2,
+ "step_escaped_iodine_atoms_m2": acct.step_escaped_iodine_atoms_m2,
+ "step_immobilized_iodine_atoms_m2": acct.step_immobilized_iodine_atoms_m2,
+ "step_conservation_residual_m2": acct.step_conservation_residual_m2,
+ "terminal_current_A_m2": acct.terminal_current_A_m2,
+ "max_total_current_spread_A_m2": acct.max_total_current_spread_A_m2,
+ },
+ checks=(gate,),
+ )
+
+ out_arr: NDArray[np.float64] | None = (
+ None
+ if output_times_s is None
+ else np.asarray(output_times_s, dtype=np.float64)
+ )
+ eff_options = options
+ if use_auto_start_jump and not device.is_unreactive_limit:
+ # Match initial step to fastest active electron-capture rate k_c * n + k_b
+ # so step-doubling accepts immediately without burning rejection budget.
+ kin = device.kinetics
+ comp_f = device.electronic_component
+ n_est = max(
+ float(
+ np.max(comp_f.parameters.conduction_dos_m3[device.chem_node_indices])
+ )
+ * 1.0e-3,
+ 1.0e21,
+ )
+ fast_rate = float(np.max(kin.k_b_s_1 + kin.k_c_m3_s * n_est))
+ if fast_rate > 0.0:
+ auto_h0 = max(options.min_step_s * 10.0, 0.02 / fast_rate)
+ if auto_h0 < options.initial_step_s:
+ from dataclasses import replace as _dc_replace
+
+ eff_options = _dc_replace(options, initial_step_s=auto_h0)
+
+ bdf_res = solve_bdf(
+ factory,
+ initial_u,
+ interval_s,
+ options=eff_options,
+ settings=iodine_bdf_newton_settings,
+ assess=assess,
+ seed=iodine_bdf_seed,
+ breakpoints_s=breakpoints_s,
+ events=tuple(all_events),
+ output_times_s=out_arr,
+ convergence_norm=iodine_convergence_norm(device, constrained_steady=False),
+ )
+ prev_esc_step = 0.0
+ prev_immob_step = 0.0
+ for attempt in bdf_res.accepted_steps:
+ assert attempt.assessment is not None
+ acc = attempt.assessment.accounting
+ c0_bdf = float(attempt.coefficients[0])
+ c2_bdf = float(attempt.coefficients[2]) if attempt.order == 2 else 0.0
+ raw_esc = float(acc["step_escaped_iodine_atoms_m2"])
+ raw_immob = float(acc["step_immobilized_iodine_atoms_m2"])
+ # Exact BDF1/2 flux-storage consistent step increments:
+ eff_esc = (c2_bdf * prev_esc_step + raw_esc) / c0_bdf
+ eff_immob = (c2_bdf * prev_immob_step + raw_immob) / c0_bdf
+ prev_esc_step = eff_esc
+ prev_immob_step = eff_immob
+ step_ledger.append(
+ IodineStepAccounting(
+ start_s=attempt.start_s,
+ end_s=attempt.end_s,
+ dt_s=attempt.end_s - attempt.start_s,
+ in_device_iodine_m2=float(acc["in_device_iodine_m2"]),
+ step_escaped_iodine_atoms_m2=eff_esc,
+ step_immobilized_iodine_atoms_m2=eff_immob,
+ step_conservation_residual_m2=float(
+ acc["step_conservation_residual_m2"]
+ ),
+ terminal_current_A_m2=float(acc["terminal_current_A_m2"]),
+ max_total_current_spread_A_m2=float(
+ acc["max_total_current_spread_A_m2"]
+ ),
+ )
+ )
+ return bdf_res, tuple(step_ledger)
diff --git a/src/solarlab_server/app.py b/src/solarlab_server/app.py
index d481881a..a55eac43 100644
--- a/src/solarlab_server/app.py
+++ b/src/solarlab_server/app.py
@@ -30,6 +30,7 @@
from solarlab_server.configuration import ConfigurationPreviewContext
from solarlab_server.job_service import JobService
from solarlab_server.routes.configs import router as configuration_router
+from solarlab_server.routes.iodine import router as iodine_router
from solarlab_server.routes.jobs import router as jobs_router
from solarlab_server.routes.materials import router as materials_router
from solarlab_server.routes.schema import router as schema_router
@@ -129,6 +130,7 @@ async def lifespan(app: FastAPI) -> AsyncIterator[None]:
app.include_router(configuration_router)
app.include_router(materials_router)
app.include_router(jobs_router)
+ app.include_router(iodine_router)
@app.exception_handler(KeyError)
async def not_found(request: Request, error: KeyError) -> JSONResponse:
diff --git a/src/solarlab_server/routes/iodine.py b/src/solarlab_server/routes/iodine.py
new file mode 100644
index 00000000..9c482d5d
--- /dev/null
+++ b/src/solarlab_server/routes/iodine.py
@@ -0,0 +1,197 @@
+"""Bounded HTTP routes for 1D iodine chemistry steady, impedance, and aging runs.
+
+Keeps module import completely free of ``scipy``, ``solarlab.equations``,
+``solarlab.solvers``, and ``solarlab.experiments`` so historical ``RunStore``
+readback and registered job supervisors never load numerical solver modules at
+application startup.
+"""
+
+from __future__ import annotations
+
+from typing import Any
+
+from fastapi import APIRouter, HTTPException, Request
+from pydantic import BaseModel, ConfigDict, Field, ValidationError, model_validator
+from starlette.concurrency import run_in_threadpool
+
+router = APIRouter(prefix="/iodine", tags=["iodine"])
+
+_MAX_HTTP_INTERVALS = 48
+_MAX_HTTP_FREQS = 61
+_MAX_HTTP_STAGES = 8
+_MAX_HTTP_BDF_STEPS = 600
+
+
+class IodineHttpRunRequest(BaseModel):
+ """Bounded HTTP request selecting a packaged preset or inline declarative deck."""
+
+ model_config = ConfigDict(extra="forbid", allow_inf_nan=False)
+
+ preset: str | None = None
+ deck: dict[str, Any] | None = None
+ overrides: dict[str, Any] | None = None
+ persist_to_store: bool = False
+ run_id: str | None = Field(
+ default=None,
+ pattern=r"^[A-Za-z0-9_][A-Za-z0-9_.:-]{0,127}$",
+ )
+
+ @model_validator(mode="after")
+ def _validate_target(self) -> IodineHttpRunRequest:
+ from solarlab.materials.iodine_presets import PACKAGED_IODINE_PRESET_NAMES
+
+ if (self.preset is None) == (self.deck is None):
+ raise ValueError("specify exactly one of 'preset' or 'deck'")
+ if self.preset is not None and self.preset not in PACKAGED_IODINE_PRESET_NAMES:
+ raise ValueError(
+ f"unknown packaged iodine preset {self.preset!r}; "
+ f"available: {list(PACKAGED_IODINE_PRESET_NAMES)}"
+ )
+ return self
+
+
+def _resolve_bounded_http_deck(body: IodineHttpRunRequest) -> tuple[Any, Any]:
+ from solarlab.experiments.iodine_declarative import (
+ IodineDeckInput,
+ IodineOverridesInput,
+ apply_iodine_deck_overrides,
+ load_iodine_deck,
+ )
+
+ if body.preset is not None:
+ base_deck, src = load_iodine_deck(body.preset)
+ else:
+ assert body.deck is not None
+ base_deck, src = load_iodine_deck(body.deck)
+ parsed_overrides = (
+ None
+ if body.overrides is None
+ else IodineOverridesInput.model_validate(body.overrides)
+ )
+ effective = apply_iodine_deck_overrides(base_deck, parsed_overrides)
+
+ intervals = effective.electronic_stack.intervals_per_layer
+ if isinstance(intervals, int):
+ if intervals > _MAX_HTTP_INTERVALS:
+ raise ValueError(
+ f"HTTP intervals_per_layer ({intervals}) exceeds {_MAX_HTTP_INTERVALS}"
+ )
+ else:
+ if len(intervals) > 6 or any(n > _MAX_HTTP_INTERVALS for n in intervals):
+ raise ValueError(
+ f"HTTP intervals_per_layer entries must not exceed {_MAX_HTTP_INTERVALS}"
+ )
+ if effective.impedance.n_frequencies > _MAX_HTTP_FREQS:
+ raise ValueError(
+ f"HTTP n_frequencies ({effective.impedance.n_frequencies}) exceeds {_MAX_HTTP_FREQS}"
+ )
+ if effective.aging is not None:
+ if len(effective.aging.stages) > _MAX_HTTP_STAGES:
+ raise ValueError(
+ f"HTTP aging stages ({len(effective.aging.stages)}) exceed {_MAX_HTTP_STAGES}"
+ )
+ if effective.aging.bdf.max_steps > _MAX_HTTP_BDF_STEPS:
+ data = effective.model_dump(mode="python")
+ data["aging"]["bdf"]["max_steps"] = _MAX_HTTP_BDF_STEPS
+ effective = IodineDeckInput.model_validate(data)
+ return effective, src
+
+
+@router.get("/presets")
+def get_iodine_presets() -> dict[str, Any]:
+ from solarlab.materials.iodine_presets import list_packaged_iodine_preset_summaries
+
+ return {
+ "schema": "solarlab.iodine-presets.v1",
+ "presets": list_packaged_iodine_preset_summaries(),
+ "scientific_acceptance": "not_evaluated",
+ "scientific_qualification": False,
+ }
+
+
+@router.get("/schema")
+def get_iodine_schema() -> dict[str, Any]:
+ from solarlab.experiments.iodine_declarative import export_iodine_deck_schema
+
+ return export_iodine_deck_schema()
+
+
+@router.post("/steady")
+async def post_iodine_steady(body: IodineHttpRunRequest) -> dict[str, Any]:
+ from solarlab.contracts import ContractError
+ from solarlab.equations.dc_1d import CapabilityError
+ from solarlab.experiments.iodine_declarative import execute_iodine_steady_deck
+ from solarlab.solvers.nonlinear.steady_1d import SteadyStateError
+
+ try:
+ deck, src = _resolve_bounded_http_deck(body)
+ return await run_in_threadpool(execute_iodine_steady_deck, deck, source=src)
+ except (
+ CapabilityError,
+ ContractError,
+ SteadyStateError,
+ ValidationError,
+ ValueError,
+ ) as exc:
+ raise HTTPException(status_code=400, detail=str(exc)) from exc
+
+
+@router.post("/impedance")
+async def post_iodine_impedance(body: IodineHttpRunRequest) -> dict[str, Any]:
+ from solarlab.contracts import ContractError
+ from solarlab.equations.dc_1d import CapabilityError
+ from solarlab.experiments.iodine_declarative import execute_iodine_impedance_deck
+ from solarlab.solvers.nonlinear.steady_1d import SteadyStateError
+
+ try:
+ deck, src = _resolve_bounded_http_deck(body)
+ return await run_in_threadpool(execute_iodine_impedance_deck, deck, source=src)
+ except (
+ CapabilityError,
+ ContractError,
+ SteadyStateError,
+ ValidationError,
+ ValueError,
+ ) as exc:
+ raise HTTPException(status_code=400, detail=str(exc)) from exc
+
+
+@router.post("/aging")
+async def post_iodine_aging(
+ request: Request,
+ body: IodineHttpRunRequest,
+) -> dict[str, Any]:
+ from solarlab.contracts import ContractError
+ from solarlab.equations.dc_1d import CapabilityError
+ from solarlab.experiments.iodine_aging import IodineAgingError
+ from solarlab.experiments.iodine_declarative import execute_iodine_aging_deck
+ from solarlab.solvers.nonlinear.steady_1d import SteadyStateError
+
+ store_dir = None
+ if body.persist_to_store:
+ job_service = request.app.state.job_service
+ if job_service is None:
+ raise HTTPException(
+ status_code=503,
+ detail="persisting runs requires an active server job_service writer",
+ )
+ store_dir = job_service.supervisor.store.root
+
+ try:
+ deck, src = _resolve_bounded_http_deck(body)
+ return await run_in_threadpool(
+ execute_iodine_aging_deck,
+ deck,
+ source=src,
+ store_dir=store_dir,
+ run_id=body.run_id,
+ )
+ except (
+ CapabilityError,
+ ContractError,
+ IodineAgingError,
+ SteadyStateError,
+ ValidationError,
+ ValueError,
+ ) as exc:
+ raise HTTPException(status_code=400, detail=str(exc)) from exc
diff --git a/tests/integration/test_iodine_aging_experiment_m4.py b/tests/integration/test_iodine_aging_experiment_m4.py
new file mode 100644
index 00000000..d7d94451
--- /dev/null
+++ b/tests/integration/test_iodine_aging_experiment_m4.py
@@ -0,0 +1,124 @@
+"""Integration tests for M4 iodine aging protocols, J-V probes, and RunStore I/O."""
+
+from __future__ import annotations
+
+import math
+from pathlib import Path
+
+import numpy as np
+import pytest
+
+from examples.research_1d.iodine_aging import prepare_bitton_tessler_stack, run_comparison
+from solarlab.contracts import ContractError
+from solarlab.device.compile_iodine_1d import (
+ bitton_tessler_2023_table_s1_chemistry,
+ compile_iodine_device_1d,
+)
+from solarlab.experiments.iodine_aging import (
+ IodineAgingProtocol,
+ IodineProbeSpec,
+ StressRecoveryStage,
+ load_iodine_aging_bundle,
+ record_iodine_aging_in_run_store,
+ run_iodine_aging_protocol,
+ save_iodine_aging_bundle,
+)
+from solarlab.io.run_store import RunStore
+
+
+def test_multi_stage_aging_both_probes_bundle_and_run_store(tmp_path: Path) -> None:
+ prepared = prepare_bitton_tessler_stack()
+ chem = bitton_tessler_2023_table_s1_chemistry(
+ domain_mode="absorber_blocking",
+ rate_mode="smoluchowski_capture_radius",
+ perovskite_ka_cm3_s=5.0e-11,
+ right_escape_m_s=2.0e-2,
+ )
+ device = compile_iodine_device_1d(prepared, chem, intervals_per_layer=(5, 16, 5))
+
+ protocol = IodineAgingProtocol(
+ stages=(
+ StressRecoveryStage(
+ name="stress_1sun_0p9V",
+ duration_s=30.0,
+ voltage_V=0.9,
+ generation_scale=1.0,
+ max_step_s=10.0,
+ ),
+ StressRecoveryStage(
+ name="dark_rest_0V",
+ duration_s=50.0,
+ voltage_V=0.0,
+ generation_scale=0.0,
+ max_step_s=25.0,
+ ),
+ ),
+ checkpoint_times_s=(0.0, 30.0, 80.0),
+ probe=IodineProbeSpec(
+ mode="both",
+ voltages_V=tuple(float(v) for v in np.linspace(0.0, 1.32, 13)),
+ scan_rate_V_s=2.0,
+ generation_scale=1.0,
+ ),
+ )
+
+ result = run_iodine_aging_protocol(device, protocol)
+ assert result.completed is True
+ assert result.scientific_qualification is False
+ assert len(result.checkpoints) == 3
+ assert result.max_relative_conservation_error <= 1.0e-9
+
+ # Verify non-destructive frozen-chemistry & dynamic J-V probes at every checkpoint
+ for ckpt in result.checkpoints:
+ assert ckpt.frozen_jv is not None
+ assert ckpt.dynamic_jv is not None
+ assert ckpt.frozen_jv.metrics.short_circuit_current_A_m2 is not None
+ assert ckpt.frozen_jv.metrics.short_circuit_current_A_m2 > 50.0
+ assert ckpt.frozen_jv.metrics.open_circuit_voltage_V is not None
+ assert 0.5 < ckpt.frozen_jv.metrics.open_circuit_voltage_V < 1.32
+ assert ckpt.dynamic_jv.hysteresis_index is not None
+ assert math.isfinite(ckpt.dynamic_jv.hysteresis_index)
+
+ # Open outgassing permanently reduced elemental iodine during light stress
+ assert result.checkpoints[1].cumulative_escaped_iodine_atoms_m2 > 0.0
+ assert result.checkpoints[-1].in_device_iodine_m2 < result.reference_iodine_inventory_m2
+
+ # Save & checksum-verify bundle readback
+ bundle_dir = tmp_path / "aging_bundle"
+ manifest = save_iodine_aging_bundle(bundle_dir, result)
+ assert manifest["scientific_qualification"] is False
+ with pytest.raises(FileExistsError):
+ save_iodine_aging_bundle(bundle_dir, result)
+
+ loaded = load_iodine_aging_bundle(bundle_dir)
+ np.testing.assert_allclose(
+ loaded["arrays"]["checkpoint_times_s"], np.array([0.0, 30.0, 80.0])
+ )
+ # Tampering with arrays.npz must fail SHA-256 verification
+ (bundle_dir / "arrays.npz").write_bytes(b"corrupted")
+ with pytest.raises(ContractError):
+ load_iodine_aging_bundle(bundle_dir)
+
+ # SQLite RunStore lifecycle persistence & verification
+ store_root = tmp_path / "run_store"
+ with RunStore(store_root) as store:
+ run_rec = record_iodine_aging_in_run_store(
+ store, "iodine_aging_m4_test", device, protocol, result
+ )
+ assert run_rec["state"] == "succeeded"
+ attempts = store.attempts("iodine_aging_m4_test")
+ assert len(attempts) == 1 and attempts[0]["state"] == "succeeded"
+
+
+def test_research_1d_iodine_aging_example_workflow(tmp_path: Path) -> None:
+ out_dir = tmp_path / "example_out"
+ summary = run_comparison(out_dir)
+ assert summary["scientific_qualification"] is False
+ closed_info = summary["closed"]
+ open_info = summary["open"]
+ assert isinstance(closed_info, dict) and isinstance(open_info, dict)
+ assert float(closed_info["final_escaped_iodine_m2"]) == 0.0
+ assert float(open_info["final_escaped_iodine_m2"]) > 0.0
+ assert float(open_info["final_in_device_iodine_m2"]) < float(
+ closed_info["final_in_device_iodine_m2"]
+ )
diff --git a/tests/integration/test_iodine_assembly_and_steady_m2.py b/tests/integration/test_iodine_assembly_and_steady_m2.py
new file mode 100644
index 00000000..63ad4054
--- /dev/null
+++ b/tests/integration/test_iodine_assembly_and_steady_m2.py
@@ -0,0 +1,364 @@
+"""Integration tests for 1D iodine sparse assembly, steady state, and BDF (M2)."""
+
+from __future__ import annotations
+
+import json
+from pathlib import Path
+
+import numpy as np
+import pytest
+
+from solarlab.config.resolve_device import resolve_device
+from solarlab.device.compile_iodine_1d import (
+ IodineChemistryDeclaration,
+ IodineLayerSpec,
+ IodineRateParameterization,
+ bitton_tessler_2023_table_s1_chemistry,
+ compile_iodine_device_1d,
+)
+from solarlab.device.defaults import DefaultCatalog
+from solarlab.device.inputs import DeviceInput
+from solarlab.device.resolved import PreparedDevice
+from solarlab.equations.assembly.iodine_1d import (
+ AssembledConstrainedIodine1DProblem,
+ AssembledIodine1DProblem,
+)
+from solarlab.equations.iodine_1d import IodineDomainMode
+from solarlab.materials.resources import ResourceLibrary
+from solarlab.materials.source import SourceDocument
+from solarlab.solvers.nonlinear.iodine_1d import (
+ solve_iodine_bdf_transient,
+ solve_iodine_steady_state,
+)
+from solarlab.solvers.time.bdf import BDFOptions
+
+
+ROOT = Path(__file__).resolve().parents[2]
+
+
+def _bitton_tessler_prepared_device() -> PreparedDevice:
+ """Construct the Bitton & Tessler (2023) SI Table S1 3-layer stack."""
+ base_path = ROOT / "examples" / "research_1d" / "device.json"
+ source = SourceDocument(str(base_path), base_path.read_bytes())
+ doc = json.loads(source.content)
+ catalog = {
+ **doc["default_catalog"],
+ "evidence": [[source.id, source.sha256]],
+ }
+ q_c = 1.602176634e-19
+ kb_j_k = 1.380649e-23
+ vt = (kb_j_k * 300.0) / q_c
+ # Langevin B_rad = q * (mu_n + mu_p) / (eps_0 * eps_r) for eps_r=3, mu=1e-3 cm^2/Vs
+ eps0 = 8.8541878128e-12
+ mu_bl = 1.0e-3 * 1.0e-4 # 1e-7 m^2/(V s)
+ b_langevin = q_c * (2.0 * mu_bl) / (eps0 * 3.0)
+
+ ni_bl = float(np.exp(0.5 * (np.log(1.0e27) + np.log(1.0e27) - 2.5 / vt)))
+ ni_pvk = float(np.exp(0.5 * (np.log(7.0e24) + np.log(2.5e24) - 1.6 / vt)))
+
+ device_dict = {
+ "schema_version": "solarlab.device-preparation.v1",
+ "id": "bitton_tessler_2023_stack",
+ "name": "Bitton & Tessler 2023 HBL/PVK/EBL stack",
+ "source_format": "canonical",
+ "settings": {
+ "built_in_potential_mode": "semiconductor_work_function",
+ "dos_band_potentials": True,
+ "T": 300.0,
+ "Phi": 2.5e21,
+ },
+ "layers": [
+ {
+ "id": "hbl",
+ "name": "HBL",
+ "role": "ETL",
+ "thickness": 50.0e-9,
+ "parameters": {
+ "chi": 4.3,
+ "Eg": 2.5,
+ "Nc300": 1.0e27,
+ "Nv300": 1.0e27,
+ "eps_r": 3.0,
+ "N_D": 2.0e22,
+ "N_A": 0.0,
+ "ni": ni_bl,
+ "n1": ni_bl,
+ "p1": ni_bl,
+ "tau_n": 1.0,
+ "tau_p": 1.0,
+ "B_rad": b_langevin,
+ "C_n": 0.0,
+ "C_p": 0.0,
+ "mu_n": mu_bl,
+ "mu_p": mu_bl,
+ "alpha": 0.0,
+ },
+ },
+ {
+ "id": "absorber",
+ "name": "Perovskite",
+ "role": "absorber",
+ "thickness": 500.0e-9,
+ "parameters": {
+ "chi": 4.3,
+ "Eg": 1.6,
+ "Nc300": 7.0e24,
+ "Nv300": 2.5e24,
+ "eps_r": 50.0,
+ "N_D": 0.0,
+ "N_A": 0.0,
+ "ni": ni_pvk,
+ "n1": ni_pvk,
+ "p1": ni_pvk,
+ "tau_n": 1.0e-5,
+ "tau_p": 1.0e-5,
+ "B_rad": 1.0e-10 * 1.0e-6,
+ "C_n": 0.0,
+ "C_p": 0.0,
+ "mu_n": 2.0e-4,
+ "mu_p": 2.0e-4,
+ "alpha": 1.0e7,
+ },
+ },
+ {
+ "id": "ebl",
+ "name": "EBL",
+ "role": "HTL",
+ "thickness": 50.0e-9,
+ "parameters": {
+ "chi": 3.4,
+ "Eg": 2.5,
+ "Nc300": 1.0e27,
+ "Nv300": 1.0e27,
+ "eps_r": 3.0,
+ "N_D": 0.0,
+ "N_A": 2.0e22,
+ "ni": ni_bl,
+ "n1": ni_bl,
+ "p1": ni_bl,
+ "tau_n": 1.0,
+ "tau_p": 1.0,
+ "B_rad": b_langevin,
+ "C_n": 0.0,
+ "C_p": 0.0,
+ "mu_n": mu_bl,
+ "mu_p": mu_bl,
+ "alpha": 0.0,
+ },
+ },
+ ],
+ }
+ return resolve_device(
+ DeviceInput.model_validate(device_dict),
+ DefaultCatalog.from_mapping(catalog),
+ ResourceLibrary(),
+ sources=(source,),
+ )
+
+
+@pytest.mark.parametrize(
+ ("domain_mode", "use_partition"),
+ [
+ ("absorber_blocking", False),
+ ("full_stack_permeable", False),
+ ("full_stack_permeable", True),
+ ],
+)
+def test_assembled_iodine_sparse_jacobians_match_central_finite_differences(
+ domain_mode: IodineDomainMode,
+ use_partition: bool,
+) -> None:
+ prepared = _bitton_tessler_prepared_device()
+ chem = bitton_tessler_2023_table_s1_chemistry(domain_mode=domain_mode)
+ if use_partition:
+ hbl_s, pvk_s, ebl_s = chem.layers
+ chem = IodineChemistryDeclaration(
+ layers=(
+ IodineLayerSpec(
+ **{
+ **{f: getattr(hbl_s, f) for f in hbl_s.__dataclass_fields__},
+ "partition_minus": 0.05,
+ "partition_atom": 0.2,
+ "partition_mol": 0.5,
+ }
+ ),
+ pvk_s,
+ IodineLayerSpec(
+ **{
+ **{f: getattr(ebl_s, f) for f in ebl_s.__dataclass_fields__},
+ "partition_minus": 0.05,
+ "partition_atom": 0.2,
+ "partition_mol": 0.5,
+ }
+ ),
+ ),
+ domain_mode="full_stack_permeable",
+ initialize_equilibrium_split=True,
+ )
+
+ device = compile_iodine_device_1d(prepared, chem, intervals_per_layer=(4, 6, 4))
+ u0 = np.array(device.initial_coordinates(voltage_V=0.45), dtype=np.float64, copy=True)
+ rng = np.random.default_rng(42)
+ u0 += 0.05 * rng.standard_normal(u0.size)
+
+ unconstrained = AssembledIodine1DProblem(device, voltage_V=0.45, generation_scale=0.8)
+ constrained = AssembledConstrainedIodine1DProblem(
+ device, voltage_V=0.45, generation_scale=0.8, inventory_node=2
+ )
+
+ for prob in (unconstrained, constrained):
+ j_exact = prob.jacobian(u0).toarray()
+ f0 = prob.residual(u0)
+ eps = np.finfo(np.float64).eps
+ j_fd = np.zeros_like(j_exact)
+ for col in range(u0.size):
+ h = 1.0e-6 * max(abs(float(u0[col])), 1.0)
+ up, um = u0.copy(), u0.copy()
+ up[col] += h
+ um[col] -= h
+ j_fd[:, col] = (prob.residual(up) - prob.residual(um)) / (2.0 * h)
+ row_round = 128.0 * eps * (np.abs(f0) + np.max(np.abs(j_exact), axis=1)) / h
+ assert np.all(
+ np.abs(j_exact[:, col] - j_fd[:, col])
+ <= 1.0e-6 * np.abs(j_fd[:, col]) + row_round + 1.0e-12
+ )
+
+ # Storage tangent S_u check
+ s_tan = unconstrained.storage_tangent(u0).toarray()
+ s0 = unconstrained.storage(u0)
+ for col in range(u0.size):
+ h = 1.0e-6 * max(abs(float(u0[col])), 1.0)
+ up, um = u0.copy(), u0.copy()
+ up[col] += h
+ um[col] -= h
+ fd_s = (unconstrained.storage(up) - unconstrained.storage(um)) / (2.0 * h)
+ s_round = 64.0 * eps * np.abs(s0) / h
+ assert np.all(
+ np.abs(s_tan[:, col] - fd_s) <= 1.0e-7 * np.abs(fd_s) + s_round + 1.0e-18
+ )
+
+
+def test_unreactive_limit_preserves_each_species_and_boltzmann_iodide_profile() -> None:
+ prepared = _bitton_tessler_prepared_device()
+ zero_chem = IodineChemistryDeclaration(
+ layers=(
+ IodineLayerSpec.from_cgs(
+ "absorber",
+ D_minus_cm2_s=1.0e-8,
+ D_atom_cm2_s=1.0e-8,
+ D_mol_cm2_s=1.0e-9,
+ initial_iodide_cm3=1.0e18,
+ initial_atom_cm3=1.0e12,
+ initial_mol_cm3=1.0e10,
+ compensating_donor_cm3=1.0e18,
+ k_a_cm3_s=0.0,
+ k_b_s_1=0.0,
+ k_c_cm3_s=0.0,
+ k_d_cm3_s=0.0,
+ k_e_cm3_s=0.0,
+ ),
+ ),
+ domain_mode="absorber_blocking",
+ thermodynamic_mode="wegscheider_detailed_balance",
+ )
+ device = compile_iodine_device_1d(
+ prepared, zero_chem, intervals_per_layer=(8, 24, 8)
+ )
+ assert device.is_unreactive_limit
+ res = solve_iodine_steady_state(device, voltage_V=0.5, generation_scale=1.0)
+ assert res.converged and res.state is not None
+
+ ref_inv = device.reference_species_inventories_m2
+ for sp in ("iodide", "iodine_atom", "iodine_molecule"):
+ assert res.state.species_inventories_m2[sp] == pytest.approx(
+ ref_inv[sp], rel=1.0e-12
+ )
+ # Neutral species have zero drift and zero reaction -> strictly flat profile!
+ c0 = res.state.iodine_atom_density_m3
+ c2 = res.state.iodine_molecule_density_m3
+ np.testing.assert_allclose(c0, c0[0], rtol=1.0e-10)
+ np.testing.assert_allclose(c2, c2[0], rtol=1.0e-10)
+
+ # Zero-flux I^- satisfies c_-(x) / c_-(0) = exp((phi(x) - phi(0)) / V_T)
+ phi_abs = res.state.electronic_state.potential_V[device.chem_node_indices]
+ vt = device.electronic_component.thermal_voltage_V
+ cm = res.state.iodide_density_m3
+ expected_ratio = np.exp((phi_abs - phi_abs[0]) / vt)
+ np.testing.assert_allclose(cm / cm[0], expected_ratio, rtol=1.0e-9)
+
+
+@pytest.mark.parametrize(
+ ("domain_mode", "rate_mode"),
+ [
+ ("absorber_blocking", "explicit_rates"),
+ ("full_stack_permeable", "explicit_rates"),
+ ("absorber_blocking", "smoluchowski_capture_radius"),
+ ],
+)
+def test_bitton_tessler_steady_and_transient_bdf_conservation_and_fig_s2_trends(
+ domain_mode: IodineDomainMode,
+ rate_mode: IodineRateParameterization,
+) -> None:
+ prepared = _bitton_tessler_prepared_device()
+ chem = bitton_tessler_2023_table_s1_chemistry(
+ domain_mode=domain_mode,
+ rate_mode=rate_mode,
+ perovskite_ka_cm3_s=1.0e-11,
+ )
+ device = compile_iodine_device_1d(prepared, chem, intervals_per_layer=(8, 30, 8))
+
+ # 1. Dark equilibrium (0 V, Dark): exact iodine inventory & tiny dark current
+ dark_eq = solve_iodine_steady_state(device, voltage_V=0.0, generation_scale=0.0)
+ assert dark_eq.converged and dark_eq.state is not None
+ assert dark_eq.state.total_iodine_inventory_m2 == pytest.approx(
+ device.reference_iodine_inventory_m2, rel=1.0e-12
+ )
+ assert abs(dark_eq.current_density_A_m2) < 1.0e-7
+
+ # 2. Illuminated forward bias (1 Sun, 0.9 V -- Bitton & Tessler Fig. S2):
+ # Photo-holes oxidize I^- -> I^0 -> I_2, elevating neutral I^0 and I_2 by orders
+ # of magnitude above dark equilibrium while conserving total iodine to 1e-12!
+ illum_steady = solve_iodine_steady_state(
+ device, voltage_V=0.9, generation_scale=1.0
+ )
+ assert illum_steady.converged and illum_steady.state is not None
+ assert illum_steady.state.total_iodine_inventory_m2 == pytest.approx(
+ device.reference_iodine_inventory_m2, rel=1.0e-12
+ )
+ assert (
+ illum_steady.state.species_inventories_m2["iodine_atom"]
+ > 1.0e4 * dark_eq.state.species_inventories_m2["iodine_atom"]
+ )
+ assert (
+ illum_steady.state.species_inventories_m2["iodine_molecule"]
+ > 50.0 * dark_eq.state.species_inventories_m2["iodine_molecule"]
+ )
+
+ # 3. Transient BDF1/2 from dark equilibrium into (1 Sun, 0.9 V) stress:
+ # Conserves elemental iodine at every step and converges to steady state!
+ bdf_opts = BDFOptions(
+ initial_step_s=1.0e-6,
+ min_step_s=1.0e-14,
+ max_step_s=200.0,
+ relative_tolerance=1.0e-3,
+ absolute_tolerance=1.0e11,
+ max_steps=600,
+ )
+ bdf_res, ledger = solve_iodine_bdf_transient(
+ device,
+ dark_eq.state.u,
+ (0.0, 1000.0),
+ voltage_fn=lambda _t: 0.9,
+ generation_fn=lambda _t: 1.0,
+ options=bdf_opts,
+ )
+ assert bdf_res.completed and len(ledger) > 0
+ inv_ref = device.reference_iodine_inventory_m2
+ for step_acc in ledger:
+ assert abs(step_acc.in_device_iodine_m2 - inv_ref) / inv_ref <= 1.0e-11
+ assert abs(step_acc.step_conservation_residual_m2) / inv_ref <= 5.0e-11
+
+ final_state = device.state(bdf_res.accepted_coordinates[-1], voltage_V=0.9)
+ assert final_state.species_inventories_m2["iodine_atom"] == pytest.approx(
+ illum_steady.state.species_inventories_m2["iodine_atom"], rel=2.0e-2
+ )
diff --git a/tests/integration/test_iodine_cli_and_server.py b/tests/integration/test_iodine_cli_and_server.py
new file mode 100644
index 00000000..6799db49
--- /dev/null
+++ b/tests/integration/test_iodine_cli_and_server.py
@@ -0,0 +1,284 @@
+"""Integration tests for declarative iodine YAML presets, CLI subcommands, and FastAPI routes."""
+
+from __future__ import annotations
+
+import json
+from pathlib import Path
+
+from fastapi.testclient import TestClient
+
+from solarlab.cli import main as solarlab_cli_main
+from solarlab.experiments.iodine_declarative import (
+ compile_iodine_deck,
+ export_iodine_deck_schema,
+ load_iodine_deck,
+)
+from solarlab.io.run_store import RunStore
+from solarlab.materials.iodine_presets import (
+ PACKAGED_IODINE_PRESET_NAMES,
+ list_packaged_iodine_preset_summaries,
+)
+from solarlab_server.app import create_app
+
+_FAST_CLASSICAL_PIN_DECK = """
+schema_version: solarlab.iodine-deck.v1
+id: custom_classical_pin_iodine
+name: Custom Classical p-i-n Iodine Aging
+electronic_stack:
+ preset: classical_pin
+ intervals_per_layer: [6, 16, 6]
+chemistry:
+ domain_mode: absorber_blocking
+ initialize_equilibrium_split: false
+ layers:
+ - layer_id: absorber
+ units: cgs
+ D_minus: 1.0e-9
+ D_atom: 1.0e-9
+ D_mol: 1.0e-9
+ initial_iodide: 1.0e16
+ rate_mode: smoluchowski_capture_radius
+ k_a: 1.0e-11
+ k_b: 1.0e-3
+ K_diss: 1.0e8
+ n_e_star: 1.0e8
+steady:
+ voltage_V: 0.8
+ generation_scale: 1.0
+ compute_frozen_jv: true
+ jv_v_min_V: 0.0
+ jv_v_max_V: 1.1
+ jv_n_points: 6
+impedance:
+ voltage_V: 0.8
+ generation_scale: 1.0
+ f_min_Hz: 1.0e-2
+ f_max_Hz: 1.0e5
+ n_frequencies: 5
+ chem_mode: both
+aging:
+ stages:
+ - name: short_stress
+ duration_s: 10.0
+ voltage_V: 0.8
+ generation_scale: 1.0
+ max_step_s: 5.0
+ checkpoint_times_s: [0.0, 10.0]
+ probe:
+ mode: none
+""".strip()
+
+
+def test_all_packaged_iodine_presets_validate_and_compile() -> None:
+ assert len(PACKAGED_IODINE_PRESET_NAMES) == 5
+ summaries = list_packaged_iodine_preset_summaries()
+ assert [item["id"] for item in summaries] == list(PACKAGED_IODINE_PRESET_NAMES)
+
+ schema_doc = export_iodine_deck_schema()
+ assert schema_doc["schema"] == "solarlab.iodine-deck-schema.v1"
+ assert schema_doc["scientific_qualification"] is False
+ assert len(schema_doc["sha256"]) == 64
+
+ for name in PACKAGED_IODINE_PRESET_NAMES:
+ deck, src = load_iodine_deck(name)
+ assert deck.id == name
+ assert len(src.sha256) == 64
+ _, compiled = compile_iodine_deck(deck, source=src)
+ assert compiled.state_size > 0
+
+
+def test_cli_iodine_subcommands_end_to_end(tmp_path: Path) -> None:
+ presets_out = tmp_path / "presets.json"
+ assert solarlab_cli_main(["iodine-presets", "--output", str(presets_out)]) == 0
+ presets_doc = json.loads(presets_out.read_text(encoding="utf-8"))
+ assert presets_doc["schema"] == "solarlab.cli.iodine-presets.v1"
+ assert len(presets_doc["presets"]) == 5
+ assert presets_doc["scientific_qualification"] is False
+
+ schema_out = tmp_path / "schema.json"
+ assert (
+ solarlab_cli_main(["iodine-presets", "--schema", "--output", str(schema_out)])
+ == 0
+ )
+ assert (
+ json.loads(schema_out.read_text(encoding="utf-8"))["deck_schema_version"]
+ == "solarlab.iodine-deck.v1"
+ )
+
+ custom_yaml = tmp_path / "user_deck.yaml"
+ custom_yaml.write_text(_FAST_CLASSICAL_PIN_DECK + "\n", encoding="utf-8")
+
+ steady_out = tmp_path / "steady.json"
+ rc_steady = solarlab_cli_main(
+ [
+ "iodine-steady",
+ "--config",
+ str(custom_yaml),
+ "--output",
+ str(steady_out),
+ ]
+ )
+ assert rc_steady == 0
+ steady_doc = json.loads(steady_out.read_text(encoding="utf-8"))
+ assert steady_doc["schema"] == "solarlab.iodine-steady-result.v1"
+ assert steady_doc["scientific_qualification"] is False
+ assert steady_doc["profiles"]["total_iodine_atoms_m2"] > 0.0
+ assert steady_doc["frozen_jv"] is not None
+
+ imp_out = tmp_path / "impedance.json"
+ rc_imp = solarlab_cli_main(
+ [
+ "iodine-impedance",
+ "--config",
+ str(custom_yaml),
+ "--output",
+ str(imp_out),
+ ]
+ )
+ assert rc_imp == 0
+ imp_doc = json.loads(imp_out.read_text(encoding="utf-8"))
+ assert imp_doc["schema"] == "solarlab.iodine-impedance-result.v1"
+ assert imp_doc["scientific_qualification"] is False
+ assert len(imp_doc["redox_excess_capacitance_F_m2"]) == 5
+ assert imp_doc["redox_excess_capacitance_F_m2"][0] > 0.0
+
+ store_dir = tmp_path / "store"
+ aging_out = tmp_path / "aging.json"
+ rc_aging = solarlab_cli_main(
+ [
+ "iodine-aging",
+ "--config",
+ str(custom_yaml),
+ "--store-dir",
+ str(store_dir),
+ "--output",
+ str(aging_out),
+ ]
+ )
+ assert rc_aging == 0
+ aging_doc = json.loads(aging_out.read_text(encoding="utf-8"))
+ assert aging_doc["schema"] == "solarlab.iodine-aging-result.v1"
+ assert aging_doc["completed"] is True
+ assert aging_doc["max_relative_conservation_error"] < 1.0e-9
+ assert aging_doc["persisted_run_store"] is not None
+ assert aging_doc["scientific_qualification"] is False
+
+
+def test_server_iodine_routes_execute_bounded_requests(tmp_path: Path) -> None:
+ store_root = tmp_path / "server_store"
+ with RunStore(store_root):
+ pass
+
+ deck, _ = load_iodine_deck(
+ json.loads(
+ json.dumps(
+ load_iodine_deck("bitton_tessler_2023_outgassing")[0].model_dump(
+ mode="python"
+ )
+ )
+ )
+ )
+ fast_deck, _ = load_iodine_deck(
+ {
+ "schema_version": "solarlab.iodine-deck.v1",
+ "id": "http_fast_pin",
+ "electronic_stack": {
+ "preset": "classical_pin",
+ "intervals_per_layer": [6, 16, 6],
+ },
+ "chemistry": {
+ "domain_mode": "absorber_blocking",
+ "initialize_equilibrium_split": False,
+ "layers": [
+ {
+ "layer_id": "absorber",
+ "units": "cgs",
+ "D_minus": 1.0e-9,
+ "D_atom": 1.0e-9,
+ "D_mol": 1.0e-9,
+ "initial_iodide": 1.0e16,
+ "rate_mode": "smoluchowski_capture_radius",
+ "k_a": 2.0e-11,
+ "k_b": 1.0e-3,
+ "K_diss": 1.0e8,
+ "n_e_star": 1.0e8,
+ }
+ ],
+ },
+ "steady": {
+ "voltage_V": 0.8,
+ "generation_scale": 1.0,
+ "compute_frozen_jv": False,
+ },
+ "impedance": {
+ "voltage_V": 0.8,
+ "generation_scale": 1.0,
+ "f_min_Hz": 0.1,
+ "f_max_Hz": 1.0e4,
+ "n_frequencies": 4,
+ "chem_mode": "mobile",
+ },
+ "aging": {
+ "stages": [
+ {
+ "name": "http_outgas_stage",
+ "duration_s": 5.0,
+ "voltage_V": 0.8,
+ "generation_scale": 1.0,
+ "max_step_s": 2.5,
+ }
+ ],
+ "checkpoint_times_s": [0.0, 5.0],
+ "probe": {"mode": "none"},
+ },
+ }
+ )
+ assert deck.id == "bitton_tessler_2023_outgassing"
+
+ app = create_app(store_root)
+ with TestClient(app) as http:
+ presets_resp = http.get("/iodine/presets")
+ assert presets_resp.status_code == 200
+ assert len(presets_resp.json()["presets"]) == 5
+
+ schema_resp = http.get("/iodine/schema")
+ assert schema_resp.status_code == 200
+ assert schema_resp.json()["deck_schema_version"] == "solarlab.iodine-deck.v1"
+
+ steady_resp = http.post(
+ "/iodine/steady",
+ json={"deck": fast_deck.model_dump(mode="python")},
+ )
+ assert steady_resp.status_code == 200
+ s_doc = steady_resp.json()
+ assert s_doc["schema"] == "solarlab.iodine-steady-result.v1"
+ assert s_doc["scientific_qualification"] is False
+
+ imp_resp = http.post(
+ "/iodine/impedance",
+ json={"deck": fast_deck.model_dump(mode="python")},
+ )
+ assert imp_resp.status_code == 200
+ assert imp_resp.json()["schema"] == "solarlab.iodine-impedance-result.v1"
+
+ aging_resp = http.post(
+ "/iodine/aging",
+ json={
+ "deck": fast_deck.model_dump(mode="python"),
+ "overrides": {"volumetric_escape_s_1": 1.0e-3},
+ },
+ )
+ assert aging_resp.status_code == 200
+ a_doc = aging_resp.json()
+ assert a_doc["completed"] is True
+ assert a_doc["trajectory"]["cumulative_escaped_iodine_atoms_m2"][-1] > 0.0
+ assert a_doc["max_relative_conservation_error"] < 1.0e-8
+
+ bad_resp = http.post(
+ "/iodine/steady",
+ json={
+ "preset": "bitton_tessler_2023_blocking",
+ "overrides": {"intervals_per_layer": 200},
+ },
+ )
+ assert bad_resp.status_code == 400
diff --git a/tests/integration/test_iodine_open_boundaries_and_ac_m3.py b/tests/integration/test_iodine_open_boundaries_and_ac_m3.py
new file mode 100644
index 00000000..c23089b6
--- /dev/null
+++ b/tests/integration/test_iodine_open_boundaries_and_ac_m3.py
@@ -0,0 +1,460 @@
+"""Integration tests for open escape, reactive contacts, and AC impedance (M3)."""
+
+from __future__ import annotations
+
+import numpy as np
+import pytest
+
+from solarlab.contracts import ContractError
+from solarlab.equations.assembly.iodine_1d import AssembledIodine1DProblem
+from solarlab.equations.dc_1d import CapabilityError
+from solarlab.device.compile_iodine_1d import (
+ IodineBoundaryDeclaration,
+ IodineChemistryDeclaration,
+ bitton_tessler_2023_table_s1_chemistry,
+ compile_iodine_device_1d,
+)
+from solarlab.solvers.linear.iodine_impedance import solve_iodine_small_signal_1d
+from solarlab.solvers.nonlinear.iodine_1d import (
+ solve_frozen_chemistry_electronic_1d,
+ solve_iodine_bdf_transient,
+ solve_iodine_steady_state,
+)
+from solarlab.solvers.time.bdf import BDFOptions
+from tests.integration.test_iodine_assembly_and_steady_m2 import (
+ _bitton_tessler_prepared_device,
+)
+
+
+def test_open_i2_escape_vs_closed_dark_recovery_and_steady_refusal() -> None:
+ prepared = _bitton_tessler_prepared_device()
+ closed_chem = bitton_tessler_2023_table_s1_chemistry(
+ domain_mode="absorber_blocking",
+ rate_mode="smoluchowski_capture_radius",
+ perovskite_ka_cm3_s=5.0e-11,
+ right_escape_m_s=0.0,
+ )
+ open_chem = bitton_tessler_2023_table_s1_chemistry(
+ domain_mode="absorber_blocking",
+ rate_mode="smoluchowski_capture_radius",
+ perovskite_ka_cm3_s=5.0e-11,
+ right_escape_m_s=5.0e-2,
+ )
+ closed_dev = compile_iodine_device_1d(
+ prepared, closed_chem, intervals_per_layer=(6, 20, 6)
+ )
+ open_dev = compile_iodine_device_1d(
+ prepared, open_chem, intervals_per_layer=(6, 20, 6)
+ )
+
+ # Steady-state solver must refuse open outgassing boundary conditions
+ with pytest.raises(CapabilityError):
+ solve_iodine_steady_state(open_dev, voltage_V=0.0, generation_scale=0.0)
+
+ dark_eq = solve_iodine_steady_state(closed_dev, voltage_V=0.0, generation_scale=0.0)
+ assert dark_eq.converged and dark_eq.state is not None
+ inv_0 = closed_dev.reference_iodine_inventory_m2
+
+ bdf_stress_opts = BDFOptions(
+ initial_step_s=1.0e-6,
+ min_step_s=1.0e-14,
+ max_step_s=20.0,
+ relative_tolerance=1.0e-3,
+ absolute_tolerance=1.0e11,
+ max_steps=300,
+ )
+ bdf_rec_opts = BDFOptions(
+ initial_step_s=1.0e-6,
+ min_step_s=1.0e-14,
+ max_step_s=50.0,
+ relative_tolerance=1.0e-3,
+ absolute_tolerance=1.0e11,
+ max_steps=300,
+ )
+
+ # 1. Closed device: 60 s light stress (0.9 V, 1 Sun) -> 200 s dark recovery (0 V)
+ res_c_stress, led_c_stress = solve_iodine_bdf_transient(
+ closed_dev,
+ dark_eq.state.u,
+ (0.0, 60.0),
+ voltage_fn=lambda _t: 0.9,
+ generation_fn=lambda _t: 1.0,
+ options=bdf_stress_opts,
+ )
+ assert res_c_stress.completed
+ stressed_c = closed_dev.state(res_c_stress.accepted_coordinates[-1], voltage_V=0.9)
+
+ res_c_rec, led_c_rec = solve_iodine_bdf_transient(
+ closed_dev,
+ stressed_c.u,
+ (60.0, 260.0),
+ voltage_fn=lambda _t: 0.0,
+ generation_fn=lambda _t: 0.0,
+ options=bdf_rec_opts,
+ )
+ assert res_c_rec.completed
+ recovered_c = closed_dev.state(res_c_rec.accepted_coordinates[-1], voltage_V=0.0)
+ assert recovered_c.total_iodine_inventory_m2 == pytest.approx(inv_0, rel=5.0e-10)
+ # Dark recovery reduces photogenerated neutral I^0 and I_2 by orders of magnitude
+ assert (
+ recovered_c.species_inventories_m2["iodine_atom"]
+ < 1.0e-2 * stressed_c.species_inventories_m2["iodine_atom"]
+ )
+ assert sum(s.step_escaped_iodine_atoms_m2 for s in led_c_stress + led_c_rec) == 0.0
+
+ # 2. Open device: volatile I_2 outgassing permanently depletes elemental iodine
+ # while BDF1/2 step ledger satisfies (in_device + cum_escaped == inv_0) identically!
+ res_o_stress, led_o_stress = solve_iodine_bdf_transient(
+ open_dev,
+ dark_eq.state.u,
+ (0.0, 60.0),
+ voltage_fn=lambda _t: 0.9,
+ generation_fn=lambda _t: 1.0,
+ options=bdf_stress_opts,
+ )
+ assert res_o_stress.completed and len(led_o_stress) > 0
+ cum_escaped = 0.0
+ for acc in led_o_stress:
+ cum_escaped += acc.step_escaped_iodine_atoms_m2
+ assert abs(acc.step_conservation_residual_m2) / inv_0 <= 1.0e-10
+ assert abs((acc.in_device_iodine_m2 + cum_escaped) - inv_0) / inv_0 <= 1.0e-10
+ assert cum_escaped > 0.0
+ final_open_inv = led_o_stress[-1].in_device_iodine_m2
+ assert final_open_inv < inv_0
+
+
+def test_charge_conserving_contact_oxidation_modes_and_contract_refusals() -> None:
+ prepared = _bitton_tessler_prepared_device()
+ base = bitton_tessler_2023_table_s1_chemistry(
+ domain_mode="full_stack_permeable",
+ rate_mode="smoluchowski_capture_radius",
+ )
+
+ # Non-conserving or negative boundary rates must be rejected by ContractError
+ with pytest.raises(ContractError):
+ compile_iodine_device_1d(
+ prepared,
+ IodineChemistryDeclaration(
+ layers=base.layers,
+ domain_mode="full_stack_permeable",
+ right_boundary=IodineBoundaryDeclaration(mol_escape_velocity_m_s=-1.0),
+ ),
+ intervals_per_layer=(4, 10, 4),
+ )
+ with pytest.raises(ContractError):
+ compile_iodine_device_1d(
+ prepared,
+ IodineChemistryDeclaration(
+ layers=base.layers,
+ domain_mode="full_stack_permeable",
+ right_boundary=IodineBoundaryDeclaration(
+ contact_reaction_mode="none",
+ contact_oxidation_rate_m4_s=1.0e-25,
+ ),
+ ),
+ intervals_per_layer=(4, 10, 4),
+ )
+
+ bdf_opts = BDFOptions(
+ initial_step_s=1.0e-6,
+ min_step_s=1.0e-14,
+ max_step_s=5.0,
+ relative_tolerance=1.0e-3,
+ absolute_tolerance=1.0e11,
+ max_steps=200,
+ )
+
+ # Mode A: hole_oxidation_to_I0 conserves in-device iodine AND Maxwell current!
+ chem_rev_contact = IodineChemistryDeclaration(
+ layers=base.layers,
+ domain_mode="full_stack_permeable",
+ right_boundary=IodineBoundaryDeclaration(
+ contact_reaction_mode="hole_oxidation_to_I0",
+ contact_oxidation_rate_m4_s=1.0e-24,
+ ),
+ initialize_equilibrium_split=True,
+ )
+ dev_rev = compile_iodine_device_1d(
+ prepared, chem_rev_contact, intervals_per_layer=(5, 14, 5)
+ )
+ u0_rev = solve_iodine_steady_state(dev_rev, voltage_V=0.0, generation_scale=0.0)
+ assert u0_rev.converged and u0_rev.state is not None
+ res_rev, led_rev = solve_iodine_bdf_transient(
+ dev_rev,
+ u0_rev.state.u,
+ (0.0, 10.0),
+ voltage_fn=lambda _t: 0.95,
+ generation_fn=lambda _t: 1.0,
+ options=bdf_opts,
+ )
+ assert res_rev.completed
+ inv_ref = dev_rev.reference_iodine_inventory_m2
+ for acc in led_rev:
+ assert abs(acc.in_device_iodine_m2 - inv_ref) / inv_ref <= 1.0e-10
+ assert acc.step_immobilized_iodine_atoms_m2 == 0.0
+
+ # Mode B: immobilized_product_sheet tracks irreversible contact corrosion sheet!
+ chem_immob = IodineChemistryDeclaration(
+ layers=base.layers,
+ domain_mode="full_stack_permeable",
+ right_boundary=IodineBoundaryDeclaration(
+ contact_reaction_mode="immobilized_product_sheet",
+ contact_oxidation_rate_m4_s=1.0e-22,
+ ),
+ initialize_equilibrium_split=True,
+ )
+ dev_immob = compile_iodine_device_1d(
+ prepared, chem_immob, intervals_per_layer=(5, 14, 5)
+ )
+ res_im, led_im = solve_iodine_bdf_transient(
+ dev_immob,
+ u0_rev.state.u,
+ (0.0, 10.0),
+ voltage_fn=lambda _t: 0.95,
+ generation_fn=lambda _t: 1.0,
+ options=bdf_opts,
+ )
+ assert res_im.completed and len(led_im) > 0
+ cum_immob = 0.0
+ for acc in led_im:
+ cum_immob += acc.step_immobilized_iodine_atoms_m2
+ assert abs((acc.in_device_iodine_m2 + cum_immob) - inv_ref) / inv_ref <= 1.0e-10
+ assert cum_immob > 0.0
+
+
+def test_iodine_small_signal_ac_impedance_limits_and_dc_slope_consistency() -> None:
+ prepared = _bitton_tessler_prepared_device()
+ chem = bitton_tessler_2023_table_s1_chemistry(
+ domain_mode="absorber_blocking",
+ perovskite_ka_cm3_s=1.0e-11,
+ )
+ device = compile_iodine_device_1d(prepared, chem, intervals_per_layer=(6, 20, 6))
+
+ v_op = 0.75
+ g_op = 1.0
+ steady = solve_iodine_steady_state(device, voltage_V=v_op, generation_scale=g_op)
+ assert steady.converged and steady.state is not None
+
+ freqs = np.r_[0.0, np.logspace(-3, 8, 23)]
+ ac_mobile = solve_iodine_small_signal_1d(
+ device,
+ steady.state,
+ freqs,
+ generation_scale=g_op,
+ chem_mode="mobile",
+ )
+ u_frozen_op, _ = solve_frozen_chemistry_electronic_1d(
+ device, steady.state.u, voltage_V=v_op, generation_scale=g_op
+ )
+ frozen_op_state = device.state(u_frozen_op, voltage_V=v_op)
+ ac_frozen = solve_iodine_small_signal_1d(
+ device,
+ frozen_op_state,
+ freqs,
+ generation_scale=g_op,
+ chem_mode="frozen",
+ )
+
+ assert ac_mobile.scientific_qualification is False
+ assert ac_mobile.max_backward_error <= 1.0e-11
+ assert ac_frozen.max_backward_error <= 1.0e-11
+ scale_m = float(np.max(np.abs(ac_mobile.admittance_S_m2)))
+ scale_f = float(np.max(np.abs(ac_frozen.admittance_S_m2)))
+ assert ac_mobile.max_maxwell_spread_A_m2_V <= 1.0e-8 + 1.0e-10 * scale_m
+ assert ac_frozen.max_maxwell_spread_A_m2_V <= 1.0e-8 + 1.0e-10 * scale_f
+
+ # 1. High-frequency geometric capacitance limit (100 MHz):
+ # Series dielectric capacitance C_geom = 1 / sum(1 / C_face)
+ inv_c = float(np.sum(1.0 / device.electronic_component.poisson.face_capacitance_F_m2))
+ c_geom = 1.0 / inv_c
+ assert ac_mobile.apparent_capacitance_F_m2[-1] == pytest.approx(c_geom, rel=2.0e-2)
+ assert ac_frozen.apparent_capacitance_F_m2[-1] == pytest.approx(c_geom, rel=2.0e-2)
+ assert ac_mobile.impedance_Ohm_m2[-1] == pytest.approx(
+ ac_frozen.impedance_Ohm_m2[-1], rel=1.0e-2
+ )
+
+ # 2. Exact 0 Hz differential conductance vs central finite-difference DC slope!
+ dv = 1.0e-4
+ sp = solve_iodine_steady_state(device, voltage_V=v_op + dv, generation_scale=g_op)
+ sm = solve_iodine_steady_state(device, voltage_V=v_op - dv, generation_scale=g_op)
+ assert sp.converged and sm.converged
+ pol = device.electronic_component.voltage_polarity
+ # Input current into positive electrode is polarity * J_mean
+ g_dc_mobile_fd = pol * (sp.current_density_A_m2 - sm.current_density_A_m2) / (2.0 * dv)
+ assert ac_mobile.admittance_S_m2[0].real == pytest.approx(g_dc_mobile_fd, rel=5.0e-4)
+ assert abs(ac_mobile.admittance_S_m2[0].imag) <= 1.0e-12
+
+ _, jp_f = solve_frozen_chemistry_electronic_1d(
+ device, steady.state.u, voltage_V=v_op + dv, generation_scale=g_op
+ )
+ _, jm_f = solve_frozen_chemistry_electronic_1d(
+ device, steady.state.u, voltage_V=v_op - dv, generation_scale=g_op
+ )
+ g_dc_frozen_fd = pol * (jp_f - jm_f) / (2.0 * dv)
+ assert ac_frozen.admittance_S_m2[0].real == pytest.approx(g_dc_frozen_fd, rel=5.0e-4)
+
+ # 3. Low-frequency (1 mHz) mobile chemical/ionic arc differs from frozen response!
+ assert abs(
+ ac_mobile.apparent_capacitance_F_m2[1] - ac_frozen.apparent_capacitance_F_m2[1]
+ ) > 10.0 * c_geom
+ for sp_name in ("iodide", "iodine_atom", "iodine_molecule"):
+ assert ac_frozen.responses[1].species_inventory_perturbation_m2[sp_name] == 0.0j
+ # Closed-domain mobile AC conserves elemental iodine phasor delta(M_- + M_0 + 2 M_2) == 0
+ inv_p = ac_mobile.responses[1].species_inventory_perturbation_m2
+ delta_elem = (
+ inv_p["iodide"] + inv_p["iodine_atom"] + 2.0 * inv_p["iodine_molecule"]
+ )
+ assert abs(delta_elem) / device.reference_iodine_inventory_m2 <= 1.0e-8
+
+
+def test_volumetric_mol_escape_jacobian_steady_refusal_and_live_depletion() -> None:
+ prepared = _bitton_tessler_prepared_device()
+ chem_closed = bitton_tessler_2023_table_s1_chemistry(
+ domain_mode="full_stack_permeable",
+ perovskite_ka_cm3_s=5.0e-11,
+ )
+ chem_vol = bitton_tessler_2023_table_s1_chemistry(
+ domain_mode="full_stack_permeable",
+ perovskite_ka_cm3_s=5.0e-11,
+ ebl_volumetric_mol_escape_s_1=50.0,
+ )
+ dev_closed = compile_iodine_device_1d(
+ prepared, chem_closed, intervals_per_layer=(5, 14, 5)
+ )
+ dev_vol = compile_iodine_device_1d(
+ prepared, chem_vol, intervals_per_layer=(5, 14, 5)
+ )
+ assert dev_vol.has_open_iodine_loss
+ assert dev_vol.sha256 != dev_closed.sha256
+ assert dev_vol.volumetric_mol_escape_s_1 is not None
+ # Shared PVK/EBL heterointerface node must remain sealed (0.0) when PVK is sealed
+ assert dev_vol.volumetric_mol_escape_s_1[19] == 0.0
+ assert np.all(dev_vol.volumetric_mol_escape_s_1[20:] == pytest.approx(50.0))
+
+ with pytest.raises(CapabilityError):
+ solve_iodine_steady_state(dev_vol, voltage_V=0.0, generation_scale=0.0)
+
+ ss_c = solve_iodine_steady_state(dev_closed, voltage_V=0.9, generation_scale=1.0)
+ assert ss_c.converged and ss_c.state is not None
+
+ # Verify analytical Jacobian of volumetric escape against central finite differences
+ prob_c = AssembledIodine1DProblem(dev_closed, voltage_V=0.9, generation_scale=1.0)
+ prob_v = AssembledIodine1DProblem(dev_vol, voltage_V=0.9, generation_scale=1.0)
+ u_test = np.array(ss_c.state.u, dtype=np.float64, copy=True)
+ dj_ana = (prob_v.jacobian(u_test) - prob_c.jacobian(u_test)).toarray()
+ mol_sl = dev_vol.chem_slices["iodine_molecule"]
+ eps = 1.0e-4
+ for col in range(mol_sl.start, mol_sl.stop):
+ up = u_test.copy()
+ um = u_test.copy()
+ up[col] += eps
+ um[col] -= eps
+ df_p = prob_v.residual(up) - prob_c.residual(up)
+ df_m = prob_v.residual(um) - prob_c.residual(um)
+ fd_col = (df_p - df_m) / (2.0 * eps)
+ np.testing.assert_allclose(
+ dj_ana[mol_sl, col], fd_col[mol_sl], rtol=1.0e-6, atol=1.0e-1
+ )
+ assert np.all(dj_ana[: mol_sl.start, col] == 0.0)
+
+ # Verify live BDF volumetric outgassing conserves elemental iodine at every step
+ res_v, led_v = solve_iodine_bdf_transient(
+ dev_vol,
+ ss_c.state.u,
+ (0.0, 1.0e4),
+ voltage_fn=lambda _t: 0.9,
+ generation_fn=lambda _t: 1.0,
+ options=BDFOptions(
+ initial_step_s=1.0e-2,
+ max_step_s=2.0e3,
+ relative_tolerance=1.0e-2,
+ absolute_tolerance=1.0e15,
+ max_order=1,
+ max_steps=200,
+ ),
+ )
+ assert res_v.completed and len(led_v) > 0
+ inv_0 = ss_c.state.total_iodine_inventory_m2
+ cum_esc = 0.0
+ for acc in led_v:
+ cum_esc += acc.step_escaped_iodine_atoms_m2
+ assert abs((acc.in_device_iodine_m2 + cum_esc) - inv_0) / inv_0 <= 1.0e-9
+ assert cum_esc > 0.0
+
+
+def test_metal_faradaic_corrosion_jacobian_capability_and_conservation() -> None:
+ prepared = _bitton_tessler_prepared_device()
+ # Reject metal_faradaic_corrosion on interior heterointerface (absorber_blocking)
+ bad_chem = bitton_tessler_2023_table_s1_chemistry(
+ domain_mode="absorber_blocking",
+ perovskite_ka_cm3_s=1.0e-11,
+ left_boundary=IodineBoundaryDeclaration(
+ contact_reaction_mode="metal_faradaic_corrosion",
+ contact_corrosion_velocity_m_s=1.0e-6,
+ ),
+ )
+ with pytest.raises(CapabilityError):
+ compile_iodine_device_1d(prepared, bad_chem, intervals_per_layer=(5, 14, 5))
+
+ chem_closed = bitton_tessler_2023_table_s1_chemistry(
+ domain_mode="full_stack_permeable",
+ perovskite_ka_cm3_s=1.0e-11,
+ )
+ chem_ag = bitton_tessler_2023_table_s1_chemistry(
+ domain_mode="full_stack_permeable",
+ perovskite_ka_cm3_s=1.0e-11,
+ left_boundary=IodineBoundaryDeclaration(
+ contact_reaction_mode="metal_faradaic_corrosion",
+ contact_corrosion_velocity_m_s=1.0e-6,
+ ),
+ )
+ dev_closed = compile_iodine_device_1d(
+ prepared, chem_closed, intervals_per_layer=(5, 14, 5)
+ )
+ dev_ag = compile_iodine_device_1d(
+ prepared, chem_ag, intervals_per_layer=(5, 14, 5)
+ )
+ assert dev_ag.has_open_iodine_loss
+ with pytest.raises(CapabilityError):
+ solve_iodine_steady_state(dev_ag, voltage_V=0.0, generation_scale=0.0)
+
+ ss_c = solve_iodine_steady_state(dev_closed, voltage_V=0.9, generation_scale=1.0)
+ assert ss_c.converged and ss_c.state is not None
+
+ # Analytical vs central FD Jacobian on cathode iodide node
+ prob_c = AssembledIodine1DProblem(dev_closed, voltage_V=0.9, generation_scale=1.0)
+ prob_ag = AssembledIodine1DProblem(dev_ag, voltage_V=0.9, generation_scale=1.0)
+ u_test = np.array(ss_c.state.u, dtype=np.float64, copy=True)
+ col0 = dev_ag.chem_slices["iodide"].start
+ eps = 1.0e-6
+ up, um = u_test.copy(), u_test.copy()
+ up[col0] += eps
+ um[col0] -= eps
+ df_p = prob_ag.residual(up) - prob_c.residual(up)
+ df_m = prob_ag.residual(um) - prob_c.residual(um)
+ fd_col = (df_p - df_m) / (2.0 * eps)
+ dj_ana = (prob_ag.jacobian(u_test) - prob_c.jacobian(u_test)).toarray()[:, col0]
+ np.testing.assert_allclose(dj_ana, fd_col, rtol=1.0e-8, atol=1.0e-8)
+
+ res_ag, led_ag = solve_iodine_bdf_transient(
+ dev_ag,
+ ss_c.state.u,
+ (0.0, 10.0),
+ voltage_fn=lambda _t: 0.9,
+ generation_fn=lambda _t: 1.0,
+ options=BDFOptions(
+ initial_step_s=1.0e-2,
+ max_step_s=1.0,
+ relative_tolerance=1.0e-2,
+ absolute_tolerance=1.0e15,
+ max_order=1,
+ max_steps=100,
+ ),
+ )
+ assert res_ag.completed and len(led_ag) > 0
+ inv_0 = ss_c.state.total_iodine_inventory_m2
+ cum_immob = 0.0
+ for acc in led_ag:
+ cum_immob += acc.step_immobilized_iodine_atoms_m2
+ assert abs((acc.in_device_iodine_m2 + cum_immob) - inv_0) / inv_0 <= 1.0e-9
+ assert cum_immob > 0.0
diff --git a/tests/unit/physics/test_iodine_chemistry.py b/tests/unit/physics/test_iodine_chemistry.py
new file mode 100644
index 00000000..18b1cb73
--- /dev/null
+++ b/tests/unit/physics/test_iodine_chemistry.py
@@ -0,0 +1,388 @@
+"""Unit tests for SolarLab iodine reaction-diffusion constitutive kernels (M1)."""
+
+from __future__ import annotations
+
+import math
+
+import numpy as np
+import pytest
+
+from solarlab.contracts import ContractError
+from solarlab.physics.chemistry import (
+ CANONICAL_IODINE_NETWORK,
+ IODINE_REACTIONS,
+ IODINE_SPECIES,
+ BoundedSpeciesMap,
+ IodineKineticsParameters,
+ PositiveSpeciesMap,
+ SoftplusSpeciesMap,
+ StoichiometricNetwork,
+ equilibrium_iodine_populations_m3,
+ evaluate_iodine_kinetics,
+ harmonic_face_diffusivity_m2_s,
+ smoluchowski_rate_m3_s,
+ species_sg_face_flux,
+)
+
+
+def _table_s1_perovskite_params(
+ size: int = 5,
+ *,
+ thermodynamic_mode: str = "wegscheider_detailed_balance",
+ reaction_e_order: str = "bimolecular_n",
+) -> IodineKineticsParameters:
+ """Bitton & Tessler (2023) SI Table S1 perovskite kinetic parameters in SI."""
+ vt_eV = 0.02585199
+ nc_m3 = 7.0e18 * 1e6
+ nv_m3 = 2.5e18 * 1e6
+ eg_eV = 1.6
+ ni_sq_m6 = nc_m3 * nv_m3 * math.exp(-eg_eV / vt_eV)
+ return IodineKineticsParameters(
+ k_a_m3_s=np.full(size, 1.0e-11 * 1e-6),
+ k_b_s_1=np.full(size, 3.0e5),
+ k_c_m3_s=np.full(size, 5.0e-7 * 1e-6),
+ k_d_m3_s=np.full(size, 5.0e-15 * 1e-6),
+ k_e_m3_s=np.full(size, 1.3e-8 * 1e-6),
+ k_e_3body_m6_s=np.full(size, 1.3e-24 * 1e-12),
+ n_i_sq_m6=np.full(size, ni_sq_m6),
+ K_diss_m3=np.full(size, 1.0e8 * 1e6),
+ n_e_star_m3=np.full(size, 1.0e8 * 1e6),
+ thermodynamic_mode=thermodynamic_mode, # type: ignore[arg-type]
+ reaction_e_order=reaction_e_order, # type: ignore[arg-type]
+ )
+
+
+def test_canonical_stoichiometric_network_nullspaces_and_bug_rejection() -> None:
+ net = CANONICAL_IODINE_NETWORK
+ assert net.species_ids == IODINE_SPECIES
+ assert net.reaction_ids == IODINE_REACTIONS
+ assert np.array_equal(net.charge_numbers @ net.nu, np.zeros(5, dtype=np.int64))
+ assert np.array_equal(net.iodine_atom_counts @ net.nu, np.zeros(5, dtype=np.int64))
+
+ # Verify exact source formula S_- = -R_a + R_b + R_c + 2 R_e
+ rates = np.array([2.0, 3.0, 5.0, 7.0, 11.0], dtype=np.float64)
+ sources = net.project_sources(rates)
+ assert sources[0] == pytest.approx(-5.0 - 2.0 * 11.0)
+ assert sources[1] == pytest.approx(-2.0 + 3.0)
+ assert sources[2] == pytest.approx(-2.0 + 3.0 + 5.0 + 2.0 * 11.0)
+ assert sources[3] == pytest.approx(2.0 - 3.0 - 5.0 - 2.0 * 7.0)
+ assert sources[4] == pytest.approx(7.0 - 11.0)
+ assert float(net.charge_numbers @ sources) == 0.0
+ assert float(net.iodine_atom_counts @ sources) == 0.0
+
+ # Reject the non-conserving derivation typo S_- = -R_a - R_b + 2 R_e
+ bad_nu = np.array(net.nu, copy=True)
+ bad_nu[2, :] = [-1, -1, 0, 0, 2]
+ with pytest.raises(ContractError, match="conservation_violated"):
+ StoichiometricNetwork(
+ species_ids=IODINE_SPECIES,
+ reaction_ids=IODINE_REACTIONS,
+ nu=bad_nu,
+ charge_numbers=net.charge_numbers,
+ iodine_atom_counts=net.iodine_atom_counts,
+ )
+
+
+def test_smoluchowski_rates_and_si_figure_s2a_quantitative_match() -> None:
+ vt_V = 0.02585199
+ r_ab_m = 0.2e-9 # 0.2 nm in Bitton & Tessler Table S1
+ d_e_m2_s = 2.0e-4 * vt_V # mu_e = 2 cm^2/(V s) -> 2e-4 m^2/(V s)
+ d_0_m2_s = 1.0e-8 * 1e-4 # D_0 = 1e-8 cm^2/s -> 1e-12 m^2/s
+
+ k_e_si = float(smoluchowski_rate_m3_s(d_e_m2_s, 1.0e-9 * 1e-4, r_ab_m)[0])
+ k_d_si = float(smoluchowski_rate_m3_s(d_0_m2_s, d_0_m2_s, r_ab_m)[0])
+ assert k_e_si * 1e6 == pytest.approx(1.30e-8, rel=1e-2)
+ assert k_d_si * 1e6 == pytest.approx(5.03e-15, rel=1e-2)
+
+ # SI Fig. S2(a) local steady balance k_d * c_0^2 = k_e * c_2 * n:
+ # Bulk: c_0 ~ 2e11 cm^-3, n ~ 2e15 cm^-3 -> c_2 < 1e2 cm^-3 (below 1e5 axis)
+ # Right interface: c_0 ~ 5e13 cm^-3, n ~ 1e11 cm^-3 -> c_2 ~ 9.6e9 cm^-3
+ k_d_cm3_s = 5.0e-15
+ k_e_cm3_s = 1.3e-8
+ c2_bulk_cm3 = k_d_cm3_s * (2.0e11) ** 2 / (k_e_cm3_s * 2.0e15)
+ c2_peak_cm3 = k_d_cm3_s * (5.0e13) ** 2 / (k_e_cm3_s * 1.0e11)
+ assert c2_bulk_cm3 < 1.0e2
+ assert 5.0e9 <= c2_peak_cm3 <= 2.0e10
+
+
+@pytest.mark.parametrize("reaction_e_order", ["bimolecular_n", "termolecular_n2"])
+def test_wegscheider_dark_thermal_equilibrium_vanishes_across_doping(
+ reaction_e_order: str,
+) -> None:
+ params = _table_s1_perovskite_params(
+ size=7,
+ thermodynamic_mode="wegscheider_detailed_balance",
+ reaction_e_order=reaction_e_order,
+ )
+ ni = np.sqrt(params.n_i_sq_m6)
+ factors = np.logspace(-6.0, 6.0, 7)
+ n_eq = ni * factors
+ p_eq = params.n_i_sq_m6 / n_eq
+ c_tot = np.full(7, 1.0e24) # 1e18 cm^-3 in SI
+
+ cm_eq, c0_eq, c2_eq = equilibrium_iodine_populations_m3(c_tot, n_eq, params)
+ np.testing.assert_allclose(cm_eq + c0_eq + 2.0 * c2_eq, c_tot, rtol=1e-15, atol=0.0)
+
+ ev = evaluate_iodine_kinetics(n_eq, p_eq, cm_eq, c0_eq, c2_eq, params)
+ forward_scale = np.maximum(ev.rates_m3_s[0], 1.0)
+ # Net hole oxidation R_a - R_b and reversible channels R_c, R_d, R_e vanish
+ np.testing.assert_allclose(
+ (ev.rates_m3_s[0] - ev.rates_m3_s[1]) / forward_scale, 0.0, atol=1e-14
+ )
+ for idx in (2, 3, 4):
+ np.testing.assert_allclose(
+ ev.rates_m3_s[idx] / forward_scale, 0.0, atol=1e-14
+ )
+ for sp in range(5):
+ np.testing.assert_allclose(
+ ev.sources_m3_s[sp] / forward_scale, 0.0, atol=1e-14
+ )
+
+
+@pytest.mark.parametrize(
+ ("thermodynamic_mode", "reaction_e_order"),
+ [
+ ("wegscheider_detailed_balance", "bimolecular_n"),
+ ("wegscheider_detailed_balance", "termolecular_n2"),
+ ("irreversible_mass_action", "bimolecular_n"),
+ ("irreversible_mass_action", "termolecular_n2"),
+ ],
+)
+def test_analytical_kinetics_jacobian_matches_central_finite_differences(
+ thermodynamic_mode: str,
+ reaction_e_order: str,
+) -> None:
+ params = _table_s1_perovskite_params(
+ size=4,
+ thermodynamic_mode=thermodynamic_mode,
+ reaction_e_order=reaction_e_order,
+ )
+ # Test on BOTH a near-dark-equilibrium regime (where forward and Wegscheider
+ # reverse terms have comparable magnitude so FD resolves every reverse partial
+ # to <= 1e-9 without float64 cancellation) AND a strong-injection regime.
+ assert params.n_1_iodine_m3 is not None
+ n_near = np.array([1.0e5, 5.0e6, 2.0e8, 1.0e10], dtype=np.float64)
+ p_near = params.n_i_sq_m6 / n_near
+ cm_eq, c0_eq, c2_eq = equilibrium_iodine_populations_m3(
+ np.full(4, 1.0e24), n_near, params
+ )
+ near_eq_state = [
+ 1.7 * n_near,
+ 0.6 * p_near,
+ 0.9 * cm_eq,
+ 1.4 * c0_eq + 1.0,
+ 2.3 * c2_eq + 1.0,
+ ]
+ high_inj_state = [
+ np.array([2.0e18, 2.5e18, 8.0e19, 3.0e20], dtype=np.float64),
+ np.array([4.0e17, 1.2e18, 5.0e17, 9.0e16], dtype=np.float64),
+ np.array([9.5e22, 1.0e23, 6.0e22, 2.0e22], dtype=np.float64),
+ np.array([8.0e18, 4.0e18, 2.0e19, 7.0e19], dtype=np.float64),
+ np.array([5.0e16, 3.0e17, 9.0e17, 1.5e18], dtype=np.float64),
+ ]
+
+ eps = np.finfo(np.float64).eps
+ net = CANONICAL_IODINE_NETWORK
+ abs_nu = np.abs(net.nu.astype(np.float64))
+
+ for state in (near_eq_state, high_inj_state):
+ ev = evaluate_iodine_kinetics(
+ state[0], state[1], state[2], state[3], state[4], params, derivatives=True
+ )
+ assert ev.dsources_dstate is not None
+
+ # Exact tangent nullspaces: z^T dS/dy == 0 and m_I^T dS/dy == 0
+ charge_tan = np.einsum(
+ "s,sjm->jm", net.charge_numbers.astype(float), ev.dsources_dstate
+ )
+ atom_tan = np.einsum(
+ "s,sjm->jm", net.iodine_atom_counts.astype(float), ev.dsources_dstate
+ )
+ scale = np.max(np.abs(ev.dsources_dstate), axis=0) + 1.0e-30
+ np.testing.assert_allclose(charge_tan / scale, 0.0, atol=1e-14)
+ np.testing.assert_allclose(atom_tan / scale, 0.0, atol=1e-14)
+
+ gross_source = abs_nu @ np.abs(ev.rates_m3_s)
+ # Gross internal operands inside each reaction rate (forward + reverse)
+ assert params.k_e_3body_m6_s is not None
+ r_internal = np.stack(
+ (
+ np.abs(ev.rates_m3_s[0]),
+ np.abs(ev.rates_m3_s[1]),
+ params.k_c_m3_s * (state[3] * state[0] + params.n_1_iodine_m3 * state[2]),
+ params.k_d_m3_s * (state[3] ** 2 + params.K_diss_m3 * state[4]),
+ np.abs(ev.rates_m3_s[4])
+ + params.k_e_m3_s * state[4] * state[0]
+ + params.k_e_3body_m6_s * state[4] * (state[0] ** 2),
+ ),
+ axis=0,
+ )
+ gross_total = np.maximum(gross_source, abs_nu @ r_internal)
+
+ for dep in range(5):
+ step = 1.0e-6 * np.maximum(state[dep], 1.0e-20)
+ plus = [arr.copy() for arr in state]
+ minus = [arr.copy() for arr in state]
+ plus[dep] += step
+ minus[dep] -= step
+ ev_plus = evaluate_iodine_kinetics(
+ plus[0], plus[1], plus[2], plus[3], plus[4], params, derivatives=False
+ )
+ ev_minus = evaluate_iodine_kinetics(
+ minus[0],
+ minus[1],
+ minus[2],
+ minus[3],
+ minus[4],
+ params,
+ derivatives=False,
+ )
+ fd = (ev_plus.sources_m3_s - ev_minus.sources_m3_s) / (2.0 * step[None, :])
+ roundoff = 32.0 * eps * gross_total / step[None, :]
+ assert np.all(
+ np.abs(ev.dsources_dstate[:, dep, :] - fd)
+ <= 1.0e-8 * np.abs(fd) + roundoff
+ )
+
+
+def test_positive_and_bounded_species_maps_overflow_free_and_cancellation_safe() -> None:
+ pmap = PositiveSpeciesMap(
+ scale_m3=np.full(5, 1.0e24),
+ eta=np.full(5, 1.0e-9),
+ vacuum_floor_m3=1.0,
+ )
+ # Extreme coordinates (from deep empty layer -1e5 to high density +1e5)
+ u_ext = np.array([-1.0e5, -1.0, 0.0, 1.0, 1.0e5], dtype=np.float64)
+ dens, tan = pmap.density_and_tangent_m3(u_ext)
+ assert np.all(np.isfinite(dens)) and np.all(dens > 0.0)
+ assert np.all(np.isfinite(tan)) and np.all(tan > 0.0)
+
+ # Exact round-trip including c = 0 mapped to vacuum_floor_m3
+ targets = np.array([0.0, 1.0, 1.0e12, 1.0e18, 1.0e24], dtype=np.float64)
+ coords = pmap.coordinate_from_density(targets)
+ recovered = pmap.density_m3(coords)
+ np.testing.assert_allclose(recovered, np.maximum(targets, 1.0), rtol=1e-14)
+
+ # Cancellation-free secant at tiny representable step matches exact tangent * du
+ raw_step = 1.0e-12 * np.maximum(np.abs(u_ext), 1.0e-9)
+ u_next = u_ext + raw_step
+ actual_du = u_next - u_ext
+ secant = pmap.secant_increment_m3(u_next, u_ext)
+ np.testing.assert_allclose(secant, tan * actual_du, rtol=1e-9)
+
+ # Bounded logistic map round-trip and cancellation-free secant
+ bmap = BoundedSpeciesMap(
+ site_limit_m3=np.full(4, 1.0e25),
+ logit_reference=np.full(4, -2.1972245773362196),
+ )
+ u_b = np.array([-40.0, -1.5, 0.5, 35.0], dtype=np.float64)
+ dens_b, tan_b = bmap.density_and_tangent_m3(u_b)
+ assert np.all((dens_b > 0.0) & (dens_b < 1.0e25))
+ u_b_next = u_b + 1.0e-11 * np.maximum(np.abs(u_b), 1.0)
+ actual_du_b = u_b_next - u_b
+ sec_b = bmap.secant_increment_m3(u_b_next, u_b)
+ np.testing.assert_allclose(sec_b, tan_b * actual_du_b, rtol=1e-9)
+ # Large step identity check against direct subtraction where uncancelled
+ u_b2 = np.array([-2.0, 1.0, 3.0, -1.0], dtype=np.float64)
+ np.testing.assert_allclose(
+ bmap.secant_increment_m3(u_b2, u_b),
+ bmap.density_m3(u_b2) - dens_b,
+ rtol=1e-13,
+ )
+
+ # Smooth log-linear Softplus map round-trip and cancellation-free secant
+ spmap = SoftplusSpeciesMap(scale_m3=np.full(5, 1.0e20), vacuum_floor_m3=1.0)
+ u_sp = np.array([-60.0, -5.0, 0.0, 8.0, 1.0e5], dtype=np.float64)
+ dens_sp, tan_sp = spmap.density_and_tangent_m3(u_sp)
+ assert np.all(np.isfinite(dens_sp)) and np.all(dens_sp > 0.0)
+ assert np.all(np.isfinite(tan_sp)) and np.all(tan_sp > 0.0)
+ sp_targets = np.array([0.0, 1.0, 1.0e14, 1.0e20, 1.0e25], dtype=np.float64)
+ sp_coords = spmap.coordinate_from_density(sp_targets)
+ np.testing.assert_allclose(
+ spmap.density_m3(sp_coords), np.maximum(sp_targets, 1.0), rtol=1e-13
+ )
+ u_sp_next = u_sp + 1.0e-12 * np.maximum(np.abs(u_sp), 1.0)
+ np.testing.assert_allclose(
+ spmap.secant_increment_m3(u_sp_next, u_sp),
+ tan_sp * (u_sp_next - u_sp),
+ rtol=1e-9,
+ )
+
+
+def test_species_sg_face_flux_equilibrium_and_analytical_derivatives() -> None:
+ vt = 0.02585199
+ phi = np.array([0.0, 0.35, -0.25, 0.60, 0.15], dtype=np.float64)
+ dx = np.array([5.0e-9, 1.2e-8, 2.0e-8, 8.0e-9], dtype=np.float64)
+ d_node = np.array([1.0e-16, 1.0e-12, 1.0e-12, 1.0e-12, 1.0e-16], dtype=np.float64)
+ d_face = harmonic_face_diffusivity_m2_s(d_node[:-1], d_node[1:])
+ k_part_nodes = np.array([0.02, 1.0, 1.0, 1.0, 0.05], dtype=np.float64)
+ log_step = np.log(k_part_nodes[1:] / k_part_nodes[:-1])
+
+ # Equilibrium profile for z = -1 with partition jump:
+ # c_eq_i = c_ref * K_part_i * exp(+phi_i / V_T)
+ c_eq = 1.0e22 * k_part_nodes * np.exp((phi - phi[0]) / vt)
+ ev_eq = species_sg_face_flux(
+ phi,
+ c_eq,
+ dx,
+ d_face,
+ vt,
+ charge_number=-1,
+ log_partition_step=log_step,
+ )
+ conductance_scale = (d_face / dx) * np.maximum(c_eq[:-1], c_eq[1:])
+ np.testing.assert_allclose(ev_eq.flux_m2_s / conductance_scale, 0.0, atol=1e-14)
+
+ # Out-of-equilibrium derivative check against central finite differences
+ c_neq = np.array([2.0e19, 9.0e23, 7.5e23, 1.1e24, 4.0e18], dtype=np.float64)
+ for z in (-1, 0):
+ ev = species_sg_face_flux(
+ phi,
+ c_neq,
+ dx,
+ d_face,
+ vt,
+ charge_number=z,
+ log_partition_step=log_step,
+ derivatives=True,
+ )
+ assert (
+ ev.dflux_dc_left is not None
+ and ev.dflux_dc_right is not None
+ and ev.dflux_dphi_left is not None
+ and ev.dflux_dphi_right is not None
+ )
+ for face in range(dx.size):
+ for side, dc_exact, dphi_exact in (
+ (face, ev.dflux_dc_left[face], ev.dflux_dphi_left[face]),
+ (face + 1, ev.dflux_dc_right[face], ev.dflux_dphi_right[face]),
+ ):
+ hc = 1.0e-6 * c_neq[side]
+ cp, cm = c_neq.copy(), c_neq.copy()
+ cp[side] += hc
+ cm[side] -= hc
+ fp = species_sg_face_flux(
+ phi, cp, dx, d_face, vt, charge_number=z,
+ log_partition_step=log_step, derivatives=False,
+ ).flux_m2_s[face]
+ fm = species_sg_face_flux(
+ phi, cm, dx, d_face, vt, charge_number=z,
+ log_partition_step=log_step, derivatives=False,
+ ).flux_m2_s[face]
+ assert dc_exact == pytest.approx((fp - fm) / (2.0 * hc), rel=1e-8, abs=1e-12)
+
+ hphi = 1.0e-6
+ pp, pm = phi.copy(), phi.copy()
+ pp[side] += hphi
+ pm[side] -= hphi
+ gp = species_sg_face_flux(
+ pp, c_neq, dx, d_face, vt, charge_number=z,
+ log_partition_step=log_step, derivatives=False,
+ ).flux_m2_s[face]
+ gm = species_sg_face_flux(
+ pm, c_neq, dx, d_face, vt, charge_number=z,
+ log_partition_step=log_step, derivatives=False,
+ ).flux_m2_s[face]
+ assert dphi_exact == pytest.approx(
+ (gp - gm) / (2.0 * hphi), rel=1e-8, abs=1e-12
+ )
diff --git a/web/src/iodine-aging-client.ts b/web/src/iodine-aging-client.ts
new file mode 100644
index 00000000..1d6a869b
--- /dev/null
+++ b/web/src/iodine-aging-client.ts
@@ -0,0 +1,229 @@
+export interface IodinePresetSummary {
+ id: string
+ name: string
+ description: string
+ reference: string
+ source_id: string
+ sha256: string
+ deck: Record
+}
+
+export interface IodinePresetCatalog {
+ schema: 'solarlab.iodine-presets.v1'
+ presets: IodinePresetSummary[]
+ scientific_acceptance: 'not_evaluated'
+ scientific_qualification: false
+}
+
+export interface IodineStateProfiles {
+ electrical_nodes_nm: number[]
+ chem_nodes_nm: number[]
+ potential_V: number[]
+ electron_density_m3: number[]
+ hole_density_m3: number[]
+ iodide_m3: number[]
+ iodine_atom_m3: number[]
+ iodine_molecule_m3: number[]
+ species_inventories_m2: Record
+ total_iodine_atoms_m2: number
+}
+
+export interface IodineFrozenJV {
+ voltages_V: number[]
+ output_current_A_m2: number[]
+ metrics: Record
+}
+
+export interface IodineSteadyResponse {
+ schema: 'solarlab.iodine-steady-result.v1'
+ deck_id: string
+ deck_name: string
+ device_sha256: string
+ domain_mode: string
+ operating_state_mode: string
+ voltage_V: number
+ generation_scale: number
+ profiles: IodineStateProfiles
+ frozen_jv: IodineFrozenJV | null
+ wall_s: number
+ scientific_acceptance: 'not_evaluated'
+ scientific_qualification: false
+}
+
+export interface IodineImpedanceSweep {
+ chem_mode: 'mobile' | 'frozen'
+ frequencies_Hz: number[]
+ admittance_real_S_m2: number[]
+ admittance_imag_S_m2: number[]
+ impedance_real_Ohm_m2: number[]
+ impedance_imag_Ohm_m2: number[]
+ apparent_capacitance_F_m2: number[]
+ max_maxwell_spread_A_m2_V: number
+ max_backward_error: number
+}
+
+export interface IodineImpedanceResponse {
+ schema: 'solarlab.iodine-impedance-result.v1'
+ deck_id: string
+ deck_name: string
+ device_sha256: string
+ domain_mode: string
+ operating_state_mode: string
+ voltage_V: number
+ generation_scale: number
+ frequencies_Hz: number[]
+ sweeps: Record
+ redox_excess_capacitance_F_m2: number[] | null
+ profiles: IodineStateProfiles
+ wall_s: number
+ scientific_acceptance: 'not_evaluated'
+ scientific_qualification: false
+}
+
+export interface IodineAgingCheckpoint {
+ time_s: number
+ stage_name: string
+ in_device_iodine_m2: number
+ cumulative_escaped_iodine_atoms_m2: number
+ cumulative_immobilized_iodine_atoms_m2: number
+ conservation_residual_m2: number
+ profiles: IodineStateProfiles
+ frozen_jv: IodineFrozenJV | null
+ dynamic_jv: Record | null
+}
+
+export interface IodineAgingResponse {
+ schema: 'solarlab.iodine-aging-result.v1'
+ deck_id: string
+ deck_name: string
+ protocol_sha256: string
+ device_sha256: string
+ domain_mode: string
+ reference_iodine_inventory_m2: number
+ max_relative_conservation_error: number
+ accepted_bdf_steps: number
+ completed: boolean
+ wall_s: number
+ trajectory: {
+ times_s: number[]
+ in_device_iodine_m2: number[]
+ cumulative_escaped_iodine_atoms_m2: number[]
+ cumulative_immobilized_iodine_atoms_m2: number[]
+ }
+ checkpoints: IodineAgingCheckpoint[]
+ persisted_run_store: { store_id: string; run_id: string; attempt_id: string } | null
+ scientific_acceptance: 'not_evaluated'
+ scientific_qualification: false
+}
+
+export interface IodineOverrides {
+ intervals_per_layer?: number | number[]
+ k_a_cm3_s?: number
+ mu_bl_cm2_V_s?: number
+ ebl_partition?: number
+ volumetric_escape_s_1?: number
+ contact_corrosion_m_s?: number
+ voltage_V?: number
+ generation_scale?: number
+ compute_frozen_jv?: boolean
+ f_min_Hz?: number
+ f_max_Hz?: number
+ n_frequencies?: number
+ chem_mode?: 'mobile' | 'frozen' | 'both'
+ probe_mode?: 'none' | 'frozen_chemistry_jv' | 'dynamic_jv_scan' | 'both'
+}
+
+export interface IodineRunRequest {
+ preset?: string
+ deck?: Record
+ overrides?: IodineOverrides
+ persist_to_store?: boolean
+ run_id?: string
+}
+
+function assertRecord(value: unknown, label: string): Record {
+ if (!value || typeof value !== 'object' || Array.isArray(value)) {
+ throw new Error(`${label} must be a JSON object`)
+ }
+ return value as Record
+}
+
+export class IodineAgingClient {
+ private readonly base: URL
+ private readonly fetchImpl: typeof fetch
+
+ constructor(endpoint: string | URL, fetchImpl: typeof fetch = globalThis.fetch.bind(globalThis)) {
+ this.base = new URL(String(endpoint))
+ if (!this.base.pathname.endsWith('/')) this.base.pathname += '/'
+ this.fetchImpl = fetchImpl
+ }
+
+ private url(path: string): string {
+ return new URL(path.replace(/^\//, ''), this.base).toString()
+ }
+
+ private async requestJson(path: string, init: RequestInit): Promise> {
+ const resp = await this.fetchImpl(this.url(path), init)
+ const text = await resp.text()
+ let parsed: unknown = null
+ try {
+ parsed = text ? JSON.parse(text) : null
+ } catch {
+ parsed = null
+ }
+ if (!resp.ok) {
+ const detail = parsed && typeof parsed === 'object' && 'detail' in parsed
+ ? String((parsed as Record).detail)
+ : `HTTP ${resp.status}`
+ throw new Error(detail)
+ }
+ return assertRecord(parsed, path)
+ }
+
+ async listPresets(signal?: AbortSignal): Promise {
+ const doc = await this.requestJson('iodine/presets', { method: 'GET', signal })
+ if (doc.schema !== 'solarlab.iodine-presets.v1' || doc.scientific_qualification !== false) {
+ throw new Error('Invalid iodine preset catalog schema or qualification flag')
+ }
+ return doc as unknown as IodinePresetCatalog
+ }
+
+ async runSteady(request: IodineRunRequest, signal?: AbortSignal): Promise {
+ const doc = await this.requestJson('iodine/steady', {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify(request),
+ signal,
+ })
+ if (doc.schema !== 'solarlab.iodine-steady-result.v1' || doc.scientific_qualification !== false) {
+ throw new Error('Invalid iodine steady response schema or qualification flag')
+ }
+ return doc as unknown as IodineSteadyResponse
+ }
+
+ async runImpedance(request: IodineRunRequest, signal?: AbortSignal): Promise {
+ const doc = await this.requestJson('iodine/impedance', {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify(request),
+ signal,
+ })
+ if (doc.schema !== 'solarlab.iodine-impedance-result.v1' || doc.scientific_qualification !== false) {
+ throw new Error('Invalid iodine impedance response schema or qualification flag')
+ }
+ return doc as unknown as IodineImpedanceResponse
+ }
+
+ async runAging(request: IodineRunRequest, signal?: AbortSignal): Promise {
+ const doc = await this.requestJson('iodine/aging', {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify(request),
+ signal,
+ })
+ if (doc.schema !== 'solarlab.iodine-aging-result.v1' || doc.scientific_qualification !== false) {
+ throw new Error('Invalid iodine aging response schema or qualification flag')
+ }
+ return doc as unknown as IodineAgingResponse
+ }
+}
diff --git a/web/src/iodine-aging.test.ts b/web/src/iodine-aging.test.ts
new file mode 100644
index 00000000..3e9bb454
--- /dev/null
+++ b/web/src/iodine-aging.test.ts
@@ -0,0 +1,189 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import Plotly from 'plotly.js-basic-dist-min'
+import { IodineAgingClient } from './iodine-aging-client'
+import { mountIodineAgingPanel } from './panels/iodine-aging'
+import type { IodineAgingPanel } from './panels/iodine-aging'
+
+vi.mock('plotly.js-basic-dist-min', () => ({
+ default: {
+ newPlot: vi.fn().mockResolvedValue(undefined),
+ purge: vi.fn(),
+ },
+}))
+
+const SAMPLE_CATALOG = {
+ schema: 'solarlab.iodine-presets.v1',
+ scientific_acceptance: 'not_evaluated',
+ scientific_qualification: false,
+ presets: [
+ {
+ id: 'bitton_tessler_2023_blocking',
+ name: 'Bitton & Tessler (2023) Blocking Absorber Stack',
+ description: 'Blocking 5-reaction iodine deck',
+ reference: 'Bitton & Tessler (2023)',
+ source_id: 'solarlab/materials/data/iodine_presets/bitton_tessler_2023_blocking.yaml',
+ sha256: '0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef',
+ deck: { schema_version: 'solarlab.iodine-deck.v1', id: 'bitton_tessler_2023_blocking' },
+ },
+ ],
+}
+
+const SAMPLE_PROFILES = {
+ electrical_nodes_nm: [0, 50, 300, 550, 600],
+ chem_nodes_nm: [50, 300, 550],
+ potential_V: [0.0, 0.2, 0.45, 0.7, 0.9],
+ electron_density_m3: [1e18, 1e20, 1e21, 1e19, 1e16],
+ hole_density_m3: [1e16, 1e19, 1e21, 1e20, 1e18],
+ iodide_m3: [1.2e24, 1.0e24, 0.8e24],
+ iodine_atom_m3: [1e19, 2e19, 3e19],
+ iodine_molecule_m3: [1e17, 5e17, 9e17],
+ species_inventories_m2: { iodide: 5.0e17, iodine_atom: 1.0e13, iodine_molecule: 2.5e11 },
+ total_iodine_atoms_m2: 5.000105e17,
+}
+
+const SAMPLE_STEADY = {
+ schema: 'solarlab.iodine-steady-result.v1',
+ deck_id: 'bitton_tessler_2023_blocking',
+ deck_name: 'Bitton & Tessler (2023) Blocking Absorber Stack',
+ device_sha256: 'deadbeef',
+ domain_mode: 'absorber_blocking',
+ operating_state_mode: 'closed_inventory_steady',
+ voltage_V: 0.9,
+ generation_scale: 1.0,
+ profiles: SAMPLE_PROFILES,
+ frozen_jv: {
+ voltages_V: [0.0, 0.6, 1.12],
+ output_current_A_m2: [215.0, 195.0, 0.0],
+ metrics: { open_circuit_voltage_V: 1.12, short_circuit_current_A_m2: 215.0 },
+ },
+ wall_s: 0.42,
+ scientific_acceptance: 'not_evaluated',
+ scientific_qualification: false,
+}
+
+const SAMPLE_IMPEDANCE = {
+ schema: 'solarlab.iodine-impedance-result.v1',
+ deck_id: 'bitton_tessler_2023_blocking',
+ deck_name: 'Bitton & Tessler (2023) Blocking Absorber Stack',
+ device_sha256: 'deadbeef',
+ domain_mode: 'absorber_blocking',
+ operating_state_mode: 'closed_inventory_steady',
+ voltage_V: 0.9,
+ generation_scale: 1.0,
+ frequencies_Hz: [0.01, 10.0, 1.0e5],
+ sweeps: {
+ mobile: {
+ chem_mode: 'mobile',
+ frequencies_Hz: [0.01, 10.0, 1.0e5],
+ admittance_real_S_m2: [10, 20, 50],
+ admittance_imag_S_m2: [0.05, 1.2, 60],
+ impedance_real_Ohm_m2: [0.1, 0.04, 0.008],
+ impedance_imag_Ohm_m2: [-0.0005, -0.002, -0.01],
+ apparent_capacitance_F_m2: [0.79, 0.019, 9.5e-5],
+ max_maxwell_spread_A_m2_V: 1e-11,
+ max_backward_error: 1e-14,
+ },
+ },
+ redox_excess_capacitance_F_m2: null,
+ profiles: SAMPLE_PROFILES,
+ wall_s: 0.35,
+ scientific_acceptance: 'not_evaluated',
+ scientific_qualification: false,
+}
+
+const SAMPLE_AGING = {
+ schema: 'solarlab.iodine-aging-result.v1',
+ deck_id: 'bitton_tessler_2023_blocking',
+ deck_name: 'Bitton & Tessler (2023) Blocking Absorber Stack',
+ protocol_sha256: 'aaaa',
+ device_sha256: 'bbbb',
+ domain_mode: 'absorber_blocking',
+ reference_iodine_inventory_m2: 5.0e17,
+ max_relative_conservation_error: 1.2e-13,
+ accepted_bdf_steps: 28,
+ completed: true,
+ wall_s: 0.78,
+ trajectory: {
+ times_s: [0, 60, 120],
+ in_device_iodine_m2: [5.0e17, 5.0e17, 5.0e17],
+ cumulative_escaped_iodine_atoms_m2: [0, 0, 0],
+ cumulative_immobilized_iodine_atoms_m2: [0, 0, 0],
+ },
+ checkpoints: [
+ {
+ time_s: 0,
+ stage_name: 'initial',
+ in_device_iodine_m2: 5.0e17,
+ cumulative_escaped_iodine_atoms_m2: 0,
+ cumulative_immobilized_iodine_atoms_m2: 0,
+ conservation_residual_m2: 0,
+ profiles: SAMPLE_PROFILES,
+ frozen_jv: SAMPLE_STEADY.frozen_jv,
+ dynamic_jv: null,
+ },
+ ],
+ persisted_run_store: null,
+ scientific_acceptance: 'not_evaluated',
+ scientific_qualification: false,
+}
+
+describe('IodineAgingClient & mountIodineAgingPanel', () => {
+ let root: HTMLElement
+ let panel: IodineAgingPanel | undefined
+
+ beforeEach(() => {
+ vi.clearAllMocks()
+ root = document.createElement('div')
+ document.body.append(root)
+ })
+
+ afterEach(() => {
+ panel?.dispose()
+ panel = undefined
+ root.remove()
+ })
+
+ it('rejects responses that violate scientific_qualification === false', async () => {
+ const badFetch = vi.fn().mockResolvedValue(
+ new Response(JSON.stringify({ ...SAMPLE_CATALOG, scientific_qualification: true }), { status: 200 }),
+ )
+ const client = new IodineAgingClient('http://localhost:8000', badFetch as unknown as typeof fetch)
+ await expect(client.listPresets()).rejects.toThrow(/qualification/)
+ })
+
+ it('mounts presets and executes steady, impedance, and aging modes', async () => {
+ const mockFetch = vi.fn(async (input: RequestInfo | URL) => {
+ const u = String(input)
+ if (u.endsWith('/iodine/presets')) return new Response(JSON.stringify(SAMPLE_CATALOG), { status: 200 })
+ if (u.endsWith('/iodine/steady')) return new Response(JSON.stringify(SAMPLE_STEADY), { status: 200 })
+ if (u.endsWith('/iodine/impedance')) return new Response(JSON.stringify(SAMPLE_IMPEDANCE), { status: 200 })
+ if (u.endsWith('/iodine/aging')) return new Response(JSON.stringify(SAMPLE_AGING), { status: 200 })
+ return new Response(JSON.stringify({ detail: 'not found' }), { status: 404 })
+ })
+
+ panel = mountIodineAgingPanel(root, 'http://localhost:8000/', mockFetch as unknown as typeof fetch)
+ await panel.ready
+ expect(root.querySelector('[data-role=state]')?.textContent).toBe('ready')
+ expect(root.querySelector('[data-role=preset-info]')?.textContent).toContain('Bitton & Tessler')
+
+ const modeSelect = root.querySelector('select[name=mode]')!
+ const kaInput = root.querySelector('input[name=k_a_cm3_s]')!
+ const submitBtn = root.querySelector('button[type=submit]')!
+
+ kaInput.value = '2e-11'
+ modeSelect.value = 'steady'
+ submitBtn.click()
+ await vi.waitFor(() => expect(root.querySelector('[data-role=state]')?.textContent).toBe('succeeded'))
+ expect(Plotly.newPlot).toHaveBeenCalledTimes(2)
+ expect(root.querySelector('[data-role=summary]')?.textContent).toContain('scientific_qualification=false')
+
+ modeSelect.value = 'impedance'
+ submitBtn.click()
+ await vi.waitFor(() => expect(Plotly.newPlot).toHaveBeenCalledTimes(3))
+
+ modeSelect.value = 'aging'
+ submitBtn.click()
+ await vi.waitFor(() => expect(Plotly.newPlot).toHaveBeenCalledTimes(5))
+ expect(panel.lastResult?.schema).toBe('solarlab.iodine-aging-result.v1')
+ })
+})
diff --git a/web/src/main.ts b/web/src/main.ts
index a5b16b89..aa7f5172 100644
--- a/web/src/main.ts
+++ b/web/src/main.ts
@@ -6,7 +6,20 @@ const app = document.querySelector('#app')!
async function mount() {
const query = new URL(location.href).searchParams
const serviceBase = new URL(resolveV2ServiceEndpoint())
- if (query.get('view') === 'steady-2d') {
+ if (query.get('view') === 'iodine-aging') {
+ const { mountIodineAgingPanel } = await import('./panels/iodine-aging')
+ app.innerHTML = ``
+ const host = app.querySelector('#iodine-aging')!
+ host.style.cssText = 'max-width:1300px;margin:auto;padding:20px;overflow:auto;max-height:calc(100vh - 90px)'
+ const panel = mountIodineAgingPanel(host, serviceBase)
+ window.addEventListener('pagehide', () => panel.dispose(), { once: true })
+ await panel.ready
+ } else if (query.get('view') === 'steady-2d') {
const { mountSteady2DPanel } = await import('./panels/steady-2d')
app.innerHTML = `