"""Movement interpretation of PhysicsNeMo mesh-stage predictions.
:class:`WorkflowInferMovement` wraps a
:class:`monai_physio.WorkflowInferPhysicsNeMo` whose targets are per-point
displacements from the subject's fitted reference mesh, and turns those raw
predictions into geometry: deformed meshes (``fitted reference + displacement``)
and rasterized deformation fields. Scoring those predictions is
:class:`monai_physio.WorkflowEvaluateMovement`'s job, so no error statistic is
computed here.
The generic workflow stays target-agnostic; everything that assumes "the target
is a 3-vector displacement in mm" lives here. Composition, not inheritance, so
one decoder serves both the MeshGraphNet and the MLP inference methods.
"""
from __future__ import annotations
import logging
from collections.abc import Sequence
from pathlib import Path
from typing import Any, Literal, Optional, cast
import itk
import numpy as np
import pyvista as pv
from .monai_physio_base import MONAIPhysioBase
from .process_physicsnemo import ProcessPhysicsNeMo
from .process_transforms import ProcessTransforms
from .workflow_convert_vtk_to_usd import WorkflowConvertVTKToUSD
from .workflow_infer_physicsnemo import WorkflowInferPhysicsNeMo
[docs]
class WorkflowInferMovement(MONAIPhysioBase):
"""Reconstruct geometry from displacement predictions.
The displacements are added to the subject's fitted reference mesh - the
manifest's ``fitted_reference_mesh``, or the ``fitted_reference_mesh``
argument of the single-subject methods - which keeps the result in that
mesh's world frame. That mesh is what
:class:`monai_physio.WorkflowFitStatisticalModelToPatient` produces: PCA
shape parameters *and* a deformable registration to the patient. A surface
reconstructed from the shape parameters alone is not a substitute and is not
accepted.
Args:
inference_workflow: A loaded :class:`WorkflowInferPhysicsNeMo` whose
model predicts three-component displacements.
log_level: Logging level. Default: ``logging.INFO``.
Raises:
ValueError: If the wrapped model does not predict exactly three
components, which cannot be a displacement.
"""
[docs]
def __init__(
self,
inference_workflow: WorkflowInferPhysicsNeMo,
log_level: int | str = logging.INFO,
) -> None:
super().__init__(class_name=self.__class__.__name__, log_level=log_level)
if inference_workflow.n_target != 3:
raise ValueError(
"WorkflowInferMovement needs a 3-component target, but the "
f"model predicts {inference_workflow.n_target} components."
)
self.inference_workflow = inference_workflow
self.model_directory = inference_workflow.model_directory
# Settings shared by process_time_series, stage_transform and
# create_zero_displacement_distance_map, so the passes of one series
# cannot disagree; each has a set_* method.
self.smoothing_sigma_mm = 10.0
self.slip_layer_mm = 2.0
self.normal_fade_ratio = 2.0
self.displaced_threshold_mm = 0.01
self.shared_fade_boundary = False
self.warp_interpolation = "linear"
self.warp_background_value = 0.0
self.anatomy_type: Optional[str] = None
self.separate_by_connectivity = False
self.return_transforms = True
@staticmethod
def _require_positive(name: str, value: float) -> None:
"""Raise unless ``value`` is finite and greater than zero."""
if not (np.isfinite(value) and value > 0.0):
raise ValueError(f"{name} must be finite and > 0, got {value}.")
[docs]
def set_smoothing_sigma_mm(self, smoothing_sigma_mm: float) -> None:
"""Set the Gaussian sigma that spreads the surface field into the volume.
Args:
smoothing_sigma_mm: Sigma in millimeters. Default: 10.0
Raises:
ValueError: If it is not finite and positive.
"""
self._require_positive("smoothing_sigma_mm", smoothing_sigma_mm)
self.smoothing_sigma_mm = smoothing_sigma_mm
[docs]
def set_slip_layer_mm(self, slip_layer_mm: float) -> None:
"""Set the slip layer of the exterior restriction.
See
:meth:`ProcessTransforms.restrict_deformation_field_to_normal_falloff_outside_mask`;
used only when an ``exterior_mask`` is given.
Args:
slip_layer_mm: Thickness in millimeters. Default: 2.0
Raises:
ValueError: If it is not finite and positive.
"""
self._require_positive("slip_layer_mm", slip_layer_mm)
self.slip_layer_mm = slip_layer_mm
[docs]
def set_normal_fade_ratio(self, normal_fade_ratio: float) -> None:
"""Set the normal fade length per millimeter of normal displacement.
Used by the exterior restriction; with a shared fade boundary it sets
only how far that boundary reaches.
Args:
normal_fade_ratio: Ratio. Default: 2.0
Raises:
ValueError: If it is not finite and positive.
"""
self._require_positive("normal_fade_ratio", normal_fade_ratio)
self.normal_fade_ratio = normal_fade_ratio
[docs]
def set_displaced_threshold_mm(self, displaced_threshold_mm: float) -> None:
"""Set how far a voxel must move to count toward the shared fade boundary.
Args:
displaced_threshold_mm: Threshold in millimeters (see
:meth:`ProcessTransforms.displaced_voxel_mask`). Default: 0.01
Raises:
ValueError: If it is negative.
"""
if displaced_threshold_mm < 0.0:
raise ValueError(
f"displaced_threshold_mm must be >= 0, got {displaced_threshold_mm}."
)
self.displaced_threshold_mm = displaced_threshold_mm
[docs]
def set_shared_fade_boundary(self, shared_fade_boundary: bool) -> None:
"""Fade every stage's exterior motion to zero on one shared boundary.
When set, :meth:`process_time_series` first builds the boundary with
:meth:`create_zero_displacement_distance_map` -- the farthest any
stage reaches under the normal fade ratio -- which predicts every
stage once more. Needs ``exterior_mask`` and ``reference_image``
there.
Args:
shared_fade_boundary: Whether to build and use it. Default: False
"""
self.shared_fade_boundary = shared_fade_boundary
[docs]
def set_warp_interpolation(self, warp_interpolation: str) -> None:
"""Choose how ``reference_image`` is resampled into each stage.
Args:
warp_interpolation: ``"linear"`` for intensity images, ``"nearest"``
for labelmaps and masks. Default: ``"linear"``
Raises:
ValueError: If it is neither.
"""
if warp_interpolation not in ("linear", "nearest"):
raise ValueError(
"warp_interpolation must be 'linear' or 'nearest', got "
f"{warp_interpolation}."
)
self.warp_interpolation = warp_interpolation
[docs]
def set_warp_background_value(self, warp_background_value: float) -> None:
"""Set the value written where a stage samples outside ``reference_image``.
Args:
warp_background_value: ``0.0`` suits labelmaps; CT needs
``-1000.0``, air in Hounsfield units. Default: 0.0
"""
self.warp_background_value = warp_background_value
[docs]
def set_anatomy_type(self, anatomy_type: Optional[str]) -> None:
"""Choose the anatomy whose materials color the time-series USD.
Args:
anatomy_type: Anatomy name, or None for a solid color. Default: None
"""
self.anatomy_type = anatomy_type
[docs]
def set_separate_by_connectivity(self, separate_by_connectivity: bool) -> None:
"""Split each USD frame into separate objects by connectivity.
Args:
separate_by_connectivity: Whether to split. Default: False
"""
self.separate_by_connectivity = separate_by_connectivity
def _fitted_reference_points(self, fitted_reference_mesh: pv.DataSet) -> np.ndarray:
"""Return the points the displacements are added to.
Raises:
ValueError: If the supplied mesh has the wrong point count.
"""
# A copy, not a view: callers add these points into other meshes'
# points, and a view would keep this mesh's VTK array alive with them,
# which VTK debug builds report as a leak.
points = np.array(fitted_reference_mesh.points, dtype=np.float32)
n_expected = self.inference_workflow.template_mesh.n_points
if points.shape[0] != n_expected:
raise ValueError(
f"Fitted reference mesh has {points.shape[0]} points, expected "
f"{n_expected} (template topology)."
)
return points
# ─────────────────────────── Public API ────────────────────────────────
[docs]
def process(
self,
subject_manifest: Path,
stages: Optional[list[float]] = None,
) -> dict[str, Any]:
"""Predict a subject's deformed meshes from a manifest.
Every phase in the manifest is predicted, or the arbitrary ``stages``
given instead. The displacements are added to the manifest's
``fitted_reference_mesh`` points. Scoring the result against a ground
truth belongs to :class:`monai_physio.WorkflowEvaluateMovement`.
Args:
subject_manifest: Path to the subject manifest JSON.
stages: Optional list of stages to predict.
Returns:
Dict with ``subject_id``, ``stages`` (the stages predicted) and
``stage_meshes`` (one ``pv.DataSet`` per stage, in that order).
"""
workflow = self.inference_workflow
manifest = ProcessPhysicsNeMo.parse_manifest(subject_manifest)
pca_coeffs = ProcessPhysicsNeMo.load_pca_coefficients(manifest.pca_coefficients)
fitted_reference_mesh = cast(
pv.DataSet, pv.read(str(manifest.fitted_reference_mesh))
)
fitted_reference_points = self._fitted_reference_points(fitted_reference_mesh)
sid = manifest.subject_id
self.log_section("INFER MOVEMENT [%s]", sid)
requested = stages if stages is not None else [p.stage for p in manifest.phases]
stage_meshes: list[pv.DataSet] = []
for stage in requested:
pred_mesh = fitted_reference_mesh.copy(deep=True)
pred_mesh.points = fitted_reference_points + workflow.predict(
pca_coeffs, stage
)
stage_meshes.append(pred_mesh)
self.log_info("predicted stage %.3f", stage)
return {
"subject_id": sid,
"stages": list(requested),
"stage_meshes": stage_meshes,
}
[docs]
def predict_single(
self,
shape_parameters: Path,
stage: float,
fitted_reference_mesh: Path,
) -> dict[str, Any]:
"""Predict one subject at one stage without a manifest.
The prediction stays in the fitted reference mesh's world frame, since
that is where the displacements are applied.
Args:
shape_parameters: JSON file with the subject PCA coefficient vector.
stage: Target stage to predict.
fitted_reference_mesh: The subject's fitted reference mesh, as
produced by
:class:`monai_physio.WorkflowFitStatisticalModelToPatient`.
Returns:
Dict with ``stage_mesh`` (the predicted ``pv.DataSet``) and
``predicted_points``.
"""
workflow = self.inference_workflow
coeffs = ProcessPhysicsNeMo.load_pca_coefficients(shape_parameters)
fitted_mesh = cast(pv.DataSet, pv.read(str(fitted_reference_mesh)))
fitted_reference_points = self._fitted_reference_points(fitted_mesh)
pred_points = fitted_reference_points + workflow.predict(coeffs, stage)
pred_mesh = fitted_mesh.copy(deep=True)
pred_mesh.points = pred_points
self.log_info("single prediction stage %.3f", stage)
return {"stage_mesh": pred_mesh, "predicted_points": pred_points}
[docs]
def process_time_series(
self,
shape_parameters: Path,
stages: Sequence[float],
output_directory: Path,
fitted_reference_mesh: Path,
*,
reference_image: Optional[itk.Image] = None,
usd_project_name: Optional[str] = None,
exterior_mask: Optional[itk.Image] = None,
zero_displacement_distance_map: Optional[itk.Image] = None,
) -> dict[str, Any]:
"""Predict one subject across a whole time series and write its geometry.
One prediction per entry of ``stages``, each written as a mesh. When
``reference_image`` is supplied, each stage also gets a deformation
field, which is Gaussian-smoothed into a continuous
:class:`itk.DisplacementFieldTransform` and used to carry
``reference_image`` into that stage's frame (:meth:`stage_transform`).
The smoothing spreads a surface-shell field into the volume, so the
warped image is an interpolation of the surface motion, not an
independent registration. The smoothing, warp, restriction and USD
settings come from this workflow's ``set_*`` methods.
Args:
shape_parameters: JSON file with the subject PCA coefficient vector.
stages: Stages to predict, in the order they are to be animated.
output_directory: Directory every artifact is written to.
fitted_reference_mesh: The subject's fitted reference mesh, as
produced by
:class:`monai_physio.WorkflowFitStatisticalModelToPatient`. The
displacements are added to its points and the result stays in
its world frame.
reference_image: Image carried through each stage's deformation, and
the grid the deformation field is rasterized on. Omit to write
meshes only.
usd_project_name: When given, the stage meshes are also written as
one animated USD under this name, one time sample per stage.
exterior_mask: Binary or label image on ``reference_image``'s grid
marking the anatomy the surface belongs to (e.g. a lung
labelmap). When given, the deformation used to warp
``reference_image`` is restricted outside this mask to its
component along the surface normal, fading to zero, via
:meth:`ProcessTransforms.restrict_deformation_field_to_normal_falloff_outside_mask`,
so tissue beyond the organ is pushed and pulled by it without
being dragged along tangentially. Omit for the plain isotropic
spread every stage otherwise gets.
zero_displacement_distance_map: A boundary already built with
:meth:`create_zero_displacement_distance_map`, for a caller
that predicts one stage per call. Ignored when
``exterior_mask`` is omitted.
Returns:
Dict with ``stages``, ``predicted_surfaces``, ``warped_images``,
``transforms``, ``usd_file`` and ``stage_meshes``. Entries that were
not requested are empty lists or ``None``.
``transforms`` is empty after ``set_return_transforms(False)``.
``stage_meshes`` are the very objects written to
``predicted_surfaces``, handed back so a caller that scores them ---
:class:`monai_physio.WorkflowEvaluateMovement` --- can annotate and
re-save them without re-reading. They are retained for the USD
writer regardless, so returning them costs nothing.
Raises:
ValueError: If ``stages`` is empty, or if the shared fade boundary
is set together with ``zero_displacement_distance_map`` or
without ``exterior_mask`` and ``reference_image``.
"""
if not stages:
raise ValueError("process_time_series needs at least one stage.")
shared_fade_boundary = self.shared_fade_boundary
if shared_fade_boundary:
if zero_displacement_distance_map is not None:
raise ValueError(
"Use set_shared_fade_boundary(True) or pass "
"zero_displacement_distance_map, not both."
)
if exterior_mask is None or reference_image is None:
raise ValueError(
"shared_fade_boundary needs exterior_mask and reference_image."
)
workflow = self.inference_workflow
coeffs = ProcessPhysicsNeMo.load_pca_coefficients(shape_parameters)
fitted_mesh = cast(pv.DataSet, pv.read(str(fitted_reference_mesh)))
fitted_reference_points = self._fitted_reference_points(fitted_mesh)
out_dir = Path(output_directory)
out_dir.mkdir(parents=True, exist_ok=True)
stem = Path(shape_parameters).stem
suffix = ".vtp" if isinstance(fitted_mesh, pv.PolyData) else ".vtu"
self.log_section("INFER MOVEMENT TIME SERIES [%s]", stem)
# Progress: a shared fade boundary takes the first 0.4, the stages
# share the rest up to 0.97 equally, and the USD export takes the last
# 0.03. Within a stage, building and smoothing the deformation field
# takes most of the time; without reference_image a stage only predicts.
self._start_progress("Time series starting")
stages_start = 0.0
if shared_fade_boundary:
assert exterior_mask is not None and reference_image is not None
stages_start = 0.4
with self._progress_range(0.0, stages_start, "Shared fade boundary"):
zero_displacement_distance_map = (
self.create_zero_displacement_distance_map(
shape_parameters,
stages,
reference_image,
fitted_reference_mesh,
exterior_mask,
)
)
stage_share = (0.97 - stages_start) / len(stages)
transform_tools = ProcessTransforms(log_level=self.log_level)
stage_meshes: list[pv.DataSet] = []
surfaces: list[Path] = []
warped_images: list[Path] = []
transforms: list[itk.Transform] = []
for index, stage in enumerate(stages):
tag = f"s{int(stage * 100):03d}"
stage_start = stages_start + index * stage_share
label = f"Stage {stage:.3f} ({index + 1}/{len(stages)})"
self._report_progress(stage_start, f"{label}: predicting")
fields: Optional[dict[str, Any]] = None
if reference_image is not None:
# One prediction serves both the stage mesh and its field.
fields = self.create_deformation_field(
shape_parameters=shape_parameters,
stage=stage,
reference_image=reference_image,
fitted_reference_mesh=fitted_reference_mesh,
direction="inverse",
)
pred_mesh = fields["deformed_surface"]
else:
pred_mesh = fitted_mesh.copy(deep=True)
pred_mesh.points = fitted_reference_points + workflow.predict(
coeffs, stage
)
# The displacement the network itself predicted. Scoring it against
# a ground truth is the evaluation workflow's job, not this one's.
pred_mesh.point_data["predicted_displacement_mm"] = (
np.asarray(pred_mesh.points) - fitted_reference_points
).astype(np.float32)
surface_file = out_dir / f"{stem}_{tag}_pred{suffix}"
pred_mesh.save(str(surface_file))
stage_meshes.append(pred_mesh)
surfaces.append(surface_file)
if reference_image is not None:
self._report_progress(
stage_start + 0.05 * stage_share,
f"{label}: creating deformation field",
)
# Only the transform is kept: holding the stage mask too would
# keep it alive into the next stage. The fields are handed over
# without a reference here, so stage_transform can free their
# rasters before the restriction allocates its own.
handoff = [fields]
del fields
transform = self.stage_transform(
shape_parameters,
stage,
reference_image,
fitted_reference_mesh,
direction="inverse",
exterior_mask=exterior_mask,
zero_displacement_distance_map=zero_displacement_distance_map,
fields=handoff.pop(),
)[0]
if self.return_transforms:
transforms.append(transform)
self._report_progress(
stage_start + 0.9 * stage_share, f"{label}: warping image"
)
warped = transform_tools.transform_image(
reference_image,
transform,
reference_image=reference_image,
interpolation_method=self.warp_interpolation,
background_value=self.warp_background_value,
)
warped_file = out_dir / f"{stem}_{tag}_warped.mha"
itk.imwrite(warped, str(warped_file), compression=True)
warped_images.append(warped_file)
del warped, transform
self.log_info("stage %.3f -> %s", stage, surface_file.name)
self._report_progress(stage_start + stage_share, f"{label}: done")
usd_file: Optional[Path] = None
if usd_project_name is not None:
usd_workflow = WorkflowConvertVTKToUSD(
log_level=self.log_level,
)
usd_workflow.set_appearance(
"anatomy" if self.anatomy_type is not None else "solid"
)
usd_workflow.set_anatomy_type(self.anatomy_type)
usd_workflow.set_separate_by_connectivity(self.separate_by_connectivity)
usd_workflow.set_frames_per_second(float(len(stage_meshes)))
with self._progress_range(0.97, 1.0, "USD"):
usd_file = Path(
usd_workflow.process(
input_meshes=stage_meshes,
usd_project_name=usd_project_name,
output_directory=out_dir,
)["usd_file"]
)
self._report_progress(1.0, "Time series complete")
return {
"stages": list(stages),
"predicted_surfaces": surfaces,
"warped_images": warped_images,
"transforms": transforms,
"usd_file": usd_file,
"stage_meshes": stage_meshes,
}
[docs]
def create_zero_displacement_distance_map(
self,
shape_parameters: Path,
stages: Sequence[float],
reference_image: itk.Image,
fitted_reference_mesh: Path,
exterior_mask: itk.Image,
*,
direction: Literal["forward", "inverse"] = "inverse",
) -> itk.Image:
"""Build the boundary every stage's exterior motion fades to zero on.
Each stage's field is built with :meth:`stage_transform` in
``direction`` and restricted with this workflow's settings
(:meth:`set_smoothing_sigma_mm`, :meth:`set_slip_layer_mm`,
:meth:`set_normal_fade_ratio`), and the voxels it displaces by more
than the :meth:`set_displaced_threshold_mm` threshold, together with
the organ itself, are added to a union over all ``stages``. The result
is :meth:`ProcessTransforms.interior_distance_map` of that union. Pass
it to :meth:`process_time_series` (or to
:meth:`ProcessTransforms.restrict_deformation_field_to_normal_falloff_outside_mask`)
as ``zero_displacement_distance_map``: every stage then fades to zero
on the same boundary, the farthest any stage reaches, instead of on
one that moves with each stage's own displacement.
:meth:`process_time_series` builds and uses it in one call after
:meth:`set_shared_fade_boundary`; either way both passes read the same
settings.
The fields are not kept; the second pass rebuilds them, which bounds
memory at one stage's fields at the cost of predicting each stage once
more.
Args:
shape_parameters: JSON file with the subject PCA coefficient vector.
stages: Every stage the map is to serve.
reference_image: Grid the fields are rasterized on.
fitted_reference_mesh: The subject's fitted reference mesh.
exterior_mask: Binary or label image on ``reference_image``'s grid
marking the organ, in the reference frame.
direction: ``"inverse"`` (the field :meth:`process_time_series`
warps images with, indexed in each stage's frame) or
``"forward"`` (indexed in the reference frame); use the
direction of the fields the map will restrict.
Returns:
itk.Image: Distance map on ``reference_image``'s grid.
Raises:
ValueError: If ``stages`` is empty.
"""
if not stages:
raise ValueError("create_zero_displacement_distance_map needs a stage.")
self.log_section("ZERO-DISPLACEMENT BOUNDARY [%s]", Path(shape_parameters).stem)
self._start_progress("Shared fade boundary starting")
union: Optional[np.ndarray] = None
for index, stage in enumerate(stages):
self._report_progress(
index / len(stages),
f"Shared fade boundary: stage {stage:.3f} ({index + 1}/{len(stages)})",
)
transform, stage_mask = self.stage_transform(
shape_parameters,
stage,
reference_image,
fitted_reference_mesh,
direction=direction,
exterior_mask=exterior_mask,
)
assert stage_mask is not None
displaced = (
itk.array_from_image(
ProcessTransforms.displaced_voxel_mask(
transform.GetDisplacementField(),
self.displaced_threshold_mm,
)
)
> 0
) | (itk.array_from_image(stage_mask) > 0.5)
union = displaced if union is None else union | displaced
del transform, stage_mask, displaced
assert union is not None
self.log_info(
"Shared fade boundary encloses %d voxels over %d stages",
int(union.sum()),
len(stages),
)
union_mask = itk.image_from_array(union.astype(np.uint8))
union_mask.CopyInformation(reference_image)
distance_map = ProcessTransforms.interior_distance_map(union_mask)
self._report_progress(1.0, "Shared fade boundary complete")
return distance_map
@staticmethod
def _vector_image_like(array: np.ndarray, reference_image: itk.Image) -> itk.Image:
"""Wrap a ``(z, y, x, 3)`` array as an ITK vector image on ``reference``'s grid."""
image = itk.image_from_array(np.ascontiguousarray(array), is_vector=True)
image.SetSpacing(reference_image.GetSpacing())
image.SetOrigin(reference_image.GetOrigin())
image.SetDirection(reference_image.GetDirection())
return image
@staticmethod
def _scalar_image_like(array: np.ndarray, reference_image: itk.Image) -> itk.Image:
"""Wrap a ``(z, y, x)`` array as an ITK scalar image on ``reference``'s grid."""
image = itk.image_from_array(np.ascontiguousarray(array))
image.SetSpacing(reference_image.GetSpacing())
image.SetOrigin(reference_image.GetOrigin())
image.SetDirection(reference_image.GetDirection())
return image