Skip to content

Conversation

strixy16
Copy link
Collaborator

@strixy16 strixy16 commented May 14, 2025

Updating import paths for the logger, io, resize, etc.
Updated RTSTRUCT loader to use new MIT setup
Updated some image readers to use read_dicom_auto
Updated tests for loading RTSTRUCTS with new MIT methods

Summary by CodeRabbit

  • Refactor

    • Improved the method for loading DICOM and RTSTRUCT files, unifying the approach and updating ROI mask extraction for greater clarity and reliability.
    • Updated several import statements to use new module paths.
  • Tests

    • Adjusted test fixtures and expected outputs to reflect changes in ROI specification and image dimensions.
    • Simplified test cases for segmentation loading and updated expected image properties.
  • Chores

    • Updated dependency requirements to support newer versions of a key imaging library.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented May 14, 2025

Warning

Rate limit exceeded

@strixy16 has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 19 minutes and 44 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

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.

📥 Commits

Reviewing files that changed from the base of the PR and between 7ba15ea and 64fba20.

📒 Files selected for processing (1)
  • src/readii/loaders.py (2 hunks)

Walkthrough

The changes update the minimum version requirement for the "med-imagetools" dependency, refactor DICOM and RTSTRUCT loading to use new unified functions, adjust ROI handling to explicit lists, and update related tests and imports. Test expectations for ROI masks, image sizes, origins, and feature values are revised to match the new loading logic and data structures. Several unused imports are removed across notebooks, source, and test files.

Changes

File(s) Change Summary
pyproject.toml Updated "med-imagetools" dependency version constraint from ">=1.9.2" to ">=2".
src/readii/feature_extraction.py Changed DICOM series reading from read_dicom_series to read_dicom_auto from a new import path.
src/readii/loaders.py Refactored loadRTSTRUCTSITK to use read_dicom_auto for both base images and RTSTRUCTs, changed segmentation mask extraction to use get_mask_ndarray per ROI name, and updated output to map ROI names to masks or None.
src/readii/process/images/crop.py Changed import of resize from imgtools.ops.functional to imgtools.transforms.functional; changed DICOM reading from read_dicom_series to read_dicom_auto.
src/readii/utils/logging_config.py Changed import of get_logger from imgtools.logging to imgtools.loggers.
src/readii/negative_controls.py Removed unused imports including logger, random, and others; retained only necessary imports.
src/readii/pipeline.py Removed unused import arg from ast module.
tests/process/images/test_crop.py Modified test fixtures and expected outputs to use explicit ROI name lists, updated expected image sizes to match new mask extraction logic.
tests/test_feature_extraction.py Changed ROI specification in fixtures from regex/dictionary to explicit list, updated expected mask/image sizes and feature values in assertions.
tests/test_image_processing.py Updated ROI specification in fixtures from dictionary/regex to explicit list, adjusted expected ROI center coordinates in tests.
tests/test_loaders.py Simplified test parameterization to only use explicit ROI list, updated expected image spacing and origin to match new loading logic.
tests/test_negative_controls.py Removed unused imports including imageoperations, applyNegativeControl, and collections.
tests/io/loaders/test_features.py Removed unused import of Path.
tests/io/writers/test_base_writer.py Removed unused import of os.
tests/io/writers/test_correlation_writer.py Removed unused imports of Path and CorrelationWriterError.
tests/io/writers/test_nifti_writer.py Removed unused import of Path.
tests/analyze/test_plot_correlation.py Removed unnecessary f-string formatting in assertions; removed unused import Path.
notebooks/crop_testing.ipynb Removed unused import rich.print; replaced f-string titles in matplotlib plots with plain string literals.
notebooks/debugging.ipynb Removed unused imports: pandas as pd, os, and Optional from typing.
notebooks/viz_neg_4D.ipynb Removed import of Image from IPython.display though usage remains.
notebooks/viz_neg_controls.ipynb Removed multiple unused and duplicate imports, simplified PIL imports, and removed repeated import of IPython.display.Image.
notebooks/writer_examples.ipynb Removed unused imports: logger, SimpleITK as sitk, and json.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant Loader
    participant ImgTools
    participant RTStruct

    User->>Loader: loadRTSTRUCTSITK(rtstructPath, baseImageDirPath, roiNames)
    Loader->>ImgTools: read_dicom_auto(baseImageDirPath)
    Loader->>ImgTools: read_dicom_auto(rtstructPath, modality="RTSTRUCT")
    loop for each ROI name
        Loader->>RTStruct: get_mask_ndarray(roiName, reference=baseImage, size=baseImage.shape)
        alt Mask found
            Loader->>Loader: Convert ndarray to SimpleITK.Image
            Loader->>Loader: Store mask in result dict
        else Mask not found
            Loader->>Loader: Store None in result dict
        end
    end
    Loader-->>User: Return {roiName: mask or None}
