Workflow Classes

Workflow classes are the highest-level Python API in MONAI Physio. They combine segmentation, registration, contour generation, and USD conversion into repeatable pipelines. The installed CLI commands are thin wrappers around these classes.

Available Workflows

Workflow

Typical use

WorkflowConvertImageToUSD

Convert a 4D cardiac CT sequence into animated USD anatomy.

WorkflowConvertImageToVTK

Segment one CT image and export anatomy-group VTK surfaces.

WorkflowConvertVTKToUSD

Convert VTK/VTP/VTU meshes or time series into USD.

WorkflowCreateMeanSurface

Build an unbiased mean surface (atlas) from a population, for use as the reference a shape model is built against.

WorkflowCreateStatisticalModel

Build a PCA shape model from sample meshes aligned to a reference.

WorkflowFitStatisticalModelToPatient

Fit a template/statistical heart model to patient-specific surfaces.

WorkflowReconstruct4D

Reconstruct a 4D image series (CT, MRI) by registering its phase images to a reference image.

WorkflowFinetuneICONRegistration

Finetune uniGradICON on your own cohort and return the weights RegisterImagesICON can load.

The blood-flow workflows AortaWorkflowSimulateFlow1DNS, AortaWorkflowSimulateFlow3DNS and AortaWorkflowSimulateFlowFSINS, and their bases AortaWorkflowSimulateFlowBase and AortaWorkflowSimulateFlow3DBase, are in the optional monai_physio.aorta subpackage, which needs the [aorta] extra (monai-physio[aorta]). They write no files; AortaVisualizeFlow and AortaVisualizeFlowNS write their results. They are listed with the Warp solvers in Blood Flow (Warp).

The PhysicsNeMo AI-surrogate workflows - WorkflowTrainPhysicsNeMo, WorkflowInferPhysicsNeMo, WorkflowInferMovement and WorkflowEvaluateMovement - have their own section. See PhysicsNeMo AI Surrogates.

Convert Image to USD

class monai_physio.WorkflowConvertImageToUSD(segmentation_method=None, registration_method=None, log_level=20)[source]

Bases: MONAIPhysioBase

Complete workflow for converting 4D CT images to dynamic USD models.

This class implements the full workflow from 4D CT images to painted USD files suitable for visualization in NVIDIA Omniverse.

segmentation_method and registration_method accept a pre-configured SegmentAnatomyBase / RegisterImagesBase instance. Configure backend-specific parameters (iteration counts, trim_branches, mass preservation, etc.) on the instance before passing it in. Defaults to SegmentChestTotalSegmentatorWithContrast / RegisterImagesGreedy when omitted.

__init__(segmentation_method=None, registration_method=None, log_level=20)[source]

Initialize the image-to-USD workflow.

The images, project name and output directory are given to process(); options have set_* methods.

Parameters:
Raises:

TypeError – If segmentation_method is neither None nor a SegmentAnatomyBase instance, or registration_method is neither None nor a RegisterImagesBase instance.

set_dynamic_labelmap_ids(dynamic_labelmap_ids)[source]

Choose the labelmap ids treated as dynamic anatomy.

They are registered and contoured separately from the remaining static anatomy.

Parameters:

dynamic_labelmap_ids (Optional[list[int]]) – Label ids; None or empty (default) splits nothing, and everything registers as “all”.

Return type:

None

set_mask_dilation_mm(mask_dilation_mm)[source]

Set the dilation, in millimeters, of the dynamic/static registration masks.

Parameters:

mask_dilation_mm (float) – Dilation radius. Default: 6.0

Raises:

ValueError – If it is negative.

Return type:

None

set_frames_per_second(frames_per_second)[source]

Set the playback rate of the animated USD.

Parameters:

frames_per_second (float) – Frames per second. Default: 1.0

Raises:

ValueError – If it is not positive.

Return type:

None

set_surface_reduction_rate(surface_reduction_rate)[source]

Remove this fraction of triangles from every extracted surface.

Parameters:

surface_reduction_rate (float) – Fraction in [0, 1); 0.0 (default) skips decimation.

Raises:

ValueError – If it is outside [0, 1).

Return type:

None

set_isotropic_spacing_mm(isotropic_spacing_mm)[source]

Set the edge length of the isotropic grid the surfaces are contoured on.

Passed to ProcessSurfaceMesh.extract_label_surfaces().

Parameters:

isotropic_spacing_mm (Optional[float]) – Spacing in millimeters; None (default) uses the labelmap’s finest spacing.

Return type:

None

set_distance_sigma_mm(distance_sigma_mm)[source]

Set the blur applied to the label distance maps before contouring.

Passed to ProcessSurfaceMesh.extract_label_surfaces(). Raising it smooths out voxel steps a coarse segmentation leaves, and thins the smallest structures.

Parameters:

distance_sigma_mm (Optional[float]) – Sigma in millimeters; None (default) uses the grid spacing.

Return type:

None

set_save_assets(save_assets)[source]

Write registered images, transforms and labelmaps to the output directory.

Parameters:

save_assets (bool) – Whether to. Default: True

Return type:

None

set_save_transforms(save_transforms)[source]

Also write each frame’s forward and inverse .hdf transforms.

Applies only when assets are saved.

Parameters:

save_transforms (bool) – Whether to. Default: True

Return type:

None

process(time_series_images, reference_image, usd_project_name, output_directory)[source]

Execute the complete workflow from 4D CT to dynamic USD models.

Parameters:
  • time_series_images (list[Image]) – List of time-series images.

  • reference_image (Image) – Reference image.

  • usd_project_name (str) – Project name for USD file organization.

  • output_directory (str) – Directory path where output files will be stored; created if it does not exist.

Returns:

Dictionary of anatomy type to filename of the final painted USD file.

Return type:

dict[str, str]

import itk

from monai_physio import (
    RegisterImagesICON,
    SegmentChestTotalSegmentatorWithContrast,
    WorkflowConvertImageToUSD,
)

time_series_images = [itk.imread(str(path)) for path in frame_files]

workflow = WorkflowConvertImageToUSD(
    segmentation_method=SegmentChestTotalSegmentatorWithContrast(),
    registration_method=RegisterImagesICON(),
)

results = workflow.process(
    time_series_images=time_series_images,
    reference_image=time_series_images[0],
    output_directory="./results",
    usd_project_name="patient_001",
)

Image to VTK

class monai_physio.WorkflowConvertImageToVTK(segmentation_method=None, log_level=20)[source]

Bases: MONAIPhysioBase

Turn a CT image or a labelmap into per-group and per-label VTK surfaces.

segmentation_method accepts a pre-configured SegmentAnatomyBase instance (e.g. SegmentChestTotalSegmentator, SegmentChestTotalSegmentatorWithContrast for contrast-enhanced studies, SegmentHeartSimpleware, or SegmentHeartSimplewareTrimmedBranches for cardiac-only segmentation with pulmonary/great-vessel branches trimmed). Defaults to a new SegmentChestTotalSegmentatorWithContrast when omitted. Its taxonomy names the labels and groups, so it is also needed when process() is given a labelmap rather than an image.

Surfaces

Every surface is closed and outward-oriented, from ProcessSurfaceMesh.extract_label_surfaces(). The per-label surfaces are extracted together, so neighbors share the wall between them; the group surfaces are extracted together in a second pass, so neighboring groups do too. Groups default to the segmenter’s taxonomy (see anatomy_groups); pass groups to process() for others, such as a heart without its chambers. Empty groups and labels are skipped.

VTK object annotation

Each surface and tetrahedral mesh returned by process() carries:

  • field_data['AnatomyGroup'] - anatomy group name, e.g. 'heart'.

  • field_data['SegmentationLabelNames'] - structure names it holds (e.g. ['left_ventricle', 'right_ventricle', ...]).

  • field_data['SegmentationLabelIds'] - corresponding integer label IDs.

  • field_data['AnatomyColor'] - RGB float color from ProcessUSDAnatomy.

  • cell_data['Color'] - RGBA uint8 array (n_cells x 4) for direct VTK rendering.

