"""Files of the Navier-Stokes (NS) aortic blood-flow results.
:class:`AortaVisualizeFlowNS` writes the result layouts of
:class:`AortaWorkflowSimulateFlow1DNS` (centerline fields) and of
:class:`AortaWorkflowSimulateFlow3DNS` and
:class:`AortaWorkflowSimulateFlowFSINS` (P2/P1 fields on the lumen mesh,
read by :class:`monai_physio.VisualizeFlowFieldsNS`), besides the plots and
series of :class:`AortaVisualizeFlow`.
"""
from __future__ import annotations
import os
from collections.abc import Mapping
from typing import Any
import numpy as np
from ..process_flow_boundaries import ProcessFlowBoundaries
from ..process_volumetric_mesh import ProcessVolumetricMesh
from .visualize_flow import AortaVisualizeFlow
from .workflow_simulate_flow_base import AortaWorkflowSimulateFlowBase
[docs]
class AortaVisualizeFlowNS(AortaVisualizeFlow):
"""Write the 1D and 3D results of the Navier-Stokes aorta flow workflows."""
[docs]
def save_results_1d(
self, result: Mapping[str, Any], output_directory: str
) -> dict[str, str]:
"""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"]``.
Args:
result: The result of
:meth:`AortaWorkflowSimulateFlow1DNS.process`.
output_directory: Directory to write into.
Returns:
File kind (``"centerline"``, ``"surface"``, ``"fields"``,
``"summary"``) -> path of the saved file.
"""
os.makedirs(output_directory, exist_ok=True)
series = result["series"]
beat_s = 60.0 / float(result["summary"]["heart_rate_bpm"])
last = AortaWorkflowSimulateFlowBase._last_beat(series["times_s"], beat_s)
pressure = (
np.asarray(series["pressure_pa"])[last] / ProcessFlowBoundaries.MMHG_PA
)
centerline = result["geometry"]["centerline"].copy()
centerline.point_data["systolic_pressure_mmhg"] = pressure.max(axis=0)
centerline.point_data["diastolic_pressure_mmhg"] = pressure.min(axis=0)
centerline.point_data["mean_pressure_mmhg"] = pressure.mean(axis=0)
centerline.point_data["peak_velocity_m_s"] = np.abs(
np.asarray(series["velocity_m_s"])[last]
).max(axis=0)
centerline.point_data["flow_fraction"] = np.asarray(
result["sections"]["flow_fraction"]
)
paths = {
"centerline": os.path.join(output_directory, "centerline.vtp"),
"surface": os.path.join(output_directory, "lumen_surface.vtp"),
"fields": os.path.join(output_directory, "fields.npz"),
"summary": os.path.join(output_directory, "summary.json"),
}
centerline.save(paths["centerline"])
result["geometry"]["surface"].save(paths["surface"])
np.savez_compressed(
paths["fields"], **self._array_items({**result["sections"], **series})
)
self._save_json(result["summary"], paths["summary"])
return paths
[docs]
def save_results_3d(
self, result: Mapping[str, Any], output_directory: str
) -> dict[str, str]:
"""Write the fields for :class:`VisualizeFlowFieldsNS` and the series.
Files written to *output_directory* (created if absent):
- ``mesh.npz`` - ``points_m``, ``tetrahedra``, ``edges`` (the P2 edge
node order, :meth:`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
:meth:`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.
Args:
result: The result of
:meth:`AortaWorkflowSimulateFlow3DNS.process` or
:meth:`AortaWorkflowSimulateFlowFSINS.process`.
output_directory: Directory to write into.
Returns:
File kind -> path of the saved file: ``"mesh"``, ``"time"``,
each field's key (``"velocity_m_s"``, ``"pressure_pa"``, ...),
``"steps"``, ``"run"`` and ``"summary"``.
"""
os.makedirs(output_directory, exist_ok=True)
frames = result["frames"]
fields = [key for key in frames if key not in ("times_s", "inlet_flow_m3_s")]
paths = {
"mesh": os.path.join(output_directory, "mesh.npz"),
"time": os.path.join(output_directory, "time.npz"),
**{key: os.path.join(output_directory, f"{key}.npy") for key in fields},
}
mesh = result["mesh"]
# int64, as the solver uses: the viewer's edge keys reach the vertex
# count squared, which overflows int32 above 46340 vertices.
tetrahedra = np.asarray(mesh["tetrahedra"], dtype=np.int64)
np.savez_compressed(
paths["mesh"],
points_m=np.asarray(mesh["points_mm"]) * 1e-3,
tetrahedra=tetrahedra,
edges=ProcessVolumetricMesh.tetrahedron_edges(tetrahedra),
boundary_faces=mesh["boundary_faces"],
boundary_regions=mesh["boundary_regions"],
)
np.savez_compressed(
paths["time"],
frame_times_s=np.asarray(frames["times_s"]),
frame_inlet_flow_m3_s=np.asarray(frames["inlet_flow_m3_s"]),
)
for key in fields:
np.save(paths[key], np.asarray(frames[key]))
stale = os.path.join(output_directory, "displacement_m.npy")
if "displacement_m" not in fields and os.path.isfile(stale):
os.remove(stale)
paths.update(self.save_series(result, output_directory))
return paths