-
Notifications
You must be signed in to change notification settings - Fork 1.3k
feat: Add RandNonCentralChiNoise transform #8618
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
base: dev
Are you sure you want to change the base?
Changes from all commits
82c0fb3
33d8aa2
7eb60ca
94b40fc
32290e6
62f738b
1a16247
a7f0862
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -165,3 +165,5 @@ runs | |
| *.pth | ||
|
|
||
| *zarr/* | ||
|
|
||
| monai-dev/ | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -48,6 +48,7 @@ | |
| RandGibbsNoise, | ||
| RandHistogramShift, | ||
| RandKSpaceSpikeNoise, | ||
| RandNonCentralChiNoise, | ||
| RandRicianNoise, | ||
| RandScaleIntensity, | ||
| RandScaleIntensityFixedMean, | ||
|
|
@@ -69,6 +70,9 @@ | |
| __all__ = [ | ||
| "RandGaussianNoised", | ||
| "RandRicianNoised", | ||
| "RandNonCentralChiNoised", | ||
| "RandNonCentralChiNoiseD", | ||
| "RandNonCentralChiNoiseDict", | ||
| "ShiftIntensityd", | ||
| "RandShiftIntensityd", | ||
| "ScaleIntensityd", | ||
|
|
@@ -236,6 +240,81 @@ def __call__(self, data: Mapping[Hashable, NdarrayOrTensor]) -> dict[Hashable, N | |
| return d | ||
|
|
||
|
|
||
| class RandNonCentralChiNoised(RandomizableTransform, MapTransform): | ||
| """ | ||
| Dictionary-based version :py:class:`monai.transforms.RandNonCentralChiNoise`. | ||
| Add non-central chi noise to image. This transform assumes all the expected fields have same shape, if want to add | ||
| different noise for every field, please use this transform separately. | ||
| This is a generalization of Rician noise. `degrees_of_freedom=2` is Rician noise. | ||
|
|
||
| Args: | ||
| keys: Keys of the corresponding items to be transformed. | ||
| See also: :py:class:`monai.transforms.compose.MapTransform` | ||
| prob: Probability to add non-central chi noise to the dictionary. | ||
| mean: Mean or "centre" of the Gaussian distributions sampled to make up | ||
| the noise. | ||
| std: Standard deviation (spread) of the Gaussian distributions sampled | ||
| to make up the noise. | ||
| degrees_of_freedom: Number of Gaussian distributions (degrees of freedom). | ||
| `degrees_of_freedom=2` is Rician noise. | ||
| channel_wise: If True, treats each channel of the image separately. | ||
| relative: If True, the spread of the sampled Gaussian distributions will | ||
| be std times the standard deviation of the image or channel's intensity | ||
| histogram. | ||
| sample_std: If True, sample the spread of the Gaussian distributions | ||
| uniformly from 0 to std. | ||
| dtype: output data type, if None, same as input image. defaults to float32. | ||
| allow_missing_keys: Don't raise exception if key is missing. | ||
| """ | ||
|
|
||
| backend = RandNonCentralChiNoise.backend | ||
|
|
||
| def __init__( | ||
| self, | ||
| keys: KeysCollection, | ||
| prob: float = 0.1, | ||
| mean: Sequence[float] | float = 0.0, | ||
| std: Sequence[float] | float = 1.0, | ||
| degrees_of_freedom: int = 64, | ||
| channel_wise: bool = False, | ||
| relative: bool = False, | ||
| sample_std: bool = True, | ||
| dtype: DtypeLike = np.float32, | ||
| allow_missing_keys: bool = False, | ||
| ) -> None: | ||
| MapTransform.__init__(self, keys, allow_missing_keys) | ||
| RandomizableTransform.__init__(self, prob) | ||
| self.rand_non_central_chi_noise = RandNonCentralChiNoise( | ||
| prob=1.0, | ||
| mean=mean, | ||
| std=std, | ||
| degrees_of_freedom=degrees_of_freedom, | ||
| channel_wise=channel_wise, | ||
| relative=relative, | ||
| sample_std=sample_std, | ||
| dtype=dtype, | ||
| ) | ||
|
|
||
| def set_random_state( | ||
| self, seed: int | None = None, state: np.random.RandomState | None = None | ||
| ) -> RandNonCentralChiNoised: | ||
| super().set_random_state(seed, state) | ||
| self.rand_non_central_chi_noise.set_random_state(seed, state) | ||
| return self | ||
|
|
||
| def __call__(self, data: Mapping[Hashable, NdarrayOrTensor]) -> dict[Hashable, NdarrayOrTensor]: | ||
| d = dict(data) | ||
| self.randomize(None) | ||
| if not self._do_transform: | ||
| for key in self.key_iterator(d): | ||
| d[key] = convert_to_tensor(d[key], track_meta=get_track_meta()) | ||
| return d | ||
|
|
||
| for key in self.key_iterator(d): | ||
| d[key] = self.rand_non_central_chi_noise(d[key], randomize=True) | ||
| return d | ||
|
Comment on lines
+305
to
+315
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Critical: Fix randomize=True to prevent inconsistent per-key behavior. Line 310 uses Apply this fix: for key in self.key_iterator(d):
- d[key] = self.rand_non_central_chi_noise(d[key], randomize=True)
+ d[key] = self.rand_non_central_chi_noise(d[key], randomize=False)
return dNote: 🤖 Prompt for AI Agents |
||
|
|
||
|
|
||
| class RandRicianNoised(RandomizableTransform, MapTransform): | ||
| """ | ||
| Dictionary-based version :py:class:`monai.transforms.RandRicianNoise`. | ||
|
|
@@ -1953,6 +2032,7 @@ def __call__(self, data: Mapping[Hashable, NdarrayOrTensor]) -> dict[Hashable, N | |
|
|
||
| RandGaussianNoiseD = RandGaussianNoiseDict = RandGaussianNoised | ||
| RandRicianNoiseD = RandRicianNoiseDict = RandRicianNoised | ||
| RandNonCentralChiNoiseD = RandNonCentralChiNoiseDict = RandNonCentralChiNoised | ||
| ShiftIntensityD = ShiftIntensityDict = ShiftIntensityd | ||
| RandShiftIntensityD = RandShiftIntensityDict = RandShiftIntensityd | ||
| StdShiftIntensityD = StdShiftIntensityDict = StdShiftIntensityd | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,83 @@ | ||
| # 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 numpy as np | ||
| import torch | ||
| from parameterized import parameterized | ||
|
|
||
| from monai.transforms import RandNonCentralChiNoise | ||
| from tests.test_utils import TEST_NDARRAYS, NumpyImageTestCase2D | ||
|
|
||
| TESTS = [] | ||
| for p in TEST_NDARRAYS: | ||
| TESTS.append(("test_zero_mean", p, 0, 0.1)) | ||
| TESTS.append(("test_non_zero_mean", p, 1, 0.5)) | ||
|
|
||
|
|
||
| class TestRandNonCentralChiNoise(NumpyImageTestCase2D): | ||
| @parameterized.expand(TESTS) | ||
| def test_correct_results(self, _, in_type, mean, std): | ||
| seed = 0 | ||
| degrees_of_freedom = 64 # 64 is common due to 32 channel head coil | ||
| noise_fn = RandNonCentralChiNoise(prob=1.0, mean=mean, std=std, degrees_of_freedom=degrees_of_freedom) | ||
| noise_fn.set_random_state(seed) | ||
| im = in_type(self.imt) | ||
| noised = noise_fn(im) | ||
| if isinstance(im, torch.Tensor): | ||
| self.assertEqual(im.dtype, noised.dtype) | ||
| np.random.seed(seed) | ||
| np.random.random() | ||
| _std = np.random.uniform(0, std) | ||
|
|
||
| noise_shape = (degrees_of_freedom, *self.imt.shape) | ||
| all_noises = np.random.normal(mean, _std, size=noise_shape).astype(np.float32) | ||
| all_noises[0] += self.imt | ||
| sum_sq = np.sum(all_noises**2, axis=0) | ||
| expected = np.sqrt(sum_sq) | ||
|
|
||
| if isinstance(noised, torch.Tensor): | ||
| noised = noised.cpu() | ||
| np.testing.assert_allclose(expected, noised, atol=1e-5) | ||
|
|
||
| @parameterized.expand(TESTS) | ||
| def test_correct_results_dof2(self, _, in_type, mean, std): | ||
| """ | ||
| Test with k=2 (the Rician case) | ||
| """ | ||
| seed = 0 | ||
| degrees_of_freedom = 2 | ||
| noise_fn = RandNonCentralChiNoise(prob=1.0, mean=mean, std=std, degrees_of_freedom=degrees_of_freedom) | ||
| noise_fn.set_random_state(seed) | ||
| im = in_type(self.imt) | ||
| noised = noise_fn(im) | ||
| if isinstance(im, torch.Tensor): | ||
| self.assertEqual(im.dtype, noised.dtype) | ||
|
|
||
| np.random.seed(seed) | ||
| np.random.random() # for prob | ||
| _std = np.random.uniform(0, std) # for sample_std | ||
| noise_shape = (degrees_of_freedom, *self.imt.shape) | ||
| all_noises = np.random.normal(mean, _std, size=noise_shape).astype(np.float32) | ||
| all_noises[0] += self.imt | ||
| sum_sq = np.sum(all_noises**2, axis=0) | ||
| expected = np.sqrt(sum_sq) | ||
|
|
||
| if isinstance(noised, torch.Tensor): | ||
| noised = noised.cpu() | ||
| np.testing.assert_allclose(expected, noised, atol=1e-5, rtol=1e-5) | ||
|
|
||
|
|
||
| if __name__ == "__main__": | ||
| unittest.main() |
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.
Fix CUDA crash for relative channel noise.
Passing
d.std()straight intonp.random.uniformworks on CPU but throwsTypeError: can't convert CUDA tensor to numpy. Use Tensor.cpu() to copy the tensor to host memory first.when the input lives on GPU (the common case for MONAI). Convert the statistic to a host-side Python float before handing it to the RNG.🤖 Prompt for AI Agents