I/O contract

process() performs no file I/O. Use save_surfaces() and save_combined_surfaces() - or the CLI monai-physio-convert-image-to-vtk - to write results to disk.

__init__(segmentation_method=None, log_level=20)[source]

Initialize the workflow.

Parameters:
Raises:

TypeError – If segmentation_method is neither None nor a SegmentAnatomyBase instance.

anatomy_groups: tuple[str, ...]

Anatomy group names registered by the active segmenter’s taxonomy, in the order they were first added.

set_surface_reduction_rate(surface_reduction_rate)[source]

Remove this fraction of each surface’s triangles by ACVD remeshing.

0.0 keeps them all, and only then do neighboring surfaces share their walls exactly; see ProcessSurfaceMesh.extract_label_surfaces().

Parameters:

surface_reduction_rate (float) – Fraction in [0, 1). Default: 0.0

Raises:

ValueError – If it is outside [0, 1).

Return type:

None

set_extract_label_surfaces(extract_label_surfaces)[source]

Also extract one surface per structure (label) of the processed groups.

For example left_ventricle and right_ventricle separately within heart.

Parameters:

extract_label_surfaces (bool) – Whether to. Default: False

Return type:

None

set_extract_group_surfaces(extract_group_surfaces)[source]

Extract one surface per group.

Parameters:

extract_group_surfaces (bool) – Whether to. Default: True

Return type:

None

set_isotropic_spacing_mm(isotropic_spacing_mm)[source]

Set the grid pitch the surfaces are contoured on.

It sets their triangle count.

Parameters:

isotropic_spacing_mm (Optional[float]) – Pitch in millimeters; None (default) uses the labelmap’s finest spacing.

Raises:

ValueError – If it is not positive.

Return type:

None

set_smoothing_iterations(smoothing_iterations)[source]

Set the number of Taubin smoothing iterations.

Parameters:

smoothing_iterations (int) – Iterations; 0 disables smoothing. Default: 30

Raises:

ValueError – If it is negative.

Return type:

None

set_tetrahedra_element_size_mm(tetrahedra_element_size_mm)[source]

Also build a tetrahedral mesh of every surface at this element size.

Each is relaxed onto its surface.

Parameters:

tetrahedra_element_size_mm (Optional[float]) – Element size in millimeters; None (default) builds none.

Raises:

ValueError – If it is not positive.

Return type:

None

process(input_image=None, anatomy_groups=None, *, labelmap_image=None, groups=None)[source]

Extract per-group and per-label surfaces from an image or a labelmap.

The surface and tetrahedra options come from this workflow’s set_* methods.

Parameters:
  • input_image (Optional[Image]) – CT image to segment. Give this or labelmap_image.

  • anatomy_groups (Optional[list[str]]) – Subset of the taxonomy’s groups to process. None (default) processes all of them. Valid names are given by anatomy_groups.

  • labelmap_image (Optional[Image]) – Labelmap produced by this workflow’s segmenter, used in place of segmenting input_image.

  • groups (Optional[Mapping[str, list[int]]]) – Group name → label ids, each extracted as one surface. None uses the processed taxonomy groups. The groups must not share a label.

Returns:

  • 'surfaces' - group name → surface.

  • 'label_surfaces' - label name → surface; empty unless extract_label_surfaces.

  • 'tetrahedra' / 'label_tetrahedra' - group / label name → tetrahedral mesh; empty unless tetrahedra_element_size_mm.

  • 'labelmap' - itk.Image: per-structure labelmap.

Return type:

dict with the following keys

Raises:

ValueError – If not exactly one of input_image and labelmap_image is given, if any name in anatomy_groups is invalid, or if two groups share a label.

static save_surfaces(surfaces, output_directory, prefix='')[source]

Save each named surface or mesh to its own VTK file.

Parameters:
  • surfaces (Mapping[str, DataSet]) – Mapping of name → mesh, e.g. a value process() returns. Surfaces are written as .vtp, volume meshes as .vtu.

  • output_directory (str) – Directory to write files into (created if absent).

  • prefix (str) – Optional filename prefix. Each file is named {prefix}_{name} (or {name} when prefix is empty).

Return type:

dict[str, str]

Returns:

Mapping of name → path of the saved file.

static save_combined_surfaces(surfaces, output_filename)[source]

Write ProcessSurfaceMesh.combine_surfaces() of surfaces to one file.

The file keeps each cell’s structure as cell_data['SegmentationLabelIds'] and its color as cell_data['Color'], but not the per-object field_data; use save_surfaces() when structure names must be recoverable from the saved files.

Parameters:
  • surfaces (Mapping[str, PolyData]) – Mapping of name → surface.

  • output_filename (str) – Path of the VTP file to write, including its directory. Any missing parent directories are created.

Return type:

str

Returns:

Path to the saved VTP file.

Raises:

ValueError – If surfaces is empty.

import itk

from monai_physio import (
    SegmentChestTotalSegmentatorWithContrast,
    WorkflowConvertImageToVTK,
)

image = itk.imread("chest_ct.nii.gz")
workflow = WorkflowConvertImageToVTK(
    segmentation_method=SegmentChestTotalSegmentatorWithContrast()
)
result = workflow.process(
    input_image=image,
    anatomy_groups=["heart", "major_vessels"],
)

WorkflowConvertImageToVTK.save_combined_surfaces(
    result["surfaces"],
    "./output/patient01_surfaces.vtp",
)

VTK to USD

class monai_physio.WorkflowConvertVTKToUSD(segmenter=None, log_level=20)[source]

Bases: MONAIPhysioBase

Workflow to convert one or more meshes to USD with configurable splitting and appearance (solid color, anatomic material, or colormap).

__init__(segmenter=None, log_level=20)[source]

Initialize the VTK-to-USD workflow.

The meshes, project name and output directory are given to process(); splitting and appearance have set_* methods.

Parameters:
  • segmenter (Optional[SegmentAnatomyBase]) – Segmenter whose taxonomy groups the labels of set_label_names() (or of the meshes’ per-cell label array) by anatomy type. Also selects each structure’s material when the appearance is “anatomy”, through ProcessUSDAnatomy.enhance_meshes(), which falls back to the containing group for a structure with no material of its own.

  • log_level (int | str) – Logging level.

set_separate_by_connectivity(separate_by_connectivity)[source]

Split each mesh into separate objects by connectivity.

Cannot be combined with set_separate_by_cell_type().

Parameters:

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

Return type:

None

set_separate_by_cell_type(separate_by_cell_type)[source]

Split each mesh by cell type (triangle, quad, …).

Cannot be combined with set_separate_by_connectivity().

Parameters:

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

Return type:

None

set_frames_per_second(frames_per_second)[source]

Set the playback rate of time-varying data.

Parameters:

frames_per_second (float) – Frames per second. Default: 60.0

Raises:

ValueError – If it is not positive.

Return type:

None

set_extract_surface(extract_surface)[source]

Extract the surface of volumetric meshes before conversion.

Parameters:

extract_surface (bool) – Whether to extract it. Default: True

Return type:

None

set_static_merge(static_merge)[source]

Treat the meshes as separate static objects rather than a time series.

Each mesh is then written as its own object with no time samples (see ConvertVTKToUSD).

Parameters:

static_merge (bool) – Whether to. Default: False

Return type:

None

set_appearance(appearance)[source]

Choose how the meshes are colored: “solid”, “anatomy” or “colormap”.

Parameters:

appearance (Literal['solid', 'anatomy', 'colormap']) – Appearance kind. Default: “solid”

Raises:

ValueError – If it is not one of the three.

Return type:

None

set_solid_color(solid_color)[source]

Set the RGB color, in [0, 1], of the “solid” appearance.

Parameters:

solid_color (tuple[float, float, float]) – RGB triple. Default: (0.8, 0.8, 0.8)

Return type:

None

set_anatomy_type(anatomy_type)[source]

