-
Notifications
You must be signed in to change notification settings - Fork 1.4k
Enhance ExtractDataKeyFromMetaKeyd to work with MetaTensor #8772
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
haoyu-haoyu
wants to merge
1
commit into
Project-MONAI:dev
Choose a base branch
from
haoyu-haoyu:fix/enhance-extract-data-key-from-meta-keyd-metatensor
base: dev
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
116 changes: 116 additions & 0 deletions
116
tests/apps/reconstruction/transforms/test_extract_data_key_from_meta_keyd.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,116 @@ | ||
| # Copyright (c) MONAI Consortium | ||
| # Licensed under the Apache License, Version 2.0 (the "License"); | ||
| # you may not use this file except in compliance with the License. | ||
| # You may obtain a copy of the License at | ||
| # http://www.apache.org/licenses/LICENSE-2.0 | ||
| # Unless required by applicable law or agreed to in writing, software | ||
| # distributed under the License is distributed on an "AS IS" BASIS, | ||
| # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| # See the License for the specific language governing permissions and | ||
| # limitations under the License. | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| import unittest | ||
|
|
||
| import torch | ||
|
|
||
| from monai.apps.reconstruction.transforms.dictionary import ExtractDataKeyFromMetaKeyd | ||
| from monai.data import MetaTensor | ||
|
|
||
|
|
||
| class TestExtractDataKeyFromMetaKeyd(unittest.TestCase): | ||
| """Tests for ExtractDataKeyFromMetaKeyd covering both dict-based and MetaTensor-based metadata.""" | ||
|
|
||
| def test_extract_from_dict(self): | ||
| """Test extracting keys from a plain metadata dictionary (image_only=False scenario).""" | ||
| data = { | ||
| "image": torch.zeros(1, 2, 2), | ||
| "image_meta_dict": {"filename_or_obj": "image.nii", "spatial_shape": [2, 2]}, | ||
| } | ||
| transform = ExtractDataKeyFromMetaKeyd(keys="filename_or_obj", meta_key="image_meta_dict") | ||
| result = transform(data) | ||
| self.assertIn("filename_or_obj", result) | ||
| self.assertEqual(result["filename_or_obj"], "image.nii") | ||
| self.assertEqual(result["image_meta_dict"]["filename_or_obj"], result["filename_or_obj"]) | ||
|
|
||
| def test_extract_from_metatensor(self): | ||
| """Test extracting keys from a MetaTensor's .meta attribute (image_only=True scenario).""" | ||
| meta = {"filename_or_obj": "image.nii", "spatial_shape": [2, 2]} | ||
| mt = MetaTensor(torch.zeros(1, 2, 2), meta=meta) | ||
| data = {"image": mt} | ||
| transform = ExtractDataKeyFromMetaKeyd(keys="filename_or_obj", meta_key="image") | ||
| result = transform(data) | ||
| self.assertIn("filename_or_obj", result) | ||
| self.assertEqual(result["filename_or_obj"], "image.nii") | ||
| self.assertEqual(result["image"].meta["filename_or_obj"], result["filename_or_obj"]) | ||
|
|
||
| def test_extract_multiple_keys_from_metatensor(self): | ||
| """Test extracting multiple keys from a MetaTensor.""" | ||
| meta = {"filename_or_obj": "image.nii", "spatial_shape": [2, 2], "affine": "identity"} | ||
| mt = MetaTensor(torch.zeros(1, 2, 2), meta=meta) | ||
| data = {"image": mt} | ||
| transform = ExtractDataKeyFromMetaKeyd(keys=["filename_or_obj", "spatial_shape"], meta_key="image") | ||
| result = transform(data) | ||
| self.assertIn("filename_or_obj", result) | ||
| self.assertIn("spatial_shape", result) | ||
| self.assertEqual(result["filename_or_obj"], "image.nii") | ||
| self.assertEqual(result["spatial_shape"], [2, 2]) | ||
|
|
||
| def test_extract_multiple_keys_from_dict(self): | ||
| """Test extracting multiple keys from a plain dictionary.""" | ||
| data = { | ||
| "image": torch.zeros(1, 2, 2), | ||
| "image_meta_dict": {"filename_or_obj": "image.nii", "spatial_shape": [2, 2]}, | ||
| } | ||
| transform = ExtractDataKeyFromMetaKeyd(keys=["filename_or_obj", "spatial_shape"], meta_key="image_meta_dict") | ||
| result = transform(data) | ||
| self.assertIn("filename_or_obj", result) | ||
| self.assertIn("spatial_shape", result) | ||
| self.assertEqual(result["filename_or_obj"], "image.nii") | ||
| self.assertEqual(result["spatial_shape"], [2, 2]) | ||
|
|
||
| def test_missing_key_raises(self): | ||
| """Test that a missing key raises KeyError when allow_missing_keys=False.""" | ||
| meta = {"filename_or_obj": "image.nii"} | ||
| mt = MetaTensor(torch.zeros(1, 2, 2), meta=meta) | ||
| data = {"image": mt} | ||
| transform = ExtractDataKeyFromMetaKeyd(keys="nonexistent_key", meta_key="image") | ||
| with self.assertRaises(KeyError): | ||
| transform(data) | ||
|
|
||
| def test_missing_key_allowed_metatensor(self): | ||
| """Test that a missing key is silently skipped when allow_missing_keys=True with MetaTensor.""" | ||
| meta = {"filename_or_obj": "image.nii"} | ||
| mt = MetaTensor(torch.zeros(1, 2, 2), meta=meta) | ||
| data = {"image": mt} | ||
| transform = ExtractDataKeyFromMetaKeyd(keys="nonexistent_key", meta_key="image", allow_missing_keys=True) | ||
| result = transform(data) | ||
| self.assertNotIn("nonexistent_key", result) | ||
|
|
||
| def test_missing_key_allowed_dict(self): | ||
| """Test that a missing key is silently skipped when allow_missing_keys=True with dict.""" | ||
| data = { | ||
| "image": torch.zeros(1, 2, 2), | ||
| "image_meta_dict": {"filename_or_obj": "image.nii"}, | ||
| } | ||
| transform = ExtractDataKeyFromMetaKeyd( | ||
| keys="nonexistent_key", meta_key="image_meta_dict", allow_missing_keys=True | ||
| ) | ||
| result = transform(data) | ||
| self.assertNotIn("nonexistent_key", result) | ||
|
|
||
| def test_original_data_preserved_metatensor(self): | ||
| """Test that the original MetaTensor remains in the data dictionary.""" | ||
| meta = {"filename_or_obj": "image.nii"} | ||
| mt = MetaTensor(torch.ones(1, 2, 2), meta=meta) | ||
| data = {"image": mt} | ||
| transform = ExtractDataKeyFromMetaKeyd(keys="filename_or_obj", meta_key="image") | ||
| result = transform(data) | ||
| self.assertIn("image", result) | ||
| self.assertIsInstance(result["image"], MetaTensor) | ||
| self.assertTrue(torch.equal(result["image"], mt)) | ||
|
|
||
|
|
||
| if __name__ == "__main__": | ||
| unittest.main() | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🧩 Analysis chain
🏁 Script executed:
Repository: Project-MONAI/MONAI
Length of output: 3258
🏁 Script executed:
Repository: Project-MONAI/MONAI
Length of output: 4638
Line 112 does not verify "original object preserved."
torch.equal(...)checks tensor value equality, not object identity. Since the transform preserves the original MetaTensor object reference (via shallow dict copy), useassertIs()to verify:Proposed test fix
🤖 Prompt for AI Agents