Blood Flow (Warp)

GPU blood-flow building blocks written with NVIDIA Warp FEM. They are demonstrated by the experiments/BloodFlow-* folders: 1D and 3D flow in a rigid aorta and two-way fluid-structure interaction with a compliant wall. The solvers are demonstrations, not validated physiology.

Classes and modules tied to a flow solver carry its tag as a suffix: NS for Navier-Stokes (WarpFlowNS in warp_flow_ns.py) and LB for lattice-Boltzmann; the parts the solvers share carry Base. The boundary conditions and units belong to no solver.

The aorta classes of the optional monai_physio.aorta subpackage apply these models to an aorta labelmap. They need the [aorta] extra (pip install "monai-physio[aorta]", which includes [netgen]) and are imported from the subpackage, not from monai_physio:

from monai_physio.aorta import AortaFlowParameters, AortaWorkflowSimulateFlow1DNS

Each workflow’s process returns a dict with "geometry", "flow_parameters", "series" (one value per time sample, including "times_s", "inlet_flow_m3_s", "root_pressure_pa" and the outlet name -> array dicts "outlet_flow_m3_s" and "outlet_pressure_pa") and "summary". The 1D result adds "sections", the arrays along the centerline; the 3D and FSI results add "mesh" (the rigid_mesh() or fsi_mesh() keys), "frames" (the last beat’s saved fields) and "run" (solver settings and timings). The 3D and FSI workflows also accept a mesh with those keys in place of meshing the geometry.

The pressure preconditioner loads the NVIDIA cuDSS library at run time. Install the cuDSS wheel for the CUDA version of your PyTorch, as Installation describes, or set CUDSS_LIBRARY to the library’s path when it is not found automatically.

Module Reference

class monai_physio.ProcessFlowBoundaries(log_level=20)[source]

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
MMHG_PA: ClassVar[float] = 133.322387415

Pa per mmHg.

__init__(log_level=20)[source]

Initialize ProcessFlowBoundaries.

Parameters:

log_level (int | str) – Logging level (default: logging.INFO)

static inlet_flow(times_s, interval_fluxes_m3_s, interval_s, smoothing_s)[source]

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.

Parameters:
  • times_s (ndarray) – Evaluation times in seconds.

  • interval_fluxes_m3_s (ndarray) – Flux of each source interval in m^3/s.

  • interval_s (float) – Duration of each source interval in seconds.

  • smoothing_s (float) – Gaussian standard deviation in seconds, much less than one period (three periodic images are summed).

Return type:

tuple[ndarray, ndarray]

Returns:

Flow in m^3/s and its derivative in m^3/s^2 at times_s.

class monai_physio.Windkessel(proximal_resistance, distal_resistance, compliance, pressure)[source]

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.

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.

classmethod from_total(fraction, total_resistance, total_compliance, proximal_fraction, pressure)[source]

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.

Return type:

Windkessel

implicit(dt)[source]

Return (R, P0) with backward-Euler pressure R Q^{n+1} + P0.

Return type:

tuple[float, float]

advance(flow, dt)[source]

Advance P_c with the new outlet flow and return the outlet pressure.

Return type:

float

__init__(proximal_resistance, distal_resistance, compliance, pressure)
class monai_physio.WarpFlowBase(class_name=None, log_level=20, log_to_file=None)[source]

Time-stepping blood-flow solver with an inlet flow and outlet models.

Ports are boundary regions identified by integer ids. The inlet takes a prescribed volume flow; every outlet ends in an object with the Windkessel members implicit(dt), advance(Q, dt) and pressure, which the solver updates in place.

dt: float

Time step in seconds.

outlets: dict[int, Windkessel]

Outlet model of every outlet region.

step(inlet_flow)[source]

Advance one time step and update the outlet models.

Parameters:

inlet_flow (float) – Volume flow entering through the inlet in m^3/s.

Return type:

dict[str, Any]

Returns:

At least "flows_m3_s", the outward flow of every port region in m^3/s, "pressures_pa", the pressure of every outlet region in Pa, and "residual", the relative residual of the step’s solve.

velocity()[source]

Return the current velocity in m/s at the solver’s velocity points.

Return type:

ndarray

pressure()[source]

Return the current pressure in Pa at the solver’s pressure points.

Return type:

ndarray

close()[source]

Release the solver’s native and GPU resources.

Return type:

None

class monai_physio.WarpFlowNS(points, tetrahedra, boundary_faces, boundary_regions, *, inlet_region, outlets, dt, density=1060.0, viscosity=0.004, backflow=1.0, blunt_fraction=0.2, tolerance=None, max_iterations=500, precision='float32')[source]

P2/P1 incompressible flow with a Dirichlet inlet and RCR outlets.

The mesh is given by vertex positions, linear tetrahedra and outward oriented boundary triangles labelled 0 (no-slip wall) or by a port region id. Velocity arrays exchanged with callers are in the canonical P2 order: vertices, then the sorted unique tetrahedron edges (edges). Pressure arrays are per vertex.

Moving walls (ALE) for fluid-structure coupling: before each step call move() with the vertex displacement and mesh velocity (ports must stay fixed; elements stay straight-sided), pass the P2 wall velocity to step() through wall_velocity, then read the fluid load on the wall with wall_force(). move() reassembles the operators; update_preconditioner() refactors the Schur block if GMRES iterations grow.

LENGTH: ClassVar[float] = 0.1
SPEED: ClassVar[float] = 0.1
PRECISIONS: ClassVar[dict[str, tuple[Any, Any, Any, float]]] = {'float32': (<class 'warp._src.types.float32'>, <class 'warp._src.types.vec3f'>, <class 'warp._src.types.mat33f'>, 1e-05), 'float64': (<class 'warp._src.types.float64'>, <class 'warp._src.types.vec3d'>, <class 'warp._src.types.mat33d'>, 1e-06)}
CELL_CHUNK: ClassVar[int] = 200000
__init__(points, tetrahedra, boundary_faces, boundary_regions, *, inlet_region, outlets, dt, density=1060.0, viscosity=0.004, backflow=1.0, blunt_fraction=0.2, tolerance=None, max_iterations=500, precision='float32')[source]

Build spaces, boundary data and operators, and factor the Schur block.

Parameters:
  • points (ndarray) – Vertex positions in metres.

  • tetrahedra (ndarray) – Positively oriented vertex indices of each tetrahedron.

  • boundary_faces (ndarray) – Outward oriented boundary triangles.

  • boundary_regions (ndarray) – 0 for wall faces, otherwise the port region id.

  • inlet_region (int) – Region id of the Dirichlet inlet.

  • outlets (dict[int, Windkessel]) – Windkessel of every outlet region; updated in place.

  • dt (float) – Time step in seconds.

  • density (float) – Fluid density in kg/m^3.

  • viscosity (float) – Dynamic viscosity in Pa s.

  • backflow (float) – Backflow stabilization coefficient beta (0 disables it).

  • blunt_fraction (float) – The inlet speed rises linearly from the wall over this fraction of the inlet’s equivalent radius, then is flat.

  • tolerance (Optional[float]) – Relative GMRES tolerance; None uses 1e-5 in float32 and 1e-6 in float64. Where the float32 residual stagnates is problem dependent, so other meshes may need a looser value.

  • max_iterations (int) – GMRES iteration limit.

  • precision (str) – “float32” or “float64” for the FEM operators, the linear solve and the cuDSS factorization.