Choose one anatomy material for every mesh of the “anatomy” appearance.

None (default) instead resolves a material per mesh prim from that prim’s name, so a stage whose objects are named after the structures they hold gets per-structure materials (e.g. ventricle_left vs. myocardium). A name matching no material falls back to the object’s field_data['AnatomyGroup'] (so “rib_left_3” still reaches the bone material) and then to the “other” material.

Parameters:

anatomy_type (Optional[str]) – Material name (e.g. heart, lung, bone, soft_tissue).

Return type:

None

set_label_names(label_names)[source]

Split every mesh on its per-cell SegmentationLabelIds array.

Every structure then becomes its own prim at /World/{usd_project_name}/{group}/{structure}: time-varying across frames, or static from a single mesh. This is the only way structure identity survives a time series; without it, parts are named by connectivity-component order, which is positional per frame. None (default) reads the ids off the meshes themselves when they carry the per-cell array, and names them from the segmenter’s taxonomy - so a mesh merged by ProcessSurfaceMesh.combine_surfaces() splits by structure without further settings. A static merge accepts only one labeled mesh: several would collide on one prim path per label.

Parameters:

label_names (Optional[Mapping[int, str]]) – Mapping of label id to structure name, or None.

Return type:

None

set_colormap_primvar(colormap_primvar)[source]

Choose the primvar the “colormap” appearance colors by.

Parameters:

colormap_primvar (Optional[str]) – Primvar name (e.g. vtk_point_stress_c0). None (default) picks a candidate automatically when possible.

Return type:

None

set_colormap_name(colormap_name)[source]

Choose the Matplotlib colormap of the “colormap” appearance.

Parameters:

colormap_name (str) – Colormap name. Default: “viridis”

Return type:

None

set_colormap_intensity_range(colormap_intensity_range)[source]

Fix the (vmin, vmax) of the “colormap” appearance.

Parameters:

colormap_intensity_range (Optional[tuple[float, float]]) – Range, or None (default) for the data’s.

Return type:

None

process(input_meshes, usd_project_name, output_directory, *, time_codes=None, object_names=None)[source]

Run the full workflow: convert meshes to USD, then apply the chosen appearance.

Parameters:
  • input_meshes (Sequence[Union[DataSet, vtkDataSet]]) – One or more PyVista/VTK meshes. A single mesh, or a static merge, produces a static scene; multiple meshes without a static merge are treated as ordered time-series frames, in list order.

  • usd_project_name (str) – Project name; used as the root USD prim name (/World/{usd_project_name}) and the output filename. A trailing USD extension (.usd, .usda, .usdc) is stripped from the prim name but preserved for the output filename; if omitted, “.usd” is used.

  • output_directory (Union[str, Path]) – Directory where the output USD file is written.

  • time_codes (Optional[list[float]]) – Explicit time codes aligned to input_meshes, used for a time series. If None, uses sequential integers [0, 1, 2, …].

  • object_names (Optional[Sequence[str]]) – Prim names aligned to input_meshes, used for a static merge. None (default) derives them from each mesh’s field_data['SegmentationLabelNames'] when that holds exactly one name (as written by WorkflowConvertImageToVTK), and falls back to {usd_project_name}_{index} otherwise.

Returns:

  • “usd_file” (str): Path to the created USD file.

Return type:

Dict with the results of the workflow

Raises:

ValueError – If input_meshes is empty, or if splitting by connectivity and by cell type are both set.

import pyvista as pv
from monai_physio import WorkflowConvertVTKToUSD

input_meshes = [pv.read("heart_000.vtp"), pv.read("heart_001.vtp")]
workflow = WorkflowConvertVTKToUSD(
)
workflow.set_appearance("anatomy")
workflow.set_anatomy_type("heart")

result = workflow.process(
    input_meshes=input_meshes,
    usd_project_name="heart",
    output_directory="./output",
)
usd_file = result["usd_file"]

Statistical Shape Modeling

class monai_physio.WorkflowCreateMeanSurface(surfaces, log_level=20)[source]

Bases: MONAIPhysioBase

Compute the mean shape of N surfaces with differing point counts.

Example

>>> workflow = WorkflowCreateMeanSurface(surfaces=[s0, s1, s2])
>>> workflow.set_number_of_iterations(3)
>>> result = workflow.process()
>>> mean_surface = result["mean_surface"]
__init__(surfaces, log_level=20)[source]

Initialize the mean-surface workflow.

Parameters:
  • surfaces (list[DataSet]) – Population of surfaces to average. Point counts and topologies may differ; only the template’s topology survives.

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

Raises:

ValueError – If fewer than two surfaces are supplied.

set_template_surface(template_surface)[source]

Choose the surface giving the mean its topology and starting shape.

Defaults to the middle entry of the surfaces. With enough iterations the result no longer depends on this choice.

Parameters:

template_surface (DataSet) – Template surface (its surface is extracted).

Return type:

None

set_spatial_resolution(spatial_resolution)[source]

Set the voxel size of the distance-map grid used for registration.

Parameters:

spatial_resolution (float) – Voxel size in millimeters. Default: 1.0

Raises:

ValueError – If it is not positive.

Return type:

None

set_buffer_factor(buffer_factor)[source]

Set the padding around the template bounding box for that grid.

Parameters:

buffer_factor (float) – Fraction of the bounding box. Default: 0.25

Raises:

ValueError – If it is negative.

Return type:

None

set_number_of_iterations(number_of_iterations)[source]

Set the atlas iteration count; 1 is a single template-biased pass.

Return type:

None

set_greedy_iterations(greedy_iterations)[source]

Set the number of greedy iterations.

Return type:

None

set_icon_iterations(icon_iterations)[source]

Set the number of icon iterations.

Return type:

None

set_convergence_tolerance(convergence_tolerance)[source]

Set the RMS point motion (mm) below which iteration stops.

Return type:

None

set_icp_transform_type(transform_type)[source]

Set the ICP alignment: 'Rigid' (default), 'Similarity' or 'Affine'.

Rigid alignment keeps size differences in the averaged shape; 'Affine' averages only the residual, size-and-pose-normalized shape.

Return type:

None

set_mask_dilation_mm(mask_dilation_mm)[source]

Set the dilation (mm) of the binary masks the Greedy stage registers in.

Return type:

None

set_distance_squared_max(distance_squared_max)[source]

Set the squared millimetres the distance maps are normalized against.

The maps saturate at its square root, and a sample further than that from the template has no gradient pulling it in, so the correspondence stops short and the mean creeps toward the template.

Parameters:

distance_squared_max (float) – Saturation radius in squared millimeters.

Raises:

ValueError – If it is not positive. The maps are normalized against its square root, so zero or less saturates every voxel alike and leaves the registration nothing to descend.

Return type:

None

set_icon_weights_path(weights_path)[source]

Use a finetuned uniGradICON checkpoint for the deformable stage.

Stock weights are out of distribution for distance maps; see RegisterModelsDistanceMaps.set_icon_weights_path.

Parameters:

weights_path (str) – Path to an existing uniGradICON checkpoint.

Return type:

None

set_distance_map_transform_type(transform_type)[source]

Set the distance-map registration type used for correspondence.

'Deformable' (default) runs Greedy affine + ICON; 'Affine' and 'Rigid' stop after the Greedy stage.

Return type:

None

process()[source]

Run the atlas iteration and return the mean surface.

Return type:

dict[str, Any]

Returns:

Dict with mean_surface (template topology, mean shape), corresponded_surfaces and fixed_to_moving_transforms from the final iteration, the per-iteration iteration_rms_mm, and number_of_iterations_run.

class monai_physio.WorkflowCreateStatisticalModel(sample_meshes, reference_mesh, log_level=20)[source]

Bases: MONAIPhysioBase

Create a PCA statistical shape model from a sample of meshes aligned to a reference.

Pipeline:

  1. Extract surfaces from sample and reference meshes, or keep as meshes

  2. ICP alignment: align each sample surface to the reference (template) surface. Always extract surfaces for ICP alignment.

  3. Deformable registration: establish dense correspondence via Greedy affine + ICON deformable registration. Uses either full meshes or surfaces.

  4. Correspondence: warp reference model by each transform to get aligned shapes, optionally snapped onto the measured ICP-aligned surfaces

  5. PCA: compute mean and modes from corresponded shapes

sample_meshes

List of sample mesh DataSets (.vtk/.vtu/.vtp geometry)

Type:

list

reference_mesh

Reference mesh; its surface is used for alignment

Type:

pv.DataSet

number_of_pca_components

Number of PCA components to retain

Type:

int

reference_spatial_resolution

Resolution for reference image from mesh

Type:

float

reference_buffer_factor

Buffer around mesh for reference image

Type:

float

icp_transform_type

Alignment applied before correspondence

Type:

str

mask_dilation_mm

Dilation of the deformable stage’s masks

Type:

float

distance_squared_max

Squared mm the distance maps saturate at

Type:

float

project_to_measured_surfaces

Snap corresponded points onto the measured surfaces before the PCA

Type:

bool

projection_max_distance_mm

Residual above which a point is left unprojected

Type:

Optional[float]

pca_input_residual_rms

Per sample, the RMS distance from the corresponded shape to the measured surface, before projection

Type:

list[float]

__init__(sample_meshes, reference_mesh, log_level=20)[source]

Initialize the create-statistical-model workflow.

Options have set_* methods.

Parameters:
  • sample_meshes (list[DataSet]) – List of sample mesh DataSets (PyVista PolyData or UnstructuredGrid).

  • reference_mesh (DataSet) – Reference mesh; its surface is used to align all samples.

  • log_level (int | str) – Logging level.

set_number_of_pca_components(n)[source]

Set number of PCA components to retain.

Parameters:

n (int) – Number of components. Default: 7

Raises:

ValueError – If it is less than 1.

Return type:

None

set_reference_spatial_resolution(reference_spatial_resolution)[source]

Set the isotropic resolution of the registration reference image.

Parameters:

reference_spatial_resolution (float) – Resolution in millimeters. Default: 1.0

Raises:

ValueError – If it is not positive.

Return type:

None

set_reference_buffer_factor(reference_buffer_factor)[source]

Set the buffer around the meshes for the registration reference image.

Parameters:

reference_buffer_factor (float) – Fraction of the bounding box. Default: 0.25

Raises:

ValueError – If it is negative.

Return type:

None

set_solve_for_surface_pca(solve_for_surface_pca)[source]

Reduce the reference mesh to a surface before the PCA.

Parameters:

solve_for_surface_pca (bool) – Whether to. Default: True

Return type:

None

set_mask_dilation_mm(mask_dilation_mm)[source]

Set the dilation of the deformable stage’s binary registration masks.

Parameters:

mask_dilation_mm (float) – Dilation in millimeters. Default: 20.0

Raises:

ValueError – If it is negative.

Return type:

None

set_distance_squared_max(distance_squared_max)[source]

Set the squared millimeters the distance maps are normalized against.

The saturation radius is its square root.

Parameters:

distance_squared_max (Optional[float]) – Squared millimeters; None (default) sizes it to the mask as the fitting workflow does, (1.25 * mask_dilation_mm) ** 2.

Raises:

ValueError – If it is not positive. The maps are normalized against its square root, so zero or less saturates every voxel alike and leaves the registration nothing to descend.

Return type:

None

set_project_to_measured_surfaces(project_to_measured_surfaces)[source]

Snap each corresponded point onto the measured ICP-aligned surface.

Done before the PCA; ignored when the PCA is not solved on surfaces.

Parameters:

project_to_measured_surfaces (bool) – Whether to. Default: True

Return type:

None

set_projection_max_distance_mm(projection_max_distance_mm)[source]

Only project points whose residual is at or below this distance.

Parameters:

projection_max_distance_mm (Optional[float]) – Distance in millimeters; None (default) projects every point.

Return type:

None

set_icp_transform_type(transform_type)[source]

Set the alignment applied to each sample before correspondence.

"Affine" (default) normalizes size, anisotropic scale and shear away, leaving only residual shape for the PCA; "Rigid" keeps them as modes. Whatever is chosen, the workflow that fits the model has to align the same way, or the model is asked to explain variation its ICP has already absorbed.

Parameters:

transform_type (str) – One of "Rigid", "Similarity", "Affine".

Raises:

ValueError – If transform_type is not one of those.

Return type:

None

set_icon_weights_path(weights_path)[source]

Use a finetuned uniGradICON checkpoint for the deformable stage.

Stock weights are out of distribution for distance maps, so without this the correspondences the model is built from barely move off the template; see RegisterModelsDistanceMaps.set_icon_weights_path.

Parameters:

weights_path (str) – Path to an existing uniGradICON checkpoint.

Return type:

None

process()[source]

Run the full pipeline and return a dictionary of results (no file I/O).

Returns:

  • pca_mean_surface: pv.PolyData mean shape surface

  • pca_mean_mesh: pv.UnstructuredGrid reference volume mesh, or None if reference was surface-only

  • pca_model: dict with “explained_variance_ratio”, “eigenvalues”, “components” (same structure as pca_model.json)

  • pca_fitted: fitted sklearn PCA object

Return type:

dict with keys

class monai_physio.WorkflowFitStatisticalModelToPatient(template_model, template_labelmap=None, labelmap_interior_object_ids=None, segmentation_method=None, log_level=20)[source]

Bases: MONAIPhysioBase

Register anatomical models using multi-stage ICP, labelmap-based, and image-based

registration.

This class provides a flexible workflow for registering generic anatomical models (e.g., cardiac models) to patient-specific surface models and images. The registration pipeline combines: - Initial model alignment using RegisterModelsICPITK (centroid + configurable

ICP)

  • Labelmap-based deformable registration using RegisterModelsDistanceMaps (Greedy/ICON)

  • Optional final labelmap-to-image refinement using Icon registration

Registration Pipeline:
  1. ICP Alignment: Rough alignment using RegisterModelsICPITK, rigid,

    similarity or affine per icp_transform_type

  2. PCA Registration: Performs PCA-based shape fitting using

    RegisterModelsPCA

  3. Labelmap-to-Labelmap: Deformable registration using RegisterModelsDistanceMaps

  4. Labelmap-to-Image: Final refinement

template_model

Generic anatomical model to be registered

Type:

pv.DataSet

template_model_surface

Surface extracted from template_model_surface

Type:

pv.PolyData

template_labelmap

Multi-label labelmap for template model

Type:

itk.Image

template_mask

Binary mask for template model registration region

Type:

itk.Image

patient_models

Patient-specific models

Type:

list of pv.DataSet

patient_model_surface

Primary patient model surface (first in list)

Type:

pv.PolyData

combined_patient_model

Merged patient models before surface extraction; used when use_surface=False.

Type:

pv.PolyData

patient_image

Reference image providing coordinate frame

Type:

itk.Image

patient_labelmap

Multi-label labelmap for patient model

Type:

itk.Image

patient_mask

Binary mask for patient registration region

Type:

itk.Image

mask_dilation_mm

Dilation for binary mask generation

Type:

float

icp_transform_type

Alignment the Stage 1 ICP solves for, one of “Rigid”, “Similarity” or “Affine”. It has to match the value the statistical model was built with (set via set_icp_transform_type)

Type:

str

distance_squared_max

Saturation radius of the labelmap-to-labelmap distance maps, in squared millimeters. None means derive it from mask_dilation_mm as (1.25 * mask_dilation_mm)**2

Type:

Optional[float]

transform_tools

Transform utilities

Type:

ProcessTransforms

registrar_icon

ICON registration instance

Type:

RegisterImagesICON

registrar_greedy

Greedy registration instance

Type:

RegisterImagesGreedy

use_pca_registration

Whether PCA registration is enabled (set via set_use_pca_registration)

Type:

bool

pca_model

PCA model dict when PCA enabled; same structure as WorkflowCreateStatisticalModel output

Type:

dict

number_of_pca_components

Number of PCA components when PCA enabled

Type:

int

labelmap_interior_object_ids

List of labelmap IDs corresponding to interior objects that should not be used when computing a distance map.

Type:

list

icp_moving_to_fixed_transform

ICP transforms

icp_fixed_to_moving_transform

ICP inverse transforms

icp_template_model_surface

template model surface after ICP alignment

icp_template_model

template model (UnstructuredGrid) after ICP alignment

pca_coefficients

PCA shape coefficients (if PCA used)

pca_template_model

template model after PCA registration (if PCA used)

Type:

pv.DataSet

pca_template_model_surface

template model surface after PCA registration (if PCA used)

l2l_fixed_to_moving_transform

Labelmap-to-labelmap fixed-to-moving transform

l2l_moving_to_fixed_transform

Labelmap-to-labelmap moving-to-fixed transform

l2l_template_model_surface

template model surface after labelmap-to-labelmap registration

l2i_fixed_to_moving_transform

Labelmap-to-image fixed-to-moving transform

l2i_moving_to_fixed_transform

Labelmap-to-image moving-to-fixed transform

l2i_template_model_surface

template model surface after labelmap-to-image registration

l2i_template_labelmap

template labelmap after labelmap-to-image registration

fitted_reference_model

Final registered model

fitted_reference_mesh

Final registered model surface

Example

>>> # Initialize with minimal parameters (no labelmap; no patient image -> reference created from patient models)
>>> registrar = WorkflowFitStatisticalModelToPatient(template_model=heart_model)
>>> registrar.set_mask_dilation_mm(20)
>>> # To enable PCA registration, call before process():
>>> # registrar.set_use_pca_registration(True, pca_model=pca_model_dict, number_of_pca_components=10)
>>> # To enable labelmap-to-image refinement:
>>> # registrar.set_use_labelmap_to_image_registration(True, template_labelmap, organ_mesh_ids, organ_extra_ids, background_ids)
>>> result = registrar.process(patient_models=[lv_model, mc_model, rv_model])
__init__(template_model, template_labelmap=None, labelmap_interior_object_ids=None, segmentation_method=None, log_level=20)[source]

Initialize the model-to-image-and-model registration pipeline.

The patient is given to process() (or prepare_patient(), when the stages are run one by one); options have set_* methods.

Parameters:
  • template_model (DataSet) – Generic anatomical model to be registered

  • template_labelmap (Optional[Image]) – Optional labels propagated with the fitted template.

  • labelmap_interior_object_ids (Optional[list]) – Optional list of labelmap IDs that should not be used when computing the distance map since they are interior (surrounded by other objects).

  • segmentation_method (Optional[SegmentAnatomyBase]) – Segmentation backend instance used by WorkflowConvertImageToVTK when a patient is given as an image without models. Defaults to a new SegmentHeartSimplewareTrimmedBranches (matches KCL-Heart-Model template extent) when None.

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

Raises:

TypeError – If segmentation_method is neither None nor a SegmentAnatomyBase instance.

set_fitting_crop_margin_mm(fitting_crop_margin_mm)[source]

Crop the fitting grid to the patient labelmap’s nonzero bounds plus a margin.

Applied before resampling. It needs a patient image and labelmap on the same grid. With either fitting option, labelmaps are resampled with nearest-neighbor interpolation before distance maps are constructed. Choose the options for the anatomy and validate fit accuracy; they do not change mesh physical coordinates.

Parameters:

fitting_crop_margin_mm (Optional[float]) – Margin in millimeters; None (default) keeps the full image.

Raises:

ValueError – If it is negative or not finite.

Return type:

None

set_fitting_spacing_mm(fitting_spacing_mm)[source]

Fit on an isotropic grid of this spacing.

The original CT is retained as original_patient_image for full-resolution warping.

Parameters:

fitting_spacing_mm (Optional[float]) – Spacing in millimeters; None (default) keeps the finest spacing of the patient image.

Raises:

ValueError – If it is not finite and positive.

Return type:

None

set_use_icon_registration_refinement(use_icon_registration_refinement)[source]

Apply ICON refinement in the labelmap-to-image stage.

The labelmap-to-labelmap stage is unaffected.

Parameters:

use_icon_registration_refinement (bool) – Whether to. Default: False

Return type:

None

prepare_patient(patient_models=None, patient_image=None, patient_labelmap=None)[source]

Set the patient the stages fit to; process() calls this first.

Call it directly only to run the stages one by one.

Parameters:
  • patient_models (Optional[list[DataSet]]) – Patient-specific models extracted from imaging data. Typically 3 models for cardiac applications: LV, myocardium, RV. When None, they are segmented from patient_image (heart group).

  • patient_image (Optional[Image]) – Optional patient image providing the target coordinate frame. If None, a reference image is created from the patient model surface via create_reference_image.

  • patient_labelmap (Optional[Image]) – Optional anatomy-specific patient labels for PCA’s distance map and, when requested, the fitting crop bounds.

Raises:

ValueError – If neither patient_models nor patient_image is given, or a fitting crop is set without a patient image and labelmap.

Return type:

None

set_mask_dilation_mm(mask_dilation_mm)[source]

Set dilation amount for binary registration masks.

Parameters:

mask_dilation_mm (float) – Dilation amount in millimeters for binary registration mask generation. Default: 10mm

Return type:

None

set_icp_transform_type(transform_type)[source]

Set the ICP alignment applied to the template before the PCA fit.

This has to match the alignment the model was built with – see WorkflowCreateStatisticalModel.set_icp_transform_type – because whatever the ICP absorbs here is variation the eigenmodes never saw.

Parameters:

transform_type (str) – One of "Rigid", "Similarity", "Affine".

Raises:

ValueError – If transform_type is not one of those.

Return type:

None

set_distance_squared_max(distance_squared_max)[source]

Set the saturation radius of the labelmap-to-labelmap distance maps.

The radius fixes those images’ intensity distribution, so it has to match the value the ICON weights in use were finetuned at – see tutorials/parameters_tcia_lung_4d_ct.py (lung) and tutorials/parameters_duke_heart_4d_labelmaps.py (heart), which carry one value per organ. Left unset, it is derived from mask_dilation_mm.

Parameters:

distance_squared_max (float) – Maximum squared distance, in squared millimeters, the distance maps are normalized against.

Return type:

None

set_labelmap_to_labelmap_icon_weights_path(weights_path)[source]

Set a finetuned ICON checkpoint for the labelmap-to-labelmap stage.

That stage (register_labelmap_to_labelmap()) registers distance maps rather than image intensities, so it benefits from weights finetuned on distance maps – e.g. by tutorials/tutorial_02_finetune_icon_distancemap_tcia_lung_4d_ct.py. The labelmap-to-image stage keeps the stock weights: it registers the patient image itself.

Parameters:

weights_path (str) – Path to an existing uniGradICON checkpoint.

Raises:

FileNotFoundError – If weights_path does not exist.

Return type:

None

set_l2l_deformable_engine(deformable_engine)[source]

Set which engine runs the labelmap-to-labelmap stage’s nonrigid step.

Parameters:

deformable_engine (str) – ‘icon’ (Greedy affine + ICON deformable, default) or ‘greedy’ (Greedy’s own affine + warp, no ICON).

Raises:

ValueError – If deformable_engine is not ‘icon’ or ‘greedy’.

Return type:

None

set_use_pca_registration(use_pca_registration, pca_model=None, number_of_pca_components=0, use_surface=False)[source]

Set whether to use PCA-based registration and provide the PCA model.

When enabling (True), pca_model and number_of_pca_components must be provided.

