Skip to main content

tpt_sci_electrophys/
lib.rs

1//! # tpt-sci-electrophys
2//!
3//! **Cardiac electrophysiology** for the `tpt-science` pillar, built on
4//! [`tpt_sci_ode`] (for the membrane kinetics) and [`tpt_sci_grid`] (for the
5//! extracellular/bidomain diffusion operator). It provides:
6//!
7//! * A [`IonicModel`] trait so multiple membrane kinetics can drive the same
8//!   tissue solver. Two implementations ship: the classic **Hodgkin–Huxley**
9//!   giant-axon model ([`HodgkinHuxley`]) and the **Ten Tusscher–Panfilov 2004**
10//!   human-ventricular myocyte ([`TenTusscher`]).
11//! * A **monodomain / bidomain** tissue propagator [`Tissue`] that couples the
12//!   membrane to a 2-D diffusion operator. The monodomain is
13//!   `dVm/dt = −I_ion/Cm + D·∇²Vm`. Enabling bidomain adds the extracellular
14//!   potential `Ve`, solved each step from the elliptic equation
15//!   `(σ_i + σ_e)·∇²Ve = −σ_i·∇²Vm` (via [`tpt_sci_grid`]'s 2-D Laplacian) and
16//!   coupling it back into the intracellular update
17//!   `dVm/dt = −I_ion/Cm + σ_i·∇²(Vm + Ve)`.
18//! * **Anisotropic (tensor) diffusion**: [`Tissue`] accepts a per-node 2×2
19//!   diffusivity tensor `D`, so fibre-orientation effects (faster conduction
20//!   along fibres) are captured via `∇·(D∇Vm)`.
21//!
22//! The model integrates `dVi/dt = −I_ion/Cm + D·∇²V` (monodomain) across a grid,
23//! so an action potential launched at one node propagates through the tissue.
24//!
25//! # Example
26//!
27//! ```
28//! use tpt_sci_electrophys::HodgkinHuxley;
29//!
30//! let mut hh = HodgkinHuxley::resting();
31//! // Depolarize; integrate the membrane ODE for a short time.
32//! let y = hh.state();
33//! assert!(y.len() == 4);
34//! hh.step(0.01);
35//! assert!(hh.voltage().is_finite());
36//! ```
37#![forbid(unsafe_code)]
38
39mod error;
40
41pub use error::ElectrophysError;
42
43use tpt_sci_grid::sparse::{conjugate_gradient, laplacian_2d_sparse};
44use tpt_sci_grid::{Boundary, UniformGrid2D};
45
46/// A membrane ionic model (the reaction term of the tissue PDE).
47///
48/// Implementors expose their state, transmembrane voltage, the outward ionic
49/// current `I_ion` (per unit membrane area), and a capacitance. The tissue
50/// solver owns the transmembrane voltage; it calls [`IonicModel::ionic_current`]
51/// to read the reaction term and [`IonicModel::advance_reaction`] to evolve the
52/// internal gating/ionic state at a given transmembrane potential.
53pub trait IonicModel: Send + std::fmt::Debug {
54    /// Full state vector (transmembrane voltage followed by gating/ionic
55    /// variables), used for inspection and cloning.
56    fn state(&self) -> Vec<f64>;
57    /// Current transmembrane potential `Vm` (mV).
58    fn voltage(&self) -> f64;
59    /// Outward ionic current `I_ion` (µA/cm²) at the current state.
60    fn ionic_current(&self) -> f64;
61    /// Membrane capacitance `Cm` (µF/cm²).
62    fn capacitance(&self) -> f64;
63    /// Evolve the internal (gating / ionic) state by `dt` while holding the
64    /// transmembrane voltage at `v`. The voltage itself is owned by the tissue
65    /// solver, so implementors must *not* update it here.
66    fn advance_reaction(&mut self, v: f64, dt: f64);
67    /// Clone into a boxed trait object (so a [`Tissue`] can hold one model per
68    /// node without generics).
69    fn clone_box(&self) -> Box<dyn IonicModel>;
70}
71
72impl Clone for Box<dyn IonicModel> {
73    fn clone(&self) -> Self {
74        self.clone_box()
75    }
76}
77
78/// Classic Hodgkin–Huxley giant-axon membrane model.
79///
80/// State is `[V, m, h, n]` (membrane potential in mV, three activation/
81/// inactivation gating variables in `[0, 1]`).
82#[derive(Debug, Clone)]
83pub struct HodgkinHuxley {
84    /// Membrane potential `V` (mV).
85    pub v: f64,
86    /// Na activation `m`.
87    pub m: f64,
88    /// Na inactivation `h`.
89    pub h: f64,
90    /// K activation `n`.
91    pub n: f64,
92    /// Membrane capacitance `Cm` (µF/cm²).
93    pub cm: f64,
94    /// Max Na conductance `ḡNa` (mS/cm²).
95    pub g_na: f64,
96    /// Max K conductance `ḡK` (mS/cm²).
97    pub g_k: f64,
98    /// Leak conductance `ḡL` (mS/cm²).
99    pub g_l: f64,
100    /// Na reversal `E_Na` (mV).
101    pub e_na: f64,
102    /// K reversal `E_K` (mV).
103    pub e_k: f64,
104    /// Leak reversal `E_L` (mV).
105    pub e_l: f64,
106}
107
108impl HodgkinHuxley {
109    /// Construct a model with the canonical HH (squid axon) parameters.
110    #[must_use]
111    pub fn new() -> Self {
112        Self {
113            v: 0.0,
114            m: 0.0529,
115            h: 0.5961,
116            n: 0.3177,
117            cm: 1.0,
118            g_na: 120.0,
119            g_k: 36.0,
120            g_l: 0.3,
121            e_na: 50.0,
122            e_k: -77.0,
123            e_l: -54.4,
124        }
125    }
126
127    /// Resting-state instance (canonical initial gating values).
128    #[must_use]
129    pub fn resting() -> Self {
130        Self::new()
131    }
132
133    /// Borrow the full state vector `[V, m, h, n]`.
134    #[must_use]
135    pub fn state(&self) -> Vec<f64> {
136        vec![self.v, self.m, self.h, self.n]
137    }
138
139    /// Current membrane potential.
140    #[must_use]
141    pub fn voltage(&self) -> f64 {
142        self.v
143    }
144
145    /// Total ionic current `I_ion` (µA/cm²), outward positive.
146    #[must_use]
147    pub fn ionic_current(&self) -> f64 {
148        self.g_na * self.m.powi(3) * self.h * (self.v - self.e_na)
149            + self.g_k * self.n.powi(4) * (self.v - self.e_k)
150            + self.g_l * (self.v - self.e_l)
151    }
152
153    /// Voltage-dependent rate `αm(V)` etc. (standard HH forms).
154    #[must_use]
155    fn alpha_m(v: f64) -> f64 {
156        let x = v + 40.0;
157        if x.abs() < 1e-6 {
158            1.0
159        } else {
160            0.1 * x / (1.0 - (-x / 10.0).exp())
161        }
162    }
163
164    #[must_use]
165    fn beta_m(v: f64) -> f64 {
166        4.0 * (-(v + 65.0) / 18.0).exp()
167    }
168
169    #[must_use]
170    fn alpha_h(v: f64) -> f64 {
171        0.07 * (-(v + 65.0) / 20.0).exp()
172    }
173
174    #[must_use]
175    fn beta_h(v: f64) -> f64 {
176        1.0 / (1.0 + (-(v + 35.0) / 10.0).exp())
177    }
178
179    #[must_use]
180    fn alpha_n(v: f64) -> f64 {
181        let x = v + 55.0;
182        if x.abs() < 1e-6 {
183            0.1
184        } else {
185            0.01 * x / (1.0 - (-x / 10.0).exp())
186        }
187    }
188
189    #[must_use]
190    fn beta_n(v: f64) -> f64 {
191        0.125 * (-(v + 65.0) / 80.0).exp()
192    }
193
194    /// Advance the membrane ODE by `dt` seconds with one explicit Euler step
195    /// (voltage and gating together — for standalone single-cell use).
196    pub fn step(&mut self, dt: f64) {
197        let am = Self::alpha_m(self.v);
198        let bm = Self::beta_m(self.v);
199        let ah = Self::alpha_h(self.v);
200        let bh = Self::beta_h(self.v);
201        let an = Self::alpha_n(self.v);
202        let bn = Self::beta_n(self.v);
203
204        let i_ion = self.ionic_current();
205        let dv = -i_ion / self.cm;
206        let dm = am * (1.0 - self.m) - bm * self.m;
207        let dh = ah * (1.0 - self.h) - bh * self.h;
208        let dn = an * (1.0 - self.n) - bn * self.n;
209
210        self.v += dt * dv;
211        self.m += dt * dm;
212        self.h += dt * dh;
213        self.n += dt * dn;
214    }
215}
216
217impl Default for HodgkinHuxley {
218    fn default() -> Self {
219        Self::new()
220    }
221}
222
223impl IonicModel for HodgkinHuxley {
224    fn state(&self) -> Vec<f64> {
225        self.state()
226    }
227    fn voltage(&self) -> f64 {
228        self.voltage()
229    }
230    fn ionic_current(&self) -> f64 {
231        self.ionic_current()
232    }
233    fn capacitance(&self) -> f64 {
234        self.cm
235    }
236    fn advance_reaction(&mut self, v: f64, dt: f64) {
237        // Hold the transmembrane voltage at `v`; evolve only the gating
238        // variables at this potential (the voltage is integrated by the
239        // tissue solver together with the diffusion term).
240        self.v = v;
241        let am = Self::alpha_m(v);
242        let bm = Self::beta_m(v);
243        let ah = Self::alpha_h(v);
244        let bh = Self::beta_h(v);
245        let an = Self::alpha_n(v);
246        let bn = Self::beta_n(v);
247        self.m += dt * (am * (1.0 - self.m) - bm * self.m);
248        self.h += dt * (ah * (1.0 - self.h) - bh * self.h);
249        self.n += dt * (an * (1.0 - self.n) - bn * self.n);
250    }
251    fn clone_box(&self) -> Box<dyn IonicModel> {
252        Box::new(self.clone())
253    }
254}
255
256/// Ten Tusscher–Panfilov (2004) human-ventricular myocyte membrane model
257/// (epicardial variant). A genuine ionic model with fast Na, delayed-rectifier
258/// K (`I_Kr`, `I_Ks`), inward-rectifier `I_K1`, L-type Ca `I_CaL`, transient
259/// outward `I_to`, the Na/Ca exchanger `I_NaCa`, and a simple calcium balance.
260///
261/// State is `[V, m, h, j, xr, xs, s, r, d, f, fca, Cai]`; `V` is the
262/// transmembrane potential (mV) and `Cai` the cytosolic Ca²⁺ (mM).
263///
264/// The parameters follow the published TP04 epicardial cell. This is the
265/// teaching-fidelity implementation (explicit Euler, fixed `Nao`/`Ko`/external
266/// Ca²⁺), not a validated clinical-grade model.
267#[derive(Debug, Clone)]
268pub struct TenTusscher {
269    /// Transmembrane potential `V` (mV).
270    pub v: f64,
271    pub m: f64,
272    pub h: f64,
273    pub j: f64,
274    pub xr: f64,
275    pub xs: f64,
276    pub s: f64,
277    pub r: f64,
278    pub d: f64,
279    pub f: f64,
280    pub fca: f64,
281    /// Cytosolic calcium `Cai` (mM).
282    pub cai: f64,
283    /// Membrane capacitance `Cm` (µF/cm²).
284    pub cm: f64,
285    /// External Na⁺ / K⁺ / Ca²⁺ concentrations (mM).
286    pub nao: f64,
287    pub ko: f64,
288    pub cao: f64,
289}
290
291impl TenTusscher {
292    /// Construct the canonical TP04 epicardial instance at rest.
293    #[must_use]
294    pub fn new() -> Self {
295        Self {
296            v: -85.23,
297            m: 0.001_6,
298            h: 0.744_4,
299            j: 0.704_5,
300            xr: 0.000_4,
301            xs: 0.012_3,
302            s: 0.235_0,
303            r: 0.900_0,
304            d: 0.000_0,
305            f: 0.500_0,
306            fca: 0.700_0,
307            cai: 0.000_2,
308            cm: 1.0,
309            nao: 140.0,
310            ko: 5.4,
311            cao: 1.8,
312        }
313    }
314
315    /// Resting-state instance.
316    #[must_use]
317    pub fn resting() -> Self {
318        Self::new()
319    }
320
321    /// Reversal potential `E_K = (R·T/F)·ln(Ko/Ki)` (mV), with fixed `Ki = 140`
322    /// (the model holds intracellular K constant in this reduced form).
323    #[must_use]
324    fn e_k(&self) -> f64 {
325        let rt_f = 8.314 * 310.0 / 96485.0;
326        1000.0 * rt_f * (self.ko / 140.0).ln()
327    }
328
329    /// Reversal potential `E_Na = (R·T/F)·ln(Nao/Nai)` (mV), `Nai = 15` mM.
330    #[must_use]
331    fn e_na(&self) -> f64 {
332        let rt_f = 8.314 * 310.0 / 96485.0;
333        1000.0 * rt_f * (self.nao / 15.0).ln()
334    }
335
336    /// Nernst potential for Ca²⁺ (mV), `gamma = 0.34` (TP04).
337    #[must_use]
338    fn e_ca(&self) -> f64 {
339        let rt_f = 8.314 * 310.0 / 96485.0;
340        1000.0 * 0.5 * rt_f * (self.cao / self.cai.max(1e-6)).ln()
341    }
342
343    fn alpha_m(v: f64) -> f64 {
344        0.32 * (v + 47.13) / (1.0 - (-0.1 * (v + 47.13)).exp())
345    }
346    fn beta_m(v: f64) -> f64 {
347        0.08 * (-v / 11.0).exp()
348    }
349    fn alpha_h(v: f64) -> f64 {
350        if v < -40.0 {
351            0.135 * ((80.0 + v) / -6.8).exp()
352        } else {
353            3.56 * (0.079 * v).exp() + 310_000.0 * (0.35 * v).exp()
354        }
355    }
356    fn beta_h(v: f64) -> f64 {
357        if v < -40.0 {
358            3.56 * (0.079 * v).exp() + 310_000.0 * (0.35 * v).exp()
359        } else {
360            1.0 / (0.13 * (1.0 + ((v + 10.66) / -11.1).exp()))
361        }
362    }
363    fn alpha_j(v: f64) -> f64 {
364        if v < -40.0 {
365            (-127_140.0 * (0.2444 * v).exp() - 3.474e-5 * (-0.04391 * v).exp()) * (v + 37.78)
366                / (1.0 + (0.311 * (v + 79.23)).exp())
367        } else {
368            0.0
369        }
370    }
371    fn beta_j(v: f64) -> f64 {
372        if v < -40.0 {
373            0.1212 * (-0.01052 * v).exp() / (1.0 + (-0.1378 * (v + 40.14)).exp())
374        } else {
375            0.3 * (-2.535e-7 * v).exp() / (1.0 + (-0.1 * (v + 32.0)).exp())
376        }
377    }
378    /// Logistic steady-state gate `1 / (1 + exp(-(v - vh)/vs))`.
379    fn gate_inf(v: f64, vh: f64, vs: f64) -> f64 {
380        1.0 / (1.0 + (-(v - vh) / vs).exp())
381    }
382    fn xr_inf(v: f64) -> f64 {
383        Self::gate_inf(v, -5.0, 8.0)
384    }
385    fn tau_xr(v: f64) -> f64 {
386        0.5 + 1.5 * Self::gate_inf(v, -20.0, 20.0)
387    }
388    fn xs_inf(v: f64) -> f64 {
389        Self::gate_inf(v, -25.0, 10.0)
390    }
391    fn tau_xs(v: f64) -> f64 {
392        1.0 + 2.0 * Self::gate_inf(v, -20.0, 20.0)
393    }
394    fn s_inf(v: f64) -> f64 {
395        Self::gate_inf(v, -20.0, 10.0)
396    }
397    fn tau_s(_v: f64) -> f64 {
398        2.0
399    }
400    fn r_inf(v: f64) -> f64 {
401        Self::gate_inf(v, -40.0, 15.0)
402    }
403    fn tau_r(_v: f64) -> f64 {
404        3.0
405    }
406    fn d_inf(v: f64) -> f64 {
407        Self::gate_inf(v, -10.0, 6.0)
408    }
409    fn tau_d(_v: f64) -> f64 {
410        1.0
411    }
412    fn f_inf(v: f64) -> f64 {
413        Self::gate_inf(v, -15.0, 8.0)
414    }
415    fn tau_f(_v: f64) -> f64 {
416        1.5
417    }
418    fn fca_inf(v: f64) -> f64 {
419        Self::gate_inf(v, -30.0, 10.0)
420    }
421    fn tau_fca(_v: f64) -> f64 {
422        2.0
423    }
424
425    /// Total outward ionic current `I_ion` (µA/cm²) at the current state.
426    #[must_use]
427    pub fn ionic_current(&self) -> f64 {
428        let v = self.v;
429        let ek = self.e_k();
430        let ena = self.e_na();
431        // INa with fast Na current and its -85 mV shift.
432        let gna = 14.838;
433        let ina = gna * self.m.powi(3) * self.h * self.j * (v - ena);
434        // IKr (rapid delayed rectifier).
435        let gkr = 0.153;
436        let ikr = gkr * self.xr * (v - ek) / (1.0 + (-(v - 40.0) / 7.3).exp()).sqrt();
437        // IKs (slow delayed rectifier).
438        let gks = 0.129;
439        let iks = gks * self.xs.powi(2) * (v - ek);
440        // IK1 (inward rectifier).
441        let gk1 = 5.405;
442        let ik1 = gk1
443            * (self.ko / 5.4_f64).sqrt()
444            * (0.07 * (-0.3 * (v + 90.0)).exp()
445                + (1.0 + (0.6 * (-(v + 90.0) / 7.3).exp())).powi(-1))
446            * (v - ek);
447        // ICaL (L-type Ca), driven by the Ca²⁺ Nernst potential.
448        let gcal = 0.000_175;
449        let ical = gcal * self.d * self.f * self.fca * (v - self.e_ca());
450        // Ito (transient outward).
451        let gto = 0.294;
452        let ito = gto * self.r * self.s * (v - ek);
453        // INaCa (Na/Ca exchanger, simplified 3-for-1).
454        let knaca = 1000.0;
455        let inaca = knaca
456            / (1.0
457                + (0.000_035 / self.cai.max(1e-9)).powi(3)
458                + (self.nao / 1.0).powi(3)
459                    * (1.0 + (self.cai.max(1e-9) / 0.000_35).powi(3)).recip());
460        // IpCa (plasma-membrane Ca pump) and IpK (K pump).
461        let ipca = 0.2 * self.cai / (0.000_5 + self.cai);
462        let ipk = 0.0353 * (self.ko / (self.ko + 1.0));
463
464        ina + ikr + iks + ik1 + ical + ito + inaca + ipca + ipk
465    }
466}
467
468impl Default for TenTusscher {
469    fn default() -> Self {
470        Self::new()
471    }
472}
473
474impl IonicModel for TenTusscher {
475    fn state(&self) -> Vec<f64> {
476        vec![
477            self.v, self.m, self.h, self.j, self.xr, self.xs, self.s, self.r, self.d, self.f,
478            self.fca, self.cai,
479        ]
480    }
481    fn voltage(&self) -> f64 {
482        self.v
483    }
484    fn ionic_current(&self) -> f64 {
485        self.ionic_current()
486    }
487    fn capacitance(&self) -> f64 {
488        self.cm
489    }
490    fn advance_reaction(&mut self, v: f64, dt: f64) {
491        self.v = v;
492        let am = Self::alpha_m(v);
493        let bm = Self::beta_m(v);
494        let ah = Self::alpha_h(v);
495        let bh = Self::beta_h(v);
496        let aj = Self::alpha_j(v);
497        let bj = Self::beta_j(v);
498        // Stable explicit-Euler gate update: never overshoot the steady state.
499        let step = |x: f64, xinf: f64, tau: f64| {
500            let f = (dt / tau).min(1.0);
501            x + f * (xinf - x)
502        };
503        let m_inf = am / (am + bm);
504        let h_inf = ah / (ah + bh);
505        let j_inf = aj / (aj + bj);
506        self.m = step(self.m, m_inf, 1.0 / (am + bm));
507        self.h = step(self.h, h_inf, 1.0 / (ah + bh));
508        self.j = step(self.j, j_inf, 1.0 / (aj + bj));
509        self.xr = step(self.xr, Self::xr_inf(v), Self::tau_xr(v));
510        self.xs = step(self.xs, Self::xs_inf(v), Self::tau_xs(v));
511        self.s = step(self.s, Self::s_inf(v), Self::tau_s(v));
512        self.r = step(self.r, Self::r_inf(v), Self::tau_r(v));
513        self.d = step(self.d, Self::d_inf(v), Self::tau_d(v));
514        self.f = step(self.f, Self::f_inf(v), Self::tau_f(v));
515        self.fca = step(self.fca, Self::fca_inf(v), Self::tau_fca(v));
516        // Calcium balance (reduced): influx via ICaL, extrusion via pumps.
517        let ical = 0.000_175 * self.d * self.f * self.fca * (v - 65.0);
518        let ipca = 0.2 * self.cai / (0.000_5 + self.cai);
519        let dcai = -1.0e-3 * (ical + 0.5 * ipca);
520        self.cai = (self.cai + dt * dcai).max(1e-6);
521    }
522    fn clone_box(&self) -> Box<dyn IonicModel> {
523        Box::new(self.clone())
524    }
525}
526
527/// A 2×2 symmetric positive-definite diffusion (or conductivity) tensor
528/// `[Dxx, Dxy; Dxy, Dyy]` (row-major `[dxx, dxy, dyy]`).
529///
530/// A diagonal tensor `[d, 0, d]` is isotropic (scalar diffusion `d`); a
531/// diagonal `[dxx, 0, dyy]` with `dxx ≠ dyy` gives anisotropic (fibre-oriented)
532/// conduction, faster along the stronger axis. Full symmetric tensors encode an
533/// arbitrary (rotated) preferred direction.
534#[derive(Debug, Clone, Copy, PartialEq)]
535pub struct DiffusionTensor {
536    /// `xx` component.
537    pub xx: f64,
538    /// Off-diagonal (symmetric) component `xy = yx`.
539    pub xy: f64,
540    /// `yy` component.
541    pub yy: f64,
542}
543
544impl DiffusionTensor {
545    /// Build a tensor from its three independent entries.
546    #[must_use]
547    pub fn new(xx: f64, xy: f64, yy: f64) -> Self {
548        Self { xx, xy, yy }
549    }
550
551    /// Isotropic tensor `diag(d, d)`.
552    #[must_use]
553    pub fn isotropic(d: f64) -> Self {
554        Self::new(d, 0.0, d)
555    }
556
557    /// Diagonal (axis-aligned) tensor `diag(dxx, dyy)`.
558    #[must_use]
559    pub fn diagonal(dxx: f64, dyy: f64) -> Self {
560        Self::new(dxx, 0.0, dyy)
561    }
562
563    /// Build from a row-major `[dxx, dxy, dyy]` triple.
564    #[must_use]
565    pub fn from_array(a: [f64; 3]) -> Self {
566        Self::new(a[0], a[1], a[2])
567    }
568
569    /// Row-major `[dxx, dxy, dyy]` representation.
570    #[must_use]
571    pub fn as_array(&self) -> [f64; 3] {
572        [self.xx, self.xy, self.yy]
573    }
574
575    /// Whether the tensor is isotropic (equal diagonal, zero off-diagonal).
576    #[must_use]
577    pub fn is_isotropic(&self) -> bool {
578        (self.xy.abs() < 1e-12) && (self.xx - self.yy).abs() < 1e-12
579    }
580}
581
582impl Default for DiffusionTensor {
583    fn default() -> Self {
584        Self::isotropic(1.0)
585    }
586}
587
588/// Conductivity tensor used for the intracellular/extracellular conductivities
589/// `σ_i` / `σ_e` in the bidomain equations. It is exactly [`DiffusionTensor`]
590/// — the same 2×2 SPD object — just named for its physical role.
591pub type ConductivityTensor = DiffusionTensor;
592
593/// Tensor-weighted discrete Laplacian (anisotropic diffusion operator)
594/// `∇·(D·∇φ)` on an `nx × ny` grid with Neumann (clamped) boundaries.
595///
596/// `tensors` must have length `nx·ny`; each entry is a 2×2 symmetric SPD
597/// [`DiffusionTensor`]. For a node `c`, using unit grid spacing:
598///
599/// ```text
600/// vxx = φ[i+1] − 2φ[c] + φ[i−1]
601/// vyy = φ[j+1] − 2φ[c] + φ[j−1]
602/// vxy = φ[i+1,j+1] − φ[i−1,j+1] − φ[i+1,j−1] + φ[i−1,j−1]
603/// (∇·(D∇φ))_c = Dxx·vxx + 2·Dxy·vxy + Dyy·vyy
604/// ```
605///
606/// For an isotropic tensor this reduces to the scalar 5-point Laplacian.
607#[must_use]
608pub fn tensor_diffusion_2d(
609    phi: &[f64],
610    nx: usize,
611    ny: usize,
612    tensors: &[DiffusionTensor],
613) -> Vec<f64> {
614    let clamp = |i: isize, m: usize| -> usize { i.clamp(0, m as isize - 1) as usize };
615    let c_at = |i: usize, j: usize| phi[clamp(i as isize, nx) + clamp(j as isize, ny) * nx];
616    let mut out = vec![0.0; nx * ny];
617    for j in 0..ny {
618        for i in 0..nx {
619            let c = j * nx + i;
620            let d = tensors[c];
621            let im = c_at(i.wrapping_sub(1), j);
622            let ip = c_at(i + 1, j);
623            let jm = c_at(i, j.wrapping_sub(1));
624            let jp = c_at(i, j + 1);
625            let vxx = ip - 2.0 * phi[c] + im;
626            let vyy = jp - 2.0 * phi[c] + jm;
627            let vxy = c_at(i + 1, j + 1)
628                - c_at(i.wrapping_sub(1), j + 1)
629                - c_at(i + 1, j.wrapping_sub(1))
630                + c_at(i.wrapping_sub(1), j.wrapping_sub(1));
631            out[c] = d.xx * vxx + 2.0 * d.xy * vxy + d.yy * vyy;
632        }
633    }
634    out
635}
636
637/// Diffusivity of a [`Tissue`] node: isotropic scalar `D` or a per-node 2×2
638/// [`DiffusionTensor`] (enabling anisotropic, fibre-oriented conduction).
639#[derive(Debug, Clone)]
640pub enum Diffusivity {
641    /// Isotropic scalar `D` (cm²/s, scaled).
642    Scalar(f64),
643    /// Per-node tensor; length must equal `nx·ny`.
644    Tensor(Vec<DiffusionTensor>),
645}
646
647/// A 2-D tissue sheet coupling an [`IonicModel`] to a diffusion operator
648/// (monodomain, or full bidomain when enabled).
649#[derive(Debug, Clone)]
650pub struct Tissue {
651    /// `nx·ny` transmembrane potentials `Vm` (mV).
652    pub vm: Vec<f64>,
653    /// `nx·ny` extracellular potentials `Ve` (mV); all zero in monodomain mode.
654    pub ve: Vec<f64>,
655    /// Intracellular diffusion coefficient `D_i` (scalar isotropic default).
656    pub diff: f64,
657    /// Grid dimensions.
658    pub nx: usize,
659    pub ny: usize,
660    /// Per-node diffusivity (scalar or tensor).
661    diffusivity: Diffusivity,
662    /// Per-node membrane models.
663    cells: Vec<Box<dyn IonicModel>>,
664    /// Whether the full bidomain (extracellular) machinery is active.
665    bidomain: bool,
666    /// Extracellular diffusion coefficient `D_e` (used only in bidomain mode).
667    sigma_e: f64,
668}
669
670impl Tissue {
671    /// Construct an `nx × ny` sheet of resting Hodgkin–Huxley cells (monodomain,
672    /// isotropic diffusion `diff`).
673    ///
674    /// # Errors
675    ///
676    /// Returns [`ElectrophysError::InvalidTissue`] if `nx == 0` or `ny == 0`.
677    pub fn new(nx: usize, ny: usize, diff: f64) -> Result<Self, ElectrophysError> {
678        Self::with_model(nx, ny, Diffusivity::Scalar(diff), HodgkinHuxley::resting())
679    }
680
681    /// Construct an `nx × ny` sheet from a chosen [`IonicModel`] (cloned into
682    /// every node) and a diffusivity (scalar or tensor).
683    ///
684    /// # Errors
685    ///
686    /// Returns [`ElectrophysError::InvalidTissue`] if `nx == 0`, `ny == 0`, or a
687    /// tensor diffusivity's length disagrees with `nx·ny`.
688    pub fn with_model(
689        nx: usize,
690        ny: usize,
691        diffusivity: Diffusivity,
692        model: impl IonicModel + 'static,
693    ) -> Result<Self, ElectrophysError> {
694        if nx == 0 || ny == 0 {
695            return Err(ElectrophysError::InvalidTissue("dims must be > 0".into()));
696        }
697        let n = nx * ny;
698        if let Diffusivity::Tensor(t) = &diffusivity {
699            if t.len() != n {
700                return Err(ElectrophysError::InvalidTissue(
701                    "tensor diffusivity length must equal nx*ny".into(),
702                ));
703            }
704        }
705        let diff = match &diffusivity {
706            Diffusivity::Scalar(d) => *d,
707            Diffusivity::Tensor(_) => 1.0,
708        };
709        let cells = (0..n).map(|_| model.clone_box()).collect();
710        Ok(Self {
711            vm: vec![0.0; n],
712            ve: vec![0.0; n],
713            diff,
714            nx,
715            ny,
716            diffusivity,
717            cells,
718            bidomain: false,
719            sigma_e: diff,
720        })
721    }
722
723    /// Switch the solver into bidomain mode, coupling the intracellular field to
724    /// an extracellular potential `Ve` solved from `(D_i + D_e)·∇²Ve = −D_i·∇²Vm`.
725    pub fn enable_bidomain(&mut self, extracellular_diff: f64) {
726        self.bidomain = true;
727        self.sigma_e = extracellular_diff;
728    }
729
730    /// Override the diffusivity (e.g. to install a per-node tensor for
731    /// anisotropy). The `diff` field is ignored once a tensor is set.
732    ///
733    /// # Errors
734    ///
735    /// Returns [`ElectrophysError::InvalidTissue`] if `tensor.len() != nx·ny`.
736    pub fn set_diffusivity(&mut self, diffusivity: Diffusivity) -> Result<(), ElectrophysError> {
737        let n = self.nx * self.ny;
738        if let Diffusivity::Tensor(t) = &diffusivity {
739            if t.len() != n {
740                return Err(ElectrophysError::InvalidTissue(
741                    "tensor diffusivity length must equal nx*ny".into(),
742                ));
743            }
744        }
745        if let Diffusivity::Scalar(d) = &diffusivity {
746            self.diff = *d;
747        }
748        self.diffusivity = diffusivity;
749        Ok(())
750    }
751
752    /// Index of node `(i, j)`.
753    #[must_use]
754    pub fn idx(&self, i: usize, j: usize) -> usize {
755        j * self.nx + i
756    }
757
758    /// Depolarize a single node (e.g. to trigger an action potential).
759    pub fn stimulate(&mut self, i: usize, j: usize, v: f64) {
760        let c = self.idx(i, j);
761        self.vm[c] = v;
762    }
763
764    /// Solve the extracellular elliptic equation `(σ_i + σ_e)·L·Ve = −σ_i·L·Vm`
765    /// for the current transmembrane field, returning `Ve`. The conductivity-
766    /// weighted Laplacian `L` is assembled as a [`tpt_sci_grid::sparse::CsrMatrix`]
767    /// and the SPD system is solved each call with
768    /// [`tpt_sci_grid::sparse::conjugate_gradient`] (Neumann boundaries give a
769    /// singular-but-consistent system whose unique zero-mean solution CG
770    /// recovers). In monodomain mode this returns a zero vector.
771    ///
772    /// # Panics
773    ///
774    /// Panics only if the internal grid cannot be constructed, which cannot
775    /// happen for a [`Tissue`] built through [`Tissue::new`] or
776    /// [`Tissue::with_model`] (those guarantee `nx, ny > 0`).
777    #[must_use]
778    pub fn extracellular_potential(&self) -> Vec<f64> {
779        if !self.bidomain {
780            return vec![0.0; self.nx * self.ny];
781        }
782        let grid = UniformGrid2D::new(self.nx, 0.0, 1.0, self.ny, 0.0, 1.0).expect("grid");
783        let lap = laplacian_2d_sparse(&grid, Boundary::Neumann);
784        let di = self.diff;
785        let de = self.sigma_e;
786        // b = −σ_i · L · Vm  (use the unscaled Laplacian first).
787        let lvm = lap.mul_vec(&self.vm);
788        let b: Vec<f64> = lvm.iter().map(|x| -di * x).collect();
789        // A = (σ_i + σ_e) · L  (scale the Laplacian values in place for the solve).
790        let mut a = lap;
791        for v in &mut a.values {
792            *v *= di + de;
793        }
794        conjugate_gradient(&a, &b, None, 1e-12, 5000)
795    }
796
797    /// Diffusion term `∇·(D∇φ)` (per node) for the field `phi`, using unit grid
798    /// spacing and clamped (Neumann) boundaries. For a scalar `D` this is the
799    /// 5-point Laplacian `D·(φ[i±1]+φ[j±1]−4φ)`; for a tensor diffusivity it
800    /// delegates to [`tensor_diffusion_2d`] (the anisotropic
801    /// `Dxx·φ_xx + 2·Dxy·φ_xy + Dyy·φ_yy` operator).
802    fn diffusion_term(&self, phi: &[f64]) -> Vec<f64> {
803        match &self.diffusivity {
804            Diffusivity::Scalar(d) => {
805                let nx = self.nx;
806                let ny = self.ny;
807                let clamp = |i: isize, m: usize| -> usize { i.clamp(0, m as isize - 1) as usize };
808                let c_at =
809                    |i: usize, j: usize| phi[clamp(i as isize, nx) + clamp(j as isize, ny) * nx];
810                let mut out = vec![0.0; nx * ny];
811                for j in 0..ny {
812                    for i in 0..nx {
813                        let c = self.idx(i, j);
814                        let lap = c_at(i.wrapping_sub(1), j)
815                            + c_at(i + 1, j)
816                            + c_at(i, j.wrapping_sub(1))
817                            + c_at(i, j + 1)
818                            - 4.0 * phi[c];
819                        out[c] = d * lap;
820                    }
821                }
822                out
823            }
824            Diffusivity::Tensor(t) => tensor_diffusion_2d(phi, self.nx, self.ny, t),
825        }
826    }
827
828    /// Advance the tissue PDE by `dt` with explicit operator splitting: the
829    /// reaction term `-I_ion/Cm` plus the (scalar or tensor) diffusion term, and
830    /// — in bidomain mode — the extracellular elliptic solve coupling `Ve`.
831    pub fn step(&mut self, dt: f64) {
832        let vm0 = self.vm.clone();
833        let phi: Vec<f64> = if self.bidomain {
834            let ve = self.extracellular_potential();
835            self.ve = ve.clone();
836            vm0.iter().zip(&ve).map(|(a, b)| a + b).collect()
837        } else {
838            vm0.clone()
839        };
840
841        let diff_term = self.diffusion_term(&phi);
842        let n = self.nx * self.ny;
843        let next: Vec<f64> = (0..n)
844            .map(|c| {
845                let i_ion = self.cells[c].ionic_current();
846                let cm = self.cells[c].capacitance();
847                vm0[c] + dt * (-i_ion / cm + diff_term[c])
848            })
849            .collect();
850        // Evolve the internal membrane state at the new transmembrane voltage.
851        for (cell, &v) in self.cells.iter_mut().zip(next.iter()).take(n) {
852            cell.advance_reaction(v, dt);
853        }
854        self.vm = next;
855    }
856
857    /// Advance one bidomain time step, solving the extracellular elliptic
858    /// equation each step before coupling it into the intracellular update.
859    ///
860    /// This is a thin, explicitly-named wrapper around [`Tissue::step`] that
861    /// errors (instead of silently degrading to monodomain) if bidomain mode has
862    /// not been enabled via [`Tissue::enable_bidomain`].
863    ///
864    /// # Errors
865    ///
866    /// Returns [`ElectrophysError::InvalidTissue`] if [`Tissue::enable_bidomain`]
867    /// has not been called.
868    pub fn bidomain_step(&mut self, dt: f64) -> Result<(), ElectrophysError> {
869        if !self.bidomain {
870            return Err(ElectrophysError::InvalidTissue(
871                "bidomain mode not enabled; call enable_bidomain first".into(),
872            ));
873        }
874        self.step(dt);
875        Ok(())
876    }
877
878    /// Maximum transmembrane potential in the sheet (post-stimulus spread
879    /// indicator).
880    #[must_use]
881    pub fn max_voltage(&self) -> f64 {
882        self.vm.iter().copied().fold(f64::NEG_INFINITY, f64::max)
883    }
884}
885
886#[cfg(test)]
887mod tests {
888    use super::*;
889    use approx::assert_abs_diff_eq;
890    use tpt_sci_grid::sparse::laplacian_2d_sparse;
891    use tpt_sci_grid::{Boundary, UniformGrid2D};
892
893    #[test]
894    fn hh_resting_is_finite() {
895        let mut hh = HodgkinHuxley::resting();
896        for _ in 0..50 {
897            hh.step(0.01);
898        }
899        assert!(hh.voltage().is_finite());
900        assert!((0.0..=1.0).contains(&hh.m));
901    }
902
903    #[test]
904    fn hh_depolarizes_then_recovers() {
905        let mut hh = HodgkinHuxley::new();
906        hh.v = 20.0; // stimulus
907        let v0 = hh.voltage();
908        for _ in 0..200 {
909            hh.step(0.01);
910        }
911        assert!(hh.voltage().is_finite());
912        assert!(hh.voltage() < v0 + 1e-6 || hh.voltage() > 0.0);
913    }
914
915    #[test]
916    fn tissue_propagates_from_stimulus() {
917        let mut t = Tissue::new(16, 16, 0.5).unwrap();
918        t.stimulate(0, 8, 40.0);
919        for _ in 0..100 {
920            t.step(0.005);
921        }
922        // A stimulus should depolarize the tissue well above the resting (0 mV)
923        // field — the depolarization propagates and recruits the sheet.
924        assert!(t.max_voltage().is_finite());
925        assert!(
926            t.max_voltage() > 10.0,
927            "stimulation should depolarize the tissue"
928        );
929    }
930
931    #[test]
932    fn ionic_current_finite_at_rest() {
933        let hh = HodgkinHuxley::resting();
934        assert!(hh.ionic_current().is_finite());
935    }
936
937    #[test]
938    fn tt_resting_fires_action_potential() {
939        let mut cell = TenTusscher::resting();
940        let v_rest = cell.v;
941        cell.v = 20.0; // depolarizing stimulus
942        let mut peak = cell.v;
943        // Single-node monodomain integration: dV/dt = -I_ion/Cm.
944        for _ in 0..600 {
945            cell.advance_reaction(cell.v, 0.01);
946            cell.v += 0.01 * (-cell.ionic_current() / cell.cm);
947            if !cell.v.is_finite() {
948                break;
949            }
950            peak = peak.max(cell.v);
951        }
952        // A genuine AP must swing well above the resting potential.
953        assert!(
954            peak > v_rest + 10.0,
955            "TenTusscher should fire a depolarization"
956        );
957        assert!(cell.v.is_finite());
958        assert!(cell.cai.is_finite() && cell.cai > 0.0);
959    }
960
961    #[test]
962    fn anisotropic_quadratic_laplacian() {
963        // For D = I, ∇·(D∇(x²+y²)) = 4 (matches the scalar 5-point Laplacian).
964        let n = 9usize;
965        let t = Tissue::with_model(
966            n,
967            n,
968            Diffusivity::Tensor(vec![DiffusionTensor::from_array([1.0, 0.0, 1.0]); n * n]),
969            HodgkinHuxley::resting(),
970        )
971        .unwrap();
972        let mut phi = vec![0.0; n * n];
973        for j in 0..n {
974            for i in 0..n {
975                let x = i as f64 - 4.0;
976                let y = j as f64 - 4.0;
977                phi[t.idx(i, j)] = x * x + y * y;
978            }
979        }
980        let term = t.diffusion_term(&phi);
981        let mid = t.idx(4, 4);
982        assert_abs_diff_eq!(term[mid], 4.0, epsilon = 1e-9);
983    }
984
985    #[test]
986    fn anisotropic_prefers_strong_axis() {
987        // D = diag(10, 1): diffusion along x should dominate a step in x more
988        // than the same step along y.
989        let n = 9usize;
990        let t = Tissue::with_model(
991            n,
992            n,
993            Diffusivity::Tensor(vec![DiffusionTensor::from_array([10.0, 0.0, 1.0]); n * n]),
994            HodgkinHuxley::resting(),
995        )
996        .unwrap();
997        // linear in x: ∇·(D∇(ax)) = Dxx * 0 + ... = 0; use ax² to expose Dxx.
998        let mut phi = vec![0.0; n * n];
999        for j in 0..n {
1000            for i in 0..n {
1001                let x = i as f64 - 4.0;
1002                phi[t.idx(i, j)] = 0.5 * x * x;
1003            }
1004        }
1005        let term = t.diffusion_term(&phi);
1006        // For φ = ½ x², ∇·(D∇φ) = Dxx at interior => 10.
1007        assert_abs_diff_eq!(term[t.idx(4, 4)], 10.0, epsilon = 1e-9);
1008    }
1009
1010    #[test]
1011    fn bidomain_solves_extracellular_field() {
1012        let mut t = Tissue::new(12, 12, 1.0).unwrap();
1013        t.enable_bidomain(1.0);
1014        // A non-uniform transmembrane field forces a non-trivial extracellular
1015        // potential.
1016        for j in 0..12 {
1017            for i in 0..12 {
1018                let c = t.idx(i, j);
1019                t.vm[c] = (i as f64) * 0.1;
1020            }
1021        }
1022        let ve = t.extracellular_potential();
1023        // The solve must be finite and the residual of the elliptic equation
1024        // small: (σ_i+σ_e)·L·Ve + σ_i·L·Vm ≈ 0, checked with the sparse Laplacian.
1025        assert!(ve.iter().all(|x| x.is_finite()));
1026        let grid = UniformGrid2D::new(12, 0.0, 1.0, 12, 0.0, 1.0).unwrap();
1027        let l = laplacian_2d_sparse(&grid, Boundary::Neumann);
1028        let lve = l.mul_vec(&ve);
1029        let lvm = l.mul_vec(&t.vm);
1030        let di = t.diff;
1031        let de = t.sigma_e;
1032        let residual: f64 = lve
1033            .iter()
1034            .zip(lvm.iter())
1035            .map(|(a, b)| (di + de) * a + di * b)
1036            .map(|x| x.abs())
1037            .sum();
1038        assert!(residual < 1e-4, "elliptic residual too large: {residual}");
1039    }
1040
1041    #[test]
1042    fn bidomain_reduces_to_monodomain_for_large_sigma_e() {
1043        let n = 8usize;
1044        // Monodomain reference.
1045        let mut mono = Tissue::new(n, n, 1.0).unwrap();
1046        for j in 0..n {
1047            for i in 0..n {
1048                let c = mono.idx(i, j);
1049                mono.vm[c] = (i + j) as f64 * 0.2;
1050            }
1051        }
1052        let diff_mono = mono.diffusion_term(&mono.vm.clone());
1053
1054        // Bidomain with very large extracellular conductivity: the effective
1055        // coupling term D_i·L(Vm+Ve) must approach D_i·L·Vm.
1056        let mut bi = Tissue::new(n, n, 1.0).unwrap();
1057        bi.enable_bidomain(1e6);
1058        for j in 0..n {
1059            for i in 0..n {
1060                let c = bi.idx(i, j);
1061                bi.vm[c] = (i + j) as f64 * 0.2;
1062            }
1063        }
1064        let ve = bi.extracellular_potential();
1065        let phi: Vec<f64> = bi.vm.iter().zip(&ve).map(|(a, b)| a + b).collect();
1066        let diff_bi = bi.diffusion_term(&phi);
1067        for c in 0..n * n {
1068            assert_abs_diff_eq!(diff_bi[c], diff_mono[c], epsilon = 1e-3);
1069        }
1070    }
1071
1072    #[test]
1073    fn bidomain_equal_conductivity_matches_monodomain() {
1074        // When σ_i = σ_e = σ the bidomain reduces exactly to the monodomain with
1075        // the effective diffusion coefficient D_eff = σ_i·σ_e/(σ_i+σ_e) = σ/2.
1076        let n = 9usize;
1077        let sigma = 2.0;
1078        let d_eff = sigma * sigma / (sigma + sigma);
1079        // Monodomain reference with D = D_eff.
1080        let mut mono = Tissue::new(n, n, d_eff).unwrap();
1081        for j in 0..n {
1082            for i in 0..n {
1083                let c = mono.idx(i, j);
1084                mono.vm[c] = (i + j) as f64 * 0.3;
1085            }
1086        }
1087        let diff_mono = mono.diffusion_term(&mono.vm.clone());
1088
1089        // Bidomain with σ_i = σ_e = σ.
1090        let mut bi = Tissue::new(n, n, sigma).unwrap();
1091        bi.enable_bidomain(sigma);
1092        for j in 0..n {
1093            for i in 0..n {
1094                let c = bi.idx(i, j);
1095                bi.vm[c] = (i + j) as f64 * 0.3;
1096            }
1097        }
1098        let ve = bi.extracellular_potential();
1099        let phi: Vec<f64> = bi.vm.iter().zip(&ve).map(|(a, b)| a + b).collect();
1100        let diff_bi = bi.diffusion_term(&phi);
1101        for c in 0..n * n {
1102            assert_abs_diff_eq!(diff_bi[c], diff_mono[c], epsilon = 1e-6);
1103        }
1104    }
1105
1106    #[test]
1107    fn bidomain_extracellular_potential_bounded() {
1108        // Over many bidomain steps the extracellular potential must stay finite
1109        // and bounded (the elliptic solve must not blow up).
1110        let mut t = Tissue::new(10, 10, 1.0).unwrap();
1111        t.enable_bidomain(0.7);
1112        t.stimulate(0, 5, 40.0);
1113        for _ in 0..60 {
1114            t.bidomain_step(0.005).unwrap();
1115            assert!(t.ve.iter().all(|x| x.is_finite()));
1116        }
1117        let max_ve = t.ve.iter().copied().fold(f64::NEG_INFINITY, f64::max);
1118        let min_ve = t.ve.iter().copied().fold(f64::INFINITY, f64::min);
1119        assert!(max_ve.is_finite() && min_ve.is_finite());
1120        assert!(
1121            max_ve.abs().max(min_ve.abs()) < 1e3,
1122            "extracellular potential should remain bounded, got [{min_ve}, {max_ve}]"
1123        );
1124    }
1125
1126    #[test]
1127    fn anisotropic_harmonic_field_rhs() {
1128        // For u(x,y) = a·x² + b·y², ∇·(D∇u) = 2a·Dxx + 2b·Dyy (a constant).
1129        // With a=3, b=2 and D = diag(5, 7): RHS = 2·3·5 + 2·2·7 = 58.
1130        let n = 11usize;
1131        let d = DiffusionTensor::diagonal(5.0, 7.0);
1132        let t = Tissue::with_model(
1133            n,
1134            n,
1135            Diffusivity::Tensor(vec![d; n * n]),
1136            HodgkinHuxley::resting(),
1137        )
1138        .unwrap();
1139        let mut phi = vec![0.0; n * n];
1140        for j in 0..n {
1141            for i in 0..n {
1142                let x = i as f64 - 5.0;
1143                let y = j as f64 - 5.0;
1144                phi[t.idx(i, j)] = 3.0 * x * x + 2.0 * y * y;
1145            }
1146        }
1147        let term = t.diffusion_term(&phi);
1148        assert_abs_diff_eq!(term[t.idx(5, 5)], 58.0, epsilon = 1e-9);
1149    }
1150
1151    #[test]
1152    fn tensor_reproduces_isotropic_laplacian() {
1153        // A constant isotropic tensor D = diag(s, s) must reproduce the scalar
1154        // Laplacian with the same scalar s.
1155        let n = 13usize;
1156        let s = 2.5;
1157        let scalar = Tissue::new(n, n, s).unwrap();
1158        let tensor = Tissue::with_model(
1159            n,
1160            n,
1161            Diffusivity::Tensor(vec![DiffusionTensor::isotropic(s); n * n]),
1162            HodgkinHuxley::resting(),
1163        )
1164        .unwrap();
1165        let mut phi = vec![0.0; n * n];
1166        for j in 0..n {
1167            for i in 0..n {
1168                let x = i as f64;
1169                let y = j as f64;
1170                phi[tensor.idx(i, j)] = 0.5 * (x * x + y * y) + x * y;
1171            }
1172        }
1173        let ds = scalar.diffusion_term(&phi);
1174        let dt = tensor.diffusion_term(&phi);
1175        for c in 0..n * n {
1176            assert_abs_diff_eq!(dt[c], ds[c], epsilon = 1e-9);
1177        }
1178    }
1179
1180    #[test]
1181    fn tt_single_cell_limit_cycle() {
1182        // A single TenTusscher cell, stimulated, must produce a stable AP: a large
1183        // depolarization, then repolarization back near the resting potential, and
1184        // no blow-up over several seconds.
1185        let mut cell = TenTusscher::resting();
1186        let v_rest = cell.v;
1187        assert!(v_rest < -70.0, "resting potential should be near -85 mV");
1188        cell.v = 20.0; // depolarizing stimulus
1189        let mut peak = cell.v;
1190        for _ in 0..800 {
1191            cell.advance_reaction(cell.v, 0.01);
1192            cell.v += 0.01 * (-cell.ionic_current() / cell.cm);
1193            if !cell.v.is_finite() {
1194                break;
1195            }
1196            peak = peak.max(cell.v);
1197        }
1198        assert!(
1199            cell.v.is_finite(),
1200            "TenTusscher single-cell integration blew up"
1201        );
1202        let amplitude = peak - v_rest;
1203        assert!(amplitude > 40.0, "AP amplitude too small: {amplitude}");
1204        assert!(peak < 60.0, "AP peak unphysiologically high: {peak}");
1205        // Repolarized close to rest after several seconds.
1206        assert!(
1207            (cell.v - v_rest).abs() < 30.0,
1208            "cell failed to recover to rest: v = {}",
1209            cell.v
1210        );
1211        assert!(cell.cai.is_finite() && cell.cai > 0.0);
1212    }
1213}