assemble()[source]

Assemble mass, viscous, outlet and divergence operators.

Return type:

None

update_preconditioner()[source]

Factor B diag(A)^-1 B^T of the current operators with cuDSS.

Return type:

None

step(inlet_flow, wall_velocity=None)[source]

Advance one time step and update the outlet Windkessels.

Parameters:
  • inlet_flow (float) – Volume flow entering through the inlet in m^3/s.

  • wall_velocity (Optional[ndarray]) – Canonical P2 velocity in m/s; only wall nodes are used. None keeps the wall at rest.

Return type:

dict[str, Any]

Returns:

GMRES iterations, the relative residual |b - A x| / |b| of the linear solve (|b - A x| when b is zero), the outward flow of every port in m^3/s and the pressure of every outlet in Pa.

velocity()[source]

Return the current velocity in m/s at the canonical P2 nodes.

Return type:

ndarray

pressure()[source]

Return the current pressure in Pa at the vertices.

Return type:

ndarray

wall_force()[source]

Return the force in N that the fluid exerts on each wall P2 node.

This is the consistent reaction of the last step’s discrete momentum equation (pressure, viscous stress and inertia), in canonical order and zero away from the wall.

Return type:

ndarray

move(displacement, velocity)[source]

Move the mesh vertices and set the ALE mesh velocity, then reassemble.

Parameters:
  • displacement (ndarray) – Vertex displacement from the input points in m.

  • velocity (ndarray) – Vertex mesh velocity in m/s, used by the backtrace along u - w; edge nodes take the mean of their two vertices.

Return type:

None

close()[source]

Release the cuDSS factorization.

Return type:

None

class monai_physio.WarpCuDssFactor(matrix, matrix_type='spd', dtype=<class 'warp._src.types.float64'>)[source]

Sparse direct factorization on the GPU with NVIDIA cuDSS.

The CSR matrix is analyzed and factored once on the current Warp stream. Each solve() overwrites the persistent solution array from the persistent rhs array, so callers can fill and read them in place. Values, rhs and solution use dtype (Warp float32 or float64).

MATRIX_TYPES: ClassVar[dict[str, int]] = {'general': 0, 'spd': 3, 'symmetric': 1}
ANALYSIS = 3
FACTORIZATION = 4
SOLVE = 1008
VALUE_TYPES: ClassVar[dict[Any, int]] = {<class 'warp._src.types.float32'>: 0, <class 'warp._src.types.float64'>: 1}
static find_library()[source]

Locate the NVIDIA cuDSS shared library.

CUDSS_LIBRARY names the library file explicitly. Otherwise the NVIDIA cuDSS Python wheels in site-packages and then the system library search path are used.

Raises:

RuntimeError – If cuDSS cannot be found.

Return type:

Path

__init__(matrix, matrix_type='spd', dtype=<class 'warp._src.types.float64'>)[source]

Upload matrix and factor it.

Parameters:
  • matrix (csr_matrix) – Square CSR matrix with 32-bit indices.

  • matrix_type (str) – “general”, “symmetric” or “spd”.

  • dtype (Any) – Value type, wp.float32 or wp.float64.

solve()[source]

Enqueue solution = A^-1 rhs on the current Warp stream.

Return type:

None

check_info()[source]

Raise if cuDSS reported a numerical error (call after synchronizing).

Return type:

None

close()[source]

Release native objects before their GPU buffers.

Return type:

None

class monai_physio.WarpHyperelasticWall(points, tetrahedra, clamped, *, young_modulus, poisson_ratio, tether_faces=None, tether_stiffness=0.0, quadrature_order=4)[source]

Quasi-static compressible Neo-Hookean wall on P2 tetrahedra.

The first Piola stress is F S0 + mu (F - F^-T) + lambda ln(J) F^-T. S0 is a prestress stored at every quadrature point (zero until prestress()). Nonlinear solves use modified Newton iterations with a tangent factored by cuDSS and refreshed only when convergence slows, so most solves reuse one factorization. Everything runs in float64: in float32 the internal force is too inexact for the Newton tolerance. Nodal arrays are in the canonical P2 order: vertices, then edges.

TRIANGLE_MASS: ClassVar[ndarray] = array([[ 0.03333333, -0.00555556, -0.00555556,  0.        , -0.02222222,          0.        ],        [-0.00555556,  0.03333333, -0.00555556,  0.        ,  0.        ,         -0.02222222],        [-0.00555556, -0.00555556,  0.03333333, -0.02222222,  0.        ,          0.        ],        [ 0.        ,  0.        , -0.02222222,  0.17777778,  0.08888889,          0.08888889],        [-0.02222222,  0.        ,  0.        ,  0.08888889,  0.17777778,          0.08888889],        [ 0.        , -0.02222222,  0.        ,  0.08888889,  0.08888889,          0.17777778]])

P2 triangle mass matrix times 180 / area, nodes (v0, v1, v2, e01, e12, e20).

__init__(points, tetrahedra, clamped, *, young_modulus, poisson_ratio, tether_faces=None, tether_stiffness=0.0, quadrature_order=4)[source]

Build the P2 space and the boundary operators.

Parameters:
  • points (ndarray) – Vertex positions in metres.

  • tetrahedra (ndarray) – Positively oriented vertex indices of each tetrahedron.

  • clamped (ndarray) – True for vertices held fixed; an edge node is fixed when both of its vertices are.

  • young_modulus (float) – E in Pa.

  • poisson_ratio (float) – nu.

  • tether_faces (Optional[ndarray]) – Boundary triangles carrying the tether springs.

  • tether_stiffness (float) – Spring stiffness per area in Pa/m.

  • quadrature_order (int) – Order of the cell quadrature.

pressure_load(faces, pressure)[source]

Nodal force in N of a uniform pressure pushing along the face normals.

On a flat triangle the P2 vertex functions integrate to zero and each edge function to a third of the area.

Return type:

ndarray

prestress(load)[source]

Store a prestress that balances load in the given geometry.

S0 is the small-strain stress of the clamped wall under load without tethers, which is in exact discrete equilibrium with load at zero displacement. The tangent is then refactored with S0.

Return type:

None

residual(load)[source]

Return load - internal force - tether force on the free DOFs.

Return type:

ndarray

solve(load, tolerance=1e-06, max_iterations=30)[source]

Find the equilibrium displacement under nodal forces load (N).

Modified Newton starts from the current displacement and stops when the free-DOF residual is below tolerance times the load norm, or warns after max_iterations. The factored tangent is reused across solves and refactored at the current displacement whenever an iteration fails to halve the residual.

Return type:

dict[str, Any]

displacement()[source]

Return the displacement in m at the canonical P2 nodes.

Return type:

ndarray

close()[source]

Release the cuDSS factorization.

Return type:

None

static to_scipy(matrix)[source]

Convert a Warp BSR matrix of 3 x 3 blocks to SciPy CSR.

Return type:

csr_matrix

class monai_physio.WarpFluidStructureNS(fluid, wall, boundary_regions, *, reference_pressure, relaxation=0.1, reuse=2, filter_tolerance=0.01, tolerance=0.001, absolute_tolerance=1e-09, max_iterations=20)[source]

Partitioned two-way coupling of WarpFlowNS and a wall.