Parameters:
  • use_pca_registration (bool) – Whether to use PCA registration after ICP.

  • pca_model (Optional[dict[str, Any]]) – Required when use is True. PCA model dict (e.g. from WorkflowCreateStatisticalModel result[“pca_model”]) with keys “eigenvalues” and “components”.

  • number_of_pca_components (int) – Required when use is True. Number of PCA components to use. Default 0 means use all components. A count larger than the model actually carries is reduced to what it carries; see below.

  • use_surface (bool) – Whether to use the surface of the patient model for PCA registration.

Raises:

ValueError – If use is True and pca_model is None.

Return type:

None

set_use_labelmap_to_labelmap_registration(use_labelmap_to_labelmap_registration)[source]

Set whether to use labelmap-to-labelmap registration.

Parameters:

use_labelmap_to_labelmap_registration (bool) – Whether to use labelmap-to-labelmap deformable registration. Default: True

Return type:

None

set_use_labelmap_to_image_registration(use_labelmap_to_image_registration, template_labelmap=None, template_labelmap_organ_mesh_ids=None, template_labelmap_organ_extra_ids=None, template_labelmap_background_ids=None)[source]

Set whether to use labelmap-to-image registration.

When enabling (True), a template labelmap and label IDs must be provided so the workflow can propagate and refine the labelmap to the patient image.

Parameters:
  • use_labelmap_to_image_registration (bool) – Whether to use labelmap-to-image registration.

  • template_labelmap (Optional[Image]) – Template labelmap in template model space (same geometry as template_model). Required when use is True unless one was already supplied to the constructor, in which case that value is used.

  • template_labelmap_organ_mesh_ids (Optional[list[int]]) – Required when use is True. Label IDs for organ mesh in the template labelmap.

  • template_labelmap_organ_extra_ids (Optional[list[int]]) – Required when use is True. Label IDs for organ-extra structures in the template labelmap.

  • template_labelmap_background_ids (Optional[list[int]]) – Required when use is True. Label IDs for background in the template labelmap.

Raises:

ValueError – If use is True and any of template_labelmap or the id lists is None or missing.

Return type:

None

register_model_to_model_icp()[source]

Perform ICP alignment of template model to patient model.

Uses RegisterModelsICPITK class for ICP alignment. With a custom fitting grid, propagated labels include the aligned template and registration margins outside the patient crop.

Returns:

Dictionary containing:
  • ’fixed_to_moving_transform’: used to warp an image from model to patient space

  • ’moving_to_fixed_transform’: used to warp an image from patient to model space

  • ’fitted_reference_mesh’: Transformed model model surface

Return type:

dict

register_model_to_model_pca()[source]

Perform PCA-based registration after ICP alignment.

Uses RegisterModelsPCA to optimize shape coefficients against a distance map of the patient. The statistical model’s modes are defined in the un-aligned template frame, so the registrar is given the raw template and the ICP alignment is passed as its post_pca_transform. With a custom fitting grid, propagated labels include the fitted template and registration margins outside the patient crop.

Returns:

Dictionary containing:
  • ’moving_to_fixed_transform’: DisplacementFieldTransform mapping un-aligned template points to their PCA-deformed positions. It excludes the ICP alignment, which is applied separately.

  • ’fixed_to_moving_transform’: its inverse

  • ’pca_coefficients’: PCA shape coefficients

  • ’fitted_reference_mesh’: PCA-registered model surface

Return type:

dict

Raises:

ValueError – If PCA data has not been set

register_labelmap_to_labelmap()[source]

Perform labelmap-based deformable registration of template model to patient model.

Uses RegisterModelsDistanceMaps with Greedy affine followed by ICON deformable registration on distance maps derived from the model surfaces. With a custom fitting grid, propagated labels remain on an expanded grid for subsequent intensity refinement.

Returns:

Dictionary containing:
  • ’fixed_to_moving_transform’: template to patient space transform

  • ’moving_to_fixed_transform’: patient to template space transform

  • ’fitted_reference_mesh’: Transformed template model surface

  • ’fitted_reference_labelmap’: Transformed template labelmap

Return type:

dict

register_labelmap_to_image(use_icon_refinement=False)[source]

Perform labelmap-to-image refinement.

Uses registration to align the propagated template labelmap to actual image intensities.

Returns:

Dictionary containing:
  • ’moving_to_fixed_transform’: patient to template space transform

  • ’fixed_to_moving_transform’: template to patient space transform

  • ’fitted_reference_mesh’: Transformed template model surface

  • ’fitted_reference_labelmap’: Transformed template labelmap

Return type:

dict

transform_model(base_model=None)[source]

Apply registration transforms to the model.

Transforms the model through all registration stages.

Parameters:

base_model (Optional[DataSet]) – Base model for generating the new model. If None, the template model is used.

Returns:

Registered model

Return type:

pv.DataSet

process(patient_models=None, patient_image=None, patient_labelmap=None)[source]

Execute the complete multi-stage registration workflow.

Runs registration stages in sequence:

  1. ICP alignment (RegisterModelsICPITK)

  2. PCA registration (PCA data was provided)

  3. Labelmap-to-labelmap deformable registration (RegisterModelsDistanceMaps)

  4. Optional labelmap-to-image refinement (Icon); requires template labelmap and IDs

    set via set_use_labelmap_to_image_registration(True, …).

Parameters:
Return type:

dict

Returns:

dict with fitted_reference_model and fitted_reference_mesh

Progress, when set_progress_callback() set a callback, is reported with messages prefixed by the stage name (“ICP”, “PCA”, “Labelmap-to-labelmap”, “Labelmap-to-image” or “Apply transforms”). Each stage owns a fixed share of the range, sized to its typical cost with every stage enabled; a disabled stage is skipped over.

import itk
import pyvista as pv

from monai_physio import WorkflowFitStatisticalModelToPatient

workflow = WorkflowFitStatisticalModelToPatient(
    template_model=pv.read("template_heart.vtu"),
)

result = workflow.process(
    patient_models=[pv.read("lv.vtp"), pv.read("rv.vtp")],
    patient_image=itk.imread("patient_ct.nii.gz"),
)

4D Image Reconstruction

class monai_physio.WorkflowReconstruct4D(registration_method=None, log_level=20)[source]

Bases: MONAIPhysioBase

Reconstruct 4D CT or MRI from time series and reference image.

This class implements a workflow for reconstructing dynamic images by registering time-series images to a reference image (often of higher resolution) using a caller-supplied registration backend.

Registration Pipeline:
  1. Time Series Registration: Register each time-series image to the reference image using RegisterTimeSeriesImages

  2. Reconstruction: Apply inverse transforms to carry the reference image to every time point

  3. Optional Upsampling: Resample to the reference image’s resolution

Input Requirements:
  • time_series_images: Ordered list of 3D images (typically lower resolution)

  • reference_image: Reference image, often of higher resolution

  • All images should be in the same anatomical coordinate system

  • CT by default; call set_modality("mri") for MRI

registration_method accepts a pre-configured RegisterImagesBase instance. Configure backend-specific parameters (iteration counts, etc.) on the instance before passing it in. Defaults to a new RegisterImagesGreedy when omitted.

time_series_images

Ordered list of time-series images

Type:

list[itk.Image]

reference_image

Reference image

Type:

itk.Image

reference_time_frame

Index of reference time frame in time series

Type:

int

register_reference_time_frame_to_reference_image

Whether to register the reference time frame to the reference image

Type:

bool

upsample_to_fixed_resolution

Whether to upsample reconstruction

Type:

bool

composite_mode

Which image is warped back to each time point: “reference” uses the reference image as-is; “mean”, “max”, or “percentile” combine it with all registered time-series images

Type:

str

composite_percentile

Percentile in [0, 100] for “percentile” mode. Default: 95.0

Type:

float

registrar

Internal registration object

Type:

RegisterTimeSeriesImages

fixed_to_moving_transforms

one per frame; each warps its moving image onto the reference grid

Type:

list[itk.Transform]

moving_to_fixed_transforms

one per frame; each warps the reference image onto that frame’s moving grid (used for reconstruction)

Type:

list[itk.Transform]

losses

Registration loss values

Type:

list[float]

reconstructed_images