Loading

Suggested reviewers

  • jjjermiah

Poem

In the garden of code, a new mask appears,
With ROIs named plainly, no regex to fear.
The loaders now smarter, the tests realigned,
Our images crisper, their origins defined.
With med-imagetools two, we hop to the sun—
Another release, another job well done!
🥕🐇

✨ Finishing Touches
  • 📝 Generate Docstrings

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
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 4

🧹 Nitpick comments (1)
tests/test_feature_extraction.py (1)

95-95: Use isinstance() instead of type comparison.

Replace direct type comparison with isinstance() for better Python practice.

-    assert type(actual) == collections.OrderedDict, \
+    assert isinstance(actual, collections.OrderedDict), \
🧰 Tools
🪛 Ruff (0.8.2)

95-95: Use is and is not for type comparisons, or isinstance() for isinstance checks

(E721)

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 08db913 and 273e6eb.

⛔ Files ignored due to path filters (1)
  • pixi.lock is excluded by !**/*.lock
📒 Files selected for processing (9)
  • pyproject.toml (1 hunks)
  • src/readii/feature_extraction.py (2 hunks)
  • src/readii/loaders.py (2 hunks)
  • src/readii/process/images/crop.py (1 hunks)
  • src/readii/utils/logging_config.py (1 hunks)
  • tests/process/images/test_crop.py (2 hunks)
  • tests/test_feature_extraction.py (3 hunks)
  • tests/test_image_processing.py (2 hunks)
  • tests/test_loaders.py (1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (2)
tests/test_image_processing.py (1)
tests/test_loaders.py (1)
  • lung4DCTPath (13-14)
tests/test_feature_extraction.py (1)
tests/test_loaders.py (1)
  • lung4DCTPath (13-14)
🪛 Ruff (0.8.2)
tests/test_feature_extraction.py

95-95: Use is and is not for type comparisons, or isinstance() for isinstance checks

(E721)

src/readii/loaders.py

19-19: imgtools.coretypes.RTStructureSet imported but unused

Remove unused import: imgtools.coretypes.RTStructureSet

(F401)

⏰ Context from checks skipped due to timeout of 90000ms (9)
  • GitHub Check: Unit-Tests (windows-latest, py312)
  • GitHub Check: Unit-Tests (windows-latest, py311)
  • GitHub Check: Unit-Tests (windows-latest, py310)
  • GitHub Check: Unit-Tests (macos-14, py312)
  • GitHub Check: Unit-Tests (macos-14, py311)
  • GitHub Check: Unit-Tests (macos-14, py310)
  • GitHub Check: Unit-Tests (macos-latest, py311)
  • GitHub Check: Unit-Tests (macos-latest, py310)
  • GitHub Check: Unit-Tests (ubuntu-latest, py312)
🔇 Additional comments (13)
src/readii/utils/logging_config.py (1)

1-1: Updated import path correctly.

The import path has been properly updated from imgtools.logging to imgtools.loggers to align with the MIT2.0 package structure changes.

pyproject.toml (1)

12-12: Dependency version update reflects MIT2.0 requirements.

The minimum required version for med-imagetools was correctly updated from ">=1.9.2" to ">=2" to support the new API changes used throughout the codebase.

src/readii/process/images/crop.py (1)

5-5: Updated import path correctly.

The import path has been properly updated from imgtools.ops.functional to imgtools.transforms.functional to reflect the MIT2.0 package structure changes.

src/readii/feature_extraction.py (1)

8-8: Updated import path correctly.

The import has been properly updated from imgtools.io.read_dicom_series to imgtools.io.readers.read_dicom_auto to align with the MIT2.0 package restructuring.

tests/test_image_processing.py (2)

21-22: ROI specification updated to reflect new MIT2.0 pattern.

The change from a dictionary with regex pattern to a direct list of ROI names aligns with the MIT2.0 update, which requires explicit ROI specification rather than pattern matching.


61-61: Adjusted expected center coordinates to match updated ROI handling.

The coordinates update from (63, 314, 318) to (63, 312, 328) reflects changes in how the new MIT2.0 methods process and position the ROI masks.

tests/test_loaders.py (2)

81-81: Updated image spacing expectations to match MIT2.0 output.

The spacing values changed from (0.9766, 0.9766, 3.0) to (1.0, 1.0, 1.0), reflecting the normalization applied by the updated MIT2.0 methods.


83-83: Origin reset in MIT2.0 reflected in test expectations.

The origin values changed from specific coordinates to (0, 0, 0), indicating that the new MIT2.0 implementation normalizes the origin.

tests/process/images/test_crop.py (2)

40-40: ROI specification updated to explicit list format.

Changed from a regex string to a direct list ["Tumor_c40"] to align with the MIT2.0 implementation's requirement for explicit ROI names.


46-46: Updated expected dimensions to match MIT2.0 cropping behavior.

The expected dimensions have been incremented (e.g., from 92 to 93 for the cube method) to align with the updated MIT2.0 implementation which produces slightly larger cropped regions.

Also applies to: 57-59

tests/test_feature_extraction.py (3)

40-41: ROI specification updated to explicit list format.

Changed from a dictionary mapping with regex to a direct list of ROI names, aligning with the MIT2.0 implementation. Correspondingly, the dictionary key used to access the segmentation is updated to the actual ROI name.


101-103: Updated expected size and volume metrics to match MIT2.0 output.

The dimensions and volume calculations differ with the new MIT2.0 implementation. Expected size changed from a smaller bounding box to (52, 93, 28) and the volume increased from ~66K to ~71K, reflecting the more accurate segmentation processing.

Also applies to: 107-107


146-146: Standardized ROI name format as a list.

Changed from a string to a list ["Tumor_c40"] for consistency with the MIT2.0 API requirements for ROI specifications.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🔭 Outside diff range comments (2)
src/readii/loaders.py (2)

44-46: ⚠️ Potential issue

Update function signature for ROI names parameter

To match the implementation which iterates over roiNames, the parameter type should be updated.

def loadRTSTRUCTSITK(
-   rtstructPath: str | Path, baseImageDirPath: str | Path, roiNames: Optional[str] = None
+   rtstructPath: str | Path, baseImageDirPath: str | Path, roiNames: Optional[Sequence[str]] = None
) -> Dict[str, sitk.Image]:

93-97: ⚠️ Potential issue

Update loadSegmentation function signature

The roiNames parameter in this function should also be updated to match the implementation in loadRTSTRUCTSITK.

def loadSegmentation(
    segImagePath: str | Path,
    modality: str,
    baseImageDirPath: Optional[str | Path] = None,
-   roiNames: Optional[str] = None,
+   roiNames: Optional[Sequence[str]] = None,
) -> Dict[str, sitk.Image]:
♻️ Duplicate comments (3)
src/readii/loaders.py (3)

16-18: Updated imports for MIT2.0 compatibility

The switch to read_dicom_auto from the new MIT2.0 API allows for unified DICOM reading. However, you should remove the commented out import and unused imports to maintain clean code.

from imgtools.io.readers import read_dicom_auto
-# from imgtools.ops import StructureSetToSegmentation

70-71: 🛠️ Refactor suggestion

Added path existence validation needed

While the new read_dicom_auto function simplifies the code, it's recommended to add path existence checks to provide more meaningful error messages.

logger.debug(f"Loading RTSTRUCT from directory: {rtstructPath}")
+if not baseImageDirPath.exists():
+    raise FileNotFoundError(f"Base-image directory not found: {baseImageDirPath}")
+if not rtstructPath.exists():
+    raise FileNotFoundError(f"RTSTRUCT file not found: {rtstructPath}")

baseImage = read_dicom_auto(path=baseImageDirPath.resolve())
segImage = read_dicom_auto(path=rtstructPath.resolve(), modality="RTSTRUCT")

76-88: 🛠️ Refactor suggestion

ROI mask processing updated for MIT2.0

The updated implementation correctly uses the new MIT2.0 API for mask generation. However, there are several improvements needed:

  1. The function still declares roiNames as Optional[str] but iterates over it
  2. No validation for empty/None roiNames
  3. The SimpleITK image created from the mask does not copy the spatial metadata from the base image
from pathlib import Path
-from typing import Dict, Optional
+from typing import Dict, Optional, Sequence

def loadRTSTRUCTSITK(
-   rtstructPath: str | Path, baseImageDirPath: str | Path, roiNames: Optional[str] = None
+   rtstructPath: str | Path, baseImageDirPath: str | Path, roiNames: Optional[Sequence[str]] = None
) -> Dict[str, sitk.Image]:
    """Load RTSTRUCT into SimpleITK Image.
    ...
    roiNames : Sequence[str], optional
        Identifiers for which region(s) of interest to load from the segmentation file.
    ...
    """

And in the implementation:

logger.debug(f"Making mask using ROI names: {roiNames}")
+if not roiNames:
+    raise ValueError("`roiNames` must be a non-empty sequence of ROI names")

img_size = baseImage.size

segMasks = {}
for roi in roiNames:
    try:
        mask_ndarray = segImage.get_mask_ndarray(reference_image = baseImage,
                                                roi_name = roi,
                                                mask_img_size = [img_size.depth, img_size.height, img_size.width, 1],
                                                continuous = False)
-        segMasks[roi] = sitk.GetImageFromArray(mask_ndarray)
+        mask = sitk.GetImageFromArray(mask_ndarray)
+        # Copy spatial metadata so the mask aligns with the base image
+        if hasattr(baseImage, 'sitk_image'):
+            mask.CopyInformation(baseImage.sitk_image)
+        else:
+            # If baseImage is already a SimpleITK image
+            mask.CopyInformation(baseImage)
+        segMasks[roi] = mask
    except ValueError:
        segMasks[roi] = None
🧹 Nitpick comments (2)
tests/test_feature_extraction.py (1)

94-94: Use isinstance() for type checking

Type comparison with == is less robust than using isinstance().

-    assert type(actual) == collections.OrderedDict, \
+    assert isinstance(actual, collections.OrderedDict), \
🧰 Tools
🪛 Ruff (0.8.2)

94-94: Use is and is not for type comparisons, or isinstance() for isinstance checks

(E721)

src/readii/loaders.py (1)

74-74: Log message needs to be updated for list of ROI names

The log message should be updated to better represent that roiNames is now expected to be a sequence.

-logger.debug(f"Making mask using ROI names: {roiNames}")
+logger.debug(f"Making masks for ROIs: {', '.join(roiNames) if roiNames else 'None'}")
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 273e6eb and 7ba15ea.

📒 Files selected for processing (17)
  • notebooks/crop_testing.ipynb (2 hunks)
  • notebooks/debugging.ipynb (0 hunks)
  • notebooks/viz_neg_4D.ipynb (0 hunks)
  • notebooks/viz_neg_controls.ipynb (1 hunks)
  • notebooks/writer_examples.ipynb (0 hunks)
  • src/readii/loaders.py (2 hunks)
  • src/readii/negative_controls.py (1 hunks)
  • src/readii/pipeline.py (0 hunks)
  • src/readii/process/images/crop.py (2 hunks)
  • tests/analyze/test_plot_correlation.py (5 hunks)
  • tests/io/loaders/test_features.py (0 hunks)
  • tests/io/writers/test_base_writer.py (0 hunks)
  • tests/io/writers/test_correlation_writer.py (1 hunks)
  • tests/io/writers/test_nifti_writer.py (0 hunks)
  • tests/process/images/test_crop.py (2 hunks)
  • tests/test_feature_extraction.py (3 hunks)
  • tests/test_negative_controls.py (1 hunks)
💤 Files with no reviewable changes (7)
  • tests/io/loaders/test_features.py
  • tests/io/writers/test_base_writer.py
  • tests/io/writers/test_nifti_writer.py
  • notebooks/writer_examples.ipynb
  • notebooks/viz_neg_4D.ipynb
  • src/readii/pipeline.py
  • notebooks/debugging.ipynb
✅ Files skipped from review due to trivial changes (5)
  • tests/io/writers/test_correlation_writer.py
  • src/readii/negative_controls.py
  • tests/analyze/test_plot_correlation.py
  • notebooks/viz_neg_controls.ipynb
  • notebooks/crop_testing.ipynb
🚧 Files skipped from review as they are similar to previous changes (2)
  • src/readii/process/images/crop.py
  • tests/process/images/test_crop.py
🧰 Additional context used
🧬 Code Graph Analysis (2)
tests/test_negative_controls.py (1)
src/readii/negative_controls.py (1)
  • negativeControlNonROIOnly (258-322)
tests/test_feature_extraction.py (1)
tests/test_loaders.py (1)
  • lung4DCTPath (13-14)
🪛 Ruff (0.8.2)
tests/test_feature_extraction.py

94-94: Use is and is not for type comparisons, or isinstance() for isinstance checks

(E721)

⏰ Context from checks skipped due to timeout of 90000ms (7)
  • GitHub Check: Unit-Tests (windows-latest, py312)
  • GitHub Check: Unit-Tests (windows-latest, py311)
  • GitHub Check: Unit-Tests (windows-latest, py310)
  • GitHub Check: Unit-Tests (macos-14, py312)
  • GitHub Check: Unit-Tests (macos-14, py311)
  • GitHub Check: Unit-Tests (macos-latest, py311)
  • GitHub Check: Unit-Tests (ubuntu-latest, py312)
🔇 Additional comments (4)
tests/test_negative_controls.py (1)

4-10: LGTM: Import cleanup aligned with MIT2.0 update

The removal of unused imports (imageoperations from radiomics, applyNegativeControl from readii.negative_controls, and collections) while keeping the necessary imports is a good cleanup. This aligns with the overall PR objective of fixing errors caused by the MIT2.0 update and streamlining imports.

tests/test_feature_extraction.py (3)

39-40: Updated ROI specification format

The change from dictionary/regex pattern {'GTV':'Tumor_c.*'} to explicit list ['Tumor_c40'] aligns with the new MIT2.0 approach for ROI specification. This is more explicit and less error-prone than using regex patterns.


100-106: Size and volume modifications match new loader implementation

The updated expected dimensions (52x93x28) and volume feature (71110.67) reflect the changes in how the segmentation masks are extracted with the new MIT2.0 implementation. These values are essential to maintain test validity after refactoring.


145-145: Consistent ROI names format

The change from string "Tumor_c40" to list ["Tumor_c40"] ensures consistent ROI specification across the codebase, improving maintainability.

@strixy16 strixy16 merged commit 2a899a7 into main May 14, 2025
11 of 18 checks passed
@github-project-automation github-project-automation bot moved this from Focus to Done in READII-2-ROQC Pipeline May 14, 2025
@strixy16 strixy16 deleted the katys/fix-logger-errors branch May 14, 2025 05:15
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

Archived in project

Development

Successfully merging this pull request may close these issues.

imgtools.logging module doesn't exist/got renamed, breaks a bunch of things

1 participant