"""Flow inputs of aortic blood-flow simulation from images and parameters.
:class:`AortaProcessFlow` turns images and :class:`AortaFlowParameters` into
what the flow workflows need, whatever their solver:
- the inflow: :meth:`~AortaProcessFlow.lv_volumes_ml` and
:meth:`~AortaProcessFlow.lv_ejection_inflow` derive it from the
left-ventricle (LV) volume of a cardiac labelmap series, assuming an ideal
non-regurgitant aortic valve and a closed mitral valve during ejection, and
:meth:`~AortaProcessFlow.lv_inflow` retimes it to the heart rate;
- the beat timing (:meth:`~AortaProcessFlow.beat_start_s`);
- one outlet model per outlet (:meth:`~AortaProcessFlow.windkessels`) and the
calibration of their totals to the patient's input pressures
(:meth:`~AortaProcessFlow.calibrated`).
It keeps no state, and reads no files: a long series of labelmaps need not
fit in memory when :meth:`~AortaProcessFlow.lv_volumes_ml` is given a
generator, which reads one frame at a time::
lv_volume_ml = AortaProcessFlow.lv_volumes_ml(
(itk.imread(f) for f in frame_files), lv_label_ids
)
inflow, interval_s = AortaProcessFlow.lv_inflow(lv_volume_ml, 60.0)
"""
from __future__ import annotations
import logging
from collections.abc import Iterable, Sequence
from dataclasses import replace
from typing import ClassVar
import itk
import numpy as np
from scipy.optimize import brentq, fsolve
from ..monai_physio_base import MONAIPhysioBase
from ..process_flow_boundaries import ProcessFlowBoundaries, Windkessel
from .flow_parameters import AortaFlowParameters
[docs]
class AortaProcessFlow(MONAIPhysioBase):
"""Inflow, beat timing, outlet models and outlet calibration of aortic flow.
The inflow and timing methods are static, pure functions of their
arguments. The outlet methods are instance methods, so that a subclass
can give other outlet models: override :meth:`windkessels` (and
:meth:`calibrated`, which fits the three-element model) and assign an
instance to a workflow's ``flow_tools``.
"""
[docs]
def __init__(self, log_level: int | str = logging.INFO) -> None:
"""Initialize AortaProcessFlow.
Args:
log_level: Logging level. Default: ``logging.INFO``.
"""
super().__init__(class_name=self.__class__.__name__, log_level=log_level)
# ─────────────────────────── Inflow from images ────────────────────────
[docs]
@staticmethod
def lv_volumes_ml(
labelmaps: Iterable[itk.Image], lv_label_ids: Sequence[int]
) -> np.ndarray:
"""Return the LV volume of each labelmap in mL.
The labelmaps are visited once, in order, and none is kept, so a
generator such as ``(itk.imread(f) for f in frame_files)`` reads one
frame at a time.
Args:
labelmaps: One labelmap per time frame.
lv_label_ids: Labels whose voxels form the LV cavity.
Returns:
Voxel count times voxel volume of each frame.
"""
volumes = []
for labelmap in labelmaps:
voxel_ml = float(np.prod(np.asarray(labelmap.GetSpacing()))) / 1000.0
voxels = np.isin(itk.array_view_from_image(labelmap), lv_label_ids)
volumes.append(np.count_nonzero(voxels) * voxel_ml)
return np.asarray(volumes)
[docs]
@staticmethod
def lv_ejection_inflow(
lv_volume_ml: np.ndarray,
interval_s: float,
minimum_ejection_fraction: float = 0.1,
) -> np.ndarray:
"""Return the mean aortic inflow of each frame interval in m^3/s.
The series is periodic: interval ``i`` runs from frame ``i`` to frame
``i + 1`` and the last one wraps to frame 0. With an ideal valve the
inflow is the positive LV volume loss over the interval and zero while
the LV fills. Segmentation noise also produces small losses, so an
ejection, a run of consecutive intervals in which the volume does not
rise (a plateau does not end it), is kept only if its volume reaches
``minimum_ejection_fraction`` of the LV volume range (maximum minus
minimum, about the stroke volume).
Args:
lv_volume_ml: LV volume of each frame in mL.
interval_s: Duration of each frame interval in seconds.
minimum_ejection_fraction: Smallest kept ejection volume relative to
the LV volume range.
Returns:
Inflow of each interval; ``len(lv_volume_ml)`` values.
"""
volume = np.asarray(lv_volume_ml, dtype=np.float64)
change = volume - np.roll(volume, -1)
loss = np.maximum(change, 0.0)
minimum = minimum_ejection_fraction * float(np.ptp(volume))
ejecting = change >= 0
# Start at a filling interval so that no run wraps around; a constant
# series has none, and no loss either.
order = np.roll(np.arange(len(loss)), -int(np.argmin(ejecting)))
run: list[int] = []
for i in [*order, order[0]]:
if ejecting[i]:
run.append(i)
continue
if run and loss[run].sum() < minimum:
loss[run] = 0.0
run = []
return loss * 1e-6 / interval_s
[docs]
@staticmethod
def lv_inflow(
lv_volume_ml: np.ndarray, heart_rate_bpm: float
) -> tuple[np.ndarray, float]:
"""Return the interval inflow of a periodic LV volume series.
The series is retimed so that its beats (``_beat_count``) beat at
``heart_rate_bpm``; the inflow is then :meth:`lv_ejection_inflow` at
that frame interval. Beats are counted for a regular rhythm (see
:attr:`BEAT_GAP_FRACTION`); with an irregular one the count can be too
low, which makes the frame interval too short.
Args:
lv_volume_ml: LV volume of each frame in mL, for example from
:meth:`lv_volumes_ml`.
heart_rate_bpm: Heart rate the series is retimed to, for example
:attr:`AortaFlowParameters.heart_rate_bpm`.
Returns:
Mean inflow of each frame interval in m^3/s and the interval in
seconds.
Raises:
ValueError: If the series has no ejection.
"""
beats = AortaProcessFlow._beat_count(lv_volume_ml)
if beats == 0:
raise ValueError("The LV volume series has no ejection")
interval_s = AortaProcessFlow._retimed_interval_s(
len(lv_volume_ml), beats, heart_rate_bpm
)
return AortaProcessFlow.lv_ejection_inflow(lv_volume_ml, interval_s), interval_s
#: A pause in ejection separates two beats when it lasts at least this
#: fraction of the longest pause of the series; shorter pauses, such as a
#: systolic plateau or a small rebound, belong to the ejection they
#: interrupt. The rule assumes a regular rhythm: a filling pause shorter
#: than this fraction of the longest one, as after a premature beat, does
#: not start a beat, so its two ejections count as one beat.
BEAT_GAP_FRACTION: ClassVar[float] = 0.5
#: For an inflow that never drops to zero, the fraction of its range
#: above its smallest value that a flux must exceed to count as ejection.
BASELINE_FRACTION: ClassVar[float] = 0.1
[docs]
@staticmethod
def beat_start_s(interval_fluxes: np.ndarray, interval_s: float) -> float:
"""Return the middle of the filling gap before the first beat.
The flow workflows start their simulated time here, so every beat window
holds one whole ejection. Beats start where :meth:`_beat_onsets` says.
Args:
interval_fluxes: Mean flux of each interval of a periodic series.
interval_s: Duration of each interval in seconds.
Returns:
The time in seconds, negative when the gap wraps from the end of
the series.
Raises:
ValueError: If the series has no ejection.
"""
onsets, gaps = AortaProcessFlow._beat_onsets(interval_fluxes)
if len(onsets) == 0:
raise ValueError("The inflow has no ejection")
return (int(onsets[0]) - 0.5 * int(gaps[0])) * interval_s
@staticmethod
def _beat_onsets(interval_fluxes: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
"""Return the intervals where beats start and the pause before each.
Every run of positive flux is an ejection; for a series without a
zero or negative interval, such as a measured inflow with a positive
diastolic baseline, every run above :attr:`BASELINE_FRACTION` of the
way from the smallest to the largest flux. An ejection starts a beat
when the run of intervals without flux before it, which may wrap from
the end of the series, lasts at least :attr:`BEAT_GAP_FRACTION` of
the longest such run; otherwise it continues the ejection before it.
Args:
interval_fluxes: Mean flux of each interval of a periodic series.
Returns:
The first interval of each beat, in increasing order, and the
number of intervals without flux before it; both empty when the
series has no ejection.
"""
fluxes = np.asarray(interval_fluxes, dtype=np.float64)
threshold = 0.0
if len(fluxes) and fluxes.min() > 0:
threshold = fluxes.min() + AortaProcessFlow.BASELINE_FRACTION * float(
np.ptp(fluxes)
)
ejecting = fluxes > threshold
onsets = np.flatnonzero(ejecting & ~np.roll(ejecting, 1))
# Intervals since the previous ejection, which may wrap from the end.
gaps = np.array(
[int(np.argmax(np.roll(ejecting, -int(onset))[::-1])) for onset in onsets],
dtype=np.int64,
)
if len(onsets) == 0:
return onsets, gaps
beats = gaps >= AortaProcessFlow.BEAT_GAP_FRACTION * gaps.max()
return onsets[beats], gaps[beats]
@staticmethod
def _beat_count(lv_volume_ml: np.ndarray) -> int:
"""Return the number of beats of a periodic LV volume series.
The beats are :meth:`_beat_onsets` of :meth:`lv_ejection_inflow`.
"""
inflow = AortaProcessFlow.lv_ejection_inflow(lv_volume_ml, 1.0)
return len(AortaProcessFlow._beat_onsets(inflow)[0])
@staticmethod
def _retimed_interval_s(
frame_count: int, beat_count: int, heart_rate_bpm: float
) -> float:
"""Return the frame interval that makes a series beat at the heart rate.
Args:
frame_count: Number of frames in the periodic series.
beat_count: Number of heart beats the series covers, for example
``_beat_count`` of its LV volume.
heart_rate_bpm: Heart rate in beats per minute.
"""
return beat_count * 60.0 / heart_rate_bpm / frame_count
# ─────────────────────────── Outlets and calibration ───────────────────
[docs]
def windkessels(
self, flow_parameters: AortaFlowParameters, outlet_names: Sequence[str]
) -> dict[str, Windkessel]:
"""Return the model that terminates each outlet: one Windkessel each.
The flow fractions of ``outlet_names`` are renormalized to sum to one,
so the outlet resistances in parallel equal the total resistance and
the outlet compliances sum to the total compliance.
This is the one place that decides which object ends each outlet. A
flow solver uses only its ``implicit(dt)``, ``advance(Q, dt)`` and
``pressure``, so a subclass may return other objects with those
members; :meth:`calibrated` fits the three-element model, so such a
subclass overrides it too, or the workflow runs with
``calibrate_outlets=False``.
Args:
flow_parameters: Outlet totals, flow fractions and initial
pressure.
outlet_names: Names of the outlets present.
Raises:
ValueError: If an outlet has no flow fraction.
"""
fractions = flow_parameters.flow_fractions
unknown = [name for name in outlet_names if name not in fractions]
if unknown:
raise ValueError(
f"No flow fraction for outlets {unknown}; "
f"known outlets are {sorted(fractions)}"
)
total = sum(fractions[name] for name in outlet_names)
return {
name: Windkessel.from_total(
fractions[name] / total,
flow_parameters.total_resistance_pa_s_m3,
flow_parameters.total_compliance_m3_pa,
flow_parameters.proximal_fraction,
flow_parameters.initial_pressure_pa,
)
for name in outlet_names
}
[docs]
def calibrated(
self,
flow_parameters: AortaFlowParameters,
interval_fluxes_m3_s: np.ndarray,
interval_s: float,
dt_s: float = 0.001,
wall_compliance_m3_pa: float = 0.0,
) -> AortaFlowParameters:
"""Return a copy whose outlets reproduce the input pressures.
The outlets are calibrated as the whole-body three-element Windkessel
they split from (:meth:`Windkessel.from_total` with fraction one and
``proximal_fraction``), fed by the smoothed periodic inflow
(:meth:`ProcessFlowBoundaries.inlet_flow` with ``inflow_smoothing_s``)
and stepped like the workflows' outlets. An elastic aorta adds its
own compliance ``C_w`` in front of them: the root pressure ``P`` then
obeys ``C_w dP/dt = Q_in - Q_out`` with ``P`` the Windkessel pressure
of the outflow ``Q_out`` (stepped implicitly in ``Q_out``, as the flow
solver does), as in ``experiments/BloodFlow-3D-FSI-Simpleware-Warp``.
- The total resistance and the total outlet compliance are fitted
together, on their logarithms, so that the periodic root pressure
has the input systolic pressure as its maximum and the input
diastolic pressure as its minimum (the venous pressure is taken as
zero). The start is the resistance that gives the clinical mean
:attr:`AortaFlowParameters.mean_pressure_mmhg` (in a periodic state
the mean pressure is the total resistance times the mean flow) with
the compliance, found by Brent root finding between 1e-12 and 1e-6
m^3/Pa, that gives the input pulse pressure; a 2D root solve then
moves both. When no compliance in that range gives the input
pulse at that resistance, or the 2D solve misses, the fit starts
again from the resistances around it (:meth:`_resistance_starts`),
nearest first, so the error is raised only when none of those
starts fits.
- The initial pressure is the periodic capacitor pressure at
:meth:`beat_start_s`, where the flow workflows start, so their
first beat starts near the periodic state, though only
approximately when a wall or a 3D pressure drop is present.
The proximal resistance carries the pulse that the flow drives
through it, so with the large total resistance a low cardiac output
needs, the root pressure follows the shape of the inflow.
The model covers one period of the inflow series,
``len(interval_fluxes_m3_s) * interval_s``, which may hold several
beats; the systolic and diastolic pressures are the extremes over
all of them. The root pressure of a flow model adds the pressure
drop along its aorta.
Args:
flow_parameters: Input pressures, inflow smoothing and outlet
parameters to calibrate.
interval_fluxes_m3_s: Mean inflow of each frame interval in
m^3/s, for example from :meth:`lv_inflow`.
interval_s: Duration of each frame interval in seconds.
dt_s: Approximate backward-Euler time step of the model.
wall_compliance_m3_pa: Compliance ``dV/dP`` of the aortic wall
in front of the outlets; 0 for a rigid aorta.
Returns:
A copy of *flow_parameters* with ``total_resistance_pa_s_m3``,
``total_compliance_m3_pa`` and ``initial_pressure_pa`` replaced.
Raises:
ValueError: If the input pressures do not satisfy
``0 < diastolic < systolic``, if the inflow has no ejection,
or if no outlet resistance and compliance give the input
pressures, as when the wall alone is too compliant.
"""
mmhg_pa = ProcessFlowBoundaries.MMHG_PA
self.check_input_pressures(flow_parameters)
systolic = flow_parameters.systolic_pressure_mmhg
diastolic = flow_parameters.diastolic_pressure_mmhg
fluxes = np.asarray(interval_fluxes_m3_s, dtype=np.float64)
period_s = len(fluxes) * interval_s
steps = max(1, round(period_s / dt_s))
step_s = period_s / steps
times = self.beat_start_s(fluxes, interval_s) + np.arange(1, steps + 1) * step_s
flow = ProcessFlowBoundaries.inlet_flow(
times, fluxes, interval_s, flow_parameters.inflow_smoothing_s
)[0]
pulse_pa = (systolic - diastolic) * mmhg_pa
unreachable = ValueError(
f"No outlet resistance and compliance give {systolic:.1f}/"
f"{diastolic:.1f} mmHg with this inflow, proximal_fraction "
f"{flow_parameters.proximal_fraction} and wall compliance "
f"{wall_compliance_m3_pa:.3g} m^3/Pa"
)
def periodic(log_r: float, log_c: float) -> tuple[np.ndarray, float]:
trial = replace(
flow_parameters,
total_resistance_pa_s_m3=float(np.exp(log_r)),
total_compliance_m3_pa=float(np.exp(log_c)),
)
return self._periodic_pressure(trial, flow, step_s, wall_compliance_m3_pa)
def error_mmhg(log_rc: np.ndarray) -> np.ndarray:
pressure = periodic(float(log_rc[0]), float(log_rc[1]))[0] / mmhg_pa
return np.array([pressure.max() - systolic, pressure.min() - diastolic])
seed = float(
np.log(flow_parameters.mean_pressure_mmhg * mmhg_pa / fluxes.mean())
)
low, high = float(np.log(1e-12)), float(np.log(1e-6))
for log_r in self._resistance_starts(seed):
def pulse_error(log_c: float, log_r: float = log_r) -> float:
return float(np.ptp(periodic(log_r, log_c)[0])) - pulse_pa
if pulse_error(low) < 0 or pulse_error(high) > 0:
continue
start = np.array([log_r, brentq(pulse_error, low, high, xtol=1e-8)])
log_rc = np.asarray(fsolve(error_mmhg, start, xtol=1e-12), dtype=np.float64)
# fsolve can stop away from a root; accept only a fit within
# 0.01 mmHg.
if np.all(np.abs(error_mmhg(log_rc)) < 1e-2):
return replace(
flow_parameters,
total_resistance_pa_s_m3=float(np.exp(log_rc[0])),
total_compliance_m3_pa=float(np.exp(log_rc[1])),
initial_pressure_pa=periodic(float(log_rc[0]), float(log_rc[1]))[1],
)
raise unreachable
#: Resistance starts of :meth:`calibrated` besides its seed: the seed
#: times ``2 ** (k / 8)`` for k = -1, 1, -2, 2, ... up to a factor of 8.
RESISTANCE_SEARCH_STEPS: ClassVar[int] = 24
@classmethod
def _resistance_starts(cls, seed: float) -> list[float]:
"""Return the log resistances :meth:`calibrated` starts from, seed first.
The seed, the resistance that gives the clinical mean pressure, misses
when the pressure waveform is far from the one-third rule, as when
the proximal resistance carries most of the pulse; the fit then
starts from resistances around it, nearest first.
"""
step = float(np.log(2.0)) / 8
starts = [seed]
for k in range(1, cls.RESISTANCE_SEARCH_STEPS + 1):
starts += [seed - k * step, seed + k * step]
return starts
def _periodic_pressure(
self,
flow_parameters: AortaFlowParameters,
flow_m3_s: np.ndarray,
dt_s: float,
wall_compliance_m3_pa: float = 0.0,
) -> tuple[np.ndarray, float]:
"""Return the periodic root pressure of the whole-body model.
*flow_m3_s* holds one period of inflow at steps of *dt_s*; see
:meth:`calibrated` for the model. Its state, the root and capacitor
pressures, at the end of the period is affine in the state at its
start, so passes from three starts give the start that repeats, and a
fourth pass from it gives the periodic pressure.
Returns:
Root pressure at every step in Pa and the periodic capacitor
pressure at the start of the period.
"""
def run(start_pa: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
windkessel = Windkessel.from_total(
1.0,
flow_parameters.total_resistance_pa_s_m3,
flow_parameters.total_compliance_m3_pa,
flow_parameters.proximal_fraction,
float(start_pa[1]),
)
root = float(start_pa[0])
pressure = []
for inflow in flow_m3_s:
outflow = float(inflow)
if wall_compliance_m3_pa > 0:
resistance, offset = windkessel.implicit(dt_s)
rate = dt_s / wall_compliance_m3_pa
outflow = (root + rate * outflow - offset) / (resistance + rate)
root = windkessel.advance(outflow, dt_s)
pressure.append(root)
return np.asarray(pressure), np.array([root, windkessel.pressure])
end_from_zero = run(np.zeros(2))[1]
response = np.column_stack([run(unit)[1] - end_from_zero for unit in np.eye(2)])
start_pa = np.linalg.solve(np.eye(2) - response, end_from_zero)
return run(start_pa)[0], float(start_pa[1])