Skip to content

ENH: Improve fit for PCA and Labelmap_to_Labelmap registration#69

Open
aylward wants to merge 2 commits into
Project-MONAI:mainfrom
aylward:optimize_pca_l2l_fit
Open

ENH: Improve fit for PCA and Labelmap_to_Labelmap registration#69
aylward wants to merge 2 commits into
Project-MONAI:mainfrom
aylward:optimize_pca_l2l_fit

Conversation

@aylward

@aylward aylward commented Jun 20, 2026

Copy link
Copy Markdown
Collaborator

No description provided.

Copilot AI review requested due to automatic review settings June 20, 2026 16:56
@coderabbitai

coderabbitai Bot commented Jun 20, 2026

Copy link
Copy Markdown

Warning

Review limit reached

@aylward, we couldn't start this review because you've reached your PR review rate limit.

More reviews will be available in 29 seconds. Learn how PR review limits work.

Your organization has used up its prepaid credits, and credit purchases are no longer available. Enable the review add-on in the billing tab to keep reviews running — you're only billed for reviews past your plan's rate limits ($0.25/file).

⌛ How to resolve this issue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based credits.

🚦 How do rate limits work?

CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan refill rate.

For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, the refill rate gradually slows as usage increases. The highest same-day bursts are limited more strictly.

Please see our Fair Usage Limits Policy for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: d751379b-b2c6-4f5b-9845-986a72871973

📥 Commits

Reviewing files that changed from the base of the PR and between 89d9583 and acafab2.

📒 Files selected for processing (9)
  • experiments/Heart-Statistical_Model_To_Patient/heart_model_to_patient-CHOPValve.py
  • src/physiomotion4d/contour_tools.py
  • src/physiomotion4d/image_tools.py
  • src/physiomotion4d/register_images_greedy.py
  • src/physiomotion4d/register_models_distance_maps.py
  • src/physiomotion4d/register_models_pca.py
  • src/physiomotion4d/transform_tools.py
  • src/physiomotion4d/workflow_fit_statistical_model_to_patient.py
  • tests/test_workflow_fit_statistical_model_to_patient.py
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

This PR aims to improve the statistical-model fitting workflow by refining PCA-based registration inputs and strengthening labelmap-based registration stages (labelmap-to-labelmap and labelmap-to-image), with some supporting utility refactors.

Changes:

  • Refactors isotropic-resampling into ImageTools.make_isotropic_image() and uses it in the fit workflow when patient spacing is anisotropic.
  • Improves labelmap propagation/selection for labelmap-to-image refinement and adds support for supplying external template/patient labelmaps to the workflow.
  • Adjusts distance-map registration behavior (metrics, masking behavior) and Greedy’s metric-grid downsampling rationale/usage.

Reviewed changes

Copilot reviewed 9 out of 9 changed files in this pull request and generated 7 comments.

Show a summary per file
File Description
tests/test_workflow_fit_statistical_model_to_patient.py Updates tests to use renamed workflow flags (use_l2l_registration, use_l2i_registration).
src/physiomotion4d/workflow_fit_statistical_model_to_patient.py Adds optional labelmap inputs, uses isotropic resampling via ImageTools, and changes PCA/L2I staging/propagation behavior.
src/physiomotion4d/transform_tools.py Broadens CuPy import failure handling to include OSError.
src/physiomotion4d/register_models_pca.py Changes distance-map generation options and introduces new invalid-point handling in the metric.
src/physiomotion4d/register_models_distance_maps.py Alters distance-map preprocessing and registration configuration (Greedy metric, ICON masking behavior).
src/physiomotion4d/register_images_greedy.py Updates comments and applies metric downsampling scale consistently via _metric_downsample_scale().
src/physiomotion4d/image_tools.py Introduces make_isotropic_image() utility method.
src/physiomotion4d/contour_tools.py Changes labelmap array dtype from uint8 to uint16.
experiments/Heart-Statistical_Model_To_Patient/heart_model_to_patient-CHOPValve.py Enables labelmap-to-labelmap registration in the experiment script.
Comments suppressed due to low confidence (2)

