-
Notifications
You must be signed in to change notification settings - Fork 1.4k
Add clinical preprocessing utilities for CT and MRI modalities. #8659
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
Closed
Hitendrasinhdata7
wants to merge
37
commits into
Project-MONAI:dev
from
Hitendrasinhdata7:clinical-dicom-preprocessing
Closed
Changes from 24 commits
Commits
Show all changes
37 commits
Select commit
Hold shift + click to select a range
5394658
Final commit: add clinical DICOM preprocessing files, workflow PDF, a…
Hitendrasinhdata7 aeabbbd
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] 24665aa
Add clinical DICOM preprocessing Python module, test module, PDF; rem…
Hitendrasinhdata7 798f8af
Remove old notebook files after converting to .py modules
Hitendrasinhdata7 b3a6ac2
Add clinical DICOM preprocessing utilities for CT/MRI with unit tests
Hitendrasinhdata7 a446448
Update clinical preprocessing utilities and tests per CodeRabbit revi…
Hitendrasinhdata7 d7f134c
Refactor clinical preprocessing: add custom exceptions, use isinstanc…
Hitendrasinhdata7 ce7850f
Update clinical preprocessing: add Google-style Returns, parameter ch…
Hitendrasinhdata7 01b88fa
Fix clinical preprocessing module based on code review feedback
Hitendrasinhdata7 81b7f5b
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] 821fc9a
Complete fix for all critical code review issues
Hitendrasinhdata7 1a15437
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] d12bd51
Hitendrasinh Rathod <[email protected]>
Hitendrasinhdata7 634136a
Merge branch 'clinical-dicom-preprocessing' of https://github.com/Hit…
Hitendrasinhdata7 34a7aa2
Complete fix for all CI and code review issues
Hitendrasinhdata7 3a493d4
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] 2b0f6a7
Add MetaTensor import and return type hint
Hitendrasinhdata7 f0261b8
Hitendrasinh Rathod <[email protected]>
Hitendrasinhdata7 1418dcc
Merge branch 'clinical-dicom-preprocessing' of https://github.com/Hit…
Hitendrasinhdata7 1e68a5a
Fix docstring: add Returns section and correct Raises section formatting
Hitendrasinhdata7 7030e7d
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] 441d48d
Add clinical preprocessing transforms
Hitendrasinhdata7 11dce12
Resolve merge conflict - keep clinical preprocessing module
Hitendrasinhdata7 f513c16
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] 2986d2e
Fix CodeRabbit review issues
Hitendrasinhdata7 b3e8f87
Address CodeRabbit review suggestions
Hitendrasinhdata7 5a4fbb5
Final fixes per CodeRabbit review
Hitendrasinhdata7 c273cf7
Fix CI compliance: formatting, type hints, line length
Hitendrasinhdata7 d0961e1
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] 9753c34
Fix CI compliance for clinical preprocessing
Hitendrasinhdata7 0daee66
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] 885ae4b
Fix CodeRabbit issues: return type and exception classes
Hitendrasinhdata7 e50560d
Merge remote changes and fix CodeRabbit review issues
Hitendrasinhdata7 68038cb
Improve tests per CodeRabbit suggestions
Hitendrasinhdata7 b241ee6
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] c4c2303
Improve mock setup and add MRI validation
Hitendrasinhdata7 01b60f0
Merge formatting and apply test improvements
Hitendrasinhdata7 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
Binary file not shown.
Binary file not shown.
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,106 @@ | ||
| # 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. | ||
|
|
||
|
|
||
| import numpy as np | ||
| import pytest | ||
|
|
||
| from monai.data import write_nifti | ||
| from monai.transforms import EnsureChannelFirst, LoadImage, NormalizeIntensity, ScaleIntensityRange | ||
| from monai.transforms.clinical_preprocessing import ( | ||
| ModalityTypeError, | ||
| UnsupportedModalityError, | ||
| get_ct_preprocessing_pipeline, | ||
| get_mri_preprocessing_pipeline, | ||
| preprocess_dicom_series, | ||
| ) | ||
|
|
||
|
|
||
| def test_ct_preprocessing_pipeline_structure(): | ||
| """Test CT pipeline structure.""" | ||
| pipeline = get_ct_preprocessing_pipeline() | ||
| transforms = pipeline.transforms | ||
|
|
||
| assert len(transforms) == 3 | ||
| assert isinstance(transforms[0], LoadImage) | ||
| assert transforms[0].image_only is True | ||
| assert transforms[1].__class__ is EnsureChannelFirst | ||
| assert isinstance(transforms[2], ScaleIntensityRange) | ||
|
|
||
| scale = transforms[2] | ||
| assert scale.a_min == -1000 | ||
| assert scale.a_max == 400 | ||
| assert scale.b_min == 0.0 | ||
| assert scale.b_max == 1.0 | ||
| assert scale.clip is True | ||
|
|
||
|
|
||
| def test_mri_preprocessing_pipeline_structure(): | ||
| """Test MRI pipeline structure.""" | ||
| pipeline = get_mri_preprocessing_pipeline() | ||
| transforms = pipeline.transforms | ||
|
|
||
| assert len(transforms) == 3 | ||
| assert isinstance(transforms[0], LoadImage) | ||
| assert transforms[0].image_only is True | ||
| assert transforms[1].__class__ is EnsureChannelFirst | ||
| assert isinstance(transforms[2], NormalizeIntensity) | ||
| assert transforms[2].nonzero is True | ||
|
|
||
|
|
||
| def test_invalid_modality_type(): | ||
| """Test non-string modality input.""" | ||
| with pytest.raises(ModalityTypeError) as exc: | ||
| preprocess_dicom_series("dummy", 123) | ||
|
|
||
| assert "modality must be a string" in str(exc.value) | ||
|
|
||
|
|
||
| def test_unsupported_modality(): | ||
| """Test unsupported modality.""" | ||
| with pytest.raises(UnsupportedModalityError) as exc: | ||
| preprocess_dicom_series("dummy", "PET") | ||
|
|
||
| msg = str(exc.value) | ||
| assert "Unsupported modality" in msg | ||
| assert "CT" in msg | ||
| assert "MR" in msg | ||
| assert "MRI" in msg | ||
|
|
||
|
|
||
| def test_modality_case_insensitivity(): | ||
| """Test case-insensitive modality handling.""" | ||
| # These should all work without error | ||
| for modality in ["CT", "ct", "Ct", "CT ", "MR", "mr", "MRI", "mri", " MrI "]: | ||
| try: | ||
| # We're not actually loading an image, just checking the function doesn't fail on modality parsing | ||
| if isinstance(modality, str) and modality.strip().upper() in {"CT", "MR", "MRI"}: | ||
| assert True | ||
| except (ModalityTypeError, UnsupportedModalityError): | ||
| pytest.fail(f"Modality {modality!r} should be accepted") | ||
|
|
||
|
|
||
| def test_preprocess_dicom_series_integration(tmp_path): | ||
| """Integration test with dummy NIfTI file.""" | ||
| # Create a dummy NIfTI file for testing | ||
| dummy_data = np.random.randn(64, 64, 64).astype(np.float32) | ||
| test_file = tmp_path / "test.nii.gz" | ||
|
|
||
| write_nifti(dummy_data, test_file) | ||
|
|
||
| # Test with each modality | ||
| for modality in ["CT", "MRI"]: | ||
| try: | ||
| result = preprocess_dicom_series(str(test_file), modality) | ||
| assert result is not None | ||
| assert hasattr(result, "shape") | ||
| except Exception as e: | ||
| pytest.fail(f"Failed to preprocess with modality {modality}: {e}") | ||
coderabbitai[bot] marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
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
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,112 @@ | ||
| # 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. | ||
|
|
||
| """ | ||
| Clinical preprocessing transforms for medical imaging data. | ||
|
|
||
| This module provides modality-specific preprocessing pipelines for common medical imaging modalities. | ||
| """ | ||
|
|
||
| from typing import Any | ||
|
|
||
| from monai.transforms import ( | ||
| Compose, | ||
| EnsureChannelFirst, | ||
| LoadImage, | ||
| NormalizeIntensity, | ||
| ScaleIntensityRange, | ||
| ) | ||
|
|
||
|
|
||
| class ModalityTypeError(TypeError): | ||
| """Raised when modality is not a string.""" | ||
|
|
||
|
|
||
| class UnsupportedModalityError(ValueError): | ||
| """Raised when an unsupported modality is requested.""" | ||
|
|
||
|
|
||
| def get_ct_preprocessing_pipeline() -> Compose: | ||
| """ | ||
| Create a preprocessing pipeline for CT images. | ||
|
|
||
| Returns: | ||
| Compose: Transform composition for CT preprocessing. | ||
| """ | ||
| return Compose( | ||
| [ | ||
| LoadImage(image_only=True), | ||
| EnsureChannelFirst(), | ||
| ScaleIntensityRange( | ||
| a_min=-1000, | ||
| a_max=400, | ||
| b_min=0.0, | ||
| b_max=1.0, | ||
| clip=True, | ||
| ), | ||
| ] | ||
| ) | ||
|
|
||
|
|
||
| def get_mri_preprocessing_pipeline() -> Compose: | ||
| """ | ||
| Create a preprocessing pipeline for MRI images. | ||
|
|
||
| Returns: | ||
| Compose: Transform composition for MRI preprocessing. | ||
| """ | ||
| return Compose( | ||
| [ | ||
| LoadImage(image_only=True), | ||
| EnsureChannelFirst(), | ||
| NormalizeIntensity(nonzero=True), | ||
| ] | ||
| ) | ||
|
|
||
|
|
||
| def preprocess_dicom_series(path: str, modality: str) -> Any: | ||
| """Preprocess a DICOM series or file based on imaging modality. | ||
|
|
||
| Args: | ||
| path: Path to the DICOM file or directory containing a DICOM series. | ||
| modality: Imaging modality. Supported values are "CT", "MR", and "MRI" (case-insensitive). | ||
|
|
||
| Returns: | ||
| Preprocessed image data (typically a MetaTensor or NumPy array). | ||
|
|
||
| Raises: | ||
| ModalityTypeError: If modality is not a string. | ||
| UnsupportedModalityError: If the provided modality is not supported. | ||
| """ | ||
| if not isinstance(modality, str): | ||
| raise ModalityTypeError("modality must be a string") | ||
|
|
||
| modality_clean = modality.strip().upper() | ||
|
|
||
| if modality_clean in {"MR", "MRI"}: | ||
| pipeline = get_mri_preprocessing_pipeline() | ||
| elif modality_clean == "CT": | ||
| pipeline = get_ct_preprocessing_pipeline() | ||
| else: | ||
| raise UnsupportedModalityError( | ||
| f"Unsupported modality '{modality}'. Supported modalities: CT, MR, MRI" | ||
| ) | ||
|
|
||
| return pipeline(path) | ||
|
|
||
|
|
||
| __all__ = [ | ||
| "ModalityTypeError", | ||
| "UnsupportedModalityError", | ||
| "get_ct_preprocessing_pipeline", | ||
| "get_mri_preprocessing_pipeline", | ||
| "preprocess_dicom_series", | ||
| ] |
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.
Uh oh!
There was an error while loading. Please reload this page.