The wall is prestressed so that the given geometry is its equilibrium at reference_pressure (uniform on the interface). Each step():

  1. predicts the interface displacement by linear extrapolation, extends it harmonically into the fluid and moves the fluid mesh (once per step; interface caps stay fixed);

  2. repeats until the interface displacement converges: fluid step with the wall velocity of the current guess, wall solve under the fluid force, quasi-Newton update of the guess.

The update is IQN-ILS (Degroote, Bathe and Vierendeels, Computers and Structures 87:793-801, 2009). With guess x, wall response x~ and residual r = x~ - x, every iteration stores the differences of r and of x~ from the previous iteration as columns of V and W. With c minimizing |V c + r|, the guess moves by (W - V) c, the quasi-Newton step for the part of r that the columns explain, plus relaxation times the rest, r + V c (all of r while there are no columns). With relaxation = 1 after the first iteration this is IQN-ILS; a light wall needs less, because an unrelaxed step along a direction not yet sampled can invert it. This relaxed form is Anderson mixing (Walker and Ni, SIAM J. Numer. Anal. 49:1715-1735, 2011). Columns of the last reuse steps are kept, newest first; a column whose part orthogonal to the newer ones is below filter_tolerance of its norm is dropped (the QR2 filter of Haelterman et al., Computers and Structures 171:9-17, 2016).

A step converges when the RMS interface residual is at most tolerance times the RMS interface motion of the step (guess minus the start-of-step displacement) plus absolute_tolerance. The reported coupling residual is the relative part only, so a converged step can report more than tolerance when its motion is small.

A step still unconverged after max_iterations is solved once more at its lowest-residual iterate, which it keeps (so the fluid and wall states belong to the kept interface), and all columns are dropped, so the next step starts without reused columns. Such a step usually stalls at the residual noise of the fluid and wall solves, and reused columns may have misled it; columns from either would mislead the next steps. It is reported, not rejected; its re-solve may also meet the convergence criterion.

__init__(fluid, wall, boundary_regions, *, reference_pressure, relaxation=0.1, reuse=2, filter_tolerance=0.01, tolerance=0.001, absolute_tolerance=1e-09, max_iterations=20)[source]

Match the interface, prestress the wall and factor the mesh extension.

Parameters:
  • fluid (WarpFlowNS) – Flow solver whose wall (region 0) nodes are wall nodes.

  • wall (WarpHyperelasticWall) – Wall solver sharing the interface nodes.

  • boundary_regions (ndarray) – Region of each fluid boundary face (0 = wall).

  • reference_pressure (float) – Uniform interface pressure (Pa) at which the given geometry is in equilibrium.

  • relaxation (float) – Relaxation of the residual part that the quasi-Newton columns do not explain (all of it without columns).

  • reuse (int) – Number of previous steps whose quasi-Newton columns are kept.

  • filter_tolerance (float) – Relative QR filter threshold of the columns.

  • tolerance (float) – Stop when the RMS interface residual is at most this fraction of the RMS interface motion over the step…

  • absolute_tolerance (float) – …plus this many metres.

  • max_iterations (int) – Coupling iteration limit per step, after which the best iterate is solved once more and kept.

extend(interface_displacement)[source]

Extend the interface displacement harmonically to all fluid vertices.

Return type:

ndarray

fluid_volume()[source]

Volume in m^3 of the current (moved) fluid mesh.

Return type:

float

step(inlet_flow)[source]

Advance the coupled system one fluid time step.

Return type:

dict[str, Any]

Returns:

The last fluid step result plus coupling iterations (fluid and wall solves; max_iterations + 1 for a capped step, whose re-solve can still meet the criterion), whether the interface converged, the relative and the RMS (m) residual of the kept iterate, the summed GMRES and wall Newton iterations, the wall tangent refactorizations, the interface displacement extremes in m, and the fluid volume in m^3 and its rate of change in m^3/s.

close()[source]

Release the factorizations of the fluid, the wall and the extension.

Return type:

None

static laplacian(points, tetrahedra)[source]

Linear (P1) finite-element Laplacian of a tetrahedral mesh.

Return type:

csr_matrix

static quasi_newton_update(residual, columns, relaxation, filter_tolerance)[source]

Change of the interface guess for residual (IQN-ILS, relaxed).

columns holds (residual difference, response difference, step) pairs, newest first. Columns beyond the length of residual, and columns whose part orthogonal to the newer ones is below filter_tolerance of their norm, are removed from it in place. See WarpFluidStructureNS for the method.

Return type:

Tensor

class monai_physio.VisualizeFlowFieldsBase(results, anatomy=None, *, caption='', off_screen=True)[source]

Render saved velocity and pressure frames with time and slice controls.

Automatic speed ranges stop at the 99.5th percentile of the shown values, so a few fast nodes at small outlets do not hide the interior flow. Subclasses implement _load_grid() and _to_grid_points() for their solver’s result layout.

SPEED_PERCENTILE = 99.5
FIELDS: ClassVar[dict[str, tuple[str, str]]] = {'pressure': ('Pressure (mmHg)', 'plasma'), 'velocity': ('Speed (m/s)', 'turbo')}
COLOR_MODES: ClassVar[dict[str, str]] = {'frame': 'Current frame (surface + slice)', 'global': 'Fixed range', 'slice': 'Current slice (surface colors clipped)'}
__init__(results, anatomy=None, *, caption='', off_screen=True)[source]

Load the saved frames and build the scene.

Parameters:
  • results (Path) – Folder written by the flow run.

  • anatomy (Optional[Path]) – Optional surface file shown as translucent context.

  • caption (str) – Text shown in the lower left corner.

  • off_screen (bool) – Render without a desktop window.

field_limits(field, frames)[source]

Fixed color limits of a field over the given frames.

Speed and wall displacement start at 0; pressure spans its range.

Return type:

tuple[float, float]

update()[source]

Show the current frame on the lumen surface and the slice.

Return type:

None

update_slice()[source]

Probe the quadratic volume on the current plane, with velocity glyphs.

Return type:

None

update_color_range()[source]

Share one color range between the lumen surface and the slice.

Return type:

None

set_color_mode(mode)[source]

Select current-frame, slice-focused or fixed all-frame color limits.

Return type:

None

set_time(index)[source]

Show a saved frame.

Return type:

None

set_field(field)[source]

Show speed, pressure or (for a moving wall) wall displacement.

Return type:

None

set_slice(axis, position)[source]

Move the slice to a fraction of the lumen bounds along an axis.

Return type:

None

set_vectors(visible)[source]

Show or hide velocity arrows on the slice.

Return type:

None

set_opacity(opacity)[source]

Change the opacity of the anatomy overlay.

Return type:

None

advance(elapsed)[source]

Show the frame at elapsed seconds of looping playback.

The saved frames are evenly spaced; each, including the last, is shown for one frame interval from its own time.

Return type:

None

rotate_camera(azimuth, elevation)[source]

Rotate the camera about the focal point (degrees).

Return type:

None

zoom_camera(factor)[source]

Zoom the camera.

Return type:

None

reset_camera()[source]

Frame the anatomy (or the lumen) from the front with Y up.

Return type:

None

screenshot(path)[source]

Save the rendered view and return its pixels.

Return type:

ndarray[tuple[Any, ...], dtype[uint8]]

snapshot()[source]

Describe the visible state.

Return type:

dict[str, Any]

record_movie(path, start_s=0.0, frames_per_second=10.0)[source]

Write the saved frames from start_s on as an MP4 of this view.