src/physiomotion4d/register_models_pca.py:161

  • Unconditional itk.imwrite() in the constructor will write files to the current working directory on every run, which is a surprising side effect for library code and can break read-only environments. Gate this behind a debug log level (or remove entirely).
        self.pca_number_of_modes: int = pca_number_of_modes

src/physiomotion4d/register_models_distance_maps.py:354

  • Commented-out mask handling makes the ICON stage behavior unclear and leaves dead code in the method. Either keep mask support enabled or remove the commented lines and update behavior intentionally (optionally via a parameter/flag).
            # self.reference_image,
            # interpolation_method="nearest",
            # )

            # Configure and run ICON
            self.registrar_ICON.set_number_of_iterations(icon_iterations)
            self.registrar_ICON.set_fixed_image(self.fixed_distance_map_image)
            # self.registrar_ICON.set_fixed_mask(self.fixed_mask_image)

            result_ICON = self.registrar_ICON.register(
                moving_image=moving_distance_map_affine_transformed,
                # moving_mask=moving_mask_affine_transformed,
            )
            forward_transform_ICON = result_ICON["forward_transform"]
            inverse_transform_ICON = result_ICON["inverse_transform"]


💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment on lines +518 to +522
if n_invalid_points > 0.05 * n_valid_points:
self.log_warning(
f"{n_invalid_points} of {n_valid_points + n_invalid_points} mapped outside of image. Rejecting."
)
return self._fixed_distance_map_max_distance
Comment on lines +217 to +218
itk.imwrite(self.fixed_distance_map_image, "l2l_fixed_distance_map.mha")
itk.imwrite(self.moving_distance_map_image, "l2l_moving_distance_map.mha")
Comment on lines +220 to +225
# Emulate CT intensity range by multiplying by 1000
tmp_arr = itk.GetArrayViewFromImage(self.fixed_distance_map_image)
tmp_arr *= 1000

tmp_arr = itk.GetArrayViewFromImage(self.moving_distance_map_image)
tmp_arr *= 1000
Comment on lines 63 to +64
**Labelmap Configuration:**
Labelmaps are automatically generated from models if not provided by the user
via set_labelmaps(). Auto-generated labelmaps use labelmap_dilation_mm parameter.
Labelmaps are automatically generated from models.
Comment on lines 125 to 129
patient_models: list[pv.DataSet] | None = None,
patient_image: Optional[itk.Image] = None,
patient_labelmap: Optional[itk.Image] = None,
template_labelmap: Optional[itk.Image] = None,
segmentation_method: str = "HeartSimplewareTrimmedBranches",
Comment on lines 497 to +507
else:
pca_template_model = self.icp_template_model
fixed_model = self.combined_patient_model
fixed_distance_map = self.labelmap_tools.create_distance_map(
self.patient_labelmap,
max_distance_mm=10.0,
distance_scale=5.0,
preserve_labels=False,
exclude_labels=[1, 2, 3, 4], # Interior chambers
fill_background_only=True,
)
Comment on lines 269 to 270
"""Set dilation amount for binary registration masks.

@codecov

codecov Bot commented Jun 20, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 17.54386% with 47 lines in your changes missing coverage. Please review.
✅ Project coverage is 32.38%. Comparing base (89d9583) to head (acafab2).

Files with missing lines Patch % Lines
src/physiomotion4d/image_tools.py 4.76% 20 Missing ⚠️
...ion4d/workflow_fit_statistical_model_to_patient.py 37.50% 15 Missing ⚠️
...rc/physiomotion4d/register_models_distance_maps.py 0.00% 5 Missing ⚠️
src/physiomotion4d/register_models_pca.py 0.00% 5 Missing ⚠️
src/physiomotion4d/register_images_greedy.py 0.00% 1 Missing ⚠️
src/physiomotion4d/transform_tools.py 0.00% 1 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main      #69      +/-   ##
==========================================
- Coverage   32.45%   32.38%   -0.08%     
==========================================
  Files          53       53              
  Lines        7244     7254      +10     
==========================================
- Hits         2351     2349       -2     
- Misses       4893     4905      +12     
Flag Coverage Δ
integration-tests 32.27% <17.54%> (?)
unittests 32.36% <17.54%> (-0.09%) ⬇️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants