Skip to content

Conversation

lukas-folle-snkeos
Copy link

@lukas-folle-snkeos lukas-folle-snkeos commented Aug 8, 2025

Fixes #8528.

Description

This PR adds the FlatttenSequence transform (a flavor of the also newly added ReduceTrait) which can flatten a nested data structure by one level. This way, #8528 can be tackled without the need to change the apply_transform of Compose significantly.

Types of changes

  • Non-breaking change (fix or new feature that would not break existing functionality).
  • Breaking change (fix or new feature that would cause existing functionality to change).
  • New tests added to cover the changes.
  • Integration tests passed locally by running ./runtests.sh -f -u --net --coverage.
  • Quick tests passed locally by running ./runtests.sh --quick --unittests --disttests.
  • In-line docstrings updated.
  • Documentation updated, tested make html command in the docs/ folder.

Copy link
Contributor

coderabbitai bot commented Aug 8, 2025

Walkthrough

Adds a new trait class ReduceTrait and exports it. Introduces FlattenSequence (array) and FlattenSequenced / FlattenSequenceD / FlattenSequenceDict (dictionary) transforms implementing ReduceTrait and exported from monai.transforms. apply_transform in monai/transforms/transform.py now guards to skip per-item list/tuple mapping when the transform is an instance of ReduceTrait. key_iterator KeyError message was collapsed into a single line. Tests for multi-sample and flattening behavior were added. Documentation and public exports updated to include the new transforms.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Assessment against linked issues

Objective Addressed Explanation
Fix handling of nested lists/tuples in apply_transform to avoid list-of-lists in MultiSampleTrait stacking (#8528) apply_transform now skips per-item mapping when the transform is a ReduceTrait, preventing recursive list-of-list wrapping for reducing transforms.

Assessment against linked issues: Out-of-scope changes

Added documentation entries, public exports, and new public transforms (FlattenSequence, FlattenSequenced and aliases). These API additions are not required for the linked-issue fix but accompany the change.

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (4 passed)
Check name Status Explanation
Linked Issues Check ✅ Passed The PR implements the requested flatten‐after-MultiSampleTrait behavior, adds ReduceTrait to prevent unintended unwrapping, introduces explicit FlattenSequence transforms, and includes relevant tests, fully addressing issue #8528.
Out of Scope Changes Check ✅ Passed All modifications—including trait additions, apply_transform logic, new transforms, exports, tests, and documentation—directly support the nested-list flattening objective and there are no unrelated changes.
Description Check ✅ Passed The pull request description adheres to the repository template by including a Fixes reference, a concise Description section outlining the addition of the FlattenSequence transform and ReduceTrait logic, and a complete Types of changes checklist with appropriate items marked, fulfilling all required sections and formatting rules.
Title Check ✅ Passed The title succinctly summarizes the primary additions in the changeset by naming the newly introduced ReduceTrait and FlattenSequence transforms, aligning with the main implementation and API updates in the PR.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment

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.

I, Lukas Folle <lukas.folle@snke.com>, hereby add my Signed-off-by to this commit: e0cda55

Signed-off-by: Lukas Folle <lukas.folle@snke.com>
I, Lukas Folle <lukas.folle@snke.com>, hereby add my Signed-off-by to this commit: e0cda55

Signed-off-by: Lukas Folle <lukas.folle@snke.com>
I, Lukas Folle <lukas.folle@snke.com>, hereby add my Signed-off-by to this commit: e0cda55

Signed-off-by: Lukas Folle <lukas.folle@snke.com>
I, Lukas Folle <lukas.folle@snke.com>, hereby add my Signed-off-by to this commit: e0cda55

Signed-off-by: Lukas Folle <lukas.folle@snke.com>
DCO Remediation Commit for Lukas Folle <lukas.folle@snke.com>

I, Lukas Folle <lukas.folle@snke.com>, hereby add my Signed-off-by to this commit: eeb7e12

Signed-off-by: Lukas Folle <lukas.folle@snke.com>
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: 1

🧹 Nitpick comments (5)
monai/transforms/transform.py (5)

127-137: Docstring: fix parameter name and clarify behavior

“map_data” should be “map_items”, and mention that list/tuple returns are flattened one level.

-    If `data` is a list or tuple and `map_data` is True, each item of `data` will be transformed
+    If `data` is a list or tuple and `map_items` is True, each item of `data` will be transformed
     and this method returns a list of outcomes.
@@
-            - If an integer is provided, it specifies the maximum level of nesting to which the transformation
-              should be recursively applied. This allows treating multi-sample transforms applied after another
-              multi-sample transform while controlling how deep the mapping goes.
+            - If an integer is provided, it specifies the maximum level of nesting to which the transformation
+              should be recursively applied. When a transform returns a list or tuple, the results are flattened
+              one level at each mapped depth.

174-199: Exception logging: style-only — OK; avoid mutating data for logging

Formatting is good. Minor nit: don’t reassign data when logging a first element; use a temp to avoid shadowing.

-            if isinstance(data, (list, tuple)):
-                data = data[0]
+            if isinstance(data, (list, tuple)):
+                _data_for_log = data[0]
+            else:
+                _data_for_log = data
@@
-            if isinstance(data, dict):
-                for k, v in data.items():
+            if isinstance(_data_for_log, dict):
+                for k, v in _data_for_log.items():
                     _log_stats(data=v, prefix=k)
             else:
-                _log_stats(data=data)
+                _log_stats(data=_data_for_log)

459-461: TypeError message should report offending element type, not keys

Inside the loop, report type(key).__name__} for clarity.

