Source code for monai_physio.process_flow_boundaries

"""Boundary conditions and units of blood-flow models, independent of the solver.

:class:`Windkessel` is the three-element (RCR) outlet model and
:class:`ProcessFlowBoundaries` holds the smoothed periodic inlet flow and the
Pa per mmHg conversion.  Neither knows about a flow solver, a mesh or an
anatomy, so flow solvers, 1D models, outlet calibrations and viewers share
them.
"""

from __future__ import annotations

import logging
from dataclasses import dataclass
from typing import ClassVar

import numpy as np
from scipy.special import ndtr

from .monai_physio_base import MONAIPhysioBase


[docs] @dataclass class Windkessel: """Three-element Windkessel (RCR) outlet. The outlet pressure is ``P = R_p Q + P_c``, where the distal capacitor pressure obeys ``C dP_c/dt = Q - P_c / R_d``. A zero distal resistance gives a pure resistance ``R_p``, a zero compliance gives a pure resistance ``R_p + R_d``, and zero resistances give zero traction. Attributes: proximal_resistance: R_p in Pa s/m^3. distal_resistance: R_d in Pa s/m^3. compliance: C in m^3/Pa. pressure: Capacitor pressure P_c in Pa. """ proximal_resistance: float distal_resistance: float compliance: float pressure: float
[docs] @classmethod def from_total( cls, fraction: float, total_resistance: float, total_compliance: float, proximal_fraction: float, pressure: float, ) -> Windkessel: """Split whole-body values to an outlet receiving ``fraction`` of flow. Resistances scale with ``1 / fraction`` and compliance with ``fraction``, so every outlet has the same time constant. """ resistance = total_resistance / fraction return cls( proximal_fraction * resistance, (1 - proximal_fraction) * resistance, total_compliance * fraction, pressure, )
def _distal_step(self, dt: float) -> tuple[float, float]: """Return ``(gain, decay)`` of a backward-Euler step of ``P_c``. The step is ``P_c^{n+1} = decay P_c^n + gain Q^{n+1}``, with ``gain = R_d dt / (R_d C + dt)`` and ``decay = R_d C / (R_d C + dt)``. The gain is the distal resistance only when ``C`` is zero. """ rc = self.distal_resistance * self.compliance denom = rc + dt return self.distal_resistance * dt / denom, rc / denom
[docs] def implicit(self, dt: float) -> tuple[float, float]: """Return ``(R, P0)`` with backward-Euler pressure ``R Q^{n+1} + P0``.""" gain, decay = self._distal_step(dt) return ( self.proximal_resistance + gain, decay * self.pressure, )
[docs] def advance(self, flow: float, dt: float) -> float: """Advance ``P_c`` with the new outlet flow and return the outlet pressure.""" gain, decay = self._distal_step(dt) self.pressure = decay * self.pressure + gain * flow return self.proximal_resistance * flow + self.pressure
[docs] class ProcessFlowBoundaries(MONAIPhysioBase): """Inlet flow signals and pressure units shared by the blood-flow models. Example: >>> flow, derivative = ProcessFlowBoundaries.inlet_flow( ... times_s, interval_fluxes_m3_s, interval_s=0.03, smoothing_s=0.03 ... ) >>> pressure_mmhg = pressure_pa / ProcessFlowBoundaries.MMHG_PA """ #: Pa per mmHg. MMHG_PA: ClassVar[float] = 133.322387415
[docs] def __init__(self, log_level: int | str = logging.INFO) -> None: """Initialize ProcessFlowBoundaries. Args: log_level: Logging level (default: logging.INFO) """ super().__init__(class_name=self.__class__.__name__, log_level=log_level)
[docs] @staticmethod def inlet_flow( times_s: np.ndarray, interval_fluxes_m3_s: np.ndarray, interval_s: float, smoothing_s: float, ) -> tuple[np.ndarray, np.ndarray]: """Return a smoothed periodic inlet flow Q(t) and dQ/dt. ``interval_fluxes_m3_s`` holds the mean flux of consecutive source intervals of ``interval_s`` seconds (for example the left-ventricle volume loss between frames of a cardiac image series) and repeats with period ``len(interval_fluxes_m3_s) * interval_s``. This staircase has unphysical jumps, so it is convolved with a periodic Gaussian of standard deviation ``smoothing_s``, evaluated exactly with the normal CDF. A nonnegative kernel of unit integral keeps Q >= 0 and preserves the volume of every beat whose window boundaries lie in diastole, many ``smoothing_s`` from ejection. Args: times_s: Evaluation times in seconds. interval_fluxes_m3_s: Flux of each source interval in m^3/s. interval_s: Duration of each source interval in seconds. smoothing_s: Gaussian standard deviation in seconds, much less than one period (three periodic images are summed). Returns: Flow in m^3/s and its derivative in m^3/s^2 at ``times_s``. """ flux = np.asarray(interval_fluxes_m3_s, dtype=np.float64) period = len(flux) * interval_s edges = np.arange(len(flux) + 1) * interval_s t = np.mod(np.asarray(times_s, dtype=np.float64), period)[:, None] flow = np.zeros(len(t)) derivative = np.zeros(len(t)) for shift in (-period, 0.0, period): start = (t - edges[:-1] - shift) / smoothing_s end = (t - edges[1:] - shift) / smoothing_s flow += (ndtr(start) - ndtr(end)) @ flux density = np.exp(-0.5 * start**2) - np.exp(-0.5 * end**2) derivative += density @ flux / (smoothing_s * np.sqrt(2 * np.pi)) return flow, derivative