Skip to main content

sciart_shared/
excitable.rs

1//! Excitable media shared by `dicty_aggregation` and `heart_fibrillation` (SPEC-002
2//! Batch M13).
3//!
4//! Two kernels, one per kind of tissue:
5//!
6//! - [`Barkley`] (1991) on a rectangular [`Grid`] with the isotropic 9-point Laplacian:
7//!   a fast FitzHugh–Nagumo-type medium with sharp fronts whose semi-implicit update keeps
8//!   `u, v ∈ [0, 1]` exactly (DICT-A5). The excitability `b` may vary per node.
9//! - [`AlievPanfilov`] (1996) on a masked [`Medium`] (any shape, no-flux walls at the mask
10//!   edge): the cardiac model whose restitution lets spirals break up (HRT).
11//!
12//! Plus the analysis both spiral scenes need: [`count_singularities`] finds phase
13//! singularities (spiral tips) by the winding of the excitation phase.
14
15use std::f32::consts::{PI, TAU as TWO_PI};
16
17use sciart_core::grid;
18use sciart_core::prelude::*;
19
20// ---- Barkley ----
21
22/// Barkley's model `∂u/∂t = ∇²u + ε⁻¹u(1 − u)(u − u_th)`, `u_th = (v + b)/a`,
23/// `∂v/∂t = u − v`, discretised with node spacing `h` and sub-step `tau` (time units).
24#[derive(Debug, Clone, Copy, PartialEq)]
25pub struct Barkley {
26    pub a: f32,
27    pub eps: f32,
28    /// Node spacing in space units.
29    pub h: f32,
30    /// Sub-step in time units.
31    pub tau: f32,
32}
33
34impl Barkley {
35    /// Diffusion weight of one explicit stage, `τ/h²` (`D = 1`).
36    pub const fn diff(&self) -> f32 {
37        self.tau / (self.h * self.h)
38    }
39
40    /// Reaction weight `τ/ε`.
41    pub const fn react(&self) -> f32 {
42        self.tau / self.eps
43    }
44
45    /// Whether every stage of [`step`](Self::step) is a convex combination or a shrinking
46    /// factor, which keeps `u, v ∈ [0, 1]` for any `b ≥ 0` without clamps: `(10/3)·τ/h² ≤ 1`
47    /// (the 9-point stencil's centre weight), `τ/ε ≤ 1` and `τ ≤ 1`.
48    pub const fn is_bounded(&self) -> bool {
49        10.0 / 3.0 * self.diff() <= 1.0 && self.react() <= 1.0 && self.tau <= 1.0
50    }
51
52    /// One Lie-split sub-step in place: explicit diffusion (9-point Laplacian, Neumann
53    /// walls), the reaction implicit on the decaying branch (`u < u_th`, a shrinking factor)
54    /// and explicit on the growing one (bounded by 1 since `τ/ε ≤ 1`), then
55    /// `v ← v + τ(u − v)`. `b(i)` is the excitability of node `i` (row-major); `lap` is
56    /// scratch.
57    #[inline]
58    pub fn step(
59        &self,
60        u: &mut Grid<f32>,
61        v: &mut Grid<f32>,
62        lap: &mut Grid<f32>,
63        b: impl Fn(usize) -> f32,
64    ) {
65        debug_assert!(self.is_bounded(), "unbounded Barkley stages: {self:?}");
66        let (a, tau, diff, react) = (self.a, self.tau, self.diff(), self.react());
67        grid::laplacian9(u, lap, Edges::Clip);
68        let fields = u.as_mut_slice().iter_mut().zip(v.as_mut_slice());
69        for (i, ((u, v), &l)) in fields.zip(lap.as_slice()).enumerate() {
70            let ud = *u + diff * l;
71            let u_th = (*v + b(i)) / a;
72            let g = react * (1.0 - ud) * (ud - u_th);
73            let ur = if ud < u_th {
74                ud / (1.0 - g)
75            } else {
76                ud + g * ud
77            };
78            *v += tau * (ur - *v);
79            *u = ur;
80        }
81    }
82}
83
84/// Excite (`u = 1`) every node within `r` nodes of `(cx, cy)` that has recovered to
85/// `v < v_max`: a pacemaker firing into a medium, which leaves refractory nodes alone.
86pub fn excite_disc(u: &mut Grid<f32>, v: &Grid<f32>, (cx, cy): (f64, f64), r: f64, v_max: f32) {
87    let reach = r.ceil() as i32;
88    let (x0, y0) = (cx.round() as i32, cy.round() as i32);
89    for y in y0 - reach..=y0 + reach {
90        for x in x0 - reach..=x0 + reach {
91            let (dx, dy) = (f64::from(x) - cx, f64::from(y) - cy);
92            let recovered = v.get(x, y).is_some_and(|&v| v < v_max);
93            if dx * dx + dy * dy <= r * r && recovered {
94                u.set(x, y, 1.0);
95            }
96        }
97    }
98}
99
100// ---- Broken fronts (spiral seeds) ----
101
102/// One broken front: a straight segment `a → b`, excited on the `n` side.
103#[derive(Debug, Clone, Copy, PartialEq)]
104pub struct Front {
105    pub a: [f64; 2],
106    pub b: [f64; 2],
107    /// Unit normal: the direction the front propagates.
108    pub n: [f64; 2],
109    /// `b` was extended to the wall, leaving `a` as the only free end.
110    pub anchored: bool,
111}
112
113/// How a [`Front`] is painted: the excited strip's width, the refractory tail's width
114/// (nodes), and `v` along the tail from the front to its end.
115#[derive(Debug, Clone, Copy, PartialEq)]
116pub struct FrontStroke {
117    pub front_w: f64,
118    pub tail_w: f64,
119    pub tail_v: (f64, f64),
120}
121
122/// Paint `front` into the fields: a `front_w`-node strip of `u = 1` on the `n` side of
123/// the segment, backed by a `tail_w`-node strip whose `v` ramps down away from it.
124pub fn paint_front(u: &mut Grid<f32>, v: &mut Grid<f32>, f: &Front, s: &FrontStroke) {
125    let (front_w, tail_w, tail_v) = (s.front_w, s.tail_w, s.tail_v);
126    let (d, len) = unit(f.a, f.b);
127    let n = f.n;
128    // Bounding box of the painted band, clipped to the lattice.
129    let xs = [f.a[0], f.b[0]].map(|x| [x + n[0] * front_w, x - n[0] * tail_w]);
130    let ys = [f.a[1], f.b[1]].map(|y| [y + n[1] * front_w, y - n[1] * tail_w]);
131    let span = |c: [[f64; 2]; 2], hi: u16| {
132        let lo = c.iter().flatten().fold(f64::INFINITY, |m, &x| m.min(x));
133        let top = c.iter().flatten().fold(f64::NEG_INFINITY, |m, &x| m.max(x));
134        (
135            lo.floor().max(0.0) as i32,
136            top.ceil().min(f64::from(hi) - 1.0) as i32,
137        )
138    };
139    let (x0, x1) = span(xs, u.width());
140    let (y0, y1) = span(ys, u.height());
141    for y in y0..=y1 {
142        for x in x0..=x1 {
143            let rel = [f64::from(x) - f.a[0], f64::from(y) - f.a[1]];
144            let along = rel[0] * d[0] + rel[1] * d[1];
145            let q = rel[0] * n[0] + rel[1] * n[1];
146            if !(0.0..=len).contains(&along) {
147                continue;
148            }
149            if (0.0..front_w).contains(&q) {
150                u.set(x, y, 1.0);
151                v.set(x, y, 0.0);
152            } else if (-tail_w..0.0).contains(&q) {
153                let t = -q / tail_w;
154                u.set(x, y, 0.0);
155                v.set(x, y, sciart_core::ease::lerp(tail_v.0, tail_v.1, t) as f32);
156            }
157        }
158    }
159}
160
161/// Unit vector from `a` to `b` and the distance (a zero-length segment points along x).
162pub fn unit(a: [f64; 2], b: [f64; 2]) -> ([f64; 2], f64) {
163    let (dx, dy) = (b[0] - a[0], b[1] - a[1]);
164    let len = dx.hypot(dy);
165    if len > 0.0 {
166        ([dx / len, dy / len], len)
167    } else {
168        ([1.0, 0.0], 0.0)
169    }
170}
171
172// ---- Masked medium ----
173
174/// A lattice region of any shape: the nodes inside a mask and each node's four
175/// neighbours, a neighbour outside the mask (or the lattice) replaced by the node itself,
176/// so the 5-point Laplacian sees a zero gradient there (no-flux wall).
177#[derive(Debug, Clone)]
178pub struct Medium {
179    size: Size,
180    /// Row-major indices of the nodes inside, ascending.
181    inside: Vec<u32>,
182    /// Per lattice node: west, east, north, south.
183    nb: Vec<[u32; 4]>,
184    /// Per lattice node: inside the mask.
185    mask: Vec<bool>,
186}
187
188impl Default for Medium {
189    /// An empty 1×1 lattice, the placeholder until the first `rebuild`.
190    fn default() -> Self {
191        Self {
192            size: Size::new(1, 1),
193            inside: Vec::new(),
194            nb: vec![[0; 4]],
195            mask: vec![false],
196        }
197    }
198}
199
200impl Medium {
201    /// Rebuild for a `size` lattice with `inside(x, y)` as the mask (reusing buffers).
202    pub fn rebuild(&mut self, size: Size, inside: impl Fn(i32, i32) -> bool) {
203        let (w, h) = (i32::from(size.width()), i32::from(size.height()));
204        self.size = size;
205        self.mask.clear();
206        self.mask.extend(
207            (0..h)
208                .flat_map(|y| (0..w).map(move |x| (x, y)))
209                .map(|(x, y)| inside(x, y)),
210        );
211        self.inside.clear();
212        self.nb.clear();
213        let mask = &self.mask;
214        let idx = |x: i32, y: i32| (y * w + x) as usize;
215        for y in 0..h {
216            for x in 0..w {
217                let i = idx(x, y) as u32;
218                let pick = |nx: i32, ny: i32| {
219                    let ok = (0..w).contains(&nx) && (0..h).contains(&ny) && mask[idx(nx, ny)];
220                    if ok { idx(nx, ny) as u32 } else { i }
221                };
222                self.nb.push([
223                    pick(x - 1, y),
224                    pick(x + 1, y),
225                    pick(x, y - 1),
226                    pick(x, y + 1),
227                ]);
228                if mask[i as usize] {
229                    self.inside.push(i);
230                }
231            }
232        }
233    }
234
235    pub fn size(&self) -> Size {
236        self.size
237    }
238
239    /// Row-major indices of the nodes inside the mask.
240    pub fn inside(&self) -> &[u32] {
241        &self.inside
242    }
243
244    /// Whether lattice node `i` is inside the mask (false off the lattice).
245    pub fn contains(&self, i: usize) -> bool {
246        self.mask.get(i).copied().unwrap_or(false)
247    }
248
249    /// Whether `(x, y)` is inside the mask (false off the lattice).
250    pub fn contains_xy(&self, x: i32, y: i32) -> bool {
251        let (w, h) = (i32::from(self.size.width()), i32::from(self.size.height()));
252        (0..w).contains(&x) && (0..h).contains(&y) && self.mask[(y * w + x) as usize]
253    }
254
255    /// The four neighbours of node `i` (walls folded back onto `i`).
256    pub fn neighbours(&self, i: usize) -> [u32; 4] {
257        self.nb[i]
258    }
259
260    /// `out[i] = Σ u[nb] − 4u[i]` for every inside node (other entries untouched).
261    fn laplacian(&self, u: &[f32], out: &mut [f32]) {
262        for &i in &self.inside {
263            let i = i as usize;
264            let [w, e, n, s] = self.nb[i].map(|j| u[j as usize]);
265            out[i] = (w + e) + (n + s) - 4.0 * u[i];
266        }
267    }
268}
269
270// ---- Aliev–Panfilov ----
271
272/// Aliev & Panfilov (1996): `∂u/∂t = D∇²u − ku(u − a)(u − 1) − uv`,
273/// `∂v/∂t = ε(u, v)(−v − ku(u − a − 1))`, `ε = ε₀ + μ₁v/(u + μ₂)`, explicit Euler with
274/// node spacing `h` and step `dt` (time units).
275#[derive(Debug, Clone, Copy, PartialEq)]
276pub struct AlievPanfilov {
277    pub k: f32,
278    pub a: f32,
279    pub eps0: f32,
280    pub mu1: f32,
281    pub mu2: f32,
282    pub d: f32,
283    pub h: f32,
284    pub dt: f32,
285}
286
287/// `v` never exceeds this in the model's own dynamics (its nullcline tops out near
288/// `k(1 + a)²/4 ≈ 2.6` for `k = 8`); the clamp only guards the display and tests.
289pub const AP_V_MAX: f32 = 4.0;
290
291impl AlievPanfilov {
292    /// Explicit diffusion is stable for `4·D·dt/h² ≤ 1` (5-point stencil); the reaction
293    /// is resolved when `k·dt` is small.
294    pub const fn is_stable(&self) -> bool {
295        4.0 * self.d * self.dt / (self.h * self.h) <= 1.0 && self.k * self.dt <= 0.5
296    }
297
298    /// One Euler step on every inside node; `u` is clamped to `[0, 1]` and `v` to
299    /// `[0, AP_V_MAX]` (HRT-A5), and `eps_scale(i)` multiplies `ε` per node (tissue
300    /// heterogeneity; `|_| 1.0` for none). `lap` is scratch of the lattice's size.
301    pub fn step(
302        &self,
303        m: &Medium,
304        u: &mut [f32],
305        v: &mut [f32],
306        lap: &mut [f32],
307        eps_scale: impl Fn(usize) -> f32,
308    ) {
309        debug_assert!(self.is_stable(), "unstable Aliev-Panfilov step: {self:?}");
310        m.laplacian(u, lap);
311        let (k, a, dt) = (self.k, self.a, self.dt);
312        let dd = self.d / (self.h * self.h);
313        for &i in m.inside() {
314            let i = i as usize;
315            let (ui, vi) = (u[i], v[i]);
316            let du = dd * lap[i] - k * ui * (ui - a) * (ui - 1.0) - ui * vi;
317            let eps = eps_scale(i) * (self.eps0 + self.mu1 * vi / (ui + self.mu2));
318            let dv = eps * (-vi - k * ui * (ui - a - 1.0));
319            u[i] = (ui + dt * du).clamp(0.0, 1.0);
320            v[i] = (vi + dt * dv).clamp(0.0, AP_V_MAX);
321        }
322    }
323}
324
325// ---- Phase singularities ----
326
327/// Excitation phase `atan2(v − v*, u − u*)` of a node (radians, `(−π, π]`).
328#[inline]
329pub fn phase(u: f32, v: f32, (us, vs): (f32, f32)) -> f32 {
330    (v - vs).atan2(u - us)
331}
332
333/// Wrap a phase difference into `(−π, π]`.
334#[inline]
335fn wrap(d: f32) -> f32 {
336    if d > PI {
337        d - TWO_PI
338    } else if d <= -PI {
339        d + TWO_PI
340    } else {
341        d
342    }
343}
344
345/// Count phase singularities (spiral tips) of the fields on `m`: plaquettes of four
346/// inside nodes around which the phase winds by ±2π. A tip found within `merge` nodes
347/// (Chebyshev) of one already counted is the same tip seen twice and is not counted
348/// again. The first `tips.len()` tips found are written to `tips` (lattice coordinates of
349/// the plaquette's top-left node), row by row. `theta` and `taken` are scratch of the
350/// lattice's size.
351#[allow(clippy::too_many_arguments)] // two fields, two scratch buffers, one output
352pub fn count_singularities(
353    m: &Medium,
354    u: &[f32],
355    v: &[f32],
356    centre: (f32, f32),
357    merge: i32,
358    theta: &mut [f32],
359    taken: &mut [bool],
360    tips: &mut [(i32, i32)],
361) -> usize {
362    let (w, h) = (i32::from(m.size().width()), i32::from(m.size().height()));
363    for &i in m.inside() {
364        let i = i as usize;
365        theta[i] = phase(u[i], v[i], centre);
366    }
367    taken.fill(false);
368    let mut count = 0;
369    for y in 0..h - 1 {
370        for x in 0..w - 1 {
371            let corners = [(x, y), (x + 1, y), (x + 1, y + 1), (x, y + 1)];
372            if !corners.iter().all(|&(cx, cy)| m.contains_xy(cx, cy)) {
373                continue;
374            }
375            let t = corners.map(|(cx, cy)| theta[(cy * w + cx) as usize]);
376            let winding: f32 = (0..4).map(|j| wrap(t[(j + 1) % 4] - t[j])).sum();
377            if winding.abs() < PI {
378                continue;
379            }
380            if taken[(y * w + x) as usize] {
381                continue;
382            }
383            if let Some(tip) = tips.get_mut(count) {
384                *tip = (x, y);
385            }
386            count += 1;
387            for ny in (y - merge).max(0)..=(y + merge).min(h - 1) {
388                for nx in (x - merge).max(0)..=(x + merge).min(w - 1) {
389                    taken[(ny * w + nx) as usize] = true;
390                }
391            }
392        }
393    }
394    count
395}
396
397#[cfg(test)]
398mod tests {
399    use super::*;
400
401    const BZ_LIKE: Barkley = Barkley {
402        a: 0.75,
403        eps: 0.02,
404        h: 0.5,
405        tau: 0.0125,
406    };
407
408    #[test]
409    fn barkley_weights_and_bounds() {
410        assert!(BZ_LIKE.is_bounded());
411        assert_eq!(BZ_LIKE.diff(), 0.0125 / 0.25);
412        assert!(
413            !Barkley {
414                tau: 0.1,
415                ..BZ_LIKE
416            }
417            .is_bounded()
418        );
419    }
420
421    #[test]
422    fn medium_walls_fold_onto_the_node() {
423        let mut m = Medium::default();
424        // A plus shape: only (1, 0), (0, 1), (1, 1), (2, 1), (1, 2) inside a 3×3 lattice.
425        m.rebuild(Size::new(3, 3), |x, y| x == 1 || y == 1);
426        assert_eq!(m.inside(), &[1, 3, 4, 5, 7]);
427        assert_eq!(m.neighbours(4), [3, 5, 1, 7]);
428        assert_eq!(m.neighbours(1), [1, 1, 1, 4]);
429        assert!(m.contains(4) && !m.contains(0) && !m.contains(99));
430        // A uniform field has a zero Laplacian, walls included.
431        let u = [0.7f32; 9];
432        let mut lap = [9.0f32; 9];
433        m.laplacian(&u, &mut lap);
434        assert!(m.inside().iter().all(|&i| lap[i as usize] == 0.0));
435    }
436
437    fn spiral_fields(n: u16) -> (Medium, Vec<f32>, Vec<f32>) {
438        let mut m = Medium::default();
439        m.rebuild(Size::new(n, n), |_, _| true);
440        let c = f32::from(n) / 2.0;
441        let mut u = vec![0.0; usize::from(n) * usize::from(n)];
442        let mut v = u.clone();
443        for y in 0..n {
444            for x in 0..n {
445                let (dx, dy) = (f32::from(x) + 0.5 - c, f32::from(y) + 0.5 - c);
446                let a = dy.atan2(dx);
447                let i = usize::from(y) * usize::from(n) + usize::from(x);
448                u[i] = 0.5 + 0.5 * a.cos_det();
449                v[i] = 0.5 + 0.5 * a.sin_det();
450            }
451        }
452        (m, u, v)
453    }
454
455    #[test]
456    fn a_single_vortex_is_one_singularity() {
457        let (m, u, v) = spiral_fields(12);
458        let n = u.len();
459        let (mut theta, mut taken) = (vec![0.0; n], vec![false; n]);
460        let mut tips = [(0, 0); 2];
461        let c = count_singularities(&m, &u, &v, (0.5, 0.5), 2, &mut theta, &mut taken, &mut tips);
462        assert_eq!(c, 1);
463        assert_eq!(tips[0], (5, 5));
464        // A uniform field has none.
465        let flat = vec![0.2; n];
466        let c = count_singularities(
467            &m,
468            &flat,
469            &flat,
470            (0.5, 0.5),
471            2,
472            &mut theta,
473            &mut taken,
474            &mut [],
475        );
476        assert_eq!(c, 0);
477    }
478
479    #[test]
480    fn aliev_panfilov_rests_and_stays_in_range() {
481        let ap = AlievPanfilov {
482            k: 8.0,
483            a: 0.15,
484            eps0: 0.002,
485            mu1: 0.2,
486            mu2: 0.3,
487            d: 1.0,
488            h: 1.0,
489            dt: 0.05,
490        };
491        assert!(ap.is_stable());
492        let mut m = Medium::default();
493        m.rebuild(Size::new(20, 1), |_, _| true);
494        let (mut u, mut v, mut lap) = (vec![0.0; 20], vec![0.0; 20], vec![0.0; 20]);
495        u[..3].fill(1.0);
496        for _ in 0..4000 {
497            ap.step(&m, &mut u, &mut v, &mut lap, |_| 1.0);
498            assert!(u.iter().all(|x| (0.0..=1.0).contains(x)));
499            assert!(v.iter().all(|x| (0.0..=AP_V_MAX).contains(x)));
500        }
501        assert!(u.iter().all(|&x| x < 0.01), "{u:?}");
502    }
503}