Reconstructed images

Type:

list[itk.Image]

Example

>>> workflow = WorkflowReconstruct4D()
>>> result = workflow.process(
...     time_series_images=time_series_images,
...     reference_image=reference_image,
...     reference_time_frame=7,
... )
>>>
>>> # Access results
>>> reconstructed = result['reconstructed_images']
>>> transforms = result['fixed_to_moving_transforms']
>>> losses = result['losses']
__init__(registration_method=None, log_level=20)[source]

Initialize the 4D image reconstruction workflow.

The series is given to process() (or prepare_series(), when the stages are run one by one); options have set_* methods.

Parameters:
  • registration_method (Optional[RegisterImagesBase]) – Registration backend instance. Defaults to a new RegisterImagesGreedy when None.

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

Raises:

TypeError – If registration_method is neither None nor a RegisterImagesBase instance

set_modality(modality)[source]

Set the imaging modality for registration optimization.

Parameters:

modality (str) – The imaging modality, ‘ct’ (default) or ‘mri’

Return type:

None

set_mask_dilation_mm(mask_dilation_mm)[source]

Set the dilation of the fixed and moving image masks.

Parameters:

mask_dilation_mm (float) – The dilation in millimeters

Return type:

None

set_register_reference_time_frame_to_reference_image(register_reference_time_frame_to_reference_image)[source]

Register the reference time frame to the reference image.

If False, that frame gets an identity transform.

Parameters:

register_reference_time_frame_to_reference_image (bool) – Whether to. Default: True

Return type:

None

prepare_series(time_series_images, reference_image, reference_time_frame=0, fixed_mask=None, moving_masks=None)[source]

Set the series the stages work on; process() calls this first.

Call it directly only to run the stages one by one.

Parameters:
  • time_series_images (list[Image]) – Ordered list of 3D time-series images to be registered and reconstructed.

  • reference_image (Image) – 3D reference image.

  • reference_time_frame (int) – Index of the reference time frame in the time series. Registration proceeds bidirectionally from this frame. Default: 0

  • fixed_mask (Optional[Image]) – Optional binary mask of the reference image’s region of interest.

  • moving_masks (Optional[list[Optional[Image]]]) – Optional binary masks, one per time-series image.

Raises:

ValueError – If time_series_images is empty, reference_time_frame is out of range, or moving_masks does not match the series length.

Return type:

None

register_time_series()[source]

Register time series images to the fixed image.

Performs sequential registration of all time-series images to the reference image using the configured parameters.

Returns:

Dictionary containing:
  • ’fixed_to_moving_transforms’ (list[itk.Transform]): one per frame; each warps its moving image onto the reference grid

  • ’moving_to_fixed_transforms’ (list[itk.Transform]): one per frame; each warps the reference image onto that frame’s moving grid (see docs/developer/transform_conventions)

  • ’losses’ (list[float]): Registration loss value for each image

Return type:

dict

Raises:

RuntimeError – If registration fails

get_composite_reference_image()[source]

Build the configured mean, max, or percentile reconstruction source.

Percentile mode uses composite_percentile (95.0 by default).

Returns:

The composite source, or None in reference mode

Return type:

Optional[itk.Image]

set_upsample_to_fixed_resolution(upsample_to_fixed_resolution)[source]

Set whether to upsample the reconstructed time series to the fixed resolution.

Parameters:

upsample_to_fixed_resolution (bool) – Whether to upsample the reconstructed time series to the fixed resolution.

Return type:

None

set_composite_mode(composite_mode, percentile=95.0)[source]

Set which image is warped back to each time point during reconstruction.

Parameters:
  • composite_mode (str) – “reference” warps the reference image back to each time point (default). “mean”/”max”/”percentile” first build a composite of the reference image and every registered time-series image, then warp it back to each time point instead.

  • percentile (float, optional) – Percentile in [0, 100], used only for “percentile” mode, with linear interpolation between samples. Out-of-coverage samples are excluded. Default: 95.0

Raises:

ValueError – If composite_mode is not one of “reference”, “mean”, “max”, or “percentile”, or percentile is not finite and within [0, 100] in “percentile” mode

Return type:

None

reconstruct_time_series()[source]

Reconstruct the time series using inverse transforms.

Applies the inverse transforms from registration to reconstruct each time-series image in the fixed (reference) image space. The source is selected by composite_mode; “percentile” uses composite_percentile.

Returns:

Dictionary containing:
  • ’reconstructed_images’ (list[itk.Image]): Reconstructed time-series images

Return type:

dict

Raises:
  • RuntimeError – If reconstruction fails

  • ValueError – If moving_to_fixed_transforms is not set (call register_time_series first)

process(time_series_images, reference_image, reference_time_frame=0, fixed_mask=None, moving_masks=None)[source]

Execute the complete 4D image reconstruction workflow.

Runs the full pipeline: 1. Register the time series to the reference image 2. Reconstruct the time series using inverse transforms

Parameters:
Returns:

Dictionary containing all results:
  • ’fixed_to_moving_transforms’ (list[itk.Transform]): Registration transforms

  • ’moving_to_fixed_transforms’ (list[itk.Transform]): Inverse transforms

  • ’losses’ (list[float]): Registration loss values

  • ’reconstructed_images’ (list[itk.Image]): Reconstructed images

Return type:

dict

Raises:

RuntimeError – If any stage of the workflow fails

import itk

from monai_physio import RegisterImagesGreedyICON, WorkflowReconstruct4D

time_series_images = [itk.imread(f"phase_{idx:02d}.mha") for idx in range(10)]
workflow = WorkflowReconstruct4D(
    registration_method=RegisterImagesGreedyICON(),
)

workflow.set_modality("ct")
result = workflow.process(
    time_series_images=time_series_images,
    reference_image=time_series_images[0],
    reference_time_frame=0,
)

Finetune ICON Registration

class monai_physio.WorkflowFinetuneICONRegistration(subject_image_files, output_directory, finetune_name, subject_ids=None, subject_labelmap_files=None, subject_mask_files=None, subject_landmark_files=None, log_level=20)[source]

Bases: MONAIPhysioBase

Finetune uniGradICON on paired 3D images.

Build a paired dataset JSON and YAML config from per-subject lists of image, labelmap, and landmark files, then launch unigradicon.finetuning.finetune as a subprocess. Each subject’s time-point images form one paired group (they share a subject_id).

subject_image_files

Per-subject lists of image paths. Images within one inner list share a subject_id during finetuning.

Type:

list[list[str]]

output_directory

Directory where the dataset JSON, YAML config, and the uniGradICON checkpoints/ tree are written.

Type:

Path

finetune_name

Sub-directory name for the experiment outputs.

Type:

str

subject_ids

One ID per subject (e.g. patient identifiers). Written into the dataset JSON’s subject_id field; falls back to synthetic subject_NNNN when None.

Type:

Optional[list[str]]

subject_labelmap_files

Per-subject multi-label labelmap paths aligned with subject_image_files. None (or per-image None) means no labelmap for that image. If supplied for at least one image, paired-with-seg training is enabled.

Type:

Optional[list[list[Optional[str]]]]

subject_mask_files

Per-subject binary mask paths aligned with subject_image_files, used for loss-function masking. None disables masking.

Type:

Optional[list[list[Optional[str]]]]

subject_landmark_files

Per-subject landmark CSV paths (Name,X,Y,Z format) aligned with subject_image_files. Recorded in the dataset JSON for traceability; not consumed by uniGradICON finetuning itself.

Type:

Optional[list[list[Optional[str]]]]

Example

