"""Files and plots of aortic blood-flow results, for any solver.
:class:`AortaVisualizeFlow` writes what every flow workflow result holds:
the pressure-and-flow plot of the last two beats and the per-step series,
run record and summary. :class:`AortaVisualizeFlowNS` adds the result
layouts of the Navier-Stokes (NS) workflows. The workflows themselves write
no files.
"""
from __future__ import annotations
import json
import logging
import os
from collections.abc import Mapping
from typing import Any
import numpy as np
from ..monai_physio_base import MONAIPhysioBase
from ..process_flow_boundaries import ProcessFlowBoundaries
from .workflow_simulate_flow_base import AortaWorkflowSimulateFlowBase
[docs]
class AortaVisualizeFlow(MONAIPhysioBase):
"""Write the plots, series and summary of an aorta flow workflow result."""
[docs]
def __init__(self, log_level: int | str = logging.INFO) -> None:
"""Initialize AortaVisualizeFlow.
Args:
log_level: Logging level. Default: ``logging.INFO``.
"""
super().__init__(class_name=self.__class__.__name__, log_level=log_level)
[docs]
def save_plots(self, result: Mapping[str, Any], output_directory: str) -> str:
"""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.
Args:
result: The result of a workflow's ``process``.
output_directory: Directory to write into (created if absent).
Returns:
Path of the saved PNG.
"""
# A plain Figure renders with Agg, without a GUI backend.
from matplotlib.figure import Figure
os.makedirs(output_directory, exist_ok=True)
series = result["series"]
times = np.asarray(series["times_s"])
beat_s = 60.0 / float(result["summary"]["heart_rate_bpm"])
shown = AortaWorkflowSimulateFlowBase._last_beat(times, 2 * beat_s)
root = (
np.asarray(series["root_pressure_pa"])[shown]
/ ProcessFlowBoundaries.MMHG_PA
)
distal = (
np.asarray(series["outlet_pressure_pa"]["distal"])[shown]
/ ProcessFlowBoundaries.MMHG_PA
)
path = os.path.join(output_directory, "pressure_flow.png")
wall = "max_displacement_m" in series
rows = 3 if wall else 2
fig = Figure(figsize=(8.0, 2.0 + 2.0 * rows))
axes = fig.subplots(rows, 1, sharex=True)
top, middle = axes[0], axes[1]
top.plot(times[shown], root, label="root")
top.plot(times[shown], distal, label="distal", linestyle="--")
top.set_ylabel("Pressure (mmHg)")
top.legend(loc="upper right")
middle.plot(
times[shown],
np.asarray(series["inlet_flow_m3_s"])[shown] * 1e6,
label="inflow",
color="black",
)
for name, values in series["outlet_flow_m3_s"].items():
middle.plot(times[shown], np.asarray(values)[shown] * 1e6, label=name)
middle.set_ylabel("Flow (mL/s)")
middle.legend(loc="upper right")
if wall:
self._plot_wall(axes[2], series, shown)
axes[-1].set_xlabel("Time (s)")
fig.tight_layout()
fig.savefig(path, dpi=100)
return path
@staticmethod
def _plot_wall(axis: Any, series: Mapping[str, Any], shown: np.ndarray) -> None:
"""Plot the lumen volume change and the largest wall displacement."""
times = np.asarray(series["times_s"])
volume = np.asarray(series["volume_m3"])
axis.plot(
times[shown],
(volume[shown] - volume[shown].min()) * 1e6,
label="lumen volume change (mL)",
)
axis.plot(
times[shown],
np.asarray(series["max_displacement_m"])[shown] * 1e3,
label="largest wall displacement (mm)",
linestyle="--",
)
axis.set_ylabel("Wall")
axis.legend(loc="upper right")
[docs]
def save_series(
self, result: Mapping[str, Any], output_directory: str
) -> dict[str, str]:
"""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"]``.
Args:
result: The result of a workflow's ``process``.
output_directory: Directory to write into.
Returns:
File kind (``"steps"``, ``"run"``, ``"summary"``) -> path of the
saved file.
"""
os.makedirs(output_directory, exist_ok=True)
paths = {"steps": os.path.join(output_directory, "steps.npz")}
if "run" in result:
paths["run"] = os.path.join(output_directory, "run.json")
paths["summary"] = os.path.join(output_directory, "summary.json")
np.savez_compressed(paths["steps"], **self._array_items(result["series"]))
if "run" in result:
self._save_json(result["run"], paths["run"])
self._save_json(result["summary"], paths["summary"])
return paths
@staticmethod
def _save_json(data: Any, path: str) -> None:
"""Write *data* as indented JSON."""
with open(path, "w", encoding="utf-8") as file:
json.dump(data, file, indent=2)
@staticmethod
def _array_items(arrays: Mapping[str, Any]) -> dict[str, Any]:
"""Return *arrays* flat for ``np.savez``: ``key_name`` for nested dicts."""
flat: dict[str, Any] = {}
for key, value in arrays.items():
if isinstance(value, Mapping):
for name, values in value.items():
flat[f"{key}_{name}"] = np.asarray(values)
else:
flat[key] = np.asarray(value)
return flat