Distance Map Registration

Register models using distance field optimization.

Class Reference

class monai_physio.RegisterModelsDistanceMaps(fixed_model, reference_image, log_level=20)[source]

Bases: RegisterModelsBase

Register anatomical models using distance-map-based deformable registration.

This class provides distance-map-based alignment of 3D surface models with support for rigid, affine, and deformable transformation modes. The registration pipeline generates signed distance maps from models, applies optional binary mask dilation, and uses Greedy for rigid/affine stages and ICON for deformable registration.

Registration Pipelines:
  • None mode: No registration (identity transform)

  • Rigid mode: Greedy rigid registration

  • Affine mode: Greedy affine registration

  • Deformable mode: Greedy affine → ICON deformable registration

Transform Convention:

These are the underlying image-registration (Greedy/ICON) transforms, so they follow the image convention (see docs/developer/transform_conventions):

  • fixed_to_moving_transform: warps the moving image/mask onto the fixed grid. Warping the moving MODEL points/landmarks onto the fixed model uses moving_to_fixed_transform instead (image and point warps use opposite transforms).

  • moving_to_fixed_transform: warps the fixed image/mask onto the moving grid.

moving_model

Surface model to be aligned

Type:

pv.PolyData

fixed_model

Target surface model

Type:

pv.PolyData

reference_image

Reference image for coordinate frame

Type:

itk.Image

mask_dilation_mm

Dilation amount in mm for binary registration masks

Type:

float

distance_squared_max

Maximum squared distance for distance map normalization

Type:

float

transform_tools

Transform utility instance

Type:

ProcessTransforms

contour_tools

Model utility instance

Type:

ProcessSurfaceMesh

registrar_greedy

Greedy registration instance

Type:

RegisterImagesGreedy

registrar_icon

ICON registration instance

Type:

RegisterImagesICON

fixed_to_moving_transform

Optimized fixed-to-moving transform

Type:

itk.CompositeTransform

moving_to_fixed_transform

Optimized moving-to-fixed transform

Type:

itk.CompositeTransform

registered_model

Aligned moving model

Type:

pv.PolyData

Example

>>> # Initialize with the target model and reference image
>>> registrar = RegisterModelsDistanceMaps(
...     fixed_model=patient_surface,
...     reference_image=patient_ct,
... )
>>>
>>> # Run rigid registration
>>> registrar.set_transform_type('Rigid')
>>> result = registrar.register(model_surface)
>>>
>>> # Get aligned model and transforms
>>> aligned_model = result['registered_model']
>>> fixed_to_moving_transform = result['fixed_to_moving_transform']
__init__(fixed_model, reference_image, log_level=20)[source]

Initialize distance-map-based model registration.

Parameters:
  • fixed_model (PolyData) – PyVista target surface model

  • reference_image (Image) – ITK image providing coordinate frame (origin, spacing, direction) for mask generation. Typically the patient CT/MRI image.

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

Note

The fixed model, and the moving model passed to register(), are typically extracted from VTU models using model.extract_surface(algorithm=”dataset_surface”).

set_transform_type(transform_type)[source]

Choose the registration: ‘None’, ‘Rigid’, ‘Affine’ or ‘Deformable’.

Parameters:

transform_type (str) – Transform type. Default: ‘Deformable’

Raises:

ValueError – If transform_type is not one of the four.

Return type:

None

set_deformable_engine(deformable_engine)[source]

Choose which engine runs the nonrigid stage of ‘Deformable’.

Parameters:

deformable_engine (str) – ‘icon’ (Greedy affine, then ICON) or ‘greedy’ (Greedy affine + warp in one call). Default: ‘icon’

Raises:

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

Return type:

None

set_distance_squared_max(distance_squared_max)[source]

Set the squared distance the distance maps are normalized against.

It fixes the maps’ intensity distribution, so it must match the value the ICON weights in use were finetuned at.

Parameters:

distance_squared_max (float) – Squared millimeters. Default: 50.0

Raises:

ValueError – If distance_squared_max is not positive.

Return type:

None

set_mask_dilation_mm(mask_dilation_mm)[source]

Set how far, in millimeters, the registration masks are dilated.

