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.
ProcessFlowBoundaries- smooth periodic inlet flow from per-interval fluxes, such as left-ventricle volume loss (inlet_flow()), and the Pa per mmHg conversionProcessFlowBoundaries.MMHG_PA.Windkessel- three-element (RCR) outlet model.WarpFlowBase- the interface of the Warp flow solvers.WarpFlowNS- P2/P1 incompressible Navier-Stokes on tetrahedra, with a cuDSS-preconditioned GMRES solve in float32 or float64.WarpCuDssFactor- sparse direct factorization on the GPU with NVIDIA cuDSS.WarpHyperelasticWall- prestressed Neo-Hookean vessel wall.WarpFluidStructureNS- Dirichlet-Neumann coupling ofWarpFlowNSand the wall with IQN-ILS acceleration.VisualizeFlowFieldsBase- interactive viewer, browser interface and movie export of saved flow fields, andVisualizeFlowFieldsNSfor the P2/P1 fields ofWarpFlowNSruns.
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
AortaProcessGeometry- centerline, section areas, ports and netgen meshes of an aorta labelmap.AortaFlowParameters- the per-patient inputs (systolic and diastolic blood pressure, heart rate), blood, Windkessel and wall parameters. The blood pressures are user-specified patient values that the outlets are calibrated to, not simulation outputs.AortaProcessFlow- the flow inputs: its static methodslv_volumes_ml(),lv_ejection_inflow()andlv_inflow()turn a labelmap series into LV volumes and inflow,beat_start_s()gives the time at which the flow workflows start, and its instance methodswindkessels()andcalibrated()build the outlet Windkessels and calibrate them to the input pressures.AortaWorkflowSimulateFlowBase- what the workflows share: the geometry from a labelmap or a prepared geometry, the outlet calibration and the last-beat root-pressure summary.AortaWorkflowSimulateFlow1DNS- rigid-wall 1D pressure and flow along the centerline (Tutorial 19).AortaWorkflowSimulateFlow3DBase- the solver-independent 3D time stepping and summary.AortaWorkflowSimulateFlow3DNS- rigid-wall 3D flow withWarpFlowNSin a netgen lumen mesh (Tutorial 20).AortaWorkflowSimulateFlowFSINS- 3D flow coupled to a moving Neo-Hookean wall withWarpFluidStructureNSin conforming netgen lumen and wall meshes, with the outlets calibrated to the input pressures behind the wall’s own compliance (Tutorial 21).AortaVisualizeFlow- the pressure and flow plot, series, run record and summary files of any workflow result, andAortaVisualizeFlowNSthe 1D centerline files and the 3D fieldsVisualizeFlowFieldsNSreads. The workflows write no files.
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
- 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_sholds the mean flux of consecutive source intervals ofinterval_sseconds (for example the left-ventricle volume loss between frames of a cardiac image series) and repeats with periodlen(interval_fluxes_m3_s) * interval_s. This staircase has unphysical jumps, so it is convolved with a periodic Gaussian of standard deviationsmoothing_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, manysmoothing_sfrom 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:
- 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 obeysC dP_c/dt = Q - P_c / R_d. A zero distal resistance gives a pure resistanceR_p, a zero compliance gives a pure resistanceR_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
fractionof flow.Resistances scale with
1 / fractionand compliance withfraction, so every outlet has the same time constant.- Return type:
- advance(flow, dt)[source]
Advance
P_cwith the new outlet flow and return the outlet pressure.- Return type:
- __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
Windkesselmembersimplicit(dt),advance(Q, dt)andpressure, which the solver updates in place.- 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:
- 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:
- 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 tostep()throughwall_velocity, then read the fluid load on the wall withwall_force().move()reassembles the operators;update_preconditioner()refactors the Schur block if GMRES iterations grow.- 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)}
- __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.
- update_preconditioner()[source]
Factor
B diag(A)^-1 B^Tof the current operators with cuDSS.- Return type:
- step(inlet_flow, wall_velocity=None)[source]
Advance one time step and update the outlet Windkessels.
- Parameters:
- Return type:
- Returns:
GMRES iterations, the relative residual
|b - A x| / |b|of the linear solve (|b - A x|whenbis zero), the outward flow of every port in m^3/s and the pressure of every outlet in Pa.
- 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:
- 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 persistentsolutionarray from the persistentrhsarray, so callers can fill and read them in place. Values,rhsandsolutionusedtype(Warp float32 or float64).- 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_LIBRARYnames 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:
- __init__(matrix, matrix_type='spd', dtype=<class 'warp._src.types.float64'>)[source]
Upload
matrixand factor it.
- 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.S0is a prestress stored at every quadrature point (zero untilprestress()). 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, thenedges.- 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:
- prestress(load)[source]
Store a prestress that balances
loadin the given geometry.S0is the small-strain stress of the clamped wall underloadwithout tethers, which is in exact discrete equilibrium withloadat zero displacement. The tangent is then refactored withS0.- Return type:
- 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
tolerancetimes the load norm, or warns aftermax_iterations. The factored tangent is reused across solves and refactored at the current displacement whenever an iteration fails to halve the residual.
- 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
WarpFlowNSand a wall.The wall is prestressed so that the given geometry is its equilibrium at
reference_pressure(uniform on the interface). Eachstep():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);
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 responsex~and residualr = x~ - x, every iteration stores the differences ofrand ofx~from the previous iteration as columns ofVandW. Withcminimizing|V c + r|, the guess moves by(W - V) c, the quasi-Newton step for the part ofrthat the columns explain, plusrelaxationtimes the rest,r + V c(all ofrwhile there are no columns). Withrelaxation = 1after 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 lastreusesteps are kept, newest first; a column whose part orthogonal to the newer ones is belowfilter_toleranceof 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
tolerancetimes the RMS interface motion of the step (guess minus the start-of-step displacement) plusabsolute_tolerance. The reported coupling residual is the relative part only, so a converged step can report more thantolerancewhen its motion is small.A step still unconverged after
max_iterationsis 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:
- step(inlet_flow)[source]
Advance the coupled system one fluid time step.
- Return type:
- Returns:
The last fluid step result plus coupling iterations (fluid and wall solves;
max_iterations + 1for 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.
- 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).columnsholds (residual difference, response difference, step) pairs, newest first. Columns beyond the length ofresidual, and columns whose part orthogonal to the newer ones is belowfilter_toleranceof their norm, are removed from it in place. SeeWarpFluidStructureNSfor the method.- Return type:
- 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.
- 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.
- update_slice()[source]
Probe the quadratic volume on the current plane, with velocity glyphs.
- Return type:
- update_color_range()[source]
Share one color range between the lumen surface and the slice.
- Return type:
- set_color_mode(mode)[source]
Select current-frame, slice-focused or fixed all-frame color limits.
- Return type:
- set_field(field)[source]
Show speed, pressure or (for a moving wall) wall displacement.
- Return type:
- set_slice(axis, position)[source]
Move the slice to a fraction of the lumen bounds along an axis.
- Return type:
- advance(elapsed)[source]
Show the frame at
elapsedseconds 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:
- rotate_camera(azimuth, elevation)[source]
Rotate the camera about the focal point (degrees).
- Return type:
- 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.
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.
AortaFlowParameters- per-patient inputs and blood, outlet and wall parameters.AortaProcessFlow- inflow from a left-ventricle volume series, beat timing, outlet Windkessels and their calibration.AortaProcessGeometry- centerline, sections, ports and meshes.AortaWorkflowSimulateFlowBase- what the flow workflows share.AortaWorkflowSimulateFlow1DNS- rigid-wall 1D flow (Tutorial 19).AortaWorkflowSimulateFlow3DBase- what the 3D flow workflows share, whatever their solver.AortaWorkflowSimulateFlow3DNS- rigid-wall 3D flow (Tutorial 20).AortaWorkflowSimulateFlowFSINS- 3D flow with a moving wall (Tutorial 21).AortaVisualizeFlow- pressure and flow plots, series and summary files of any workflow result.AortaVisualizeFlowNS- the files of the NS workflow results.
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 ofbranch_label_ids, so they match the keys ofAortaFlowParameters.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_acrosselements are refined within this many port radii of their center byrigid_mesh().
- 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.
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.
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.
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.The vessel is cut normal to the centerline end_margin_mm inside each end; a
END_PLUG_THICKNESS_MMslab beyond each cut becomes that end’s plug and the rest beyond it is removed.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) andarc_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’slabel_id)."centerline": polyline from the root cut to the distal cut with point dataarc_length_mm(0 at the root),area_mm2(lumen section normal to the centerline),radius_mm(the equivalent radiussqrt(area / pi)) andtangent."wall_thickness_mm": wall_thickness_mm, the thickness of the wall shell thatfsi_mesh()meshes.- Return type:
"labelmap"- Raises:
ValueError – If two branch names are equal, or one is
rootordistal, 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 withinPORT_ZONE_RADIIport 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 ofgeometry["surface"].- Parameters:
- Return type:
- 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’slabel_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
WarpFluidStructureNSrequires. 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 coarserspacing_mmfor a smaller mesh.- Parameters:
- Return type:
- 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’slabel_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_mmhgandheart_rate_bpmdescribe 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 ofexperiments/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_paandinitial_pressure_pamay 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.
- 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).
- 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()(andcalibrated(), which fits the three-element model) and assign an instance to a workflow’sflow_tools.- 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.
- 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
iruns from frameito framei + 1and 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 reachesminimum_ejection_fractionof the LV volume range (maximum minus minimum, about the stroke volume).- Parameters:
- Return type:
- 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 atheart_rate_bpm; the inflow is thenlv_ejection_inflow()at that frame interval. Beats are counted for a regular rhythm (seeBEAT_GAP_FRACTION); with an irregular one the count can be too low, which makes the frame interval too short.- Parameters:
lv_volume_ml (
ndarray) – LV volume of each frame in mL, for example fromlv_volumes_ml().heart_rate_bpm (
float) – Heart rate the series is retimed to, for exampleAortaFlowParameters.heart_rate_bpm.
- Return type:
- 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:
- Return type:
- 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_namesare 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)andpressure, 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 withcalibrate_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:
- 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 andproximal_fraction), fed by the smoothed periodic inflow (ProcessFlowBoundaries.inlet_flow()withinflow_smoothing_s) and stepped like the workflows’ outlets. An elastic aorta adds its own complianceC_win front of them: the root pressurePthen obeysC_w dP/dt = Q_in - Q_outwithPthe Windkessel pressure of the outflowQ_out(stepped implicitly inQ_out, as the flow solver does), as inexperiments/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 fromlv_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) – CompliancedV/dPof the aortic wall in front of the outlets; 0 for a rigid aorta.
- Return type:
- Returns:
A copy of flow_parameters with
total_resistance_pa_s_m3,total_compliance_m3_paandinitial_pressure_pareplaced.- 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
- class monai_physio.aorta.AortaWorkflowSimulateFlowBase(flow_parameters=None, log_level=20)[source]
Shared inputs, calibration and summary of the aorta flow workflows.
flow_parameterssupplies the patient’s input blood pressure and heart rate, the blood properties, the inflow smoothing and the outlet Windkessel totals; seeAortaFlowParameters.flow_tools, anAortaProcessFlow, 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
processcalibrates a copy of the outlets to them and to the given inflow (AortaProcessFlow.calibrated()), leavingflow_parametersunchanged; the simulated root pressure then differs from the inputs by the model’s pressure drop along the aorta.calibrate_outlets=Falseuses the outlet totals offlow_parametersas given.Inflow
Any sampled periodic inflow works:
inflow_m3_sholds the mean flow of each interval ofinflow_interval_s, for example fromAortaProcessFlow.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 atAortaFlowParameters.heart_rate_bpm. It is smoothed byProcessFlowBoundaries.inlet_flow()withAortaFlowParameters.inflow_smoothing_s.Beats
The simulation covers
beatsheart beats of60 / heart_rate_bpmseconds. 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 atAortaFlowParameters.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
processperforms no file I/O.AortaVisualizeFlowandAortaVisualizeFlowNSwrite its result to disk.- __init__(flow_parameters=None, log_level=20)[source]
Initialize the workflow.
- Parameters:
flow_parameters (
Optional[AortaFlowParameters]) – Blood, inflow, outlet and wall parameters. Defaults toAortaFlowParameters().log_level (
int|str) – Logging level. Default:logging.INFO.
- set_aorta_label_ids(aorta_label_ids)[source]
Choose the labels whose union is the aortic lumen.
- Parameters:
- Raises:
ValueError – If it is empty.
- Return type:
- 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.
- 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:
- 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:
- 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 renormalizedAortaFlowParameters.flow_fractionsshare 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:
labelmap_image (
Optional[Image]) – Labelmap holding the aorta and, optionally, its branches; prepared byAortaProcessGeometry.prepare()with its defaults. Give this or geometry.inflow_m3_s (
ndarray) – Mean inflow of each interval of a periodic series, for example fromAortaProcessFlow.lv_inflow().inflow_interval_s (
float) – Duration of each inflow interval in seconds.geometry (
Optional[Mapping[str,Any]]) – AAortaProcessGeometry.prepare()result, used in place of preparing labelmap_image. Only its"centerline"(point dataarc_length_mmandarea_mm2), its"ports"(roleandarc_length_mm) and, forAortaVisualizeFlowNS.save_results_1d(), its"surface"are read.
- Returns:
'geometry'- the prepared geometry.'flow_parameters'- theAortaFlowParameterssimulated:flow_parameters, calibrated unless calibrate_outlets isFalse.'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 ofAortaWorkflowSimulateFlowBase._pressure_summary(), then each outlet’s flow shareoutlet_flow_sharesand stroke volumeoutlet_stroke_volume_ml(mL), the peak section-mean velocitypeak_velocity_m_s(m/s) and the peak Reynolds numberrho V D / muof the equivalent circular sectionpeak_reynolds, all over the last beat.
- Return type:
dictwith 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-elementWindkesselby default. The solver uses only itsimplicit(dt), which returns(R, P0)such that the outlet pressure over a step isR Q + P0for the step’s outflowQ(Rmust not change between steps),advance(Q, dt), which ends the step and returns that pressure, and itspressurestate, which a coupled step restores between iterations. A subclass ofAortaProcessFlowwhosewindkesselsreturns other objects with these three members, assigned toflow_tools, gives other outlet models.Steppers
_simulate()steps the object_build_stepper()returns: aWarpFlowBasesolver, or an object wrapping one as.fluid(such asWarpFluidStructureNS), whosestep(inlet_flow)returns the step result ofWarpFlowBase.step()plus its own entries.STEP_KEYSnames 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:
- 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:
- 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:
- 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.
- 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 isWarpFlowNSon a tetrahedral lumen mesh, kept in the result as'mesh'.AortaVisualizeFlowNS.save_results_3d()writes the result formonai_physio.VisualizeFlowFieldsNS.- 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:
labelmap_image (
Optional[Image]) – Labelmap holding the aorta and, optionally, its branches; prepared byAortaProcessGeometry.prepare()with its defaults. Give this or geometry.inflow_m3_s (
ndarray) – Mean inflow of each interval of a periodic series, for example fromAortaProcessFlow.lv_inflow().inflow_interval_s (
float) – Duration of each inflow interval in seconds.geometry (
Optional[Mapping[str,Any]]) – AAortaProcessGeometry.prepare()result, used in place of preparing labelmap_image.mesh (
Optional[Mapping[str,Any]]) – A lumen mesh with the keys ofAortaProcessGeometry.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’slabel_idon each of the geometry’s ports. The geometry still supplies the ports.
- Returns:
'geometry'- the prepared geometry.'flow_parameters'- theAortaFlowParameterssimulated:flow_parameters, calibrated unless calibrate_outlets isFalse.'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 ofAortaWorkflowSimulateFlow3DBase._summarize(), with the 1D workflow’s meanings for the shared ones, then the linear solver’smax_linear_residual,mean_gmres_iterationsandunconverged_stepsover the whole run.
- Return type:
dictwith 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_parametersalso 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 withincollar_mmof 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_CELLSgrid 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 compliancedV/dPwith 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()withwall_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’slumen_compliance_m3_pa), so the simulated pulse and systolic pressure come out a little low.calibrate_outlets=Falseuses the outlet totals offlow_parametersas 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:
- 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:
- 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 ofexperiments/BloodFlow-3D-FSI-Simpleware-Warpexcept 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_iterationsandresidualare those of the step’s last blood solve;total_gmres_iterationssums every blood solve.
- 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:
labelmap_image (
Optional[Image]) – Labelmap holding the aorta and, optionally, its branches; prepared byAortaProcessGeometry.prepare()at spacing_mm with the wall thickness to mesh (see Wall above). Give this or geometry.inflow_m3_s (
ndarray) – Mean inflow of each interval of a periodic series, for example fromAortaProcessFlow.lv_inflow().inflow_interval_s (
float) – Duration of each inflow interval in seconds.geometry (
Optional[Mapping[str,Any]]) – AAortaProcessGeometry.prepare()result, used in place of preparing labelmap_image; its spacing replaces spacing_mm, and the Young’s modulus is scaled to itswall_thickness_mm.mesh (
Optional[Mapping[str,Any]]) – Lumen and wall meshes with the keys ofAortaProcessGeometry.fsi_mesh(), used in place of meshing the geometry: the lumen keys ofAortaWorkflowSimulateFlow3DNS.process()plus"wall_points_mm","wall_tetrahedra","wall_clamped"and"wall_tether_faces". Every lumen point on a wall triangle (region 0) must be a wall point.
- Return type:
- Returns:
dictwith the keys ofAortaWorkflowSimulateFlow3DNS.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_residualrelative to the step’s interface motion,max_coupling_residual_mthe RMS residual in metres).max_net_port_flow_relativecounts 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 satisfy0 < 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.
- 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.
- 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 ofresult["series"], the outlet arrays asoutlet_flow_m3_s_<name>andoutlet_pressure_pa_<name>.run.json-result["run"], when the result has one.summary.json-result["summary"].
- 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 datasystolic_pressure_mmhg,diastolic_pressure_mmhg,mean_pressure_mmhg,peak_velocity_m_sandflow_fraction.lumen_surface.vtp- the tagged lumen surface of the geometry.fields.npz- every array ofresult["sections"]andresult["series"], the outlet arrays asoutlet_flow_m3_s_<name>andoutlet_pressure_pa_<name>.summary.json-result["summary"].
- save_results_3d(result, output_directory)[source]
Write the fields for
VisualizeFlowFieldsNSand 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_facesandboundary_regionsof the lumen mesh.time.npz- the frames’frame_times_sandframe_inlet_flow_m3_s.<field>.npy- every other array ofresult["frames"]:velocity_m_s.npyandpressure_pa.npy(and the FSI workflow’sdisplacement_m.npy).steps.npz,run.jsonandsummary.jsonofsave_series().
A
displacement_m.npyalready in output_directory is removed when the result has no displacement, so the viewer does not move a rigid result’s wall.- Parameters:
result (
Mapping[str,Any]) – The result ofAortaWorkflowSimulateFlow3DNS.process()orAortaWorkflowSimulateFlowFSINS.process().output_directory (
str) – Directory to write into.
- 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