"""Workflow for 3D rigid-wall Navier-Stokes (NS) blood flow in an aorta.
The workflow prepares an aorta labelmap with :class:`AortaProcessGeometry`
(or takes a prepared geometry), meshes its lumen alone with netgen
(:meth:`AortaProcessGeometry.rigid_mesh`) and solves time-dependent
incompressible Navier-Stokes flow in it with :class:`WarpFlowNS`, the model
of ``experiments/BloodFlow-3D-Rigid-Warp``: quadratic velocity and linear
pressure (P2/P1) on Warp FEM, a blunt inlet profile carrying the given
inflow through the root, and at every outlet the three-element Windkessel
:meth:`AortaProcessFlow.windkessels` builds for that outlet's share, with
backflow stabilization. Unlike the 1D workflow the flow split is computed,
not imposed: each outlet receives what its Windkessel and the lumen let
through. The wall does not move.
The solver needs a CUDA GPU and NVIDIA cuDSS
(:meth:`monai_physio.WarpCuDssFactor.find_library`).
Typical usage::
import itk
from monai_physio import SegmentNVSegmentCTMRI
from monai_physio.aorta import (
AortaFlowParameters,
AortaProcessFlow,
AortaVisualizeFlowNS,
AortaWorkflowSimulateFlow3DNS,
)
# Label ids of the segmenter that wrote the labelmaps.
taxonomy = SegmentNVSegmentCTMRI().taxonomy
# The patient's measured blood pressure, an input of the simulation.
flow_parameters = AortaFlowParameters(
systolic_pressure_mmhg=124.0, diastolic_pressure_mmhg=82.0
)
# The generator reads one frame at a time: a long series of labelmaps
# may not fit in memory.
lv_volume_ml = AortaProcessFlow.lv_volumes_ml(
(itk.imread(f) for f in frame_files), [taxonomy.label_id("ventricle_left")]
)
inflow, interval_s = AortaProcessFlow.lv_inflow(
lv_volume_ml, flow_parameters.heart_rate_bpm
)
workflow = AortaWorkflowSimulateFlow3DNS(flow_parameters)
result = workflow.process(
itk.imread("labelmap.mha"),
aorta_label_ids=(taxonomy.label_id("aorta"),),
branch_label_ids={
"BCT": taxonomy.label_id("brachiocephalic_trunk"),
"LCCA": taxonomy.label_id("common_carotid_artery_left"),
"LSA": taxonomy.label_id("subclavian_artery_left"),
},
inflow_m3_s=inflow,
inflow_interval_s=interval_s,
)
visualize = AortaVisualizeFlowNS()
visualize.save_results_3d(result, "./out")
visualize.save_plots(result, "./out")
"""
from __future__ import annotations
from collections.abc import Mapping, Sequence
from typing import Any, ClassVar, Optional, cast
import itk
import numpy as np
from ..warp_flow_base import WarpFlowBase
from ..warp_flow_ns import WarpFlowNS
from .flow_parameters import AortaFlowParameters
from .workflow_simulate_flow_3d_base import AortaWorkflowSimulateFlow3DBase
[docs]
class AortaWorkflowSimulateFlow3DNS(AortaWorkflowSimulateFlow3DBase):
"""Simulate rigid-wall 3D Navier-Stokes blood flow in an aorta.
The inputs, outlet calibration, beats, outlets, steppers and I/O
contract are those of :class:`AortaWorkflowSimulateFlow3DBase`; the
solver is :class:`WarpFlowNS` on a tetrahedral lumen mesh, kept in the
result as ``'mesh'``. :meth:`AortaVisualizeFlowNS.save_results_3d`
writes the result for :class:`monai_physio.VisualizeFlowFieldsNS`.
"""
_DEFAULT_DT_S = 0.005
DOMAIN_KEY: ClassVar[str] = "mesh"
#: Backflow stabilization coefficient of the outlets.
BACKFLOW_BETA = 1.0
#: The inlet speed rises from the wall over this fraction of the root's
#: equivalent radius and is flat inside it.
INLET_BLUNT_FRACTION = 0.2
#: Keys a mesh given to :meth:`process` must hold.
MESH_KEYS: ClassVar[tuple[str, ...]] = (
"points_mm",
"tetrahedra",
"boundary_faces",
"boundary_regions",
)
#: Series kept from every step: series key -> (step-result key, dtype).
STEP_KEYS: ClassVar[dict[str, tuple[str, Any]]] = {
"gmres_iterations": ("iterations", np.int64),
"residual": ("residual", np.float64),
}
# ─────────────────────────── Main workflow ─────────────────────────────
[docs]
def process(
self,
labelmap_image: Optional[itk.Image] = None,
*,
inflow_m3_s: np.ndarray,
inflow_interval_s: float,
geometry: Optional[Mapping[str, Any]] = None,
mesh: Optional[Mapping[str, Any]] = None,
) -> dict[str, Any]:
"""Simulate 3D flow in an aorta labelmap or a prepared geometry.
Args:
labelmap_image: Labelmap holding the aorta and, optionally, its
branches; prepared by :meth:`AortaProcessGeometry.prepare`
with its defaults. Give this or *geometry*.
inflow_m3_s: Mean inflow of each interval of a periodic series,
for example from :meth:`AortaProcessFlow.lv_inflow`.
inflow_interval_s: Duration of each inflow interval in seconds.
geometry: A :meth:`AortaProcessGeometry.prepare` result, used in
place of preparing *labelmap_image*.
mesh: A lumen mesh with the keys of
:meth:`AortaProcessGeometry.rigid_mesh`, used in place of
meshing the geometry: (n, 3) ``"points_mm"``, (m, 4)
positively oriented ``"tetrahedra"``, (f, 3) outward
``"boundary_faces"`` and (f,) ``"boundary_regions"``, 0 on
the wall and the port's ``label_id`` on each of the
geometry's ports. The geometry still supplies the ports.
Returns:
``dict`` with the following keys:
- ``'geometry'`` - the prepared geometry.
- ``'flow_parameters'`` - the :class:`AortaFlowParameters`
simulated: :attr:`flow_parameters`, calibrated unless
*calibrate_outlets* is ``False``.
- ``'mesh'`` - the lumen mesh (millimetres).
- ``'series'`` - per step, (T,) ``'times_s'`` (end of the step),
``'inlet_flow_m3_s'`` (the smoothed inflow imposed at the
root), ``'root_flow_m3_s'`` (the flow the solution carries in
through the root), ``'root_pressure_pa'`` (area-weighted mean
over the root), ``'gmres_iterations'`` and ``'residual'`` (of
the linear solve) and ``'step_seconds'`` (wall time); and
outlet name -> (T,) ``'outlet_flow_m3_s'`` (outward) and
``'outlet_pressure_pa'`` (Windkessel pressure).
- ``'frames'`` - the saved last-beat frames: (F,) ``'times_s'``
and ``'inlet_flow_m3_s'``, (F, nodes, 3) ``'velocity_m_s'`` at
the P2 nodes (the mesh points, then the midpoints of the
sorted unique tetrahedron edges,
:meth:`ProcessVolumetricMesh.tetrahedron_edges`) and
(F, points) ``'pressure_pa'`` at the mesh points.
- ``'run'`` - solver settings, sizes, device and timings.
- ``'summary'`` - the keys of
:meth:`AortaWorkflowSimulateFlow3DBase._summarize`, with the 1D
workflow's meanings for the shared ones, then the linear
solver's ``max_linear_residual``, ``mean_gmres_iterations``
and ``unconverged_steps`` over the whole run.
Raises:
ValueError: If not exactly one of *labelmap_image* and *geometry*
is given, if *beats* is below two, if *frame_interval_s* is
longer than a beat, if *dt_s* or the inflow series does not
fit the heart rate (see ``_check_timing``), if *mesh* lacks a
key or a port, if the inflow has no ejection, or if an outlet
has no flow fraction.
RuntimeError: If a linear solve diverges.
"""
aorta_label_ids = self.aorta_label_ids
branch_label_ids = self.branch_label_ids
beats = self.beats
dt_s = self.dt_s
calibrate_outlets = self.calibrate_outlets
element_size_mm = self.element_size_mm
precision = self.precision
frame_interval_s = self.frame_interval_s
return self._simulate(
labelmap_image,
aorta_label_ids,
branch_label_ids,
inflow_m3_s=inflow_m3_s,
inflow_interval_s=inflow_interval_s,
geometry=geometry,
beats=beats,
dt_s=dt_s,
frame_interval_s=frame_interval_s,
calibrate_outlets=calibrate_outlets,
domain_options={"mesh": mesh, "element_size_mm": element_size_mm},
solver_options={"precision": precision},
)
# ─────────────────────────── Model hooks ───────────────────────────────
def _prepare_domain(
self,
geometry: Mapping[str, Any],
*,
mesh: Optional[Mapping[str, Any]] = None,
element_size_mm: float = 2.0,
**mesh_options: Any,
) -> Mapping[str, Any]:
"""Return *mesh* after checking it, or mesh the geometry (:meth:`_mesh`)."""
if mesh is None:
return self._mesh(geometry, element_size_mm, **mesh_options)
self._check_mesh(mesh, geometry["ports"])
return mesh
def _mesh(
self, geometry: Mapping[str, Any], element_size_mm: float, **options: Any
) -> dict[str, Any]:
"""Mesh the lumen (:meth:`AortaProcessGeometry.rigid_mesh`)."""
return self._geometry_tools.rigid_mesh(geometry, element_size_mm, **options)
def _check_mesh(
self, mesh: Mapping[str, Any], ports: Mapping[str, Mapping[str, Any]]
) -> None:
"""Raise ValueError unless *mesh* has :attr:`MESH_KEYS` and every port."""
missing = [key for key in self.MESH_KEYS if key not in mesh]
if missing:
raise ValueError(f"The mesh lacks {missing}; it needs {self.MESH_KEYS}")
points = np.asarray(mesh["points_mm"])
tetrahedra = np.asarray(mesh["tetrahedra"])
faces = np.asarray(mesh["boundary_faces"])
regions = np.asarray(mesh["boundary_regions"])
if (
points.ndim != 2
or points.shape[1] != 3
or tetrahedra.ndim != 2
or tetrahedra.shape[1] != 4
or faces.ndim != 2
or faces.shape[1] != 3
or regions.shape != (len(faces),)
):
raise ValueError(
"The mesh needs (n, 3) points_mm, (m, 4) tetrahedra, (f, 3) "
"boundary_faces and (f,) boundary_regions"
)
labels = {int(port["label_id"]) for port in ports.values()}
unknown = sorted(set(np.unique(regions).tolist()) - labels - {0})
absent = [
name
for name, port in ports.items()
if not np.any(regions == port["label_id"])
]
if unknown or absent:
raise ValueError(
f"The mesh's boundary regions do not match the geometry's ports: "
f"regions {unknown} are no port and ports {absent} have no "
"boundary triangle"
)
def _navier_stokes(
self,
mesh: Mapping[str, Any],
ports: Mapping[str, Mapping[str, Any]],
outlets: Sequence[str],
flow_parameters: AortaFlowParameters,
dt_s: float,
precision: str,
) -> WarpFlowNS:
"""Return the blood solver on the lumen mesh with the outlets' Windkessels."""
windkessels = self.flow_tools.windkessels(flow_parameters, outlets)
return WarpFlowNS(
np.asarray(mesh["points_mm"]) * 1e-3,
mesh["tetrahedra"],
mesh["boundary_faces"],
mesh["boundary_regions"],
inlet_region=ports["root"]["label_id"],
outlets={ports[name]["label_id"]: windkessels[name] for name in outlets},
dt=dt_s,
density=flow_parameters.density_kg_m3,
viscosity=flow_parameters.viscosity_pa_s,
backflow=self.BACKFLOW_BETA,
blunt_fraction=self.INLET_BLUNT_FRACTION,
precision=precision,
)
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 blood solver, the flow parameters simulated and no extras.
*options* holds the solver ``precision``.
"""
flow_parameters = self._calibrate(*inflow, dt_s, calibrate_outlets)
solver = self._navier_stokes(
domain,
geometry["ports"],
outlets,
flow_parameters,
dt_s,
options["precision"],
)
return solver, flow_parameters, {}
def _root_pressure_weights(
self,
fluid: WarpFlowBase,
domain: Any,
ports: Mapping[str, Mapping[str, Any]],
) -> np.ndarray:
"""Return the area weights of the root's vertices, summing to one.
Each root triangle gives a third of its area to each of its vertices.
"""
points = np.asarray(np.asarray(domain["points_mm"]) * 1e-3, dtype=np.float64)
faces = np.asarray(domain["boundary_faces"])
root = np.asarray(domain["boundary_regions"]) == ports["root"]["label_id"]
corners = points[np.asarray(faces[root], dtype=np.int64)]
area_vectors = (
np.cross(corners[:, 1] - corners[:, 0], corners[:, 2] - corners[:, 0]) / 2
)
root_area = np.linalg.norm(area_vectors, axis=1)
weights = np.zeros(len(points))
np.add.at(weights, faces[root], root_area[:, None] / 3)
weights /= weights.sum()
return weights
def _field_points(self, fluid: WarpFlowBase) -> np.ndarray:
"""Return the P2 velocity nodes in m."""
return cast(WarpFlowNS, fluid).dof_points
def _run_settings(
self,
fluid: WarpFlowBase,
domain_options: Mapping[str, Any],
solver_options: Mapping[str, Any],
) -> dict[str, Any]:
"""Return the precision, GMRES tolerance and mesh element size."""
return {
"precision": solver_options["precision"],
"gmres_tolerance": cast(WarpFlowNS, fluid).tolerance,
"element_size_mm": domain_options["element_size_mm"],
}
def _run_sizes(self, fluid: WarpFlowBase) -> dict[str, Any]:
"""Return the velocity and pressure node and tetrahedron counts."""
solver = cast(WarpFlowNS, fluid)
return {
"velocity_nodes": len(solver.dof_points),
"pressure_nodes": len(solver.points),
"tetrahedra": len(solver.tetrahedra),
}
def _solver_summary(
self, series: Mapping[str, Any], run: Mapping[str, Any]
) -> dict[str, Any]:
"""Return the linear solver's statistics over the whole run.
``max_linear_residual``, ``mean_gmres_iterations`` and
``unconverged_steps``, the steps whose residual exceeds the GMRES
tolerance.
"""
residual = np.asarray(series["residual"])
return {
"max_linear_residual": float(residual.max()),
"mean_gmres_iterations": float(np.mean(series["gmres_iterations"])),
"unconverged_steps": int(np.sum(~(residual <= run["gmres_tolerance"]))),
}
def _step_message(self, step: Mapping[str, Any]) -> str:
"""Return the solver statistics of a step for the log."""
return f"GMRES={step['iterations']}"