Parameters:

mask_dilation_mm (float) – Dilation; 0 registers without masks. Default: 20.0

Raises:

ValueError – If mask_dilation_mm is negative.

Return type:

None

set_icon_weights_path(weights_path)[source]

Use a finetuned uniGradICON checkpoint for the deformable stage.

The distance maps this class registers are not CT intensities, so stock uniGradICON weights are out of distribution for them. Weights finetuned on distance maps, e.g. by tutorials/tutorial_02_finetune_icon_distancemap_tcia_lung_4d_ct.py, are supplied here.

Parameters:

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

Raises:

FileNotFoundError – If weights_path does not exist.

Return type:

None

registration_method(moving_model)[source]

Perform mask-based registration of moving model to fixed model.

The register() hook. It executes progressive multi-stage registration, chosen with set_transform_type() and set_deformable_engine():

None transform type:
  1. No registration (identity transform)

Rigid transform type:
  1. Greedy rigid registration

Affine transform type:
  1. Greedy affine registration

Deformable transform type, engine ‘icon’ (default):
  1. Greedy affine registration

  2. ICON deformable registration on the affine-pre-aligned masks

Deformable transform type, engine ‘greedy’:
  1. Greedy’s own affine + warp deformable registration, in one call

Parameters:

moving_model (DataSet) – PyVista surface model to be aligned to fixed model

Returns:

  • ‘registered_model’: Aligned moving model (PyVista PolyData)

  • ’fixed_to_moving_transform’: Fixed-to-moving transform (ITK CompositeTransform)

  • ’moving_to_fixed_transform’: Moving-to-fixed transform (ITK CompositeTransform)

Return type:

Dictionary containing

classmethod get_log_classes()

Get the list of classes currently showing logs.

Return type:

list[str]

Returns:

List of class names that are allowed to show logs. Empty list if filter is disabled (all classes shown).

Example

>>> classes = MONAIPhysioBase.get_log_classes()
>>> print(classes)
['RegisterModelsPCA', 'WorkflowFitStatisticalModelToPatient']
log_critical(message, *args)

Log a critical message with optional %-style formatting.

Parameters:
  • message (str) – The critical message to log (can contain %-style placeholders)

  • *args (Any) – Arguments for %-style string formatting

Return type:

None

Example

>>> self.log_critical('System failure at %s', timestamp)
>>> self.log_critical('Critical error: %(msg)s', {'msg': 'Out of memory'})
log_debug(message, *args)

Log a debug message with optional %-style formatting.

Parameters:
  • message (str) – The debug message to log (can contain %-style placeholders)

  • *args (Any) – Arguments for %-style string formatting

Return type:

None

Example

>>> self.log_debug('Processing %s with %d items', filename, count)
>>> self.log_debug('Value is %(value)d', {'value': 42})
log_error(message, *args)

Log an error message with optional %-style formatting.

Parameters:
  • message (str) – The error message to log (can contain %-style placeholders)

  • *args (Any) – Arguments for %-style string formatting

Return type:

None

Example

>>> self.log_error('Failed to load %s: %s', filename, error_msg)
>>> self.log_error('Error code: %(code)d', {'code': 404})
log_info(message, *args)

Log an info message with optional %-style formatting.

Parameters:
  • message (str) – The info message to log (can contain %-style placeholders)

  • *args (Any) – Arguments for %-style string formatting

Return type:

None

Example

>>> self.log_info('Loading file: %s', filepath)
>>> self.log_info('Iteration %(iter)d of %(total)d', {'iter': 5, 'total': 10})
log_progress(current, total, prefix='Progress', *, log=True)

Log progress information and report it to the progress callback.

current / total is also reported, within the current range, to the callback set by set_progress_callback().

Parameters:
  • current (int) – Current step/iteration number

  • total (int) – Total number of steps/iterations

  • prefix (str) – Prefix text for the progress message. Default: ‘Progress’

  • log (bool) – Whether to also write the progress to the log. Pass False for per-iteration progress that would flood it. Default: True

Return type:

None

Example

>>> for i in range(100):
...     self.log_progress(i + 1, 100)
>>> self.log_progress(5, 10, prefix='Processing')