-                raise TypeError(
-                    f"keys must be one of (Hashable, Iterable[Hashable]) but is {type(keys).__name__}."
-                )
+                raise TypeError(
+                    f"keys must be one of (Hashable, Iterable[Hashable]); "
+                    f"found element of type {type(key).__name__}."
+                )

515-518: key_iterator: signature formatting — OK

Optional: annotate as Generator[Any, None, None] for completeness.


66-68: Docstring nits in _apply_transform

  • Typo: “this class is function” → “this function”.
  • Sphinx ref missing closing backtick: :ref:Lazy Resampling topic<lazy_resampling>.

Also applies to: 75-78

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Knowledge Base: Disabled due to Reviews > Disable Knowledge Base setting

📥 Commits

Reviewing files that changed from the base of the PR and between b92b2ce and 7560a37.

📒 Files selected for processing (1)
  • monai/transforms/transform.py (10 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
**/*.py

⚙️ CodeRabbit Configuration File

Review the Python code for quality and correctness. Ensure variable names adhere to PEP8 style guides, are sensible and informative in regards to their function, though permitting simple names for loop and comprehension variables. Ensure routine names are meaningful in regards to their function and use verbs, adjectives, and nouns in a semantically appropriate way. Docstrings should be present for all definition which describe each variable, return value, and raised exception in the appropriate section of the Google-style of docstrings. Examine code for logical error or inconsistencies, and suggest what may be changed to addressed these. Suggest any enhancements for code improving efficiency, maintainability, comprehensibility, and correctness. Ensure new or modified definitions will be covered by existing or new unit tests.

Files:

  • monai/transforms/transform.py
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (19)
  • GitHub Check: quick-py3 (ubuntu-latest)
  • GitHub Check: flake8-py3 (codeformat)
  • GitHub Check: quick-py3 (windows-latest)
  • GitHub Check: flake8-py3 (pytype)
  • GitHub Check: build-docs
  • GitHub Check: quick-py3 (macOS-latest)
  • GitHub Check: flake8-py3 (mypy)
  • GitHub Check: packaging
  • GitHub Check: min-dep-os (ubuntu-latest)
  • GitHub Check: min-dep-os (macOS-latest)
  • GitHub Check: min-dep-pytorch (2.7.1)
  • GitHub Check: min-dep-pytorch (2.4.1)
  • GitHub Check: min-dep-os (windows-latest)
  • GitHub Check: min-dep-py3 (3.10)
  • GitHub Check: min-dep-pytorch (2.6.0)
  • GitHub Check: min-dep-pytorch (2.5.1)
  • GitHub Check: min-dep-py3 (3.9)
  • GitHub Check: min-dep-py3 (3.11)
  • GitHub Check: min-dep-py3 (3.12)
🔇 Additional comments (8)
monai/transforms/transform.py (8)

93-108: _apply_transform: style-only refactor — OK

Multiline call/returns improve readability; logic unchanged.


225-263: set_random_state: seeding cast and MAX_SEED mod — OK

Casting to int64 and modding by MAX_SEED is appropriate for NumPy 2.0 compatibility; type checks/readability improved.


256-259: Type check message — OK

Clear, explicit message; no change requested.


277-279: NotImplemented message — OK

Consistent and informative.


335-337: NotImplemented message — OK

Consistent and informative.


441-448: Hook attachment formatting — OK

No behavioral change; readability improved.


481-483: sync_meta_info call — OK

Style change only; behavior preserved.


511-513: NotImplemented message — OK

Consistent across classes.

I, Lukas Folle <lukas.folle@snke.com>, hereby add my Signed-off-by to this commit: e0cda55

Signed-off-by: Lukas Folle <lukas.folle@snke.com>
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: 1

🧹 Nitpick comments (2)
monai/transforms/transform.py (2)

156-165: Type annotation tightening

The function currently declares -> list[Any] | ReturnType but constructs list[ReturnType]. Prefer narrowing to list[ReturnType] | ReturnType for consistency.

Proposed signature (outside this hunk):

def apply_transform(...) -> list[ReturnType] | ReturnType:
    ...

515-518: Return type hint could be more explicit

key_iterator yields either a Hashable or a tuple when extra iterables are present. Consider tightening the annotation for better tooling.

-    ) -> Generator:
+    ) -> Generator[Hashable | tuple[Hashable, ...], None, None]:
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Knowledge Base: Disabled due to Reviews > Disable Knowledge Base setting

📥 Commits

Reviewing files that changed from the base of the PR and between b92b2ce and 7560a37.

📒 Files selected for processing (1)
  • monai/transforms/transform.py (10 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
**/*.py

⚙️ CodeRabbit Configuration File

Review the Python code for quality and correctness. Ensure variable names adhere to PEP8 style guides, are sensible and informative in regards to their function, though permitting simple names for loop and comprehension variables. Ensure routine names are meaningful in regards to their function and use verbs, adjectives, and nouns in a semantically appropriate way. Docstrings should be present for all definition which describe each variable, return value, and raised exception in the appropriate section of the Google-style of docstrings. Examine code for logical error or inconsistencies, and suggest what may be changed to addressed these. Suggest any enhancements for code improving efficiency, maintainability, comprehensibility, and correctness. Ensure new or modified definitions will be covered by existing or new unit tests.

Files:

  • monai/transforms/transform.py
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (4)
  • GitHub Check: quick-py3 (ubuntu-latest)
  • GitHub Check: quick-py3 (windows-latest)
  • GitHub Check: quick-py3 (macOS-latest)
  • GitHub Check: packaging
🔇 Additional comments (14)
monai/transforms/transform.py (14)

93-96: Refactor-only: OK

Call-site reformatting reads cleaner. No functional change.


98-103: Refactor-only: OK

Tuple-unpack branch formatting is fine. No logic change.


104-108: Refactor-only: OK

Single-arg branch formatting is fine. No logic change.


174-199: Refactor-only: OK

Error-logging reformatting is clear; logic unchanged.


225-227: Refactor-only: OK

Signature reflow is fine; types unchanged.


245-251: Seed normalization: OK

Modulo against MAX_SEED post np.int64 cast is reasonable for NumPy 2.0 compat.


256-258: Refactor-only: OK

TypeError message formatting is fine.


277-279: Refactor-only: OK

NotImplementedError reflow is fine.


335-337: Refactor-only: OK

Abstract call error message reflow is fine.


441-443: Refactor-only: OK

Hook attachment formatting is clearer.


447-448: Refactor-only: OK

Inverse hook formatting is clearer.


459-461: Refactor-only: OK

Type check error formatting is fine.


481-483: Refactor-only: OK

sync_meta_info call formatting is fine.


511-513: Refactor-only: OK

NotImplementedError reflow is fine.

DCO Remediation Commit for Lukas Folle <lukas.folle@snke.com>

I, Lukas Folle <lukas.folle@snke.com>, hereby add my Signed-off-by to this commit: e0cda55

Signed-off-by: Lukas Folle <lukas.folle@snke.com>
DCO Remediation Commit for Lukas Folle <lukas.folle@snke.com>

I, Lukas Folle <lukas.folle@snke.com>, hereby add my Signed-off-by to this commit: e0cda55

Signed-off-by: Lukas Folle <lukas.folle@snke.com>
@lukas-folle-snkeos
Copy link
Author

All remaining failing CI runs are not coming from this change.

@ericspod ericspod requested a review from atbenmurray August 15, 2025 02:46
@ericspod
Copy link
Member

Hi @lukas-folle-snkeos thanks for the contribution! Please check the logic I flagged and we do need tests to check that this behaviour is correct. You can take the mentioned issue as an example of what to check for but I think we need to test this logic thoroughly and more clearly document what's going on in comments.

@ericspod ericspod mentioned this pull request Sep 12, 2025
55 tasks
@atbenmurray
Copy link
Contributor

Taking a look.

@lukas-folle-snkeos
Copy link
Author

Thanks for the review @ericspod! I added a test with a real transform and refactored the code as suggested.

I, Lukas Folle <lukas.folle@snke.com>, hereby add my Signed-off-by to this commit: 2d58774

Signed-off-by: Lukas Folle <lukas.folle@snke.com>
I, Lukas Folle <lukas.folle@snke.com>, hereby add my Signed-off-by to this commit: 2d58774

Signed-off-by: Lukas Folle <lukas.folle@snke.com>
I, Lukas Folle <lukas.folle@snke.com>, hereby add my Signed-off-by to this commit: 2d58774

Signed-off-by: Lukas Folle <lukas.folle@snke.com>

Merge branch 'dev' of github.com:lukas-folle-snkeos/MONAI into dev
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

🧹 Nitpick comments (3)
tests/transforms/compose/test_compose.py (3)

286-290: Use existing mt import for consistency.

Avoid method-local imports; leverage import monai.transforms as mt already present.

-        from monai.transforms import CenterSpatialCrop, RandSpatialCropSamples
-
-        center_crop = CenterSpatialCrop([128, 128])
-        multi_sample_transform = RandSpatialCropSamples([64, 64], 1)
+        center_crop = mt.CenterSpatialCrop([128, 128])
+        multi_sample_transform = mt.RandSpatialCropSamples([64, 64], 1)

293-305: Prefer unittest assertions over bare assert.

Gives richer failure messages and isn’t optimized away with -O. Also add explicit tensor-type checks.

-        assert execute_compose(img, [center_crop]).shape == torch.Size([1, 128, 128])
+        self.assertEqual(execute_compose(img, [center_crop]).shape, torch.Size([1, 128, 128]))
         single_multi_sample_trait_result = execute_compose(img, [multi_sample_transform, center_crop])
-        assert (
-            isinstance(single_multi_sample_trait_result, list)
-            and len(single_multi_sample_trait_result) == 1
-            and single_multi_sample_trait_result[0].shape == torch.Size([1, 64, 64])
-        )
+        self.assertIsInstance(single_multi_sample_trait_result, list)
+        self.assertEqual(len(single_multi_sample_trait_result), 1)
+        self.assertIsInstance(single_multi_sample_trait_result[0], torch.Tensor)
+        self.assertEqual(single_multi_sample_trait_result[0].shape, torch.Size([1, 64, 64]))
         double_multi_sample_trait_result = execute_compose(img, [multi_sample_transform, multi_sample_transform, center_crop])
-        assert (
-            isinstance(double_multi_sample_trait_result, list)
-            and len(double_multi_sample_trait_result) == 1
-            and double_multi_sample_trait_result[0].shape == torch.Size([1, 64, 64])
-        )
+        self.assertIsInstance(double_multi_sample_trait_result, list)
+        self.assertEqual(len(double_multi_sample_trait_result), 1)
+        self.assertIsInstance(double_multi_sample_trait_result[0], torch.Tensor)
+        self.assertEqual(double_multi_sample_trait_result[0].shape, torch.Size([1, 64, 64]))

291-306: Add 2 more assertions to harden behavior.

  • Cardinality when chaining (e.g., 2 samples then 2 samples => 4).
  • Preservation when the original input is a list (no over-flatten).

Proposed test to add nearby:

def test_multi_sample_trait_cardinality_and_preserve_nested(self):
    img = torch.zeros([1, 128, 128])
    t2 = mt.RandSpatialCropSamples([32, 32], num_samples=2)

    # chaining should multiply counts: 2 x 2 = 4, flattened
    res = execute_compose(img, [t2, t2])
    self.assertIsInstance(res, list)
    self.assertEqual(len(res), 4)
    for r in res:
        self.assertEqual(r.shape, torch.Size([1, 32, 32]))

    # original list input should preserve nested structure
    res2 = execute_compose([img], [t2])
    self.assertIsInstance(res2, list)
    self.assertEqual(len(res2), 1)
    self.assertIsInstance(res2[0], list)
    self.assertEqual(len(res2[0]), 2)
📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Knowledge base: Disabled due to Reviews -> Disable Knowledge Base setting

📥 Commits

Reviewing files that changed from the base of the PR and between be46018 and 2d58774.

📒 Files selected for processing (2)
  • monai/transforms/transform.py (2 hunks)
  • tests/transforms/compose/test_compose.py (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • monai/transforms/transform.py
🧰 Additional context used
📓 Path-based instructions (1)
**/*.py

⚙️ CodeRabbit configuration file

Review the Python code for quality and correctness. Ensure variable names adhere to PEP8 style guides, are sensible and informative in regards to their function, though permitting simple names for loop and comprehension variables. Ensure routine names are meaningful in regards to their function and use verbs, adjectives, and nouns in a semantically appropriate way. Docstrings should be present for all definition which describe each variable, return value, and raised exception in the appropriate section of the Google-style of docstrings. Examine code for logical error or inconsistencies, and suggest what may be changed to addressed these. Suggest any enhancements for code improving efficiency, maintainability, comprehensibility, and correctness. Ensure new or modified definitions will be covered by existing or new unit tests.

Files:

  • tests/transforms/compose/test_compose.py
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (19)
  • GitHub Check: build-docs
  • GitHub Check: quick-py3 (ubuntu-latest)
  • GitHub Check: quick-py3 (macOS-latest)
  • GitHub Check: quick-py3 (windows-latest)
  • GitHub Check: flake8-py3 (codeformat)
  • GitHub Check: flake8-py3 (mypy)
  • GitHub Check: packaging
  • GitHub Check: flake8-py3 (pytype)
  • GitHub Check: min-dep-pytorch (2.6.0)
  • GitHub Check: min-dep-pytorch (2.7.1)
  • GitHub Check: min-dep-pytorch (2.8.0)
  • GitHub Check: min-dep-pytorch (2.5.1)
  • GitHub Check: min-dep-py3 (3.11)
  • GitHub Check: min-dep-py3 (3.9)
  • GitHub Check: min-dep-py3 (3.10)
  • GitHub Check: min-dep-py3 (3.12)
  • GitHub Check: min-dep-os (ubuntu-latest)
  • GitHub Check: min-dep-os (windows-latest)
  • GitHub Check: min-dep-os (macOS-latest)
🔇 Additional comments (1)
tests/transforms/compose/test_compose.py (1)

285-306: Good targeted coverage for MultiSampleTrait flattening.

This guards against list-of-lists when chaining multi-sample transforms. Nice.

DCO Remediation Commit for Lukas Folle <lukas.folle@snke.com>

I, Lukas Folle <lukas.folle@snke.com>, hereby add my Signed-off-by to this commit: 2d58774

Signed-off-by: Lukas Folle <lukas.folle@snke.com>
@atbenmurray
Copy link
Contributor

Hi folks. I've taken an initial look at this. I'm always a little afraid of these kind of changes that mandate a particular behaviour. Are there no situations where someone might multi-sample something and then multi-sample the multi-sampled thing and expect the lists to be nested? Should this be fixed in execute_compose instead? Please give me a couple of hours today to take a look at that.

@lukas-folle-snkeos
Copy link
Author

@atbenmurray @ericspod could you please check the status of this PR again?

@atbenmurray
Copy link
Contributor

@lukas-folle-snkeos My apologies; taking a look now

@atbenmurray
Copy link
Contributor

atbenmurray commented Oct 9, 2025

Okay, so apologies for the long wait. I finally managed to get my head into it properly:

I'd like to suggest a slight change. I think that, if a user wants to run multisamples on top of multisamples there will be scenarios in which they don't want to next the output and scenarios in which they do. I'd rather we didn't remove the ability to do so:

I propose that we do the following instead:

  1. Add ReduceTrait to the list of traits
  2. Tweak the code in apply_transform, but slightly differently
  3. Add a FlattenSequence transform that can be inserted when the user wants multiply nested transforms to not generate nested lists
        # modified apply_transform snippet that is ReduceTrait aware
        map_items_ = int(map_items) if isinstance(map_items, bool) else map_items
        if isinstance(data, (list, tuple)) and map_items_ > 0 and not isinstance(transform, ReduceTrait):
            return [
                apply_transform(transform, item, map_items_ - 1, unpack_items, log_stats, lazy, overrides)
                for item in data
            ]
        return _apply_transform(transform, data, unpack_items, lazy, overrides, log_stats)
class ReduceTrait:
    """
    An interface to indicate that the transform has the capability to reduce multiple samples
    into a single sample.
    This interface can be extended from by people adapting transforms to the MONAI framework as well
    as by implementors of MONAI transforms.
    """

    pass
class FlattenSequence(mt.Transform, mtt.ReduceTrait):
    def __init__(self):
        super().__init__()

    def __call__(self, data):
        if isinstance(data, (list, tuple)):
            if len(data) == 0:
                return data
            if isinstance(data[0], (list, tuple)):
                return [item for sublist in data for item in sublist]
        return data

The footprint has a slightly larger change but then we don't lose the flexibility

It would be used as follows:

        mt.CenterSpatialCrop((128, 128)),
        mt.RandSpatialCropSamples((96, 96), num_samples=3),
        mt.RandSpatialCropSamples((64, 64), num_samples=2),
        FlattenSequence(),

We can make interesting uses of ReduceTrait, allowing it to be a trait that can do things like aggregations, catting, etc, as well as flattening lists. WDYT?

@lukas-folle-snkeos
Copy link
Author

@atbenmurray I like that idea; looks a whole lot cleaner to me compared to the initially proposed change! I will bring the changes into this PR.

Signed-off-by: Lukas Folle <lukas.folle@snke.com>
Signed-off-by: Lukas Folle <lukas.folle@snke.com>
Signed-off-by: Lukas Folle <lukas.folle@snke.com>
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: 2

📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Knowledge base: Disabled due to Reviews -> Disable Knowledge Base setting

📥 Commits

Reviewing files that changed from the base of the PR and between fee6cd3 and 416584d.

📒 Files selected for processing (5)
  • monai/transforms/__init__.py (3 hunks)
  • monai/transforms/transform.py (3 hunks)
  • monai/transforms/utility/array.py (3 hunks)
  • monai/transforms/utility/dictionary.py (5 hunks)
  • tests/transforms/compose/test_compose.py (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (3)
  • monai/transforms/transform.py
  • monai/transforms/utility/dictionary.py
  • tests/transforms/compose/test_compose.py
🧰 Additional context used
📓 Path-based instructions (1)
**/*.py

⚙️ CodeRabbit configuration file

Review the Python code for quality and correctness. Ensure variable names adhere to PEP8 style guides, are sensible and informative in regards to their function, though permitting simple names for loop and comprehension variables. Ensure routine names are meaningful in regards to their function and use verbs, adjectives, and nouns in a semantically appropriate way. Docstrings should be present for all definition which describe each variable, return value, and raised exception in the appropriate section of the Google-style of docstrings. Examine code for logical error or inconsistencies, and suggest what may be changed to addressed these. Suggest any enhancements for code improving efficiency, maintainability, comprehensibility, and correctness. Ensure new or modified definitions will be covered by existing or new unit tests.

Files:

  • monai/transforms/utility/array.py
  • monai/transforms/__init__.py
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (19)
  • GitHub Check: min-dep-py3 (3.11)
  • GitHub Check: min-dep-pytorch (2.5.1)
  • GitHub Check: min-dep-os (ubuntu-latest)
  • GitHub Check: min-dep-pytorch (2.7.1)
  • GitHub Check: min-dep-os (macOS-latest)
  • GitHub Check: min-dep-pytorch (2.8.0)
  • GitHub Check: min-dep-pytorch (2.6.0)
  • GitHub Check: min-dep-os (windows-latest)
  • GitHub Check: min-dep-py3 (3.9)
  • GitHub Check: min-dep-py3 (3.12)
  • GitHub Check: min-dep-py3 (3.10)
  • GitHub Check: build-docs
  • GitHub Check: quick-py3 (ubuntu-latest)
  • GitHub Check: quick-py3 (macOS-latest)
  • GitHub Check: packaging
  • GitHub Check: flake8-py3 (codeformat)
  • GitHub Check: flake8-py3 (pytype)
  • GitHub Check: flake8-py3 (mypy)
  • GitHub Check: quick-py3 (windows-latest)
🔇 Additional comments (3)
monai/transforms/__init__.py (3)

509-509: LGTM!

ReduceTrait import is correctly placed with other trait imports.


524-524: LGTM!

FlattenSequence import is correctly placed and alphabetically sorted.


597-599: LGTM!

Dictionary variant imports are correctly placed and follow naming conventions.

Signed-off-by: Lukas Folle <lukas.folle@snke.com>
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: 1

📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Knowledge base: Disabled due to Reviews -> Disable Knowledge Base setting

📥 Commits

Reviewing files that changed from the base of the PR and between 416584d and a8f3fe9.

📒 Files selected for processing (1)
  • monai/transforms/utility/array.py (3 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
**/*.py

⚙️ CodeRabbit configuration file

Review the Python code for quality and correctness. Ensure variable names adhere to PEP8 style guides, are sensible and informative in regards to their function, though permitting simple names for loop and comprehension variables. Ensure routine names are meaningful in regards to their function and use verbs, adjectives, and nouns in a semantically appropriate way. Docstrings should be present for all definition which describe each variable, return value, and raised exception in the appropriate section of the Google-style of docstrings. Examine code for logical error or inconsistencies, and suggest what may be changed to addressed these. Suggest any enhancements for code improving efficiency, maintainability, comprehensibility, and correctness. Ensure new or modified definitions will be covered by existing or new unit tests.

Files:

  • monai/transforms/utility/array.py
🪛 Ruff (0.13.3)
monai/transforms/utility/array.py

1976-1976: Unused function argument: self

(ARG001)

⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (19)
  • GitHub Check: flake8-py3 (codeformat)
  • GitHub Check: quick-py3 (macOS-latest)
  • GitHub Check: packaging
  • GitHub Check: build-docs
  • GitHub Check: flake8-py3 (pytype)
  • GitHub Check: flake8-py3 (mypy)
  • GitHub Check: quick-py3 (ubuntu-latest)
  • GitHub Check: quick-py3 (windows-latest)
  • GitHub Check: min-dep-py3 (3.12)
  • GitHub Check: min-dep-pytorch (2.8.0)
  • GitHub Check: min-dep-pytorch (2.7.1)
  • GitHub Check: min-dep-py3 (3.11)
  • GitHub Check: min-dep-pytorch (2.5.1)
  • GitHub Check: min-dep-pytorch (2.6.0)
  • GitHub Check: min-dep-py3 (3.9)
  • GitHub Check: min-dep-py3 (3.10)
  • GitHub Check: min-dep-os (macOS-latest)
  • GitHub Check: min-dep-os (ubuntu-latest)
  • GitHub Check: min-dep-os (windows-latest)
🔇 Additional comments (2)
monai/transforms/utility/array.py (2)

46-46: LGTM!

Import of ReduceTrait is correct and necessary for the new FlattenSequence class.


113-113: LGTM!

Export declaration properly adds FlattenSequence to the public API.

Signed-off-by: Lukas Folle <lukas.folle@snke.com>
Signed-off-by: Lukas Folle <lukas.folle@snke.com>
@lukas-folle-snkeos lukas-folle-snkeos changed the title added list extend to MultiSampleTrait added list extend to MultiSampleTrait, added ReduceTrait, added FlattenSequence Oct 10, 2025
@lukas-folle-snkeos lukas-folle-snkeos changed the title added list extend to MultiSampleTrait, added ReduceTrait, added FlattenSequence added ReduceTrait and FlattenSequence Oct 10, 2025
@lukas-folle-snkeos
Copy link
Author

@atbenmurray do you want to have a look at the proposed changes?

Copy link
Contributor

@atbenmurray atbenmurray left a comment

Choose a reason for hiding this comment

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

Looks good to me

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.

Stacking two or more MultiSampleTrait-like transforms breaks execute_compose()

3 participants