"""Base class of the aortic blood-flow workflows.
:class:`AortaWorkflowSimulateFlowBase` holds what the 1D, 3D rigid and 3D
fluid-structure workflows share: the flow parameters, the geometry from a
labelmap or a prepared geometry, the calibration of the outlets to the input
pressures, the selection of the last beat and the root-pressure summary.
Every workflow result holds ``"geometry"``, ``"flow_parameters"``,
``"series"`` and ``"summary"``. ``"series"`` holds one value per simulated
sample: ``"times_s"``, ``"inlet_flow_m3_s"``, ``"root_pressure_pa"`` and the
outlet name -> array dicts ``"outlet_flow_m3_s"`` and
``"outlet_pressure_pa"``, plus each model's own series.
"""
from __future__ import annotations
import logging
from collections.abc import Mapping, Sequence
from typing import Any, ClassVar, Optional
import itk
import numpy as np
from ..monai_physio_base import MONAIPhysioBase
from ..process_flow_boundaries import ProcessFlowBoundaries
from .flow_parameters import AortaFlowParameters
from .process_flow import AortaProcessFlow
from .process_geometry import AortaProcessGeometry
[docs]
class AortaWorkflowSimulateFlowBase(MONAIPhysioBase):
"""Shared inputs, calibration and summary of the aorta flow workflows.
``flow_parameters`` supplies the patient's input blood pressure and heart
rate, the blood properties, the inflow smoothing and the outlet
Windkessel totals; see :class:`AortaFlowParameters`.
:attr:`flow_tools`, an :class:`AortaProcessFlow`, builds the outlet
models and calibrates them; assign a subclass instance to it for other
outlet models.
**Input pressures**
The patient's systolic and diastolic pressures are inputs, not results.
By default ``process`` calibrates a copy of the outlets to them and to
the given inflow (:meth:`AortaProcessFlow.calibrated`), leaving
:attr:`flow_parameters` unchanged; the simulated root pressure then
differs from the inputs by the model's pressure drop along the aorta.
``calibrate_outlets=False`` uses the outlet totals of
``flow_parameters`` as given.
**Inflow**
Any sampled periodic inflow works: ``inflow_m3_s`` holds the mean flow
of each interval of ``inflow_interval_s``, for example from
:meth:`AortaProcessFlow.lv_inflow` or a measured flow curve, and must
hold at least one ejection (a run of positive flow, or of flow above its
diastolic baseline) and last a whole number of beats at
:attr:`AortaFlowParameters.heart_rate_bpm`. It is smoothed by
:meth:`ProcessFlowBoundaries.inlet_flow` with
:attr:`AortaFlowParameters.inflow_smoothing_s`.
**Beats**
The simulation covers ``beats`` heart beats of ``60 / heart_rate_bpm``
seconds. Time 0 is the middle of the filling gap before the first
ejection of the inflow series, so every beat window holds one whole
ejection. The summary reports the last beat; the outlet capacitors start
at :attr:`AortaFlowParameters.initial_pressure_pa` (the calibrated
periodic pressure by default), and the change of mean root pressure from
the beat before shows how periodic the last beat is.
**I/O contract**
``process`` performs *no* file I/O. :class:`AortaVisualizeFlow` and
:class:`AortaVisualizeFlowNS` write its result to disk.
"""
[docs]
def __init__(
self,
flow_parameters: Optional[AortaFlowParameters] = None,
log_level: int | str = logging.INFO,
) -> None:
"""Initialize the workflow.
Args:
flow_parameters: Blood, inflow, outlet and wall parameters.
Defaults to :class:`AortaFlowParameters` ``()``.
log_level: Logging level. Default: ``logging.INFO``.
"""
super().__init__(class_name=self.__class__.__name__, log_level=log_level)
self.flow_parameters = (
flow_parameters if flow_parameters is not None else AortaFlowParameters()
)
self.flow_tools = AortaProcessFlow(log_level=log_level)
self._geometry_tools = AortaProcessGeometry(log_level=log_level)
# Simulation settings; each has a set_* method.
self.aorta_label_ids: Sequence[int] = (1,)
self.branch_label_ids: Optional[Mapping[str, int]] = None
self.beats = 3
self.dt_s = self._DEFAULT_DT_S
self.calibrate_outlets = True
#: Solver time step each workflow starts with; set_dt_s overrides it.
_DEFAULT_DT_S: float = 0.003
[docs]
def set_aorta_label_ids(self, aorta_label_ids: Sequence[int]) -> None:
"""Choose the labels whose union is the aortic lumen.
Args:
aorta_label_ids: Label ids. Default: (1,)
Raises:
ValueError: If it is empty.
"""
if not aorta_label_ids:
raise ValueError("aorta_label_ids must name at least one label")
self.aorta_label_ids = tuple(aorta_label_ids)
[docs]
def set_branch_label_ids(
self, branch_label_ids: Optional[Mapping[str, int]]
) -> None:
"""Map branch names to labels; each branch found becomes an outlet.
Each outlet is named by its lowercased key, which must be a key of
:attr:`AortaFlowParameters.flow_fractions`.
Args:
branch_label_ids: Branch name -> label, or None (default) for no
branches.
"""
self.branch_label_ids = (
dict(branch_label_ids) if branch_label_ids is not None else None
)
[docs]
def set_beats(self, beats: int) -> None:
"""Set the number of heart beats to simulate.
Args:
beats: Beats, at least two. Default: 3
Raises:
ValueError: If it is less than two.
"""
if beats < 2:
raise ValueError(f"beats must be at least 2, got {beats}")
self.beats = beats
[docs]
def set_dt_s(self, dt_s: float) -> None:
"""Set the solver time step in seconds.
Args:
dt_s: Time step; each workflow has its own default.
Raises:
ValueError: If it is not positive.
"""
if not dt_s > 0:
raise ValueError(f"dt_s must be > 0, got {dt_s}")
self.dt_s = dt_s
[docs]
def set_calibrate_outlets(self, calibrate_outlets: bool) -> None:
"""Calibrate the outlet totals and initial pressure to this inflow.
``False`` uses the outlet totals of :attr:`flow_parameters` as given.
Args:
calibrate_outlets: Whether to. Default: True
"""
self.calibrate_outlets = calibrate_outlets
# ─────────────────────────── Shared steps ──────────────────────────────
def _resolve_geometry(
self,
labelmap_image: Optional[itk.Image],
geometry: Optional[Mapping[str, Any]],
aorta_label_ids: Sequence[int],
branch_label_ids: Optional[Mapping[str, int]],
**prepare_options: Any,
) -> Mapping[str, Any]:
"""Return *geometry*, or prepare it from *labelmap_image*.
Args:
labelmap_image: Labelmap to prepare with
:meth:`AortaProcessGeometry.prepare`.
geometry: A prepared geometry, returned as given.
aorta_label_ids: Labels whose union is the aortic lumen.
branch_label_ids: Branch name -> label.
prepare_options: Keyword arguments of
:meth:`AortaProcessGeometry.prepare`.
Raises:
ValueError: If not exactly one of *labelmap_image* and *geometry*
is given.
"""
if (labelmap_image is None) == (geometry is None):
raise ValueError("Give exactly one of labelmap_image and geometry")
if geometry is not None:
return geometry
return self._geometry_tools.prepare(
labelmap_image, aorta_label_ids, branch_label_ids, **prepare_options
)
#: Largest difference, in beats, between the inflow series' duration and
#: a whole number of beats at the heart rate.
INFLOW_PERIOD_TOLERANCE: ClassVar[float] = 0.01
def _check_timing(
self, inflow_m3_s: np.ndarray, interval_s: float, dt_s: float
) -> None:
"""Check that the inflow and time step fit beats of the heart rate.
The summary reports beats of ``60 / heart_rate_bpm`` seconds, so the
periodic inflow series must last a whole number of those beats, and
a beat must hold at least two time steps.
Raises:
ValueError: If *dt_s* is not positive or exceeds half a beat, or
if the series does not last a whole number of beats.
"""
beat_s = 60.0 / self.flow_parameters.heart_rate_bpm
if not 0 < dt_s <= beat_s / 2:
raise ValueError(
f"dt_s {dt_s} s must be positive and at most half the "
f"{beat_s:.3g} s beat"
)
period_beats = len(inflow_m3_s) * interval_s / beat_s
whole = round(period_beats)
if whole < 1 or abs(period_beats - whole) > self.INFLOW_PERIOD_TOLERANCE:
raise ValueError(
f"The inflow series lasts {period_beats:.3f} beats of "
f"{beat_s:.3g} s, not a whole number; retime it, for example "
"with AortaProcessFlow.lv_inflow, or set heart_rate_bpm to "
"its rate"
)
def _calibrate(
self,
inflow_m3_s: np.ndarray,
interval_s: float,
dt_s: float,
calibrate: bool,
wall_compliance_m3_pa: float = 0.0,
) -> AortaFlowParameters:
"""Return :attr:`flow_parameters`, calibrated to this inflow if *calibrate*.
See :meth:`AortaProcessFlow.calibrated`; *wall_compliance_m3_pa* is
the compliance of an elastic aorta in front of the outlets.
"""
flow_parameters = self.flow_parameters
if calibrate:
flow_parameters = self.flow_tools.calibrated(
flow_parameters,
inflow_m3_s,
interval_s,
dt_s,
wall_compliance_m3_pa=wall_compliance_m3_pa,
)
self.log_info(
"Input patient pressure %.0f/%.0f mmHg (mean %.1f); outlets %s: "
"R %.4g Pa s/m^3, C %.4g m^3/Pa, initial %.1f mmHg",
flow_parameters.systolic_pressure_mmhg,
flow_parameters.diastolic_pressure_mmhg,
flow_parameters.mean_pressure_mmhg,
"calibrated to it" if calibrate else "as given",
flow_parameters.total_resistance_pa_s_m3,
flow_parameters.total_compliance_m3_pa,
flow_parameters.initial_pressure_pa / ProcessFlowBoundaries.MMHG_PA,
)
if wall_compliance_m3_pa > 0:
self.log_info(
"Compliance total %.4g = wall %.4g + outlets %.4g m^3/Pa",
flow_parameters.total_compliance_m3_pa + wall_compliance_m3_pa,
wall_compliance_m3_pa,
flow_parameters.total_compliance_m3_pa,
)
return flow_parameters
@staticmethod
def _last_beat(times_s: np.ndarray, beat_s: float) -> np.ndarray:
"""Return which samples fall in the last *beat_s* of the run.
The samples are evenly spaced, one per time step, so these are the
last ``round(beat_s / step)`` of them.
"""
times_s = np.asarray(times_s)
count = round(beat_s / float(times_s[1] - times_s[0]))
last = np.zeros(len(times_s), dtype=bool)
last[max(0, len(times_s) - count) :] = True
return last
def _pressure_summary(
self, flow_parameters: AortaFlowParameters, series: Mapping[str, Any]
) -> dict[str, Any]:
"""Return the input pressures, outlet totals and last-beat root metrics.
The keys are ``heart_rate_bpm``, the input patient pressures
``input_systolic_mmhg``, ``input_diastolic_mmhg`` and
``input_mean_mmhg`` (:attr:`AortaFlowParameters.mean_pressure_mmhg`),
the outlet totals simulated ``outlet_total_resistance_pa_s_m3`` and
``outlet_total_compliance_m3_pa``; then, over the last beat, the root's
``root_systolic_mmhg``, ``root_diastolic_mmhg``, ``root_mean_mmhg``
and ``root_pulse_pressure_mmhg``, the largest and smallest root minus
distal-outlet pressure ``root_to_distal_max_mmhg`` and
``root_to_distal_min_mmhg``, the change of mean root pressure from
the beat before ``mean_pressure_change_mmhg``, ``peak_inflow_ml_s``,
``stroke_volume_ml`` and ``cardiac_output_l_min``.
"""
beat_s = 60.0 / flow_parameters.heart_rate_bpm
times = np.asarray(series["times_s"])
dt_s = float(times[1] - times[0])
last = self._last_beat(times, beat_s)
previous = self._last_beat(times, 2 * beat_s) & ~last
root = np.asarray(series["root_pressure_pa"]) / ProcessFlowBoundaries.MMHG_PA
distal = (
np.asarray(series["outlet_pressure_pa"]["distal"])
/ ProcessFlowBoundaries.MMHG_PA
)
difference = root[last] - distal[last]
inflow = np.asarray(series["inlet_flow_m3_s"])
stroke_ml = float(inflow[last].sum() * dt_s * 1e6)
return {
"heart_rate_bpm": flow_parameters.heart_rate_bpm,
"input_systolic_mmhg": flow_parameters.systolic_pressure_mmhg,
"input_diastolic_mmhg": flow_parameters.diastolic_pressure_mmhg,
"input_mean_mmhg": flow_parameters.mean_pressure_mmhg,
"outlet_total_resistance_pa_s_m3": (
flow_parameters.total_resistance_pa_s_m3
),
"outlet_total_compliance_m3_pa": flow_parameters.total_compliance_m3_pa,
"root_systolic_mmhg": float(root[last].max()),
"root_diastolic_mmhg": float(root[last].min()),
"root_mean_mmhg": float(root[last].mean()),
"root_pulse_pressure_mmhg": float(np.ptp(root[last])),
"root_to_distal_max_mmhg": float(difference.max()),
"root_to_distal_min_mmhg": float(difference.min()),
"mean_pressure_change_mmhg": float(
root[last].mean() - root[previous].mean()
),
"peak_inflow_ml_s": float(inflow[last].max() * 1e6),
"stroke_volume_ml": stroke_ml,
"cardiac_output_l_min": stroke_ml * 60.0 / beat_s / 1000.0,
}