>>> workflow = WorkflowFinetuneICONRegistration(
...     subject_image_files=[
...         ['pm0001/g000.nii.gz', 'pm0001/g050.nii.gz'],
...         ['pm0002/g000.nii.gz', 'pm0002/g050.nii.gz'],
...     ],
...     output_directory=Path('d:/MONAI-Physio/icon_finetuned'),
...     finetune_name='duke_4d_gated_icon_ft',
...     subject_labelmap_files=[
...         ['pm0001/g000_labelmap.nii.gz', 'pm0001/g050_labelmap.nii.gz'],
...         ['pm0002/g000_labelmap.nii.gz', 'pm0002/g050_labelmap.nii.gz'],
...     ],
... )
>>> weights_path = workflow.process()
__init__(subject_image_files, output_directory, finetune_name, subject_ids=None, subject_labelmap_files=None, subject_mask_files=None, subject_landmark_files=None, log_level=20)[source]

Initialize the ICON finetuning workflow.

Parameters:
  • subject_image_files (list[list[str]]) – Per-subject lists of image file paths. Each inner list groups frames belonging to one subject; all of those frames share a subject_id for paired training.

  • output_directory (Path) – Directory for the dataset JSON, YAML config, and the uniGradICON checkpoint tree.

  • finetune_name (str) – Sub-directory name for the experiment outputs (used as the uniGradICON experiment.name stem).

  • subject_ids (Optional[list[str]]) – One ID per subject, in the same order as subject_image_files. Written verbatim into the dataset JSON’s subject_id field so paired training groups frames that share an ID. None falls back to synthetic IDs of the form subject_0000, subject_0001, … Must be unique.

  • subject_labelmap_files (Optional[list[list[Optional[str]]]]) – Per-subject multi-label segmentation (labelmap) paths matching subject_image_files. None disables paired-with-seg training. Individual None entries inside the inner lists skip just those frames when paired-with-seg training is enabled.

  • subject_mask_files (Optional[list[list[Optional[str]]]]) – Per-subject binary mask paths matching subject_image_files, used for ICON loss-function masking. None disables loss-function masking. Per-image None entries skip just those frames.

  • subject_landmark_files (Optional[list[list[Optional[str]]]]) – Per-subject landmark CSV paths matching subject_image_files. Stored in the dataset JSON for traceability; not consumed by uniGradICON finetuning.

  • log_level (Union[int, str]) – Logging level (logging.DEBUG, logging.INFO, …).

Raises:
  • ValueError – If subject_image_files is empty.

  • ValueError – If subject_labelmap_files, subject_mask_files, or subject_landmark_files is provided with a shape that does not match subject_image_files.

set_epochs(epochs)[source]

Set the uniGradICON training.epochs.

Parameters:

epochs (int) – Value. Default: 500

Raises:

ValueError – If it is not positive.

Return type:

None

set_batch_size(batch_size)[source]

Set the uniGradICON training.batch_size.

Parameters:

batch_size (int) – Value. Default: 4

Raises:

ValueError – If it is not positive.

Return type:

None

set_learning_rate(learning_rate)[source]

Set the uniGradICON training.learning_rate.

Parameters:

learning_rate (float) – Value. Default: 5e-5

Raises:

ValueError – If it is not positive.

Return type:

None

set_input_shape(input_shape)[source]

Set the uniGradICON training.input_shape (voxels, X/Y/Z).

Parameters:

input_shape (tuple[int, int, int]) – Value. Default: (175, 175, 175)

Return type:

None

set_similarity(similarity)[source]

Set the uniGradICON training.similarity metric, e.g. lncc.

Parameters:

similarity (str) – Value. Default: “lncc”

Return type:

None

set_lambda_value(lambda_value)[source]

Set the uniGradICON training.lambda regularization weight.

Parameters:

lambda_value (float) – Value. Default: 1.5

Raises:

ValueError – If it is negative.

Return type:

None

set_dice_loss_weight(dice_loss_weight)[source]

Set the uniGradICON training.dice_loss_weight.

Parameters:

dice_loss_weight (float) – Value. Default: 0.5

Raises:

ValueError – If it is negative.

Return type:

None

set_lncc_sigma(lncc_sigma)[source]

Set the uniGradICON training.lncc_sigma.

Parameters:

lncc_sigma (int) – Value. Default: 1

Raises:

ValueError – If it is not positive.

Return type:

None

set_ct_window(ct_window)[source]

Set the uniGradICON dataset ct_window [low, high] in HU.

Parameters:

ct_window (tuple[float, float]) – Value. Default: (-1000.0, 1000.0)

Return type:

None

set_is_ct(is_ct)[source]

Mark the dataset as CT (passed through to the dataset config).

Parameters:

is_ct (bool) – Value. Default: True

Return type:

None

set_gpus(gpus)[source]

Set the GPU device indices for training; None means [0].

Parameters:

gpus (Optional[list[int]]) – Value. Default: None

Return type:

None

set_eval_period(eval_period)[source]

Set the uniGradICON training.eval_period.

Parameters:

eval_period (int) – Value. Default: 10

Raises:

ValueError – If it is not positive.

Return type:

None

set_save_period(save_period)[source]

Set the uniGradICON training.save_period.

Parameters:

save_period (int) – Value. Default: 50

Raises:

ValueError – If it is not positive.

Return type:

None

set_unigradicon_src_path(unigradicon_src_path)[source]

Set a local uniGradICON source tree to prepend to PYTHONPATH.

Finetuning then uses that checked-out copy instead of the installed package; None uses the installed package.

Parameters:

unigradicon_src_path (Optional[Path]) – Value. Default: None

Return type:

None

set_seed(seed)[source]

Set the uniGradICON training.seed.

It seeds Python, NumPy and PyTorch at startup. GPU training is still not bit-reproducible, as uniGradICON’s 3-D grid_sample backward has no deterministic CUDA kernel.

Parameters:

seed (Optional[int]) – Seed, or None to leave training unseeded. Default: 0

Return type:

None

prepare_dataset(use_labelmaps=None, use_masks=None)[source]

Write the uniGradICON dataset JSON from the configured file lists.

Builds one entry per image with image, optional segmentation, optional mask, optional landmarks (path only), and a subject_id derived from the inner-list index.

Masks come from subject_mask_files only; none are derived. Frames are skipped (with a log warning) when a required companion (segmentation for paired-with-seg training, or mask for loss-function masking) is missing.

Return type:

Path

Returns:

Path to the dataset JSON written under experiment_dir.

Raises:

FileNotFoundError – If an image listed in subject_image_files does not exist on disk.

prepare_config(dataset_json_path=None)[source]

Write the uniGradICON finetuning YAML config.

Parameters:

dataset_json_path (Optional[Path]) – Path to the dataset JSON to reference. Defaults to the JSON last produced by prepare_dataset().

Return type:

Path

Returns:

Path to the YAML config written under experiment_dir.

Raises:

ValueError – If no dataset JSON path is available.

expected_weights_path()[source]

Return the path uniGradICON writes its final checkpoint to.

unigradicon.finetuning.finetune writes <experiment.name>/checkpoints/network_weights_final.trch at the end of training – its NETWORK_WEIGHTS_PREFIX plus the "final" epoch label. Also the return value of process().

The filename is hard-coded rather than imported to keep the training package in its subprocess instead of importing it here. An upstream rename is caught by test_expected_weights_path_layout, which compares this filename against NETWORK_WEIGHTS_PREFIX wherever the submodule is installed, and by the FileNotFoundError process() raises when the checkpoint is not where this says it should be.

Return type:

Path

process()[source]

Build configs and launch unigradicon.finetuning.finetune.

Equivalent to running prepare_dataset() → prepare_config() → subprocess launch. Any existing dataset JSON or YAML in experiment_dir is overwritten.

Return type:

Path

Returns:

Path to the final checkpoint (network_weights_final.trch). The file is written by the subprocess and exists only after a successful run.

Raises:
from monai_physio import RegisterImagesICON, WorkflowFinetuneICONRegistration

workflow = WorkflowFinetuneICONRegistration(
    subject_image_files=subject_image_files,
    output_directory=weights_dir,
    finetune_name="my_cohort",
    subject_ids=subject_ids,
)
workflow.set_epochs(100)
weights_path = workflow.process()

registrar = RegisterImagesICON()
registrar.set_weights_path(str(weights_path))

See Also