The color limits of the shown field are fixed over those frames.

Return type:

dict[str, Any]

create_app(title, notes)[source]

Build the local Trame browser interface around this viewer.

Parameters:
  • title (str) – Toolbar title.

  • notes (list[str]) – Short paragraphs describing the model and its limitations.

Return type:

Any

Returns:

The Trame server; call start(port=...) to serve it.

class monai_physio.VisualizeFlowFieldsNS(results, anatomy=None, *, caption='', off_screen=True)[source]

Render saved P2/P1 velocity and pressure frames on quadratic tetrahedra.

Per-vertex values (pressure, wall displacement) are shown at the edge nodes as the mean of the edge’s two vertices.

VTK_TET_EDGES: ClassVar[list[list[int]]] = [[0, 1], [1, 2], [0, 2], [0, 3], [1, 3], [2, 3]]

Vertex pairs of the six edge nodes of a VTK quadratic tetrahedron.

edges: ndarray

Sorted unique tetrahedron edges of the mesh, kept by _load_grid().

Aorta Subpackage

Requires the [aorta] extra (monai-physio[aorta]).

Aortic blood-flow simulation from an aorta labelmap.

This optional subpackage needs the [aorta] extra (pip install "monai-physio[aorta]"), which installs scikit-image for the centerline and netgen (the [netgen] extra) for the lumen and wall meshes. import monai_physio does not import it; import its classes from monai_physio.aorta.

Every class here starts with Aorta and lives in the module named after the rest of the class name, so AortaProcessGeometry is in monai_physio.aorta.process_geometry and AortaWorkflowSimulateFlow1DNS in monai_physio.aorta.workflow_simulate_flow_1d_ns.

Classes and modules tied to a flow solver carry its tag as a suffix: NS (...NS, *_ns.py) for Navier-Stokes models, and LB (...LB, *_lb.py) for lattice-Boltzmann models; the parts they share carry Base (*_base.py), and solver-independent classes carry no tag.

The workflows write no files; the visualize classes do.

class monai_physio.aorta.AortaProcessGeometry(log_level=20)[source]

Prepare an aorta labelmap for 1D, 3D rigid and 3D FSI flow models.

Ports are named "root" (the inlet), "distal" and the lowercased keys of branch_label_ids, so they match the keys of AortaFlowParameters.flow_fractions. Every port’s region id is its plug label in the flow labelmap, and region 0 is the wall, in the surface and in both meshes.

LUMEN_LABEL = 1
WALL_LABEL = 2
FIRST_PORT_LABEL = 10
END_PLUG_THICKNESS_MM = 4.0

Thickness of the root and distal plugs, beyond which the vessel is removed.

SMOOTHING_ITERATIONS = 10

Taubin smoothing of the contoured surfaces. More pinches the thin wall shell between the lumen and the background.

CENTERLINE_STEP_MM = 0.5

Arc-length step of the raw centerline before smoothing, and the Gaussian smoothing of that centerline.

CENTERLINE_SIGMA_MM = 3.0
PORT_ZONE_RADII = 1.5

Ports narrower than port_cells_across elements are refined within this many port radii of their center by rigid_mesh().

__init__(log_level=20)[source]

Initialize AortaProcessGeometry.

Parameters:

log_level (int | str) – Logging level (default: logging.INFO)

prepare(labelmap_image, aorta_label_ids=(1,), branch_label_ids=None, *, root_point_mm=None, distal_point_mm=None, spacing_mm=0.7, wall_thickness_mm=2.0, end_margin_mm=10.0, branch_gap_mm=3.0, centerline_spacing_mm=1.5)[source]

Build the flow labelmap, tagged lumen surface, ports and centerline.

  1. The aorta labels (and branch labels) are cropped and resampled to an isotropic spacing_mm grid with a label vote; the lumen is the largest connected component of the aorta labels.

  2. The distal end is the lumen voxel at distal_point_mm, else the most central voxel of the most inferior lumen slice; the root end is the voxel at root_point_mm, else the lumen voxel geodesically farthest from the distal end. The centerline is the radius-weighted interior geodesic between them, smoothed.

  3. The wall is every voxel within wall_thickness_mm outside the lumen. Each branch opens an outlet window: the voxels outside the lumen within max(branch_gap_mm, wall_thickness_mm) of it and within branch_gap_mm of that branch’s label.

  4. The vessel is cut normal to the centerline end_margin_mm inside each end; a END_PLUG_THICKNESS_MM slab beyond each cut becomes that end’s plug and the rest beyond it is removed.

  5. The labels’ surfaces are contoured together and the lumen surface’s triangles are tagged: a triangle shared with the wall surface is wall (0), any other belongs to the port whose plug it touches.

Parameters:
  • labelmap_image (Image) – Labelmap holding the aorta and, optionally, its branches.

  • aorta_label_ids (Sequence[int]) – Labels whose union is the aortic lumen.

  • branch_label_ids (Optional[Mapping[str, int]]) – Branch name -> label. Each branch present becomes an outlet port named by its lowercased key. None (or empty) gives a tube with only the root and distal ports.

  • root_point_mm (Optional[Sequence[float]]) – Optional LPS point at the root end of the vessel; the centerline starts at the lumen voxel nearest it.

  • distal_point_mm (Optional[Sequence[float]]) – Optional LPS point at the distal end of the vessel; the centerline ends at the lumen voxel nearest it.

  • spacing_mm (float) – Isotropic grid spacing of the flow labelmap and the contoured surfaces. The FSI mesh size grows about as its inverse cube.

  • wall_thickness_mm (float) – Thickness of the wall shell.

  • end_margin_mm (float) – Distance along the centerline from each end of the vessel to its cut. 0 cuts through the end points.

  • branch_gap_mm (float) – How far a branch label may lie from the lumen and still open a window, and how far the window spreads around it.

  • centerline_spacing_mm (float) – Arc-length spacing of the returned centerline points.

Returns:

the flow labelmap (uint16; 1 lumen, 2 wall, 10+ port plugs) on the isotropic grid, with the input direction. "ports": port name -> label_id, role ("inlet" or "outlet"), center_mm (area-weighted centroid of the port triangles), normal (unit, out of the lumen), area_mm2 (magnitude of the summed triangle vector areas, the area that flux crosses) and arc_length_mm (arc length of the centerline point nearest the center). "surface": the closed, outward-oriented lumen surface with cell data "Region" (0 wall, else the port’s label_id). "centerline": polyline from the root cut to the distal cut with point data arc_length_mm (0 at the root), area_mm2 (lumen section normal to the centerline), radius_mm (the equivalent radius sqrt(area / pi)) and tangent. "wall_thickness_mm": wall_thickness_mm, the thickness of the wall shell that fsi_mesh() meshes.

Return type:

"labelmap"

Raises:

ValueError – If two branch names are equal, or one is root or distal, once lowercased, if wall_thickness_mm is below spacing_mm, if the labelmap holds none of aorta_label_ids, if the root and distal ends select the same lumen voxel, if the centerline is too short for the two end margins, or if the root or distal port receives no surface triangle.

rigid_mesh(geometry, element_size_mm=2.0, port_cells_across=8)[source]

Mesh the lumen alone with netgen for a rigid-wall 3D flow model.

