Skip to main content

tpt_sci_hemodynamics/
lib.rs

1//! # tpt-sci-hemodynamics
2//!
3//! **1-D compliant-vessel hemodynamics** for the `tpt-science` pillar, built on
4//! [`tpt_sci_cfd_core`] and [`tpt_sci_ode`]. It models blood flow in a
5//! compliant arterial network using the 1-D augmented Navier–Stokes equations
6//! reduced to a vessel centerline, with:
7//!
8//! * A [`Vessel`] carrying a cross-sectional area `A`, flow `Q`, and a linear
9//!   pressure–area (tube) law `p = p0 + (β/A0)·(sqrt(A) - sqrt(A0))`
10//!   ([`tube_law_beta`]).
11//! * **Womersley** pulsatile inlet conditions [`womersley_velocity`] for a
12//!   given cardiac frequency and vessel radius (analytic oscillatory profile).
13//! * A non-Newtonian (shear-thinning) viscosity correction [`casson_viscosity`]
14//!   via the Casson model.
15//! * A [`Network`] that steps a `Vessel` forward in time with the method of
16//!   lines (area/flow ODE integrated by `tpt-sci-ode`).
17//! * The **exact** Womersley pulsatile solution [`womersley_velocity_profile`]
18//!   (complex-Bessel `J0`/`J1`), including the analytic flow-rate formula.
19//! * 0-D/1-D/3-D coupling: a lumped [`Windkessel`] (RCR) terminal load and a
20//!   [`couple`] step, plus the [`CfdCoupling`] trait a `tpt-sci-cfd-core` 3-D
21//!   domain can implement.
22//!
23//! The model is a 1-D reduced-order vascular primitive — not a patient-specific
24//! 3-D solver.
25//!
26//! # Example
27//!
28//! ```
29//! use tpt_sci_hemodynamics::{Vessel, tube_law_beta};
30//!
31//! // Aortic-scale vessel, A0 = 1 cm², wall stiffness beta.
32//! let beta = tube_law_beta(1.0e5, 1.0, 1.0);
33//! let v = Vessel::new(1.0, 0.0, 1.0, beta).unwrap();
34//! assert!(v.area > 0.0);
35//! ```
36#![forbid(unsafe_code)]
37
38mod coupling;
39mod error;
40mod womersley;
41
42pub use coupling::{CfdCoupling, Windkessel, couple};
43pub use error::HemodynamicsError;
44pub use womersley::{
45    bessel_j0, bessel_j1, womersley_complex_velocity, womersley_factor,
46    womersley_flow_rate_analytic, womersley_flow_rate_numeric, womersley_number,
47    womersley_velocity_profile,
48};
49
50/// Stiffness parameter `β = sqrt(π·E·h) / (2·sqrt(A0))` for the linear tube law
51/// `p = p0 + β·(sqrt(A) - sqrt(A0))`, given Young's modulus `e`,
52/// wall thickness `h`, and reference area `a0`.
53///
54/// # Panics
55///
56/// Panics if `a0 <= 0`, `e < 0`, or `h < 0`.
57#[must_use]
58pub fn tube_law_beta(e: f64, h: f64, a0: f64) -> f64 {
59    assert!(a0 > 0.0, "A0 must be > 0");
60    assert!(e >= 0.0, "E must be >= 0");
61    assert!(h >= 0.0, "h must be >= 0");
62    (std::f64::consts::PI * e * h).sqrt() / (2.0 * a0.sqrt())
63}
64
65/// Wall stiffness `β` requires a reference area; see [`tube_law_beta`].
66#[derive(Debug, Clone)]
67pub struct Vessel {
68    /// Cross-sectional area `A` (cm²).
69    pub area: f64,
70    /// Volumetric flow rate `Q` (cm³/s).
71    pub flow: f64,
72    /// Reference area `A0` (cm²).
73    pub area0: f64,
74    /// Tube-law stiffness `β`.
75    pub beta: f64,
76}
77
78impl Vessel {
79    /// Construct a validated vessel.
80    ///
81    /// # Errors
82    ///
83    /// Returns [`HemodynamicsError::InvalidVessel`] if any area/flow is
84    /// non-positive, or `beta` is non-finite.
85    pub fn new(area: f64, flow: f64, area0: f64, beta: f64) -> Result<Self, HemodynamicsError> {
86        if area <= 0.0 || area0 <= 0.0 {
87            return Err(HemodynamicsError::InvalidVessel(
88                "area and area0 must be > 0".into(),
89            ));
90        }
91        if !beta.is_finite() {
92            return Err(HemodynamicsError::InvalidVessel("non-finite beta".into()));
93        }
94        Ok(Self {
95            area,
96            flow,
97            area0,
98            beta,
99        })
100    }
101
102    /// Transmural pressure `p = β·(sqrt(A) - sqrt(A0))` (gauge, relative to
103    /// reference).
104    #[must_use]
105    pub fn pressure(&self) -> f64 {
106        self.beta * (self.area.sqrt() - self.area0.sqrt())
107    }
108
109    /// Wave speed `c = sqrt(β / (2·ρ) · sqrt(A0/A))` (linear tube law), with
110    /// blood density `rho` (g/cm³, ~1.06).
111    #[must_use]
112    pub fn wave_speed(&self, rho: f64) -> f64 {
113        (self.beta * self.area0.sqrt() / (2.0 * rho * self.area.sqrt())).sqrt()
114    }
115}
116
117/// Approximate analytic **Womersley** axial velocity profile amplitude at
118/// radius `r` (parabolic Poiseuille shape modulated by a flattening factor).
119/// For the exact complex-Bessel solution, see [`womersley_velocity_profile`].
120///
121/// Analytic **Womersley** axial velocity profile amplitude at radius `r` for a
122/// pulsatile flow with angular frequency `omega`, vessel radius `r0`, and
123/// kinematic viscosity `nu`. Returns the velocity scale `|u(r)|` relative to
124/// the mean (so the mean over the cross-section is 1.0), using the parabolic
125/// Poiseuille shape `2·(1 - (r/r0)²)` modulated by a Womersley flattening
126/// factor, where `α = r0·sqrt(ω/ν)` is the Womersley number.
127///
128/// At low `α` the profile is the full parabolic Poiseuille shape (centreline
129/// `≈ 2×` mean); as `α` grows the profile flattens toward plug flow
130/// (centreline `→ 1×` mean).
131///
132/// # Panics
133///
134/// Panics if `r0 <= 0`, `nu <= 0`, `omega < 0`, or `r` outside `[0, r0]`.
135#[must_use]
136pub fn womersley_velocity(r: f64, r0: f64, omega: f64, nu: f64) -> f64 {
137    assert!(r0 > 0.0, "r0 must be > 0");
138    assert!(nu > 0.0, "nu must be > 0");
139    assert!(omega >= 0.0, "omega must be >= 0");
140    assert!((0.0..=r0).contains(&r), "r must be in [0, r0]");
141    let alpha = r0 * (omega / nu).sqrt();
142    // Parabolic Poiseuille shape; the Womersley flattening factor runs from 1.0
143    // (low α, full parabola) down to 0.5 (high α, plug flow: centreline = mean).
144    let parabolic = 2.0 * (1.0 - (r / r0).powi(2));
145    let flatten = 0.5 + 0.5 / (1.0 + alpha / 3.0);
146    parabolic * flatten
147}
148
149/// **Casson** non-Newtonian viscosity `μ = (sqrt(μ∞) + sqrt(τy·(3n+1)/(4n)) /
150/// sqrt(γ̇))²` evaluated at shear rate `gamma_dot`, with asymptotic viscosity
151/// `mu_inf` and yield stress `tau_y`. Returns `mu_inf` when `gamma_dot` is 0
152/// (fully yielded limit handled by caller).
153///
154/// # Panics
155///
156/// Panics if `mu_inf <= 0`, `tau_y < 0`, or `gamma_dot < 0`.
157#[must_use]
158pub fn casson_viscosity(mu_inf: f64, tau_y: f64, gamma_dot: f64) -> f64 {
159    assert!(mu_inf > 0.0, "mu_inf must be > 0");
160    assert!(tau_y >= 0.0, "tau_y must be >= 0");
161    assert!(gamma_dot >= 0.0, "gamma_dot must be >= 0");
162    if gamma_dot == 0.0 {
163        return mu_inf;
164    }
165    let sq = mu_inf.sqrt() + (tau_y / gamma_dot.sqrt());
166    sq * sq
167}
168
169/// A small compliant arterial `Network` that advances a [`Vessel`] state with
170/// the 1-D area/flow ODE `dA/dt = -∂Q/∂x`, `dQ/dt = ...` (method of lines,
171/// integrated by [`tpt_sci_ode`]).
172#[derive(Debug, Clone)]
173pub struct Network {
174    /// The vessel states along the centerline (1 cell here; a chain of vessels
175    /// can be appended for a full network).
176    pub vessels: Vec<Vessel>,
177    /// Blood density `ρ` (g/cm³).
178    pub rho: f64,
179    /// Friction coefficient (viscous) `k = 8·π·μ / A²`.
180    pub friction: f64,
181}
182
183impl Network {
184    /// Construct a single-vessel network.
185    ///
186    /// # Errors
187    ///
188    /// Returns [`HemodynamicsError::InvalidNetwork`] if `rho <= 0` or
189    /// `friction <= 0`.
190    pub fn new(vessel: Vessel, rho: f64, friction: f64) -> Result<Self, HemodynamicsError> {
191        if rho <= 0.0 {
192            return Err(HemodynamicsError::InvalidNetwork("rho must be > 0".into()));
193        }
194        if friction <= 0.0 {
195            return Err(HemodynamicsError::InvalidNetwork(
196                "friction must be > 0".into(),
197            ));
198        }
199        Ok(Self {
200            vessels: vec![vessel],
201            rho,
202            friction,
203        })
204    }
205
206    /// Flow at cell `j` with boundary ghosts: the inlet flow is imposed (zero
207    /// gradient at `j < 0`), and the terminal face is closed (`Q` antisymmetric
208    /// about the last cell, so the flux through it is zero).
209    fn flow_at(&self, j: isize) -> f64 {
210        let n = self.vessels.len() as isize;
211        if j < 0 {
212            self.vessels[0].flow
213        } else if j >= n {
214            -self.vessels[(n - 1) as usize].flow
215        } else {
216            self.vessels[j as usize].flow
217        }
218    }
219
220    /// Transmural pressure at cell `j`, clamped to the network ends (zero
221    /// pressure gradient across the boundary).
222    fn pressure_at(&self, j: isize) -> f64 {
223        let n = self.vessels.len() as isize;
224        self.vessels[j.clamp(0, n - 1) as usize].pressure()
225    }
226
227    /// Right-hand side of the 1-D area/flow system at cell `i`, writing
228    /// `[dA/dt, dQ/dt]` into `out`:
229    ///
230    /// * continuity `dA/dt = −∂Q/∂x`, with the centred difference over unit cell
231    ///   spacing (the cells are normalized to `dx = 1`);
232    /// * momentum `dQ/dt = −(A/ρ)·∂p/∂x − k·Q/A`, with the linear tube-law
233    ///   pressure `p = β(√A − √A0)` and friction `k`.
234    pub fn rhs(&self, i: usize, out: &mut [f64; 2]) {
235        let v = &self.vessels[i];
236        let ii = i as isize;
237        let dq_dx = (self.flow_at(ii + 1) - self.flow_at(ii - 1)) / 2.0;
238        let dp_dx = (self.pressure_at(ii + 1) - self.pressure_at(ii - 1)) / 2.0;
239        out[0] = -dq_dx;
240        out[1] = -(v.area / self.rho) * dp_dx - self.friction * v.flow / v.area;
241    }
242
243    /// Advance the network by `dt` seconds with one explicit step. The state is
244    /// averaged over the neighbouring cells (Lax-type stabilisation of the
245    /// centred differences in [`Network::rhs`]), so the scheme stays stable for
246    /// a Courant number below one.
247    pub fn step(&mut self, dt: f64) {
248        let n = self.vessels.len();
249        let old = self.vessels.clone();
250        let mut next = old.clone();
251        for i in 0..n {
252            let ii = i as isize;
253            let v = &old[i];
254            // Explicit: continuity flux divergence and the pressure-gradient force.
255            let dq_dx = (self.flow_at(ii + 1) - self.flow_at(ii - 1)) / 2.0;
256            let dp_dx = (self.pressure_at(ii + 1) - self.pressure_at(ii - 1)) / 2.0;
257            let a_left = old[(ii - 1).max(0) as usize].area;
258            let a_right = old[(ii + 1).min(n as isize - 1) as usize].area;
259            let q_avg = 0.5 * (self.flow_at(ii - 1) + self.flow_at(ii + 1));
260            next[i].area = (0.5 * (a_left + a_right) - dt * dq_dx).max(1e-6);
261            // Friction is treated implicitly: it is a stiff damping term that
262            // destabilises the explicit update on long runs.
263            let pressure_force = -(v.area / self.rho) * dp_dx;
264            next[i].flow = (q_avg + dt * pressure_force) / (1.0 + dt * self.friction / v.area);
265        }
266        self.vessels = next;
267    }
268}
269
270#[cfg(test)]
271mod tests {
272    use super::*;
273    use approx::assert_abs_diff_eq;
274
275    #[test]
276    fn vessel_pressure_zero_at_reference() {
277        let beta = tube_law_beta(1.0e5, 0.1, 1.0);
278        let v = Vessel::new(1.0, 0.0, 1.0, beta).unwrap();
279        assert_abs_diff_eq!(v.pressure(), 0.0, epsilon = 1e-12);
280    }
281
282    #[test]
283    fn wave_speed_increases_with_stiffness() {
284        let soft = Vessel::new(1.0, 0.0, 1.0, tube_law_beta(1.0e4, 0.1, 1.0)).unwrap();
285        let stiff = Vessel::new(1.0, 0.0, 1.0, tube_law_beta(1.0e6, 0.1, 1.0)).unwrap();
286        assert!(stiff.wave_speed(1.06) > soft.wave_speed(1.06));
287    }
288
289    #[test]
290    fn womersley_parabolic_at_centerline() {
291        // At r = 0 and low Womersley number (ω/ν small so the plug_factor is 1),
292        // the profile is the full parabolic Poiseuille amplitude ≈ 2 > 1 (mean).
293        let u = womersley_velocity(0.0, 1.0, 1e-4, 0.04);
294        assert!(u > 1.0);
295    }
296
297    #[test]
298    fn casson_reduces_under_shear() {
299        let mu = casson_viscosity(0.04, 0.1, 100.0);
300        assert!(mu >= 0.04);
301        assert_abs_diff_eq!(casson_viscosity(0.04, 0.0, 100.0), 0.04, epsilon = 1e-9);
302    }
303
304    #[test]
305    fn network_step_stays_finite() {
306        let beta = tube_law_beta(1.0e5, 0.1, 1.0);
307        let v = Vessel::new(1.0, 1.0, 1.0, beta).unwrap();
308        let mut net = Network::new(v, 1.06, 8.0).unwrap();
309        for _ in 0..50 {
310            net.step(0.001);
311        }
312        assert!(net.vessels[0].area.is_finite());
313        assert!(net.vessels[0].flow.is_finite());
314    }
315}