"""4D image reconstruction workflow.
This module provides the WorkflowReconstruct4D class for reconstructing
a 4D CT or MRI time series by registering its time-series images to a single
reference image, often a higher-resolution scan.
The workflow uses a caller-supplied RegisterImagesBase backend to:
1. Register each time-series image to the reference image
2. Apply inverse transforms to carry the reference image to every time point
3. Optionally upsample to the reference image resolution
This is useful for gated CT or MRI: the time-series images capture the motion,
and the reference image -- a separate, often higher-resolution scan, or one
frame of the series -- supplies the anatomical detail that moves with it.
Key Features:
- Sequential time-series registration using RegisterTimeSeriesImages
- Any RegisterImagesBase backend, defaulting to RegisterImagesGreedy
- Bidirectional registration from reference frame
- Optional temporal smoothing with prior transforms
- Reconstruction on each frame's grid, with optional upsampling
- No I/O operations (data passed in-memory)
"""
import logging
from typing import Literal, Optional
import itk
from .monai_physio_base import MONAIPhysioBase
from .register_images_base import RegisterImagesBase
from .register_time_series_images import RegisterTimeSeriesImages
[docs]
class WorkflowReconstruct4D(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
:class:`RegisterImagesBase` instance. Configure backend-specific
parameters (iteration counts, etc.) on the instance before passing it
in. Defaults to a new :class:`RegisterImagesGreedy` when omitted.
Attributes:
time_series_images (list[itk.Image]): Ordered list of time-series images
reference_image (itk.Image): Reference image
reference_time_frame (int): Index of reference time frame in time series
register_reference_time_frame_to_reference_image (bool): Whether to register
the reference time frame to the reference image
upsample_to_fixed_resolution (bool): Whether to upsample reconstruction
composite_mode (str): 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
composite_percentile (float): Percentile in [0, 100] for "percentile"
mode. Default: 95.0
registrar (RegisterTimeSeriesImages): Internal registration object
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 (used for reconstruction)
losses (list[float]): Registration loss values
reconstructed_images (list[itk.Image]): Reconstructed images
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']
"""
[docs]
def __init__(
self,
registration_method: Optional[RegisterImagesBase] = None,
log_level: int | str = logging.INFO,
):
"""Initialize the 4D image reconstruction workflow.
The series is given to :meth:`process` (or :meth:`prepare_series`,
when the stages are run one by one); options have ``set_*`` methods.
Args:
registration_method (Optional[RegisterImagesBase]): Registration
backend instance. Defaults to a new
:class:`RegisterImagesGreedy` when None.
log_level: Logging level (logging.DEBUG, logging.INFO, etc.).
Default: logging.INFO
Raises:
TypeError: If registration_method is neither None nor a
RegisterImagesBase instance
"""
super().__init__(class_name=self.__class__.__name__, log_level=log_level)
if registration_method is not None and not isinstance(
registration_method, RegisterImagesBase
):
raise TypeError(
"registration_method must be a RegisterImagesBase instance or None"
)
# The series, set by prepare_series() (process() calls it).
self.time_series_images: list[itk.Image] = []
self.reference_image: Optional[itk.Image] = None
self.reference_time_frame = 0
self.fixed_mask: Optional[itk.Image] = None
self.moving_masks: Optional[list[Optional[itk.Image]]] = None
self.register_reference_time_frame_to_reference_image = True
self.composite_reference_image: Optional[itk.Image] = None
# Initialize parameters with defaults
self.upsample_to_fixed_resolution: bool = True
self.composite_mode: Literal["reference", "mean", "max", "percentile"] = (
"reference"
)
self.composite_percentile: float = 95.0
self.modality: str = "ct"
self.mask_dilation_mm: float = 0.0
# Initialize registrar
self.registrar = RegisterTimeSeriesImages(
registration_method=registration_method, log_level=log_level
)
# Results storage
self.fixed_to_moving_transforms: Optional[list[itk.Transform]] = None
self.moving_to_fixed_transforms: Optional[list[itk.Transform]] = None
self.losses: Optional[list[float]] = None
self.reconstructed_images: Optional[list[itk.Image]] = None
[docs]
def set_modality(self, modality: str) -> None:
"""Set the imaging modality for registration optimization.
Args:
modality (str): The imaging modality, 'ct' (default) or 'mri'
"""
self.modality = modality
[docs]
def set_mask_dilation_mm(self, mask_dilation_mm: float) -> None:
"""Set the dilation of the fixed and moving image masks.
Args:
mask_dilation_mm (float): The dilation in millimeters
"""
self.mask_dilation_mm = mask_dilation_mm
[docs]
def set_register_reference_time_frame_to_reference_image(
self, register_reference_time_frame_to_reference_image: bool
) -> None:
"""Register the reference time frame to the reference image.
If False, that frame gets an identity transform.
Args:
register_reference_time_frame_to_reference_image: Whether to.
Default: True
"""
self.register_reference_time_frame_to_reference_image = (
register_reference_time_frame_to_reference_image
)
[docs]
def prepare_series(
self,
time_series_images: list[itk.Image],
reference_image: itk.Image,
reference_time_frame: int = 0,
fixed_mask: Optional[itk.Image] = None,
moving_masks: Optional[list[Optional[itk.Image]]] = None,
) -> None:
"""Set the series the stages work on; :meth:`process` calls this first.
Call it directly only to run the stages one by one.
Args:
time_series_images: Ordered list of 3D time-series images to be
registered and reconstructed.
reference_image: 3D reference image.
reference_time_frame: Index of the reference time frame in the
time series. Registration proceeds bidirectionally from this
frame. Default: 0
fixed_mask: Optional binary mask of the reference image's region
of interest.
moving_masks: 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.
"""
if not time_series_images:
raise ValueError("time_series_images cannot be empty")
if reference_time_frame < 0 or reference_time_frame >= len(time_series_images):
raise ValueError(
f"reference_time_frame {reference_time_frame} out of range "
f"[0, {len(time_series_images) - 1}]"
)
if moving_masks is not None and len(moving_masks) != len(time_series_images):
raise ValueError(
f"moving_masks length ({len(moving_masks)}) must match "
f"time_series_images length ({len(time_series_images)})"
)
self.time_series_images = time_series_images
self.reference_image = reference_image
self.reference_time_frame = reference_time_frame
self.fixed_mask = fixed_mask
self.moving_masks = moving_masks
self.composite_reference_image = None
self.fixed_to_moving_transforms = None
self.moving_to_fixed_transforms = None
self.losses = None
self.reconstructed_images = None
[docs]
def register_time_series(self) -> dict:
"""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:
dict: 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
Raises:
RuntimeError: If registration fails
"""
self.log_section(
"Stage 1: Time Series Registration (RegisterTimeSeriesImages)", width=70
)
# Configure registrar
self.registrar.set_fixed_image(self.reference_image)
self.registrar.set_modality(self.modality)
self.registrar.set_mask_dilation_mm(self.mask_dilation_mm)
self.registrar.set_fixed_mask(self.fixed_mask)
self.log_info(f"Registration method: {type(self.registrar.registrar).__name__}")
self.log_info(f"Number of time points: {len(self.time_series_images)}")
self.log_info(f"Reference time frame: {self.reference_time_frame}")
self.log_info(
"Register reference time frame to reference image: "
f"{self.register_reference_time_frame_to_reference_image}"
)
# Perform registration
result = self.registrar.register_time_series(
moving_images=self.time_series_images,
moving_masks=self.moving_masks,
reference_frame=self.reference_time_frame,
register_reference=self.register_reference_time_frame_to_reference_image,
)
# Store results
self.fixed_to_moving_transforms = result["fixed_to_moving_transforms"]
self.moving_to_fixed_transforms = result["moving_to_fixed_transforms"]
self.losses = result["losses"]
self.log_info("Stage 1 complete: Time series registration finished.")
self.log_info(f" Average loss: {sum(self.losses) / len(self.losses):.6f}")
self.log_info(f" Min loss: {min(self.losses):.6f}")
self.log_info(f" Max loss: {max(self.losses):.6f}")
self.get_composite_reference_image()
return {
"fixed_to_moving_transforms": self.fixed_to_moving_transforms,
"moving_to_fixed_transforms": self.moving_to_fixed_transforms,
"losses": self.losses,
}
[docs]
def get_composite_reference_image(self) -> Optional[itk.Image]:
"""Build the configured mean, max, or percentile reconstruction source.
Percentile mode uses ``composite_percentile`` (95.0 by default).
Returns:
Optional[itk.Image]: The composite source, or None in reference mode
"""
if self.fixed_to_moving_transforms is None:
raise ValueError(
"fixed_to_moving_transforms not set. Call register_time_series() first."
)
if self.moving_to_fixed_transforms is None:
raise ValueError(
"moving_to_fixed_transforms not set. Call register_time_series() first."
)
if self.composite_mode not in ("mean", "max", "percentile"):
return None
self.composite_reference_image = self.registrar.compute_composite_reference(
self.time_series_images,
self.fixed_to_moving_transforms,
self.composite_mode,
percentile=self.composite_percentile,
)
return self.composite_reference_image
[docs]
def set_upsample_to_fixed_resolution(
self, upsample_to_fixed_resolution: bool
) -> None:
"""Set whether to upsample the reconstructed time series to the fixed
resolution.
Args:
upsample_to_fixed_resolution (bool): Whether to upsample the reconstructed
time series to the fixed resolution.
"""
self.upsample_to_fixed_resolution = upsample_to_fixed_resolution
[docs]
def set_composite_mode(
self,
composite_mode: Literal["reference", "mean", "max", "percentile"],
percentile: float = 95.0,
) -> None:
"""Set which image is warped back to each time point during reconstruction.
Args:
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
"""
if composite_mode not in ("reference", "mean", "max", "percentile"):
raise ValueError(
f"composite_mode must be 'reference', 'mean', 'max', or 'percentile', "
f"got {composite_mode!r}"
)
if composite_mode == "percentile" and not 0 <= percentile <= 100:
raise ValueError("percentile must be finite and in [0, 100]")
self.composite_mode = composite_mode
self.composite_percentile = percentile
self.composite_reference_image = None
[docs]
def reconstruct_time_series(self) -> dict:
"""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:
dict: Dictionary containing:
- 'reconstructed_images' (list[itk.Image]): Reconstructed
time-series images
Raises:
RuntimeError: If reconstruction fails
ValueError: If moving_to_fixed_transforms is not set (call register_time_series first)
"""
if self.moving_to_fixed_transforms is None:
raise ValueError(
"moving_to_fixed_transforms not set. Call register_time_series() first."
)
self.log_section("Stage 2: Time Series Reconstruction", width=70)
self.log_info(
f"Upsampling to fixed resolution: {self.upsample_to_fixed_resolution}"
)
self.log_info(f"Composite mode: {self.composite_mode}")
composite_mode: Literal["reference", "mean", "max", "percentile", "existing"]
composite_mode = self.composite_mode
if self.composite_reference_image is not None:
composite_mode = "existing"
self.registrar.composite_reference_image = self.composite_reference_image
# Reconstruct time series
self.reconstructed_images = self.registrar.reconstruct_time_series(
moving_images=self.time_series_images,
moving_to_fixed_transforms=self.moving_to_fixed_transforms,
upsample_to_fixed_resolution=self.upsample_to_fixed_resolution,
fixed_to_moving_transforms=self.fixed_to_moving_transforms,
composite_mode=composite_mode,
composite_percentile=self.composite_percentile,
)
self.log_info("Stage 2 complete: Time series reconstruction finished.")
self.log_info(f" Reconstructed {len(self.reconstructed_images)} images")
# Log image properties for first reconstructed image
if self.reconstructed_images:
img = self.reconstructed_images[0]
self.log_info(f" Reconstructed image size: {itk.size(img)}")
self.log_info(f" Reconstructed image spacing: {itk.spacing(img)}")
return {"reconstructed_images": self.reconstructed_images}
[docs]
def process(
self,
time_series_images: list[itk.Image],
reference_image: itk.Image,
reference_time_frame: int = 0,
fixed_mask: Optional[itk.Image] = None,
moving_masks: Optional[list[Optional[itk.Image]]] = None,
) -> dict:
"""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
Args:
time_series_images: See :meth:`prepare_series`.
reference_image: See :meth:`prepare_series`.
reference_time_frame: See :meth:`prepare_series`.
fixed_mask: See :meth:`prepare_series`.
moving_masks: See :meth:`prepare_series`.
Returns:
dict: 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
Raises:
RuntimeError: If any stage of the workflow fails
"""
self.prepare_series(
time_series_images,
reference_image,
reference_time_frame=reference_time_frame,
fixed_mask=fixed_mask,
moving_masks=moving_masks,
)
self.log_section("STARTING 4D IMAGE RECONSTRUCTION WORKFLOW", width=70)
self.log_info("Input configuration:")
self.log_info(f" Number of time points: {len(self.time_series_images)}")
registrar_type = type(self.registrar.registrar).__name__
self.log_info(f" Registration method: {registrar_type}")
self.log_info(f" Reference time frame: {self.reference_time_frame}")
self.log_info(
f" Upsample to fixed resolution: {self.upsample_to_fixed_resolution}"
)
# Stage 1: Register time series
_ = self.register_time_series()
# Stage 2: Reconstruct the time series
_ = self.reconstruct_time_series()
self.log_section("RECONSTRUCTION WORKFLOW COMPLETE", width=70)
assert self.reconstructed_images is not None, "Reconstructed images must be set"
self.log_info(
f"Successfully reconstructed {len(self.reconstructed_images)} images"
)
return {
"fixed_to_moving_transforms": self.fixed_to_moving_transforms,
"moving_to_fixed_transforms": self.moving_to_fixed_transforms,
"losses": self.losses,
"reconstructed_images": self.reconstructed_images,
}