The lumen label of the flow labelmap is contoured on its own and netgen re-tiles it to triangles about element_size_mm across, so the mesh is much coarser than the conforming fsi_mesh(). Ports narrower than port_cells_across elements get elements of their diameter / port_cells_across within PORT_ZONE_RADII port radii of their center; otherwise a narrow opening is tiled by a few triangles whose no-slip rim blocks it. Each boundary triangle takes the region of the nearest triangle of geometry["surface"].

Parameters:
  • geometry (Mapping[str, Any]) – The result of prepare().

  • element_size_mm (float) – Target edge length away from small ports.

  • port_cells_across (int) – Elements across the narrowest port diameter.

Return type:

dict[str, Any]

Returns:

"points_mm" (n, 3), "tetrahedra" (m, 4) positively oriented, "boundary_faces" (f, 3) wound outward, "boundary_regions" (f,) 0 for wall else the port’s label_id, and "port_element_size_mm" port name -> the element size used at that port.

Raises:
  • ImportError – If netgen, part of the [aorta] extra, is missing.

  • ValueError – If a port receives no boundary triangle.

fsi_mesh(geometry, element_size_mm=2.0, collar_mm=2.0)[source]

Mesh the lumen and wall together with netgen for an FSI model.

All labels of the flow labelmap are contoured together and netgen fills each surface keeping its triangles, so the lumen and wall meshes have identical points on their interface. The contours of three labels do not quite conform where they meet, so a lumen triangle is wall only when it is exactly a wall triangle; the rest are port triangles. Every wall triangle of the lumen, and so every P2 edge node on it, is then a wall node, as WarpFluidStructureNS requires. The wall is clamped within collar_mm of every plug and every non-conforming triangle, all of which lie at the ports, and its outer surface carries the tether.

The boundary triangles keep the contour’s size, so geometry["labelmap"]’s spacing, not element_size_mm, sets the mesh size; prepare with a coarser spacing_mm for a smaller mesh.

Parameters:
  • geometry (Mapping[str, Any]) – The result of prepare().

  • element_size_mm (float) – Largest interior edge length.

  • collar_mm (float) – Wall points this close to a plug or a non-conforming lumen triangle are clamped.

Return type:

dict[str, Any]

Returns:

The keys of rigid_mesh() but "port_element_size_mm" for the lumen: "points_mm", "tetrahedra" (positive), "boundary_faces" (outward) and "boundary_regions" (0 for wall, else the port’s label_id); then "wall_points_mm", "wall_tetrahedra" (positive), "wall_clamped" (bool per wall point) and "wall_tether_faces" (outward wall triangles facing the background) of the solid; and "nonconforming_faces", the number of lumen triangles that match no wall or plug triangle.

Raises:

ImportError – If netgen, part of the [aorta] extra, is missing.

class monai_physio.aorta.AortaFlowParameters(heart_rate_bpm=60.0, systolic_pressure_mmhg=112.0, diastolic_pressure_mmhg=78.0, inflow_smoothing_s=0.03, total_resistance_pa_s_m3=333000000.0, total_compliance_m3_pa=6.8e-09, proximal_fraction=0.06, flow_fractions=<factory>, initial_pressure_pa=10665.7909932, density_kg_m3=1060.0, viscosity_pa_s=0.004, young_modulus_pa=1000000.0, poisson_ratio=0.45, wall_thickness_mm=1.5, tether_stiffness_pa_m=500000.0)[source]

Per-patient inputs and blood, outlet and wall parameters of aortic flow.

Per-patient inputs. systolic_pressure_mmhg, diastolic_pressure_mmhg and heart_rate_bpm describe the patient being simulated - for example a cuff measurement taken with the CT - and are meant to be set by the user. Their defaults are example patient inputs (112/78 mmHg, the root pressures of experiments/BloodFlow-1D-Rigid-Warp), not simulation outputs. The simulation does not predict these pressures: AortaProcessFlow.calibrated() sets the outlet resistance and compliance so that the patient’s inflow reproduces them as the systolic and diastolic pressure of a whole-body model.

Outlet totals. total_resistance_pa_s_m3, total_compliance_m3_pa and initial_pressure_pa may instead be set directly; AortaProcessFlow.calibrated() replaces them in its copy. Their defaults are the values the rigid BloodFlow experiments tuned for their inflow.

heart_rate_bpm: float = 60.0

Patient heart rate; the inflow series is retimed to it. Adult rest 60-100 bpm.

systolic_pressure_mmhg: float = 112.0

Patient systolic arterial pressure, a user input the outlets are calibrated to. Typical adult ~120 mmHg.

diastolic_pressure_mmhg: float = 78.0

Patient diastolic arterial pressure, a user input the outlets are calibrated to. Typical adult ~80 mmHg.

inflow_smoothing_s: float = 0.03

Standard deviation of the periodic Gaussian that smooths the interval inflow staircase.

total_resistance_pa_s_m3: float = 333000000.0

Total outlet resistance of all Windkessels in parallel. Adult ~1.65e8 (93 mmHg mean at 4.5 L/min); a lower cardiac output needs more for the same pressures.

total_compliance_m3_pa: float = 6.8e-09

Summed outlet compliance. Adult total arterial compliance ~1-2e-8 m^3/Pa (1-2 mL/mmHg).

proximal_fraction: float = 0.06

Fraction of each outlet resistance that is proximal. Adult characteristic impedance 5-10% of R.

flow_fractions: dict[str, float]

Fraction of the inflow leaving each named outlet; renormalized over the outlets present in a model. Assumed splits; adult arch branches take roughly 30% of cardiac output in total.

initial_pressure_pa: float = 10665.7909932

Initial Windkessel capacitor pressure. Adult diastolic ~80 mmHg.

density_kg_m3: float = 1060.0

Blood density. Adult blood 1050-1060 kg/m^3.

viscosity_pa_s: float = 0.004

Blood dynamic viscosity (Newtonian). Adult blood 3-4 mPa s at high shear.

young_modulus_pa: float = 1000000.0

Wall Young’s modulus (FSI only). Adult aorta ~0.3-1 MPa, stiffer with age.

poisson_ratio: float = 0.45

Wall Poisson ratio (FSI only). The arterial wall is nearly incompressible (~0.5).

wall_thickness_mm: float = 1.5

Wall thickness (FSI only). Adult thoracic aorta ~2 mm.

tether_stiffness_pa_m: float = 500000.0

Stiffness of the elastic support of the outer wall surface (FSI only). Perivascular support, not measured.

property mean_pressure_mmhg: float

Mean arterial pressure of the input pressures.

The clinical estimate diastolic + (systolic - diastolic) / 3, reported for reference; AortaProcessFlow.calibrated() starts its fit from it but fits the systolic and diastolic pressures.

__init__(heart_rate_bpm=60.0, systolic_pressure_mmhg=112.0, diastolic_pressure_mmhg=78.0, inflow_smoothing_s=0.03, total_resistance_pa_s_m3=333000000.0, total_compliance_m3_pa=6.8e-09, proximal_fraction=0.06, flow_fractions=<factory>, initial_pressure_pa=10665.7909932, density_kg_m3=1060.0, viscosity_pa_s=0.004, young_modulus_pa=1000000.0, poisson_ratio=0.45, wall_thickness_mm=1.5, tether_stiffness_pa_m=500000.0)
class monai_physio.aorta.AortaProcessFlow(log_level=20)[source]

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 windkessels() (and calibrated(), which fits the three-element model) and assign an instance to a workflow’s flow_tools.

__init__(log_level=20)[source]

