1#![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
46pub trait IonicModel: Send + std::fmt::Debug {
54 fn state(&self) -> Vec<f64>;
57 fn voltage(&self) -> f64;
59 fn ionic_current(&self) -> f64;
61 fn capacitance(&self) -> f64;
63 fn advance_reaction(&mut self, v: f64, dt: f64);
67 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#[derive(Debug, Clone)]
83pub struct HodgkinHuxley {
84 pub v: f64,
86 pub m: f64,
88 pub h: f64,
90 pub n: f64,
92 pub cm: f64,
94 pub g_na: f64,
96 pub g_k: f64,
98 pub g_l: f64,
100 pub e_na: f64,
102 pub e_k: f64,
104 pub e_l: f64,
106}
107
108impl HodgkinHuxley {
109 #[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 #[must_use]
129 pub fn resting() -> Self {
130 Self::new()
131 }
132
133 #[must_use]
135 pub fn state(&self) -> Vec<f64> {
136 vec![self.v, self.m, self.h, self.n]
137 }
138
139 #[must_use]
141 pub fn voltage(&self) -> f64 {
142 self.v
143 }
144
145 #[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 #[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 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 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#[derive(Debug, Clone)]
268pub struct TenTusscher {
269 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 pub cai: f64,
283 pub cm: f64,
285 pub nao: f64,
287 pub ko: f64,
288 pub cao: f64,
289}
290
291impl TenTusscher {
292 #[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 #[must_use]
317 pub fn resting() -> Self {
318 Self::new()
319 }
320
321 #[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 #[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 #[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 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 #[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 let gna = 14.838;
433 let ina = gna * self.m.powi(3) * self.h * self.j * (v - ena);
434 let gkr = 0.153;
436 let ikr = gkr * self.xr * (v - ek) / (1.0 + (-(v - 40.0) / 7.3).exp()).sqrt();
437 let gks = 0.129;
439 let iks = gks * self.xs.powi(2) * (v - ek);
440 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 let gcal = 0.000_175;
449 let ical = gcal * self.d * self.f * self.fca * (v - self.e_ca());
450 let gto = 0.294;
452 let ito = gto * self.r * self.s * (v - ek);
453 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 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 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 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#[derive(Debug, Clone, Copy, PartialEq)]
535pub struct DiffusionTensor {
536 pub xx: f64,
538 pub xy: f64,
540 pub yy: f64,
542}
543
544impl DiffusionTensor {
545 #[must_use]
547 pub fn new(xx: f64, xy: f64, yy: f64) -> Self {
548 Self { xx, xy, yy }
549 }
550
551 #[must_use]
553 pub fn isotropic(d: f64) -> Self {
554 Self::new(d, 0.0, d)
555 }
556
557 #[must_use]
559 pub fn diagonal(dxx: f64, dyy: f64) -> Self {
560 Self::new(dxx, 0.0, dyy)
561 }
562
563 #[must_use]
565 pub fn from_array(a: [f64; 3]) -> Self {
566 Self::new(a[0], a[1], a[2])
567 }
568
569 #[must_use]
571 pub fn as_array(&self) -> [f64; 3] {
572 [self.xx, self.xy, self.yy]
573 }
574
575 #[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
588pub type ConductivityTensor = DiffusionTensor;
592
593#[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#[derive(Debug, Clone)]
640pub enum Diffusivity {
641 Scalar(f64),
643 Tensor(Vec<DiffusionTensor>),
645}
646
647#[derive(Debug, Clone)]
650pub struct Tissue {
651 pub vm: Vec<f64>,
653 pub ve: Vec<f64>,
655 pub diff: f64,
657 pub nx: usize,
659 pub ny: usize,
660 diffusivity: Diffusivity,
662 cells: Vec<Box<dyn IonicModel>>,
664 bidomain: bool,
666 sigma_e: f64,
668}
669
670impl Tissue {
671 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 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 pub fn enable_bidomain(&mut self, extracellular_diff: f64) {
726 self.bidomain = true;
727 self.sigma_e = extracellular_diff;
728 }
729
730 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 #[must_use]
754 pub fn idx(&self, i: usize, j: usize) -> usize {
755 j * self.nx + i
756 }
757
758 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 #[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 let lvm = lap.mul_vec(&self.vm);
788 let b: Vec<f64> = lvm.iter().map(|x| -di * x).collect();
789 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 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 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 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 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 #[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; 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 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; let mut peak = cell.v;
943 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 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 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 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 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 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 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 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 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 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 let n = 9usize;
1077 let sigma = 2.0;
1078 let d_eff = sigma * sigma / (sigma + sigma);
1079 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 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 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 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 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 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; 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 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}