"""Solver-independent part of the 3D aortic blood-flow workflows.
:class:`AortaWorkflowSimulateFlow3DBase` prepares the geometry, steps a
:class:`monai_physio.WarpFlowBase` solver over whole beats, keeps the
last-beat fields and summarizes the last beat. Its subclasses build the
solver's domain and the solver itself, such as
:class:`AortaWorkflowSimulateFlow3DNS` for Navier-Stokes (NS) flow on a
tetrahedral lumen mesh.
"""
from __future__ import annotations
import logging
import time
from collections.abc import Mapping, Sequence
from typing import Any, ClassVar, Optional
import itk
import numpy as np
import warp as wp
from scipy.spatial import cKDTree
from ..process_flow_boundaries import ProcessFlowBoundaries
from ..warp_flow_base import WarpFlowBase
from .flow_parameters import AortaFlowParameters
from .process_flow import AortaProcessFlow
from .workflow_simulate_flow_base import AortaWorkflowSimulateFlowBase
[docs]
class AortaWorkflowSimulateFlow3DBase(AortaWorkflowSimulateFlowBase):
"""Step a 3D blood-flow solver in an aorta and summarize the last beat.
The inputs, outlet calibration (at the solver time step), beats and I/O
contract are those of :class:`AortaWorkflowSimulateFlowBase`; the
simulated root pressure adds the 3D pressure drop along the aorta. The
run starts from rest, and full velocity and pressure fields are kept for
the last beat.
**Outlets**
Each outlet ends in the object :meth:`AortaProcessFlow.windkessels`
returns for it, a three-element :class:`Windkessel` by default. The
solver uses only its ``implicit(dt)``, which returns ``(R, P0)`` such
that the outlet pressure over a step is ``R Q + P0`` for the step's
outflow ``Q`` (``R`` must not change between steps), ``advance(Q, dt)``,
which ends the step and returns that pressure, and its ``pressure``
state, which a coupled step restores between iterations. A subclass of
:class:`AortaProcessFlow` whose ``windkessels`` returns other objects
with these three members, assigned to :attr:`flow_tools`, gives other
outlet models.
**Steppers**
:meth:`_simulate` steps the object :meth:`_build_stepper` returns: a
:class:`WarpFlowBase` solver, or an object wrapping one as ``.fluid``
(such as :class:`WarpFluidStructureNS`), whose ``step(inlet_flow)``
returns the step result of :meth:`WarpFlowBase.step` plus its own
entries. :attr:`STEP_KEYS` names the entries kept as series and
:meth:`_frame_extras` adds fields to the saved frames.
**Subclasses** implement :meth:`_prepare_domain`, :meth:`_build_stepper`,
:meth:`_root_pressure_weights`, :meth:`_field_points`,
:meth:`_run_settings`, :meth:`_run_sizes`, :meth:`_solver_summary` and
:meth:`_step_message`.
"""
[docs]
def __init__(
self,
flow_parameters: Optional[AortaFlowParameters] = None,
log_level: int | str = logging.INFO,
) -> None:
"""Initialize the workflow; see :class:`AortaWorkflowSimulateFlowBase`."""
super().__init__(flow_parameters=flow_parameters, log_level=log_level)
self.element_size_mm = 2.0
self.precision = "float32"
self.frame_interval_s = 0.03
[docs]
def set_element_size_mm(self, element_size_mm: float) -> None:
"""Set the largest interior edge length of the meshes.
Args:
element_size_mm: Edge length in millimeters. Default: 2.0
Raises:
ValueError: If it is not positive.
"""
if not element_size_mm > 0:
raise ValueError(f"element_size_mm must be > 0, got {element_size_mm}")
self.element_size_mm = element_size_mm
[docs]
def set_precision(self, precision: str) -> None:
"""Choose the precision of the blood operators and linear solves.
Args:
precision: ``"float32"`` (default) or ``"float64"``.
Raises:
ValueError: If it is neither.
"""
if precision not in ("float32", "float64"):
raise ValueError(
f"precision must be 'float32' or 'float64', got {precision}"
)
self.precision = precision
[docs]
def set_frame_interval_s(self, frame_interval_s: float) -> None:
"""Set the interval of the saved fields over the last beat.
Rounded to a multiple of the time step.
Args:
frame_interval_s: Interval in seconds. Default: 0.03
Raises:
ValueError: If it is not positive.
"""
if not frame_interval_s > 0:
raise ValueError(f"frame_interval_s must be > 0, got {frame_interval_s}")
self.frame_interval_s = frame_interval_s
#: Model name of the log and progress messages.
TITLE: ClassVar[str] = "3D aorta flow"
#: Result key of the solver's domain, such as its mesh.
DOMAIN_KEY: ClassVar[str] = "domain"
#: Speeds within this distance of an outlet center are left out of
#: ``peak_speed_away_from_outlets_m_s``: the short branch stumps end in
#: small caps whose speeds are not mesh converged.
OUTLET_EXCLUSION_MM = 10.0
#: Series kept from every step: series key -> (step-result key, dtype).
STEP_KEYS: ClassVar[dict[str, tuple[str, Any]]] = {}
#: Steps between progress lines in the log.
LOG_STEPS: ClassVar[int] = 100
# ─────────────────────────── Main workflow ─────────────────────────────
def _simulate(
self,
labelmap_image: Optional[itk.Image],
aorta_label_ids: Sequence[int],
branch_label_ids: Optional[Mapping[str, int]],
*,
inflow_m3_s: np.ndarray,
inflow_interval_s: float,
geometry: Optional[Mapping[str, Any]],
beats: int,
dt_s: float,
frame_interval_s: float,
calibrate_outlets: bool,
domain_options: Mapping[str, Any],
solver_options: Mapping[str, Any],
prepare_options: Optional[Mapping[str, Any]] = None,
) -> dict[str, Any]:
"""Run a subclass's ``process``.
*prepare_options* go to :meth:`AortaProcessGeometry.prepare`,
*domain_options* to :meth:`_prepare_domain` and *solver_options* to
:meth:`_build_stepper`.
Returns:
``dict`` with ``'geometry'``, ``'flow_parameters'``, the domain
under :attr:`DOMAIN_KEY`, ``'series'``, ``'frames'``, ``'run'``
and ``'summary'``; see the subclasses' ``process``.
"""
self.log_section("STARTING %s WORKFLOW", self.TITLE.upper())
# Progress: geometry 0-0.1, mesh 0.1-0.2, solver setup 0.2-0.25 and
# the time steps the rest.
self._start_progress(f"{self.TITLE} starting")
if beats < 2:
raise ValueError(f"beats must be at least 2, not {beats}")
inflow_series = np.asarray(inflow_m3_s, dtype=np.float64)
self._check_timing(inflow_series, inflow_interval_s, dt_s)
beat_s = 60.0 / self.flow_parameters.heart_rate_bpm
if round(frame_interval_s / dt_s) > round(beat_s / dt_s):
raise ValueError(
f"frame_interval_s {frame_interval_s} s exceeds the {beat_s:.3g} s "
"beat, so no frame of the last beat would be saved"
)
geometry = self._resolve_geometry(
labelmap_image,
geometry,
aorta_label_ids,
branch_label_ids,
**(prepare_options or {}),
)
self._report_progress(0.1, "geometry prepared")
start_s = AortaProcessFlow.beat_start_s(inflow_series, inflow_interval_s)
ports = geometry["ports"]
outlets = [name for name, port in ports.items() if port["role"] == "outlet"]
domain = self._prepare_domain(geometry, **domain_options)
self._report_progress(0.2, "mesh ready")
wp.init()
started = time.perf_counter()
stepper, flow_parameters, run_extras = self._build_stepper(
geometry,
domain,
outlets,
(inflow_series, inflow_interval_s),
dt_s=dt_s,
calibrate_outlets=calibrate_outlets,
**solver_options,
)
setup_seconds = time.perf_counter() - started
fluid: WarpFlowBase = getattr(stepper, "fluid", stepper)
try:
with self._progress_range(0.25, 1.0):
series, frames = self._run(
stepper,
fluid,
flow_parameters,
ports,
outlets,
domain,
inflow=(inflow_series, inflow_interval_s, start_s),
beats=beats,
frame_interval_s=frame_interval_s,
)
finally:
stepper.close()
result: dict[str, Any] = {
"geometry": geometry,
"flow_parameters": flow_parameters,
self.DOMAIN_KEY: domain,
"series": series,
"frames": frames,
"run": {
"dt_s": dt_s,
**self._run_settings(fluid, domain_options, solver_options),
**run_extras,
"steps": len(series["times_s"]),
"frames": len(frames["times_s"]),
**self._run_sizes(fluid),
"device": wp.get_device().name,
"setup_seconds": setup_seconds,
"stepping_seconds": float(np.sum(series["step_seconds"])),
},
}
outlet_distance_mm = cKDTree(
[ports[name]["center_mm"] for name in outlets]
).query(self._field_points(fluid) * 1e3)[0]
near = np.asarray(outlet_distance_mm) < self.OUTLET_EXCLUSION_MM
result["summary"] = self._summarize(result, near)
self.log_section("%s WORKFLOW COMPLETE", self.TITLE.upper())
for key, value in result["summary"].items():
self.log_info("%-38s %s", key, value)
self._report_progress(1.0, f"{self.TITLE} complete")
return result
# ─────────────────────────── Model hooks ───────────────────────────────
def _prepare_domain(self, geometry: Mapping[str, Any], **options: Any) -> Any:
"""Return the solver's domain (a mesh or grid) for *geometry*."""
raise NotImplementedError
def _build_stepper(
self,
geometry: Mapping[str, Any],
domain: Any,
outlets: Sequence[str],
inflow: tuple[np.ndarray, float],
*,
dt_s: float,
calibrate_outlets: bool,
**options: Any,
) -> tuple[Any, AortaFlowParameters, dict[str, Any]]:
"""Return the stepper, the flow parameters simulated and run entries.
*inflow* is the interval inflow series and its interval; the outlets
are calibrated to it with :meth:`_calibrate` if *calibrate_outlets*.
"""
raise NotImplementedError
def _root_pressure_weights(
self,
fluid: WarpFlowBase,
domain: Any,
ports: Mapping[str, Mapping[str, Any]],
) -> np.ndarray:
"""Return weights of the pressure values whose sum is the root pressure."""
raise NotImplementedError
def _field_points(self, fluid: WarpFlowBase) -> np.ndarray:
"""Return the points in m of the saved velocity field."""
raise NotImplementedError
def _run_settings(
self,
fluid: WarpFlowBase,
domain_options: Mapping[str, Any],
solver_options: Mapping[str, Any],
) -> dict[str, Any]:
"""Return the solver settings recorded in the result's ``'run'``."""
raise NotImplementedError
def _run_sizes(self, fluid: WarpFlowBase) -> dict[str, Any]:
"""Return the solver sizes recorded in the result's ``'run'``."""
raise NotImplementedError
def _solver_summary(
self, series: Mapping[str, Any], run: Mapping[str, Any]
) -> dict[str, Any]:
"""Return the solver's own summary entries over the whole run."""
raise NotImplementedError
def _frame_extras(self, stepper: Any) -> dict[str, np.ndarray]:
"""Return fields saved with each frame besides velocity and pressure."""
return {}
def _step_message(self, step: Mapping[str, Any]) -> str:
"""Return the solver statistics of a step for the log."""
raise NotImplementedError
# ─────────────────────────── Time stepping ─────────────────────────────
def _run(
self,
stepper: Any,
fluid: WarpFlowBase,
flow_parameters: AortaFlowParameters,
ports: Mapping[str, Mapping[str, Any]],
outlets: Sequence[str],
domain: Any,
*,
inflow: tuple[np.ndarray, float, float],
beats: int,
frame_interval_s: float,
) -> tuple[dict[str, Any], dict[str, Any]]:
"""Step the solver; return the per-step series and last-beat frames."""
dt_s = fluid.dt
beat_s = 60.0 / flow_parameters.heart_rate_bpm
count = round(beats * beat_s / dt_s)
times = np.arange(1, count + 1) * dt_s
series_m3_s, interval_s, start_s = inflow
flow = ProcessFlowBoundaries.inlet_flow(
times + start_s,
series_m3_s,
interval_s,
flow_parameters.inflow_smoothing_s,
)[0]
root_region = ports["root"]["label_id"]
root_weights = self._root_pressure_weights(fluid, domain, ports)
stride = max(1, round(frame_interval_s / dt_s))
last_beat = self._last_beat(times, beat_s)
series: dict[str, Any] = {
"times_s": times,
"inlet_flow_m3_s": flow,
"root_flow_m3_s": np.zeros(count),
"root_pressure_pa": np.zeros(count),
"outlet_flow_m3_s": {name: np.zeros(count) for name in outlets},
"outlet_pressure_pa": {name: np.zeros(count) for name in outlets},
**{
key: np.zeros(count, dtype=kind)
for key, (_, kind) in self.STEP_KEYS.items()
},
"step_seconds": np.zeros(count),
}
frame_index: list[int] = []
fields: dict[str, list[np.ndarray]] = {}
for index, inlet in enumerate(flow):
tic = time.perf_counter()
step = stepper.step(float(inlet))
if not np.isfinite(step["residual"]):
raise RuntimeError(f"Linear solve diverged at step {index}: {step}")
pressure = fluid.pressure()
series["step_seconds"][index] = time.perf_counter() - tic
for key, (step_key, _) in self.STEP_KEYS.items():
series[key][index] = step[step_key]
series["root_flow_m3_s"][index] = -step["flows_m3_s"][root_region]
series["root_pressure_pa"][index] = root_weights @ pressure
for name in outlets:
region = ports[name]["label_id"]
series["outlet_flow_m3_s"][name][index] = step["flows_m3_s"][region]
series["outlet_pressure_pa"][name][index] = step["pressures_pa"][region]
if last_beat[index] and (index + 1) % stride == 0:
frame_index.append(index)
frame = {
"velocity_m_s": fluid.velocity(),
"pressure_pa": pressure,
**self._frame_extras(stepper),
}
for key, values in frame.items():
fields.setdefault(key, []).append(values)
self.log_progress(index + 1, count, "Step", log=False)
if (
index % self.LOG_STEPS == 0
or index == count - 1
or not step.get("converged", True)
):
self.log_info(
"t=%.4f s Q=%.1f mL/s root=%.1f mmHg %s %.3f s",
times[index],
inlet * 1e6,
series["root_pressure_pa"][index] / ProcessFlowBoundaries.MMHG_PA,
self._step_message(step),
series["step_seconds"][index],
)
frames = {
"times_s": times[frame_index],
"inlet_flow_m3_s": flow[frame_index],
**{key: np.stack(values) for key, values in fields.items()},
}
return series, frames
# ─────────────────────────── Summary ───────────────────────────────────
def _summarize(
self, result: Mapping[str, Any], near_outlet: np.ndarray
) -> dict[str, Any]:
"""Return the metrics of the last simulated beat.
The keys of :meth:`_pressure_summary`, each outlet's computed flow
share ``outlet_flow_shares`` and stroke volume
``outlet_stroke_volume_ml``, the peak speed anywhere
``peak_speed_m_s``, the peak speed more than
:attr:`OUTLET_EXCLUSION_MM` from every outlet center
``peak_speed_away_from_outlets_m_s`` (None when every field point is
that close), the 99.9th percentile of the speed anywhere
``speed_99_9_percentile_m_s`` (all m/s, over the saved frames), the
peak Reynolds number of the mean root velocity
``root_peak_reynolds`` and the largest net flow through all ports
relative to the peak inflow ``max_net_port_flow_relative``; then
:meth:`_solver_summary`.
"""
flow_parameters = result["flow_parameters"]
series = result["series"]
summary = self._pressure_summary(flow_parameters, series)
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)
inflow = np.asarray(series["inlet_flow_m3_s"])
outlet_flow = {
name: np.asarray(values)
for name, values in series["outlet_flow_m3_s"].items()
}
net = np.asarray(series["root_flow_m3_s"]) - sum(outlet_flow.values())
speed = np.linalg.norm(np.asarray(result["frames"]["velocity_m_s"]), axis=2)
root_area_m2 = result["geometry"]["ports"]["root"]["area_mm2"] * 1e-6
root_diameter_m = 2.0 * np.sqrt(root_area_m2 / np.pi)
away = speed[:, ~near_outlet]
summary.update(
{
"outlet_flow_shares": {
name: float(flow[last].sum() / inflow[last].sum())
for name, flow in outlet_flow.items()
},
"outlet_stroke_volume_ml": {
name: float(flow[last].sum() * dt_s * 1e6)
for name, flow in outlet_flow.items()
},
"peak_speed_m_s": float(speed.max()),
"peak_speed_away_from_outlets_m_s": (
float(away.max()) if away.size else None
),
"speed_99_9_percentile_m_s": float(np.percentile(speed, 99.9)),
"root_peak_reynolds": float(
flow_parameters.density_kg_m3
* inflow[last].max()
/ root_area_m2
* root_diameter_m
/ flow_parameters.viscosity_pa_s
),
"max_net_port_flow_relative": float(
np.abs(net[last]).max() / inflow[last].max()
),
}
)
summary.update(self._solver_summary(series, result["run"]))
return summary