Initialize AortaProcessFlow.

Parameters:

log_level (int | str) – Logging level. Default: logging.INFO.

static lv_volumes_ml(labelmaps, lv_label_ids)[source]

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.

Parameters:
  • labelmaps (Iterable[Image]) – One labelmap per time frame.

  • lv_label_ids (Sequence[int]) – Labels whose voxels form the LV cavity.

Return type:

ndarray

Returns:

Voxel count times voxel volume of each frame.

static lv_ejection_inflow(lv_volume_ml, interval_s, minimum_ejection_fraction=0.1)[source]

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).

Parameters:
  • lv_volume_ml (ndarray) – LV volume of each frame in mL.

  • interval_s (float) – Duration of each frame interval in seconds.

  • minimum_ejection_fraction (float) – Smallest kept ejection volume relative to the LV volume range.

Return type:

ndarray

Returns:

Inflow of each interval; len(lv_volume_ml) values.

static lv_inflow(lv_volume_ml, heart_rate_bpm)[source]

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 lv_ejection_inflow() at that frame interval. Beats are counted for a regular rhythm (see BEAT_GAP_FRACTION); with an irregular one the count can be too low, which makes the frame interval too short.

Parameters:
Return type:

tuple[ndarray, float]

Returns:

Mean inflow of each frame interval in m^3/s and the interval in seconds.

Raises:

ValueError – If the series has no ejection.

BEAT_GAP_FRACTION: ClassVar[float] = 0.5

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.

BASELINE_FRACTION: ClassVar[float] = 0.1

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.

static beat_start_s(interval_fluxes, interval_s)[source]

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 _beat_onsets() says.

Parameters:
  • interval_fluxes (ndarray) – Mean flux of each interval of a periodic series.

  • interval_s (float) – Duration of each interval in seconds.

Return type:

float

Returns:

The time in seconds, negative when the gap wraps from the end of the series.

Raises:

ValueError – If the series has no ejection.

windkessels(flow_parameters, outlet_names)[source]

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; calibrated() fits the three-element model, so such a subclass overrides it too, or the workflow runs with calibrate_outlets=False.

Parameters:
  • flow_parameters (AortaFlowParameters) – Outlet totals, flow fractions and initial pressure.

  • outlet_names (Sequence[str]) – Names of the outlets present.

Raises:

ValueError – If an outlet has no flow fraction.

Return type:

dict[str, Windkessel]

calibrated(flow_parameters, interval_fluxes_m3_s, interval_s, dt_s=0.001, wall_compliance_m3_pa=0.0)[source]

Return a copy whose outlets reproduce the input pressures.

