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 |
|---|---|
Convert a 4D cardiac CT sequence into animated USD anatomy. |
|
Segment one CT image and export anatomy-group VTK surfaces. |
|
Convert VTK/VTP/VTU meshes or time series into USD. |
|
Build an unbiased mean surface (atlas) from a population, for use as the reference a shape model is built against. |
|
Build a PCA shape model from sample meshes aligned to a reference. |
|
Fit a template/statistical heart model to patient-specific surfaces. |
|
Reconstruct a 4D image series (CT, MRI) by registering its phase images to a reference image. |
|
Finetune uniGradICON on your own cohort and return the weights
|
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:
MONAIPhysioBaseComplete 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_methodandregistration_methodaccept a pre-configuredSegmentAnatomyBase/RegisterImagesBaseinstance. Configure backend-specific parameters (iteration counts, trim_branches, mass preservation, etc.) on the instance before passing it in. Defaults toSegmentChestTotalSegmentatorWithContrast/RegisterImagesGreedywhen 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 haveset_*methods.- Parameters:
segmentation_method (Optional[SegmentAnatomyBase]) – Segmentation backend instance. Defaults to a new
SegmentChestTotalSegmentatorWithContrastwhen None.registration_method (Optional[RegisterImagesBase]) – Registration backend instance. Defaults to a new
RegisterImagesGreedywhen None. A caller-supplied instance is mutated (fixed image/mask/modality) duringprocess()- pass a fresh instance per run unless intentionally reusing state.log_level (
int|str) – Logging level (default: logging.INFO)
- 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.
- 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:
- 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:
- 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:
- 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().
- 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.
- set_save_assets(save_assets)[source]
Write registered images, transforms and labelmaps to the output directory.
- set_save_transforms(save_transforms)[source]
Also write each frame’s forward and inverse
.hdftransforms.Applies only when assets are saved.
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:
MONAIPhysioBaseTurn a CT image or a labelmap into per-group and per-label VTK surfaces.
segmentation_methodaccepts a pre-configuredSegmentAnatomyBaseinstance (e.g.SegmentChestTotalSegmentator,SegmentChestTotalSegmentatorWithContrastfor contrast-enhanced studies,SegmentHeartSimpleware, orSegmentHeartSimplewareTrimmedBranchesfor cardiac-only segmentation with pulmonary/great-vessel branches trimmed). Defaults to a newSegmentChestTotalSegmentatorWithContrastwhen omitted. Its taxonomy names the labels and groups, so it is also needed whenprocess()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 (seeanatomy_groups); passgroupstoprocess()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 fromProcessUSDAnatomy.cell_data['Color']- RGBA uint8 array (n_cells x 4) for direct VTK rendering.
I/O contract
process()performs no file I/O. Usesave_surfaces()andsave_combined_surfaces()- or the CLImonai-physio-convert-image-to-vtk- to write results to disk.- __init__(segmentation_method=None, log_level=20)[source]
Initialize the workflow.
- Parameters:
segmentation_method (
Optional[SegmentAnatomyBase]) – Segmentation backend instance. Defaults to a newSegmentChestTotalSegmentatorWithContrastwhen None.log_level (
int|str) – Logging level. Default:logging.INFO.
- 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.0keeps them all, and only then do neighboring surfaces share their walls exactly; seeProcessSurfaceMesh.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:
- set_extract_label_surfaces(extract_label_surfaces)[source]
Also extract one surface per structure (label) of the processed groups.
For example
left_ventricleandright_ventricleseparately withinheart.
- 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:
- 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:
- 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:
- 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 byanatomy_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.Noneuses 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:
dictwith 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 valueprocess()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:
- 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 ascell_data['Color'], but not the per-objectfield_data; usesave_surfaces()when structure names must be recoverable from the saved files.- Parameters:
- Return type:
- 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:
MONAIPhysioBaseWorkflow 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 haveset_*methods.- Parameters:
segmenter (
Optional[SegmentAnatomyBase]) – Segmenter whose taxonomy groups the labels ofset_label_names()(or of the meshes’ per-cell label array) by anatomy type. Also selects each structure’s material when the appearance is “anatomy”, throughProcessUSDAnatomy.enhance_meshes(), which falls back to the containing group for a structure with no material of its own.
- 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().
- 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().
- 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:
- set_extract_surface(extract_surface)[source]
Extract the surface of volumetric meshes before conversion.
- 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).
- 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:
- 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.
- set_label_names(label_names)[source]
Split every mesh on its per-cell
SegmentationLabelIdsarray.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 byProcessSurfaceMesh.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.
- set_colormap_primvar(colormap_primvar)[source]
Choose the primvar the “colormap” appearance colors by.
- set_colormap_name(colormap_name)[source]
Choose the Matplotlib colormap of the “colormap” appearance.
- set_colormap_intensity_range(colormap_intensity_range)[source]
Fix the (vmin, vmax) of the “colormap” appearance.
- 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’sfield_data['SegmentationLabelNames']when that holds exactly one name (as written byWorkflowConvertImageToVTK), 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:
MONAIPhysioBaseCompute 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:
- 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:
- 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:
- 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:
- set_number_of_iterations(number_of_iterations)[source]
Set the atlas iteration count;
1is a single template-biased pass.- Return type:
- set_convergence_tolerance(convergence_tolerance)[source]
Set the RMS point motion (mm) below which iteration stops.
- Return type:
- 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:
- set_mask_dilation_mm(mask_dilation_mm)[source]
Set the dilation (mm) of the binary masks the Greedy stage registers in.
- Return type:
- 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:
- 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.
- 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:
- class monai_physio.WorkflowCreateStatisticalModel(sample_meshes, reference_mesh, log_level=20)[source]
Bases:
MONAIPhysioBaseCreate a PCA statistical shape model from a sample of meshes aligned to a reference.
Pipeline:
Extract surfaces from sample and reference meshes, or keep as meshes
ICP alignment: align each sample surface to the reference (template) surface. Always extract surfaces for ICP alignment.
Deformable registration: establish dense correspondence via Greedy affine + ICON deformable registration. Uses either full meshes or surfaces.
Correspondence: warp reference model by each transform to get aligned shapes, optionally snapped onto the measured ICP-aligned surfaces
PCA: compute mean and modes from corresponded shapes
- reference_mesh
Reference mesh; its surface is used for alignment
- Type:
pv.DataSet
- project_to_measured_surfaces
Snap corresponded points onto the measured surfaces before the PCA
- Type:
- pca_input_residual_rms
Per sample, the RMS distance from the corresponded shape to the measured surface, before projection
- __init__(sample_meshes, reference_mesh, log_level=20)[source]
Initialize the create-statistical-model workflow.
Options have
set_*methods.
- 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:
- 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:
- 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:
- set_solve_for_surface_pca(solve_for_surface_pca)[source]
Reduce the reference mesh to a surface before the PCA.
- 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:
- 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:
- 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.
- set_projection_max_distance_mm(projection_max_distance_mm)[source]
Only project points whose residual is at or below this distance.
- 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:
- 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.
- 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:
- ICP Alignment: Rough alignment using RegisterModelsICPITK, rigid,
similarity or affine per
icp_transform_type
- PCA Registration: Performs PCA-based shape fitting using
RegisterModelsPCA
Labelmap-to-Labelmap: Deformable registration using RegisterModelsDistanceMaps
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_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
- 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:
- 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:
- registrar_icon
ICON registration instance
- Type:
- registrar_greedy
Greedy registration instance
- Type:
- use_pca_registration
Whether PCA registration is enabled (set via set_use_pca_registration)
- Type:
- pca_model
PCA model dict when PCA enabled; same structure as WorkflowCreateStatisticalModel output
- Type:
- labelmap_interior_object_ids
List of labelmap IDs corresponding to interior objects that should not be used when computing a distance map.
- Type:
- 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()(orprepare_patient(), when the stages are run one by one); options haveset_*methods.- Parameters:
template_model (
DataSet) – Generic anatomical model to be registeredtemplate_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 newSegmentHeartSimplewareTrimmedBranches(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:
- set_fitting_spacing_mm(fitting_spacing_mm)[source]
Fit on an isotropic grid of this spacing.
The original CT is retained as
original_patient_imagefor 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:
- 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.
- 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 frompatient_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:
- 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:
- 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) andtutorials/parameters_duke_heart_4d_labelmaps.py(heart), which carry one value per organ. Left unset, it is derived frommask_dilation_mm.
- 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. bytutorials/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:
- 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:
- 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:
- set_use_labelmap_to_labelmap_registration(use_labelmap_to_labelmap_registration)[source]
Set whether to use labelmap-to-labelmap registration.
- 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:
- 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:
- 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:
- 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:
- 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:
- 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:
ICP alignment (RegisterModelsICPITK)
PCA registration (PCA data was provided)
Labelmap-to-labelmap deformable registration (RegisterModelsDistanceMaps)
- Optional labelmap-to-image refinement (Icon); requires template labelmap and IDs
set via set_use_labelmap_to_image_registration(True, …).
- Parameters:
patient_models (
Optional[list[DataSet]]) – Patient-specific models; seeprepare_patient().patient_image (
Optional[Image]) – Patient image; seeprepare_patient().patient_labelmap (
Optional[Image]) – Patient labels; seeprepare_patient().
- Return type:
- 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:
MONAIPhysioBaseReconstruct 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:
Time Series Registration: Register each time-series image to the reference image using RegisterTimeSeriesImages
Reconstruction: Apply inverse transforms to carry the reference image to every time point
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_methodaccepts a pre-configuredRegisterImagesBaseinstance. Configure backend-specific parameters (iteration counts, etc.) on the instance before passing it in. Defaults to a newRegisterImagesGreedywhen omitted.- reference_image
Reference image
- Type:
itk.Image
- register_reference_time_frame_to_reference_image
Whether to register the reference time frame to the reference image
- Type:
- 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:
- registrar
Internal registration object
- Type:
- 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]
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()(orprepare_series(), when the stages are run one by one); options haveset_*methods.- Parameters:
registration_method (Optional[RegisterImagesBase]) – Registration backend instance. Defaults to a new
RegisterImagesGreedywhen 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_mask_dilation_mm(mask_dilation_mm)[source]
Set the dilation of the fixed and moving image masks.
- 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.
- 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: 0fixed_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:
- 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:
- 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.
- 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:
- 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” usescomposite_percentile.- Returns:
- Dictionary containing:
’reconstructed_images’ (list[itk.Image]): Reconstructed time-series images
- Return type:
- 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:
time_series_images (
list[Image]) – Seeprepare_series().reference_image (
Image) – Seeprepare_series().reference_time_frame (
int) – Seeprepare_series().fixed_mask (
Optional[Image]) – Seeprepare_series().moving_masks (
Optional[list[Optional[Image]]]) – Seeprepare_series().
- 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:
- 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:
MONAIPhysioBaseFinetune 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.finetuneas a subprocess. Each subject’s time-point images form one paired group (they share asubject_id).- subject_image_files
Per-subject lists of image paths. Images within one inner list share a subject_id during finetuning.
- output_directory
Directory where the dataset JSON, YAML config, and the uniGradICON
checkpoints/tree are written.- Type:
Path
- subject_ids
One ID per subject (e.g. patient identifiers). Written into the dataset JSON’s
subject_idfield; falls back to syntheticsubject_NNNNwhenNone.
- subject_labelmap_files
Per-subject multi-label labelmap paths aligned with
subject_image_files.None(or per-imageNone) means no labelmap for that image. If supplied for at least one image, paired-with-seg training is enabled.
- subject_mask_files
Per-subject binary mask paths aligned with
subject_image_files, used for loss-function masking.Nonedisables masking.
- subject_landmark_files
Per-subject landmark CSV paths (
Name,X,Y,Zformat) aligned withsubject_image_files. Recorded in the dataset JSON for traceability; not consumed by uniGradICON finetuning itself.
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 asubject_idfor 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 uniGradICONexperiment.namestem).subject_ids (
Optional[list[str]]) – One ID per subject, in the same order assubject_image_files. Written verbatim into the dataset JSON’ssubject_idfield so paired training groups frames that share an ID.Nonefalls back to synthetic IDs of the formsubject_0000,subject_0001, … Must be unique.subject_labelmap_files (
Optional[list[list[Optional[str]]]]) – Per-subject multi-label segmentation (labelmap) paths matchingsubject_image_files.Nonedisables paired-with-seg training. IndividualNoneentries 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 matchingsubject_image_files, used for ICON loss-function masking.Nonedisables loss-function masking. Per-imageNoneentries skip just those frames.subject_landmark_files (
Optional[list[list[Optional[str]]]]) – Per-subject landmark CSV paths matchingsubject_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_filesis empty.ValueError – If
subject_labelmap_files,subject_mask_files, orsubject_landmark_filesis provided with a shape that does not matchsubject_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:
- 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:
- 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:
- set_lambda_value(lambda_value)[source]
Set the uniGradICON
training.lambdaregularization weight.- Parameters:
lambda_value (
float) – Value. Default: 1.5- Raises:
ValueError – If it is negative.
- Return type:
- 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:
- 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:
- 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:
- 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:
- 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.
- 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_samplebackward has no deterministic CUDA kernel.
- 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, optionalsegmentation, optionalmask, optionallandmarks(path only), and asubject_idderived from the inner-list index.Masks come from
subject_mask_filesonly; 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:
- Returns:
Path to the dataset JSON written under
experiment_dir.- Raises:
FileNotFoundError – If an image listed in
subject_image_filesdoes 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 byprepare_dataset().- Return type:
- 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.finetunewrites<experiment.name>/checkpoints/network_weights_final.trchat the end of training – itsNETWORK_WEIGHTS_PREFIXplus the"final"epoch label. Also the return value ofprocess().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 againstNETWORK_WEIGHTS_PREFIXwherever the submodule is installed, and by theFileNotFoundErrorprocess()raises when the checkpoint is not where this says it should be.- Return type:
- process()[source]
Build configs and launch
unigradicon.finetuning.finetune.Equivalent to running
prepare_dataset()→prepare_config()→ subprocess launch. Any existing dataset JSON or YAML inexperiment_diris overwritten.- Return type:
- 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:
subprocess.CalledProcessError – If the finetuning subprocess exits with a non-zero status.
FileNotFoundError – If the subprocess succeeded but the checkpoint is not where
expected_weights_path()says it should be.
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))