Note

For custom formatted progress messages, use log_info() directly: >>> self.log_info(‘Loading %s: %d/%d’, filename, current, total)

log_section(title, *args, width=70, char='=')

Log a formatted section header with optional %-style formatting.

Useful for visually separating major sections of output.

Parameters:
  • title (str) – The section title (can contain %-style placeholders)

  • *args (Any) – Arguments for %-style string formatting of title

  • width (int) – Total width of the header line. Default: 70

  • char (str) – Character to use for the header line. Default: ‘=’

Return type:

None

Example

>>> self.log_section('Stage 1: Initialization')
>>> self.log_section('Processing file: %s', filename)
>>> self.log_section('Stage %(num)d: %(name)s', {'num': 2, 'name': 'Analysis'})
# Outputs:
# ======================================================================
# Stage 2: Analysis
# ======================================================================
log_warning(message, *args)

Log a warning message with optional %-style formatting.

Parameters:
  • message (str) – The warning message to log (can contain %-style placeholders)

  • *args (Any) – Arguments for %-style string formatting

Return type:

None

Example

>>> self.log_warning('Memory usage at %d%%', usage_percent)
>>> self.log_warning('Parameter %(name)s out of range', {'name': 'threshold'})
register(moving_model)

Register moving_model to the fixed model.

Calls registration_method() and keeps its standard results on the instance.

Parameters:

moving_model (DataSet) – Model to align to the fixed model.

Returns:

registered_model, moving_to_fixed_transform, fixed_to_moving_transform and any keys the subclass adds.

Return type:

The hook’s dictionary

set_fixed_model(fixed_model)

Replace the target model and forget the previous results.

Parameters:

fixed_model (DataSet) – New target model.

Return type:

None

classmethod set_log_all_classes()

Enable logging output from all MONAI Physio classes.

Disables the class filter so all classes show their logs.

Example

>>> MONAIPhysioBase.set_log_all_classes()
>>> # Now all classes will show their logs
Return type:

None

classmethod set_log_classes(class_names)

Set which classes should show their logging output.

Only log messages from the specified classes will be displayed. All other classes will have their logs hidden.

Parameters:

class_names (list[str]) – List of class names to show logs from. Example: [“RegisterModelsPCA”, “WorkflowFitStatisticalModelToPatient”]

Return type:

None

Example

>>> MONAIPhysioBase.set_log_classes(['RegisterModelsPCA'])
>>> # Now only RegisterModelsPCA logs will be shown
classmethod set_log_level(log_level)

Set a floor on the logging level of every MONAI Physio object.

Each object logs at its own log_level; messages below this floor are dropped whatever that level is. Lowering the floor does not make an object log below its own log_level.

Parameters:

log_level (int | str) – Logging level. Can be an integer (logging.DEBUG, logging.INFO, logging.WARNING, logging.ERROR, logging.CRITICAL) or a string (‘DEBUG’, ‘INFO’, ‘WARNING’, ‘ERROR’, ‘CRITICAL’).

Return type:

None

Example

>>> import logging
>>> MONAIPhysioBase.set_log_level(logging.DEBUG)
>>> # or
>>> MONAIPhysioBase.set_log_level('DEBUG')
classmethod set_progress_callback(progress_callback)

Set the callback that receives progress from all MONAI Physio classes.

Like the log level, this is shared: set it once and every workflow and registrar reports to it, including those a workflow runs internally.

Each long-running method reports a fraction in [0, 1] and a short message. A workflow divides that range among its steps once, as if every optional step ran; a step that is disabled is skipped, so the fraction jumps over its share. The fraction never decreases during a run and reaches 1.0 when the run completes. Progress from runs in concurrent threads is not kept apart.

Parameters:

progress_callback (Optional[Callable[[float, str], None]]) – Receives each fraction and message, or None to stop reporting.

Return type:

None

Example

>>> def show(fraction: float, message: str) -> None:
...     print(f"{fraction:6.1%} {message}")
>>> MONAIPhysioBase.set_progress_callback(show)
>>> result = workflow.process()
logger: Logger
log_level: int

Navigation

ICP with ITK Backend | Model Registration Modules | PCA-Based Registration