The outlets are calibrated as the whole-body three-element Windkessel they split from (Windkessel.from_total() with fraction one and proximal_fraction), fed by the smoothed periodic inflow (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 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 (_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 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.

Parameters:
  • flow_parameters (AortaFlowParameters) – Input pressures, inflow smoothing and outlet parameters to calibrate.

  • interval_fluxes_m3_s (ndarray) – Mean inflow of each frame interval in m^3/s, for example from lv_inflow().

  • interval_s (float) – Duration of each frame interval in seconds.

  • dt_s (float) – Approximate backward-Euler time step of the model.

  • wall_compliance_m3_pa (float) – Compliance dV/dP of the aortic wall in front of the outlets; 0 for a rigid aorta.

Return type:

AortaFlowParameters

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.

RESISTANCE_SEARCH_STEPS: ClassVar[int] = 24

the seed times 2 ** (k / 8) for k = -1, 1, -2, 2, … up to a factor of 8.

Type:

Resistance starts of calibrated() besides its seed

static check_input_pressures(flow_parameters)[source]

Raise ValueError unless 0 < diastolic < systolic.

Return type:

None

class monai_physio.aorta.AortaWorkflowSimulateFlowBase(flow_parameters=None, log_level=20)[source]

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 AortaFlowParameters. flow_tools, an 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 (AortaProcessFlow.calibrated()), leaving 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 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 AortaFlowParameters.heart_rate_bpm. It is smoothed by ProcessFlowBoundaries.inlet_flow() with 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 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. AortaVisualizeFlow and AortaVisualizeFlowNS write its result to disk.

__init__(flow_parameters=None, log_level=20)[source]

Initialize the workflow.

Parameters:
set_aorta_label_ids(aorta_label_ids)[source]

Choose the labels whose union is the aortic lumen.

Parameters:

aorta_label_ids (Sequence[int]) – Label ids. Default: (1,)

Raises:

ValueError – If it is empty.

Return type:

None

set_branch_label_ids(branch_label_ids)[source]

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 AortaFlowParameters.flow_fractions.

Parameters:

branch_label_ids (Optional[Mapping[str, int]]) – Branch name -> label, or None (default) for no branches.

Return type:

None

set_beats(beats)[source]

Set the number of heart beats to simulate.

Parameters:

beats (int) – Beats, at least two. Default: 3

Raises:

ValueError – If it is less than two.

Return type:

None

set_dt_s(dt_s)[source]

Set the solver time step in seconds.

Parameters:

dt_s (float) – Time step; each workflow has its own default.

Raises:

ValueError – If it is not positive.

Return type:

None

set_calibrate_outlets(calibrate_outlets)[source]

Calibrate the outlet totals and initial pressure to this inflow.

False uses the outlet totals of flow_parameters as given.

Parameters:

calibrate_outlets (bool) – Whether to. Default: True

Return type:

None

INFLOW_PERIOD_TOLERANCE: ClassVar[float] = 0.01

Largest difference, in beats, between the inflow series’ duration and a whole number of beats at the heart rate.

class monai_physio.aorta.AortaWorkflowSimulateFlow1DNS(flow_parameters=None, log_level=20)[source]

Simulate rigid-wall 1D blood flow along an aorta’s centerline.

The inputs, outlet calibration, beats and I/O contract are those of AortaWorkflowSimulateFlowBase. The flow split is imposed: each outlet takes its renormalized AortaFlowParameters.flow_fractions share of the inflow, and every outlet, branch or distal, carries the distal outlet’s Windkessel pressure (see the module docstring). AortaVisualizeFlowNS.save_results_1d() writes the result.

process(labelmap_image=None, *, inflow_m3_s, inflow_interval_s, geometry=None)[source]

Simulate 1D flow in an aorta labelmap or a prepared geometry.

Parameters:
Returns:

  • 'geometry' - the prepared geometry.

  • 'flow_parameters' - the AortaFlowParameters simulated: flow_parameters, calibrated unless calibrate_outlets is False.

  • 'sections' - (N,) 'arc_length_m', 'area_m2' and 'flow_fraction': the arc length, lumen area and fraction of the inflow of each centerline section.

  • 'series' - per time sample: (T,) 'times_s' (the middle of each step), 'inlet_flow_m3_s' and 'inlet_flow_derivative_m3_s2' (the smoothed inflow and its time derivative) and 'root_pressure_pa'; outlet name -> (T,) 'outlet_flow_m3_s' and 'outlet_pressure_pa' (Windkessel pressure); and (T, N) 'flow_m3_s', 'velocity_m_s' (section mean) and 'pressure_pa'.

  • 'summary' - the keys of AortaWorkflowSimulateFlowBase._pressure_summary(), then each outlet’s flow share outlet_flow_shares and stroke volume outlet_stroke_volume_ml (mL), the peak section-mean velocity peak_velocity_m_s (m/s) and the peak Reynolds number rho V D / mu of the equivalent circular section peak_reynolds, all over the last beat.

Return type:

dict with the following keys

Raises:

ValueError – If not exactly one of labelmap_image and geometry is given, if beats is below two, if the inflow has no ejection, if dt_s or the inflow series does not fit the heart rate (see _check_timing), or if an outlet has no flow fraction.

class monai_physio.aorta.AortaWorkflowSimulateFlow3DBase(flow_parameters=None, log_level=20)[source]

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 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 AortaProcessFlow.windkessels() returns for it, a three-element 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 AortaProcessFlow whose windkessels returns other objects with these three members, assigned to flow_tools, gives other outlet models.

Steppers

_simulate() steps the object _build_stepper() returns: a WarpFlowBase solver, or an object wrapping one as .fluid (such as WarpFluidStructureNS), whose step(inlet_flow) returns the step result of WarpFlowBase.step() plus its own entries. STEP_KEYS names the entries kept as series and _frame_extras() adds fields to the saved frames.

Subclasses implement _prepare_domain(), _build_stepper(), _root_pressure_weights(), _field_points(), _run_settings(), _run_sizes(), _solver_summary() and _step_message().

__init__(flow_parameters=None, log_level=20)[source]

Initialize the workflow; see AortaWorkflowSimulateFlowBase.

set_element_size_mm(element_size_mm)[source]

Set the largest interior edge length of the meshes.

Parameters:

element_size_mm (float) – Edge length in millimeters. Default: 2.0

Raises:

ValueError – If it is not positive.

Return type:

None

set_precision(precision)[source]

Choose the precision of the blood operators and linear solves.

Parameters:

precision (str) – "float32" (default) or "float64".

Raises:

ValueError – If it is neither.

Return type:

None

set_frame_interval_s(frame_interval_s)[source]

Set the interval of the saved fields over the last beat.

Rounded to a multiple of the time step.

Parameters:

frame_interval_s (float) – Interval in seconds. Default: 0.03

Raises:

ValueError – If it is not positive.

Return type:

None

TITLE: ClassVar[str] = '3D aorta flow'

Model name of the log and progress messages.

DOMAIN_KEY: ClassVar[str] = 'domain'

Result key of the solver’s domain, such as its mesh.

OUTLET_EXCLUSION_MM = 10.0

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.

STEP_KEYS: ClassVar[dict[str, tuple[str, Any]]] = {}

series key -> (step-result key, dtype).

Type:

Series kept from every step

LOG_STEPS: ClassVar[int] = 100

Steps between progress lines in the log.

class monai_physio.aorta.AortaWorkflowSimulateFlow3DNS(flow_parameters=None, log_level=20)[source]

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 AortaWorkflowSimulateFlow3DBase; the solver is WarpFlowNS on a tetrahedral lumen mesh, kept in the result as 'mesh'. AortaVisualizeFlowNS.save_results_3d() writes the result for monai_physio.VisualizeFlowFieldsNS.

DOMAIN_KEY: ClassVar[str] = 'mesh'

Result key of the solver’s domain, such as its mesh.

BACKFLOW_BETA = 1.0

Backflow stabilization coefficient of the outlets.

INLET_BLUNT_FRACTION = 0.2

The inlet speed rises from the wall over this fraction of the root’s equivalent radius and is flat inside it.

MESH_KEYS: ClassVar[tuple[str, ...]] = ('points_mm', 'tetrahedra', 'boundary_faces', 'boundary_regions')

Keys a mesh given to process() must hold.

STEP_KEYS: ClassVar[dict[str, tuple[str, Any]]] = {'gmres_iterations': ('iterations', <class 'numpy.int64'>), 'residual': ('residual', <class 'numpy.float64'>)}

series key -> (step-result key, dtype).

Type:

Series kept from every step

process(labelmap_image=None, *, inflow_m3_s, inflow_interval_s, geometry=None, mesh=None)[source]

Simulate 3D flow in an aorta labelmap or a prepared geometry.

Parameters:
Returns:

  • 'geometry' - the prepared geometry.

  • 'flow_parameters' - the AortaFlowParameters simulated: 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, ProcessVolumetricMesh.tetrahedron_edges()) and (F, points) 'pressure_pa' at the mesh points.

  • 'run' - solver settings, sizes, device and timings.

  • 'summary' - the keys of 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.

Return type:

dict with the following keys

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.

class monai_physio.aorta.AortaWorkflowSimulateFlowFSINS(flow_parameters=None, log_level=20)[source]

Simulate 3D blood flow in an aorta whose wall moves with the blood.

The blood model, its inflow, outlets and summary are those of AortaWorkflowSimulateFlow3DNS; this class adds the wall. flow_parameters also supplies the wall’s Young’s modulus, Poisson ratio, thickness and tether stiffness.

Wall

A compressible Neo-Hookean solid of the given thickness around the lumen, quasi-static (massless), prestressed so that the imaged geometry is its equilibrium at AortaFlowParameters.initial_pressure_pa, the pressure where the simulation starts (with calibrated outlets, the calibrated periodic pressure at the start of the beats), so the run starts at rest in equilibrium; clamped within collar_mm of every port and held by springs on its outer surface (WarpHyperelasticWall).

Netgen fills a wall shell reliably only when it is at least MIN_WALL_CELLS grid spacings thick, so a thinner wall is prepared that thick and its Young’s modulus scaled by the physiological over the meshed thickness. Keeping modulus times thickness is a thin-wall approximation: the Lame thick-wall solution makes the default 1.5 mm, 1 MPa wall meshed 3.75 mm thick at 0.4 MPa about 20-35% more compliant for inner radii of 12-7.5 mm. The reported wall motion, strain, distensibility and wave speed describe that surrogate wall. The run records the thickness and modulus meshed.

Input pressures and wall compliance

As in the rigid workflows the patient’s systolic and diastolic pressures are inputs, but here the wall stores part of each stroke itself and smooths the root pressure before the outlets see it. process() therefore first measures the wall’s compliance dV/dP with a quasi-static solve under uniform pressure, prestressed at the diastolic input and loaded with the systolic one, and then calibrates the outlets with that compliance in front of them (AortaProcessFlow.calibrated() with wall_compliance_m3_pa). The total compliance reported is the outlets’ plus the wall’s. The lumen is somewhat more compliant in the flow than in this static, uniform-pressure estimate (compare the summary’s lumen_compliance_m3_pa), so the simulated pulse and systolic pressure come out a little low. calibrate_outlets=False uses the outlet totals of flow_parameters as given.

__init__(flow_parameters=None, log_level=20)[source]

Initialize the workflow; see AortaWorkflowSimulateFlowBase.

set_spacing_mm(spacing_mm)[source]

Set the grid spacing of the prepared geometry.

It sets the mesh size; the run time grows about as its inverse cube.

Parameters:

spacing_mm (float) – Spacing in millimeters. Default: 1.25

Raises:

ValueError – If it is not positive.

Return type:

None

set_collar_mm(collar_mm)[source]

Clamp wall points this close to a port.

Parameters:

collar_mm (float) – Distance in millimeters. Default: 2.0

Raises:

ValueError – If it is negative.

Return type:

None

TITLE: ClassVar[str] = '3D FSI aorta flow'

Model name of the log and progress messages.

COUPLING: ClassVar[dict[str, Any]] = {'absolute_tolerance': 1e-08, 'max_iterations': 20, 'relaxation': 0.1, 'reuse': 2, 'tolerance': 0.001}

Interface quasi-Newton settings of WarpFluidStructureNS, those of experiments/BloodFlow-3D-FSI-Simpleware-Warp except a looser absolute tolerance, since float32 blood solves hold the interface residual above the experiment’s 1 nm.

MIN_WALL_CELLS = 3.0

Fewest grid spacings across the wall shell that netgen fills reliably.

WALL_TOLERANCE: ClassVar[float] = 1e-06

Relative residual the static wall solve of the compliance must reach.

MESH_KEYS: ClassVar[tuple[str, ...]] = ('points_mm', 'tetrahedra', 'boundary_faces', 'boundary_regions', 'wall_points_mm', 'wall_tetrahedra', 'wall_clamped', 'wall_tether_faces')

Keys a mesh given to process() must hold.

STEP_KEYS: ClassVar[dict[str, tuple[str, Any]]] = {'converged': ('converged', <class 'bool'>), 'coupling_iterations': ('coupling_iterations', <class 'numpy.int64'>), 'coupling_residual': ('coupling_residual', <class 'numpy.float64'>), 'coupling_residual_m': ('coupling_residual_m', <class 'numpy.float64'>), 'gmres_iterations': ('iterations', <class 'numpy.int64'>), 'max_displacement_m': ('max_displacement_m', <class 'numpy.float64'>), 'mean_displacement_m': ('mean_displacement_m', <class 'numpy.float64'>), 'residual': ('residual', <class 'numpy.float64'>), 'total_gmres_iterations': ('gmres_iterations', <class 'numpy.int64'>), 'volume_m3': ('volume_m3', <class 'numpy.float64'>), 'volume_rate_m3_s': ('volume_rate_m3_s', <class 'numpy.float64'>), 'wall_iterations': ('wall_iterations', <class 'numpy.int64'>), 'wall_tangent_updates': ('wall_tangent_updates', <class 'numpy.int64'>)}

gmres_iterations and residual are those of the step’s last blood solve; total_gmres_iterations sums every blood solve.

LOG_STEPS: ClassVar[int] = 20

Steps between progress lines in the log.

process(labelmap_image=None, *, inflow_m3_s, inflow_interval_s, geometry=None, mesh=None)[source]

Simulate coupled flow and wall motion in an aorta.

Parameters:
Return type:

dict[str, Any]

Returns:

dict with the keys of AortaWorkflowSimulateFlow3DNS.process(), where 'mesh' holds the lumen and wall meshes (millimetres), the velocity is at the P2 nodes of the lumen mesh as given, every field belongs to the mesh moved by the frame’s displacement, and 'gmres_iterations' and 'residual' are those of the last blood solve of each step. Added:

  • 'series' - (T,) 'total_gmres_iterations', 'coupling_iterations', 'converged', 'coupling_residual', 'coupling_residual_m', 'wall_iterations' and 'wall_tangent_updates', the coupling statistics of every step (WarpFluidStructureNS.step()); 'max_displacement_m' and 'mean_displacement_m', the largest and mean interface displacement; 'volume_m3' and 'volume_rate_m3_s', the lumen volume and its rate of change.

  • 'frames' - (F, points, 3) 'displacement_m' of the lumen mesh points (the wall’s on the wall, its harmonic extension inside).

  • 'summary' - the 3D summary plus the total, wall and outlet compliances, the wall’s metrics over the last beat (peak displacement and outward normal displacement in mm, lumen volume and mean diameter strain in percent, the lumen’s compliance fitted to the root pressure, the distensibility and the Bramwell-Hill pulse-wave speed) and the coupling statistics of the whole run (max_coupling_residual relative to the step’s interface motion, max_coupling_residual_m the RMS residual in metres). max_net_port_flow_relative counts the lumen volume change as outflow.

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 input pressures do not satisfy 0 < diastolic < systolic, if the inflow has no ejection, if an outlet has no flow fraction, or if no outlet resistance and compliance give the input pressures, as when the wall alone is too compliant.

  • RuntimeError – If a linear solve or a coupled step diverges, or if the static wall solve of the compliance does not converge.

class monai_physio.aorta.AortaVisualizeFlow(log_level=20)[source]

Write the plots, series and summary of an aorta flow workflow result.

__init__(log_level=20)[source]

Initialize AortaVisualizeFlow.

Parameters:

log_level (int | str) – Logging level. Default: logging.INFO.

save_plots(result, output_directory)[source]

Plot the last two beats of pressure and flow to pressure_flow.png.

The top panel shows the root and distal-outlet pressures, the next one the inflow and each outlet’s flow; when result["series"] holds "max_displacement_m", a moving wall’s, a third shows the lumen volume change and the largest wall displacement.

Parameters:
  • result (Mapping[str, Any]) – The result of a workflow’s process.

  • output_directory (str) – Directory to write into (created if absent).

Return type:

str

Returns:

Path of the saved PNG.

save_series(result, output_directory)[source]

Write the per-step series, the run record and the summary.

Files written to output_directory (created if absent):

  • steps.npz - every array of result["series"], the outlet arrays as outlet_flow_m3_s_<name> and outlet_pressure_pa_<name>.

  • run.json - result["run"], when the result has one.

  • summary.json - result["summary"].

Parameters:
  • result (Mapping[str, Any]) – The result of a workflow’s process.

  • output_directory (str) – Directory to write into.

Return type:

dict[str, str]

Returns:

File kind ("steps", "run", "summary") -> path of the saved file.

class monai_physio.aorta.AortaVisualizeFlowNS(log_level=20)[source]

Write the 1D and 3D results of the Navier-Stokes aorta flow workflows.

save_results_1d(result, output_directory)[source]

Write the centerline, lumen surface, fields and summary.

Files written to output_directory (created if absent):

  • centerline.vtp - the centerline with last-beat point data systolic_pressure_mmhg, diastolic_pressure_mmhg, mean_pressure_mmhg, peak_velocity_m_s and flow_fraction.

  • lumen_surface.vtp - the tagged lumen surface of the geometry.

  • fields.npz - every array of result["sections"] and result["series"], the outlet arrays as outlet_flow_m3_s_<name> and outlet_pressure_pa_<name>.

  • summary.json - result["summary"].

Parameters:
Return type:

dict[str, str]

Returns:

File kind ("centerline", "surface", "fields", "summary") -> path of the saved file.

save_results_3d(result, output_directory)[source]

Write the fields for VisualizeFlowFieldsNS and the series.

Files written to output_directory (created if absent):

  • mesh.npz - points_m, tetrahedra, edges (the P2 edge node order, ProcessVolumetricMesh.tetrahedron_edges()), boundary_faces and boundary_regions of the lumen mesh.

  • time.npz - the frames’ frame_times_s and frame_inlet_flow_m3_s.

  • <field>.npy - every other array of result["frames"]: velocity_m_s.npy and pressure_pa.npy (and the FSI workflow’s displacement_m.npy).

  • steps.npz, run.json and summary.json of save_series().

A displacement_m.npy already in output_directory is removed when the result has no displacement, so the viewer does not move a rigid result’s wall.

Parameters:
Returns:

"mesh", "time", each field’s key ("velocity_m_s", "pressure_pa", …), "steps", "run" and "summary".

Return type:

File kind -> path of the saved file