ENH: Initial implementation of a PhysicsNeMo tutorial#54
Conversation
|
Warning Rate limit exceeded
You’ve run out of usage credits. Purchase more in the billing tab. ⌛ How to resolve this issue?After the wait time has elapsed, a review can be triggered using the We recommend that you space out your commits to avoid hitting the rate limit. 🚦 How do rate limits work?CodeRabbit enforces hourly rate limits for each developer per organization. Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout. Please see our FAQ for further information. ℹ️ Review info⚙️ Run configurationConfiguration used: Organization UI Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (2)
WalkthroughThis PR adds Tutorial 9, a PhysicsNeMo-based mesh stage model that predicts per-vertex respiratory stage-dependent displacements. It includes configuration updates to enable type-checking of the tutorials directory, auto-generated API documentation for the LongitudinalRegistration experiment suite, and the full tutorial implementation with training and inference logic. ChangesTutorial 9 PhysicsNeMo Stage Model
Sequence DiagramsequenceDiagram
participant TutorialScript
participant MeshLoader
participant Normalizer
participant PhysicsNeMoMLP
participant InferenceEngine
participant OutputWriter
TutorialScript->>MeshLoader: Load PCA-fitted VTP meshes per case
MeshLoader->>Normalizer: Pass loaded mesh point coordinates
Normalizer->>PhysicsNeMoMLP: Normalized [x,y,z,stage] + displacement targets
PhysicsNeMoMLP->>PhysicsNeMoMLP: Train FullyConnected MLP with MSE loss
TutorialScript->>InferenceEngine: Predict displacements at TARGET_STAGE
InferenceEngine->>InferenceEngine: Chunked inference over reference points
InferenceEngine->>OutputWriter: Rescaled displacement predictions
OutputWriter->>OutputWriter: Apply displacements, write .vtp mesh, checkpoint, metadata, loss history
OutputWriter->>TutorialScript: Return per-case result paths
Estimated code review effort🎯 2 (Simple) | ⏱️ ~12 minutes Poem
🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches🧪 Generate unit tests (beta)
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. Comment |
There was a problem hiding this comment.
Actionable comments posted: 2
🧹 Nitpick comments (1)
tutorials/tutorial_09_physicsnemo_mesh_stage_model.py (1)
64-262: 🏗️ Heavy liftConsider splitting
run_tutorial()into focused helpers.This function currently mixes case discovery, dataset assembly, training, inference, and artifact writing. Extracting those into small helpers would improve readability and make failures easier to isolate.
As per coding guidelines, "Keep functions focused and small in Python code."
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@tutorials/tutorial_09_physicsnemo_mesh_stage_model.py` around lines 64 - 262, run_tutorial() is doing too many things (case discovery, dataset assembly, training, inference, and artifact writing); split it into focused helper functions to improve readability and testability. Create helpers such as discover_cases() (returns case_numbers and case_prefix), build_case_dataset(case_prefix, tutorial_08_output_dir, points_per_mesh) (returns reference_mesh, point_indices, coordinate_mean/scale, inputs_array, targets_array, mesh_files), train_stage_model(inputs_tensor, targets_tensor, device, learning_rate, epochs) (constructs FullyConnected, optimizer, trains and returns model and losses and displacement_scale), predict_mesh_for_stage(model, reference_mesh, coordinate_mean, coordinate_scale, displacement_scale, target_stage, point_indices, device) (returns predicted_mesh), and write_case_artifacts(case_output_dir, model, metadata, losses, predicted_mesh, mesh_files) (saves checkpoint, metadata, losses, mesh). Replace the big loop inside run_tutorial() with calls to these helpers, ensure each helper has clear return values (e.g., model, losses, predicted_mesh, checkpoint path) and that existing names like FullyConnected, run_tutorial, inputs_tensor, targets_tensor, and tutorial_outputs are preserved and used to assemble final tutorial_outputs.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@tutorials/tutorial_09_physicsnemo_mesh_stage_model.py`:
- Line 100: Replace the ad-hoc print calls that use case_prefix (e.g.,
print(f"Skipping {case_prefix}: fewer than two Tutorial 8 meshes found")) and
the other print(s) around the mesh-processing block with structured logging
calls; import and use the module-level logger (logging.info(...)) instead of
print so messages respect configured verbosity and handlers—locate the prints by
searching for the string "Skipping {case_prefix}" and the prints in the
mesh-processing section (around the same function/loop that references
case_prefix) and change them to logging.info(...) with the same formatted
message.
- Around line 89-97: Validate CASE bounds before indexing DIRLAB_CASE_PREFIXES:
ensure any value in case_numbers is between 1 and len(DIRLAB_CASE_PREFIXES)
(inclusive) and raise a clear ValueError if not. Specifically, where
case_numbers is derived (the CASE variable or range(1, 11)), add a quick check
before using case_prefix = DIRLAB_CASE_PREFIXES[case_number - 1] (or validate
inside the loop) to fail fast with an informative message mentioning the invalid
CASE value and the accepted range; reference variables/keys: case, case_numbers,
DIRLAB_CASE_PREFIXES, case_number, case_prefix, mesh_dir,
tutorial_08_output_dir.
---
Nitpick comments:
In `@tutorials/tutorial_09_physicsnemo_mesh_stage_model.py`:
- Around line 64-262: run_tutorial() is doing too many things (case discovery,
dataset assembly, training, inference, and artifact writing); split it into
focused helper functions to improve readability and testability. Create helpers
such as discover_cases() (returns case_numbers and case_prefix),
build_case_dataset(case_prefix, tutorial_08_output_dir, points_per_mesh)
(returns reference_mesh, point_indices, coordinate_mean/scale, inputs_array,
targets_array, mesh_files), train_stage_model(inputs_tensor, targets_tensor,
device, learning_rate, epochs) (constructs FullyConnected, optimizer, trains and
returns model and losses and displacement_scale), predict_mesh_for_stage(model,
reference_mesh, coordinate_mean, coordinate_scale, displacement_scale,
target_stage, point_indices, device) (returns predicted_mesh), and
write_case_artifacts(case_output_dir, model, metadata, losses, predicted_mesh,
mesh_files) (saves checkpoint, metadata, losses, mesh). Replace the big loop
inside run_tutorial() with calls to these helpers, ensure each helper has clear
return values (e.g., model, losses, predicted_mesh, checkpoint path) and that
existing names like FullyConnected, run_tutorial, inputs_tensor, targets_tensor,
and tutorial_outputs are preserved and used to assemble final tutorial_outputs.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: 517b7b8a-440b-4950-908b-8c12d6306367
📒 Files selected for processing (5)
.pre-commit-config.yamldocs/API_MAP.mdpyproject.tomltutorials/__init__.pytutorials/tutorial_09_physicsnemo_mesh_stage_model.py
There was a problem hiding this comment.
Pull request overview
Adds a new tutorial script demonstrating how to train a PhysicsNeMo MLP to predict DirLab mesh displacements as a function of normalized respiratory stage, using meshes generated by Tutorial 8.
Changes:
- Add
tutorial_09_physicsnemo_mesh_stage_model.pyto train per-case PhysicsNeMo models and write predicted meshes/checkpoints/metadata. - Update mypy configuration and pre-commit mypy hook to include PhysicsNeMo imports and type-check the
tutorials/directory. - Regenerate
docs/API_MAP.mdto reflect the updated public API map.
Reviewed changes
Copilot reviewed 4 out of 5 changed files in this pull request and generated 3 comments.
Show a summary per file
| File | Description |
|---|---|
| tutorials/tutorial_09_physicsnemo_mesh_stage_model.py | New end-to-end tutorial for training a PhysicsNeMo stage-conditioned displacement model and exporting predicted meshes. |
| tutorials/init.py | Tutorials package marker (as included in PR file list). |
| pyproject.toml | Mypy override updates to tolerate PhysicsNeMo imports and tutorial module typing configuration. |
| docs/API_MAP.md | Regenerated API map output. |
| .pre-commit-config.yaml | Run mypy against both src/ and tutorials/ in pre-commit. |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
| # tutorials also matches the style of tutorial_01. | ||
| if __name__ == "__main__": | ||
| # %% | ||
| REPO_ROOT = Path(__file__).resolve().parent.parent |
| mesh_files = sorted(mesh_dir.glob("*_pca_fit.vtp")) | ||
| if len(mesh_files) < 2: | ||
| print(f"Skipping {case_prefix}: fewer than two Tutorial 8 meshes found") |
| "model_state_dict": model.state_dict(), | ||
| "coordinate_mean": coordinate_mean.tolist(), | ||
| "coordinate_scale": coordinate_scale.tolist(), | ||
| "displacement_scale": displacement_scale, | ||
| "target_stage": target_stage, | ||
| "mesh_files": [str(mesh_file) for mesh_file in mesh_files], | ||
| }, |
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #54 +/- ##
==========================================
+ Coverage 30.61% 30.62% +0.01%
==========================================
Files 49 49
Lines 6808 6808
==========================================
+ Hits 2084 2085 +1
+ Misses 4724 4723 -1
Flags with carried forward coverage won't be shown. Click here to find out more. ☔ View full report in Codecov by Sentry. 🚀 New features to boost your workflow:
|
Summary by CodeRabbit
Release Notes
New Features
Documentation
Chores