Predicting With a Mesh-Stage Model

Inference is split in two so that the generic half stays target-agnostic:

  • WorkflowInferPhysicsNeMo loads the checkpoint and returns the raw (n_points, n_target) prediction, whatever the target means.

  • WorkflowInferMovement wraps it and interprets three-component targets as displacements - deformed meshes, error statistics in millimetres, and rasterized deformation fields.

Generic prediction

class monai_physio.WorkflowInferPhysicsNeMo(model_directory, inference_method=None, epoch=None, log_level=20)[source]

Bases: MONAIPhysioBase

Predict per-point targets for a subject at requested stages.

The network is supplied as an inference method - pass a monai_physio.InferPhysicsNeMoMGN or monai_physio.InferPhysicsNeMoMLP instance as inference_method; a default MeshGraphNet method is used when none is given.

__init__(model_directory, inference_method=None, epoch=None, log_level=20)[source]

Load a trained model and its normalization statistics.

Parameters:
Raises:
  • FileNotFoundError – If the model checkpoint or the template mesh is missing.

  • TypeError – If inference_method is neither None nor an InferPhysicsNeMoBase instance.

check_held_out(subject_id)[source]

Warn if the loaded checkpoint was trained on subject_id.

Predicting a subject the network trained on overstates how well it generalizes, so evaluations of a held-out subject should call this first. Checkpoints that do not record their training subjects pass.

Return type:

bool

Returns:

True if subject_id is not among the checkpoint’s train_subject_ids, False (after logging a warning) if it is.

property template_mesh: pyvista.DataSet

The shared PCA template mesh defining node order and topology.

predict(pca_coeffs, stage)[source]

Predict (n_points, n_target) targets for a subject at a stage.

Return type:

ndarray

predicted_mesh(targets)[source]

Return a template copy carrying targets as its target array.

Return type:

DataSet

process(subject_manifest, stages=None, output_directory=None)[source]

Predict a subject’s targets from a manifest.

Every phase in the manifest is predicted, or the arbitrary stages given instead.

Parameters:
  • subject_manifest (Path) – Path to the subject manifest JSON.

  • stages (Optional[list[float]]) – Optional list of stages to predict.

  • output_directory (Optional[Path]) – Output directory; defaults to <model_directory>/<subject_id>.

Return type:

dict[str, Any]

Returns:

Dict with subject_id and predicted_meshes (paths).

Displacement interpretation

class monai_physio.WorkflowInferMovement(inference_workflow, log_level=20)[source]

Bases: 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 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.

Parameters:
Raises:

ValueError – If the wrapped model does not predict exactly three components, which cannot be a displacement.

__init__(inference_workflow, log_level=20)[source]

Initialize the base class with logging configuration.

Parameters:
  • class_name – Name for the class (used in log messages). If None, uses the class name. Default: None

  • log_level (int | str) – Lowest level this object logs at. Can be an integer (logging.DEBUG, logging.INFO, logging.WARNING, logging.ERROR, logging.CRITICAL) or a string (‘DEBUG’, ‘INFO’, ‘WARNING’, ‘ERROR’, ‘CRITICAL’). set_log_level() sets a floor for every object at once. Default: logging.INFO

  • log_to_file – Optional file path to write all MONAI Physio logs to as well; only the first object’s value is used. Default: None

set_smoothing_sigma_mm(smoothing_sigma_mm)[source]

Set the Gaussian sigma that spreads the surface field into the volume.

Parameters:

smoothing_sigma_mm (float) – Sigma in millimeters. Default: 10.0

Raises:

ValueError – If it is not finite and positive.

Return type:

None

set_slip_layer_mm(slip_layer_mm)[source]

Set the slip layer of the exterior restriction.

See ProcessTransforms.restrict_deformation_field_to_normal_falloff_outside_mask(); used only when an exterior_mask is given.

Parameters:

slip_layer_mm (float) – Thickness in millimeters. Default: 2.0

Raises:

ValueError – If it is not finite and positive.

Return type:

None

set_normal_fade_ratio(normal_fade_ratio)[source]

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.

Parameters:

normal_fade_ratio (float) – Ratio. Default: 2.0

Raises:

ValueError – If it is not finite and positive.

Return type:

None

set_displaced_threshold_mm(displaced_threshold_mm)[source]

Set how far a voxel must move to count toward the shared fade boundary.

Parameters:

displaced_threshold_mm (float) – Threshold in millimeters (see ProcessTransforms.displaced_voxel_mask()). Default: 0.01

Raises:

ValueError – If it is negative.

Return type:

None

set_shared_fade_boundary(shared_fade_boundary)[source]

Fade every stage’s exterior motion to zero on one shared boundary.

When set, process_time_series() first builds the boundary with 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.

Parameters:

shared_fade_boundary (bool) – Whether to build and use it. Default: False

Return type:

None

set_warp_interpolation(warp_interpolation)[source]

Choose how reference_image is resampled into each stage.

Parameters:

warp_interpolation (str) – "linear" for intensity images, "nearest" for labelmaps and masks. Default: "linear"

Raises:

ValueError – If it is neither.

Return type:

None

set_warp_background_value(warp_background_value)[source]

Set the value written where a stage samples outside reference_image.

Parameters:

warp_background_value (float) – 0.0 suits labelmaps; CT needs -1000.0, air in Hounsfield units. Default: 0.0

Return type:

None

set_anatomy_type(anatomy_type)[source]

Choose the anatomy whose materials color the time-series USD.

Parameters:

anatomy_type (Optional[str]) – Anatomy name, or None for a solid color. Default: None

Return type:

None

set_separate_by_connectivity(separate_by_connectivity)[source]

Split each USD frame into separate objects by connectivity.

Parameters:

separate_by_connectivity (bool) – Whether to split. Default: False

Return type:

None

set_return_transforms(return_transforms)[source]

Keep each stage’s dense transform in the time-series result.

Set False when the saved images and meshes are enough: the dense working fields and warped image buffers are then released before the next stage.

Parameters:

return_transforms (bool) – Whether to keep them. Default: True

Return type:

None

process(subject_manifest, stages=None)[source]

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 monai_physio.WorkflowEvaluateMovement.

Parameters:
  • subject_manifest (Path) – Path to the subject manifest JSON.

  • stages (Optional[list[float]]) – Optional list of stages to predict.

Return type:

dict[str, Any]

Returns:

Dict with subject_id, stages (the stages predicted) and stage_meshes (one pv.DataSet per stage, in that order).

predict_single(shape_parameters, stage, fitted_reference_mesh)[source]

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.

Parameters:
Return type:

dict[str, Any]

Returns:

Dict with stage_mesh (the predicted pv.DataSet) and predicted_points.

process_time_series(shape_parameters, stages, output_directory, fitted_reference_mesh, *, reference_image=None, usd_project_name=None, exterior_mask=None, zero_displacement_distance_map=None)[source]

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 itk.DisplacementFieldTransform and used to carry reference_image into that stage’s frame (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.

Parameters:
  • shape_parameters (Path) – JSON file with the subject PCA coefficient vector.

  • stages (Sequence[float]) – Stages to predict, in the order they are to be animated.

  • output_directory (Path) – Directory every artifact is written to.

  • fitted_reference_mesh (Path) – The subject’s fitted reference mesh, as produced by monai_physio.WorkflowFitStatisticalModelToPatient. The displacements are added to its points and the result stays in its world frame.

  • reference_image (Optional[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 (Optional[str]) – When given, the stage meshes are also written as one animated USD under this name, one time sample per stage.

  • exterior_mask (Optional[Image]) – 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 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 (Optional[Image]) – A boundary already built with create_zero_displacement_distance_map(), for a caller that predicts one stage per call. Ignored when exterior_mask is omitted.

Return type:

dict[str, Any]

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

create_zero_displacement_distance_map(shape_parameters, stages, reference_image, fitted_reference_mesh, exterior_mask, *, direction='inverse')[source]

Build the boundary every stage’s exterior motion fades to zero on.

Each stage’s field is built with stage_transform() in direction and restricted with this workflow’s settings (set_smoothing_sigma_mm(), set_slip_layer_mm(), set_normal_fade_ratio()), and the voxels it displaces by more than the set_displaced_threshold_mm() threshold, together with the organ itself, are added to a union over all stages. The result is ProcessTransforms.interior_distance_map() of that union. Pass it to process_time_series() (or to 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. process_time_series() builds and uses it in one call after 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.

Parameters:
  • shape_parameters (Path) – JSON file with the subject PCA coefficient vector.

  • stages (Sequence[float]) – Every stage the map is to serve.

  • reference_image (Image) – Grid the fields are rasterized on.

  • fitted_reference_mesh (Path) – The subject’s fitted reference mesh.

  • exterior_mask (Image) – Binary or label image on reference_image’s grid marking the organ, in the reference frame.

  • direction (Literal['forward', 'inverse']) – "inverse" (the field 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:

Distance map on reference_image’s grid.

Return type:

itk.Image

Raises:

ValueError – If stages is empty.

stage_transform(shape_parameters, stage, reference_image, fitted_reference_mesh, *, direction='inverse', exterior_mask=None, zero_displacement_distance_map=None, fields=None)[source]

Build one stage’s dense transform, restricted outside exterior_mask.

The stage’s deformation field (create_deformation_field()) is spread into a continuous field with ProcessTransforms.smooth_deformation_field_transform(). With exterior_mask the field is then restricted outside the organ with ProcessTransforms.restrict_deformation_field_to_normal_falloff_outside_mask(). The smoothing and restriction settings come from this workflow’s set_* methods. The mask is given in the reference frame, which is the frame a "forward" field is indexed in; an "inverse" field is indexed in the stage’s own frame, so the mask is first resampled into it through the unrestricted transform.

Parameters:
  • shape_parameters (Path) – JSON file with the subject PCA coefficient vector.

  • stage (float) – Stage to build the transform for.

  • reference_image (Image) – Grid the field is rasterized on.

  • fitted_reference_mesh (Path) – The subject’s fitted reference mesh.

  • direction (Literal['forward', 'inverse']) – "inverse" to resample images into the stage frame, "forward" to move mesh points to the stage.

  • exterior_mask (Optional[Image]) – Binary or label image on reference_image’s grid marking the organ, in the reference frame. Omit for the unrestricted spread.

  • zero_displacement_distance_map (Optional[Image]) – Passed to the restriction.

  • fields (Optional[dict[str, Any]]) – This stage’s create_deformation_field() result in direction, when the caller already has it; otherwise the stage is predicted here.

Return type:

tuple[DisplacementFieldTransform, Optional[Image]]

Returns:

The transform, and the organ mask in the frame the field is indexed in (None without exterior_mask).

create_deformation_field(shape_parameters, stage, reference_image, fitted_reference_mesh, direction='forward')[source]

Rasterize the inferred deformation onto a reference image grid.

Each mesh vertex is binned by its reference (undeformed) position into reference_image’s voxel grid. Each voxel of the deformation field holds the mean network displacement (dx, dy, dz) of the vertices that fall in it. Empty voxels are zero.

That is the "forward" field, which maps reference positions to stage positions and is what transforming a mesh needs. Resampling an image, though, maps each output point through the transform to find where to sample the input, so carrying the reference image into the stage frame needs the opposite mapping. direction="inverse" builds it exactly rather than by negating the forward field: each vertex is binned by its deformed position reference + displacement and contributes -displacement.

The binning positions come from fitted_reference_mesh, so a patient scan whose statistical-model fit applied a pose transform not captured by the shape coefficients is binned where it actually aligns with reference_image. The network displacements themselves depend only on the coefficients and stage, not on the binning positions.

Parameters:
  • shape_parameters (Path) – JSON file with the subject PCA coefficient vector.

  • stage (float) – Target stage for the deformation.

  • reference_image (Image) – The frame’s image; defines the output grid geometry (size, spacing, origin, direction).

  • fitted_reference_mesh (Path) – The subject’s fitted reference mesh, as produced by monai_physio.WorkflowFitStatisticalModelToPatient. Its points supply the binning positions, and must share the template topology (same point count and ordering).

  • direction (Literal['forward', 'inverse']) – "forward" for the reference-to-stage field that deforms meshes, "inverse" for the stage-to-reference field that resamples images into the stage frame.

Return type:

dict[str, Any]

Returns:

Dict with deformation_field (ITK vector image), weight_image (the vertex count per voxel, which distinguishes an empty voxel from one whose displacement happens to be zero and is what ProcessTransforms.smooth_deformation_field_transform() normalizes by) and deformed_surface (the stage mesh as pv.DataSet).

Inference methods

class monai_physio.InferPhysicsNeMoBase(model_tag='base', log_level=20)[source]

Bases: MONAIPhysioBase

Base class for a PhysicsNeMo mesh-stage inference method.

Not instantiated directly - use monai_physio.InferPhysicsNeMoMGN or monai_physio.InferPhysicsNeMoMLP. Subclasses implement build_model(), load_artifacts() and predict().

__init__(model_tag='base', log_level=20)[source]

Initialize the inference method.

Parameters:
  • model_tag (str) – Prefix of the checkpoint files to load (<model_tag>_stage_model.pt); must match the tag of the training method that wrote them. Default: "base".

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

build_model(meta)[source]

Rebuild the (uncompiled) network from checkpoint metadata.

Return type:

Module

load_artifacts(model_directory, n_points, device)[source]

Load any architecture-specific artifacts (MGN graph tensors).

Return type:

None

predict(node_feats)[source]

Run the network over all nodes; return the (n, n_target) output.

Return type:

ndarray

set_model(model, device)[source]

Attach the loaded model and its device before predicting.

Return type:

None

class monai_physio.InferPhysicsNeMoMGN(model_tag='mgn', log_level=20)[source]

Bases: InferPhysicsNeMoBase

Predict mesh stages with a trained PhysicsNeMo MeshGraphNet.

The shared graph topology and edge features are loaded from the tensors the training workflow saved next to the checkpoint.

__init__(model_tag='mgn', log_level=20)[source]

Initialize the MeshGraphNet inference method.

Parameters:
build_model(meta)[source]

Rebuild the (uncompiled) network from checkpoint metadata.

Return type:

Module

load_artifacts(model_directory, n_points, device)[source]

Load any architecture-specific artifacts (MGN graph tensors).

Return type:

None

predict(node_feats)[source]

Run the network over all nodes; return the (n, n_target) output.

Return type:

ndarray

class monai_physio.InferPhysicsNeMoMLP(model_tag='mlp', log_level=20)[source]

Bases: InferPhysicsNeMoBase

Predict mesh stages with a trained PhysicsNeMo FullyConnected model.

__init__(model_tag='mlp', log_level=20)[source]

Initialize the MLP inference method.

Parameters:
  • model_tag (str) – Prefix of the checkpoint files to load (<model_tag>_stage_model.pt). Default: "mlp".

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

build_model(meta)[source]

Rebuild the (uncompiled) network from checkpoint metadata.

Return type:

Module

load_artifacts(model_directory, n_points, device)[source]

Load any architecture-specific artifacts (MGN graph tensors).

Return type:

None

predict(node_feats)[source]

Run the network over all nodes; return the (n, n_target) output.

Return type:

ndarray

Example

from monai_physio import (
    InferPhysicsNeMoMGN,
    WorkflowInferMovement,
    WorkflowInferPhysicsNeMo,
)

infer = WorkflowInferPhysicsNeMo(
    model_directory=model_dir,
    inference_method=InferPhysicsNeMoMGN(),   # the default
)

# Raw targets, whatever the model was trained to predict.
targets = infer.predict(pca_coefficients, stage=0.5)

# Or, for a displacement model, geometry and mm error statistics.
movement = WorkflowInferMovement(infer)
result = movement.process(subject_manifest)
for stage, mesh in zip(result["stages"], result["stage_meshes"]):
    mesh.save(str(out_dir / f"stage_{stage:.2f}.vtp"))

Notes

Where the displacements are applied. WorkflowInferMovement.predict_single() and create_deformation_field() both require a fitted_reference_mesh - the patient’s shape-model surface as fitted by WorkflowFitStatisticalModelToPatient, which is shape parameters and a deformable registration. The prediction stays in that mesh’s world frame, so a fit that carried a pose transform lands where the patient actually is. A surface reconstructed from the shape parameters alone is not a substitute and is not accepted.

Arbitrary stages. Nothing constrains stage to a phase that was acquired; predicting between acquired phases is the reason to train a surrogate at all.

Deformation fields. create_deformation_field() bins the per-vertex displacements onto a caller-supplied image grid, giving an ITK vector image and a per-voxel vertex count that smooth_deformation_field_transform() spreads into a transform for volumes and labelmaps.

See Also