diff --git a/docs/source/transforms.rst b/docs/source/transforms.rst index 2d5d452dc03..3dfb2838433 100644 --- a/docs/source/transforms.rst +++ b/docs/source/transforms.rst @@ -498,6 +498,18 @@ Intensity :members: :special-members: __call__ +`RandSpeckleNoise` +"""""""""""""""""" +.. autoclass:: RandSpeckleNoise + :members: + :special-members: __call__ + +`RandUltrasoundDepthGain` +""""""""""""""""""""""""" +.. autoclass:: RandUltrasoundDepthGain + :members: + :special-members: __call__ + `RandCoarseTransform` """"""""""""""""""""" .. autoclass:: RandCoarseTransform @@ -1548,6 +1560,18 @@ Intensity (Dict) :members: :special-members: __call__ +`RandSpeckleNoised` +""""""""""""""""""" +.. autoclass:: RandSpeckleNoised + :members: + :special-members: __call__ + +`RandUltrasoundDepthGaind` +"""""""""""""""""""""""""" +.. autoclass:: RandUltrasoundDepthGaind + :members: + :special-members: __call__ + `ScaleIntensityRangePercentilesd` """"""""""""""""""""""""""""""""" .. image:: https://raw.githubusercontent.com/Project-MONAI/DocImages/main/transforms/ScaleIntensityRangePercentilesd.png diff --git a/monai/transforms/__init__.py b/monai/transforms/__init__.py index 62cf49937ec..76009cb1f7d 100644 --- a/monai/transforms/__init__.py +++ b/monai/transforms/__init__.py @@ -121,7 +121,9 @@ RandScaleIntensity, RandScaleIntensityFixedMean, RandShiftIntensity, + RandSpeckleNoise, RandStdShiftIntensity, + RandUltrasoundDepthGain, SavitzkyGolaySmooth, ScaleIntensity, ScaleIntensityFixedMean, @@ -211,9 +213,15 @@ RandShiftIntensityd, RandShiftIntensityD, RandShiftIntensityDict, + RandSpeckleNoised, + RandSpeckleNoiseD, + RandSpeckleNoiseDict, RandStdShiftIntensityd, RandStdShiftIntensityD, RandStdShiftIntensityDict, + RandUltrasoundDepthGaind, + RandUltrasoundDepthGainD, + RandUltrasoundDepthGainDict, SavitzkyGolaySmoothd, SavitzkyGolaySmoothD, SavitzkyGolaySmoothDict, diff --git a/monai/transforms/intensity/array.py b/monai/transforms/intensity/array.py index a80f94727ee..fb540e7b42b 100644 --- a/monai/transforms/intensity/array.py +++ b/monai/transforms/intensity/array.py @@ -44,6 +44,8 @@ __all__ = [ "RandGaussianNoise", "RandRicianNoise", + "RandSpeckleNoise", + "RandUltrasoundDepthGain", "ShiftIntensity", "RandShiftIntensity", "StdShiftIntensity", @@ -231,6 +233,234 @@ def __call__(self, img: NdarrayOrTensor, randomize: bool = True) -> NdarrayOrTen return img +def _get_float_compute_dtype(img: NdarrayOrTensor) -> DtypeLike: + """ + Return the floating point dtype to use for intermediate multiplication. + + float64 is used where supported, but the MPS backend does not support + float64 tensors, so float32 is used for MPS inputs. + """ + if isinstance(img, torch.Tensor) and img.device.type == "mps": + return np.float32 + return np.float64 + + +class RandSpeckleNoise(RandomizableTransform): + """ + Add multiplicative speckle noise to image, simulating the speckle pattern + characteristic of B-mode ultrasound images. + + Fully developed speckle is commonly modelled as multiplicative noise: the + backscattered intensity follows a Gamma distribution, see for example + `Statistics of speckle in ultrasound B-scans + `_. The noise factor has unit mean, + so the mean image intensity is unchanged in expectation, while the + variance of the factor is controlled by `std`. With `std` fixed, the + Gamma shape is ``1 / std ** 2`` (the number of looks) and the scale is + ``std ** 2``. + + Args: + prob: Probability to add speckle noise. + std: relative standard deviation of the multiplicative speckle factor. + Must be non-negative. A larger value produces stronger speckle. + sample_std: If True, sample the relative standard deviation uniformly + from 0 to `std` on each call. + dtype: output data type, if None, same as input image. defaults to float32. + + """ + + backend = [TransformBackends.TORCH, TransformBackends.NUMPY] + + def __init__( + self, prob: float = 0.1, std: float = 0.5, sample_std: bool = True, dtype: DtypeLike = np.float32 + ) -> None: + """ + Args: + prob: probability to add speckle noise. + std: relative standard deviation of the multiplicative speckle factor. Must be non-negative. + sample_std: if True, sample the relative standard deviation uniformly from 0 to `std` on each call. + dtype: output data type, if None, same as input image. + + Raises: + ValueError: if `std` is negative. + """ + RandomizableTransform.__init__(self, prob) + if std < 0: + raise ValueError(f"`std` must be non-negative, got {std}.") + self.std = std + self.sample_std = sample_std + self.dtype = dtype + self.speckle: np.ndarray | None = None + + def randomize(self, img: NdarrayOrTensor) -> None: + """ + Randomize the speckle factor for the given image. + + Args: + img: image the speckle factor is sampled for, only its shape is used. + The sampled factor is stored in `self.speckle` and reused when + `__call__` is invoked with `randomize=False`. + """ + super().randomize(None) + if not self._do_transform: + return None + std = self.R.uniform(0, self.std) if self.sample_std else self.std + if std <= 0: + self.speckle = np.ones(img.shape, dtype=self.dtype) + return None + # Gamma with mean 1 and variance std ** 2: shape = 1 / std ** 2, scale = std ** 2 + self.speckle, *_ = convert_data_type(self.R.gamma(1.0 / std**2, std**2, size=img.shape), dtype=self.dtype) + + def __call__(self, img: NdarrayOrTensor, randomize: bool = True) -> NdarrayOrTensor: + """ + Apply the transform to `img`. + + Args: + img: input image. + randomize: if True, sample a fresh speckle factor, otherwise reuse the + factor stored by a previous `randomize` call. + + Returns: + image multiplied by the speckle factor, converted to `dtype` (or the input dtype if `dtype` is None). + + Raises: + RuntimeError: if `randomize` is False and no speckle factor was sampled yet. + """ + img = convert_to_tensor(img, track_meta=get_track_meta()) + if randomize: + self.randomize(img=img) + + if not self._do_transform: + return img + + if self.speckle is None: + raise RuntimeError("please call the `randomize()` function first.") + # Multiply in floating point, then convert to the requested output dtype, + # so fractional factors are not truncated for integer inputs when `dtype` is None. + # MPS does not support float64, so float32 is used for the intermediate + # computation on MPS inputs. + out_dtype = self.dtype if self.dtype is not None else img.dtype + img_f, *_ = convert_data_type(img, dtype=_get_float_compute_dtype(img)) + speckle, *_ = convert_to_dst_type(self.speckle, img_f) + out = img_f * speckle + out, *_ = convert_data_type(out, dtype=out_dtype) + return out + + +class RandUltrasoundDepthGain(RandomizableTransform): + """ + Apply a smooth depth-dependent gain to a B-mode ultrasound image, + simulating time-gain compensation (TGC) adjustments and depth attenuation. + + Ultrasound signal attenuates with imaging depth, and scanners compensate + with a depth-dependent (TGC) gain. Varying that gain is a natural + augmentation for ultrasound models, making them robust to transducer + settings at deployment time. The gain profile is log-linear along the + depth axis: ``gain(t) = exp(slope * (t - 0.5))`` for ``t`` in ``[0, 1]`` + from the shallow to the deep end of the image. A negative slope darkens + the image with depth (attenuation / shadowing), a positive slope + brightens it with depth (TGC over-compensation). The slope is sampled + uniformly from `gain_range` on each call. + + Args: + prob: Probability to apply the depth gain. + gain_range: (minimum, maximum) log-gain slope sampled uniformly. + A slope of 0 leaves the image unchanged. + depth_axis: axis of the image along which depth increases. Defaults to 1, + the first spatial axis for channel-first images, where depth + typically increases downwards in a B-mode frame. + dtype: output data type, if None, same as input image. defaults to float32. + + """ + + backend = [TransformBackends.TORCH, TransformBackends.NUMPY] + + def __init__( + self, + prob: float = 0.1, + gain_range: tuple[float, float] = (-1.0, 1.0), + depth_axis: int = 1, + dtype: DtypeLike = np.float32, + ) -> None: + """ + Args: + prob: probability to apply the depth gain. + gain_range: (minimum, maximum) log-gain slope sampled uniformly. + depth_axis: axis of the image along which depth increases. + dtype: output data type, if None, same as input image. + + Raises: + ValueError: if `gain_range` does not contain exactly two values. + """ + RandomizableTransform.__init__(self, prob) + if len(gain_range) != 2: + raise ValueError(f"`gain_range` must be a (min, max) tuple, got {gain_range}.") + self.gain_range = gain_range + self.depth_axis = depth_axis + self.dtype = dtype + self.slope: float | None = None + + def randomize(self, img: NdarrayOrTensor | None = None) -> None: + """ + Randomize the gain slope. + + Args: + img: unused, accepted for a uniform `randomize` signature across transforms. + The sampled slope is stored in `self.slope` and reused when + `__call__` is invoked with `randomize=False`. + """ + super().randomize(None) + if not self._do_transform: + return None + self.slope = float(self.R.uniform(self.gain_range[0], self.gain_range[1])) + + def __call__(self, img: NdarrayOrTensor, randomize: bool = True) -> NdarrayOrTensor: + """ + Apply the transform to `img`. + + Args: + img: input image. + randomize: if True, sample a fresh slope, otherwise reuse the slope + stored by a previous `randomize` call. + + Returns: + image multiplied by the depth-gain profile, converted to `dtype` + (or the input dtype if `dtype` is None). + + Raises: + RuntimeError: if `randomize` is False and no slope was sampled yet. + ValueError: if `depth_axis` is out of range for the image. + """ + img = convert_to_tensor(img, track_meta=get_track_meta()) + if randomize: + self.randomize(img=img) + + if not self._do_transform: + return img + + if self.slope is None: + raise RuntimeError("please call the `randomize()` function first.") + depth_axis = self.depth_axis if self.depth_axis >= 0 else img.ndim + self.depth_axis + if depth_axis < 0 or depth_axis >= img.ndim: + raise ValueError(f"`depth_axis` {self.depth_axis} is out of range for image with {img.ndim} dims.") + n = img.shape[depth_axis] + t = np.linspace(0.0, 1.0, n) + profile = np.exp(self.slope * (t - 0.5)) + gain_shape = [1] * img.ndim + gain_shape[depth_axis] = n + profile = profile.reshape(gain_shape) + # Multiply in floating point, then convert to the requested output dtype, + # so fractional gains are not truncated for integer inputs when `dtype` is None. + # MPS does not support float64, so float32 is used for the intermediate + # computation on MPS inputs. + out_dtype = self.dtype if self.dtype is not None else img.dtype + img_f, *_ = convert_data_type(img, dtype=_get_float_compute_dtype(img)) + gain, *_ = convert_to_dst_type(profile, img_f) + out = img_f * gain + out, *_ = convert_data_type(out, dtype=out_dtype) + return out + + class ShiftIntensity(Transform): """ Shift intensity uniformly for the entire image with specified `offset`. diff --git a/monai/transforms/intensity/dictionary.py b/monai/transforms/intensity/dictionary.py index a91ad4f59c6..0df5a659ef0 100644 --- a/monai/transforms/intensity/dictionary.py +++ b/monai/transforms/intensity/dictionary.py @@ -52,7 +52,9 @@ RandScaleIntensity, RandScaleIntensityFixedMean, RandShiftIntensity, + RandSpeckleNoise, RandStdShiftIntensity, + RandUltrasoundDepthGain, SavitzkyGolaySmooth, ScaleIntensity, ScaleIntensityRange, @@ -70,6 +72,8 @@ __all__ = [ "RandGaussianNoised", "RandRicianNoised", + "RandSpeckleNoised", + "RandUltrasoundDepthGaind", "ShiftIntensityd", "RandShiftIntensityd", "ScaleIntensityd", @@ -305,6 +309,183 @@ def __call__(self, data: Mapping[Hashable, NdarrayOrTensor]) -> dict[Hashable, N return d +class RandSpeckleNoised(RandomizableTransform, MapTransform): + """ + Dictionary-based version :py:class:`monai.transforms.RandSpeckleNoise`. + Add multiplicative speckle noise to image. This transform assumes all the expected fields have same shape, + if you want to add different noise for every field, please use this transform separately. + + Args: + keys: keys of the corresponding items to be transformed. + See also: :py:class:`monai.transforms.compose.MapTransform` + prob: Probability to add speckle noise to the dictionary. + std: relative standard deviation of the multiplicative speckle factor. + Must be non-negative. A larger value produces stronger speckle. + sample_std: If True, sample the relative standard deviation uniformly + from 0 to `std` on each call. + 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 = RandSpeckleNoise.backend + + def __init__( + self, + keys: KeysCollection, + prob: float = 0.1, + std: float = 0.5, + sample_std: bool = True, + dtype: DtypeLike = np.float32, + allow_missing_keys: bool = False, + ) -> None: + """ + Args: + keys: keys of the corresponding items to be transformed. + prob: probability to add speckle noise to the dictionary. + std: relative standard deviation of the multiplicative speckle factor. Must be non-negative. + sample_std: if True, sample the relative standard deviation uniformly from 0 to `std` on each call. + dtype: output data type, if None, same as input image. + allow_missing_keys: do not raise an exception if a key is missing. + """ + MapTransform.__init__(self, keys, allow_missing_keys) + RandomizableTransform.__init__(self, prob) + self.rand_speckle_noise = RandSpeckleNoise(prob=1.0, std=std, sample_std=sample_std, dtype=dtype) + + def set_random_state( + self, seed: int | None = None, state: np.random.RandomState | None = None + ) -> RandSpeckleNoised: + """ + Set the random state for this transform and its array transform. + + Args: + seed: seed for the random state. + state: random state to use instead of `seed`. + + Returns: + this transform, for chaining. + """ + super().set_random_state(seed, state) + self.rand_speckle_noise.set_random_state(seed, state) + return self + + def __call__(self, data: Mapping[Hashable, NdarrayOrTensor]) -> dict[Hashable, NdarrayOrTensor]: + """ + Apply the transform to `data`. + + Args: + data: dictionary of images. All configured fields are expected to have the same shape + and share one speckle factor, as documented in the class docstring. + + Returns: + dictionary with the configured fields multiplied by the shared speckle factor. + Missing keys are skipped when `allow_missing_keys` is True; when no configured + field is present, the values are only converted to tensors. + """ + 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 + + # all the keys share the same random noise + first_key: Hashable = self.first_key(d) + if first_key == (): + for key in self.key_iterator(d): + d[key] = convert_to_tensor(d[key], track_meta=get_track_meta()) + return d + + self.rand_speckle_noise.randomize(d[first_key]) + + for key in self.key_iterator(d): + d[key] = self.rand_speckle_noise(img=d[key], randomize=False) + return d + + +class RandUltrasoundDepthGaind(RandomizableTransform, MapTransform): + """ + Dictionary-based version :py:class:`monai.transforms.RandUltrasoundDepthGain`. + Apply a smooth depth-dependent gain to a B-mode ultrasound image, simulating + time-gain compensation (TGC) adjustments and depth attenuation. + + Args: + keys: keys of the corresponding items to be transformed. + See also: :py:class:`monai.transforms.compose.MapTransform` + prob: Probability to apply the depth gain to the dictionary. + gain_range: (minimum, maximum) log-gain slope sampled uniformly. + A slope of 0 leaves the image unchanged. + depth_axis: axis of the image along which depth increases. Defaults to 1, + the first spatial axis for channel-first images. + 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 = RandUltrasoundDepthGain.backend + + def __init__( + self, + keys: KeysCollection, + prob: float = 0.1, + gain_range: tuple[float, float] = (-1.0, 1.0), + depth_axis: int = 1, + dtype: DtypeLike = np.float32, + allow_missing_keys: bool = False, + ) -> None: + """ + Args: + keys: keys of the corresponding items to be transformed. + prob: probability to apply the depth gain to the dictionary. + gain_range: (minimum, maximum) log-gain slope sampled uniformly. + depth_axis: axis of the image along which depth increases. + dtype: output data type, if None, same as input image. + allow_missing_keys: do not raise an exception if a key is missing. + """ + MapTransform.__init__(self, keys, allow_missing_keys) + RandomizableTransform.__init__(self, prob) + self.rand_ultrasound_depth_gain = RandUltrasoundDepthGain( + prob=1.0, gain_range=gain_range, depth_axis=depth_axis, dtype=dtype + ) + + def set_random_state( + self, seed: int | None = None, state: np.random.RandomState | None = None + ) -> RandUltrasoundDepthGaind: + """ + Set the random state for this transform and its array transform. + + Args: + seed: seed for the random state. + state: random state to use instead of `seed`. + + Returns: + this transform, for chaining. + """ + super().set_random_state(seed, state) + self.rand_ultrasound_depth_gain.set_random_state(seed, state) + return self + + def __call__(self, data: Mapping[Hashable, NdarrayOrTensor]) -> dict[Hashable, NdarrayOrTensor]: + """ + Apply the transform to `data`. + + Args: + data: dictionary of images. + + Returns: + dictionary with the configured fields multiplied by the depth-gain profile. + Missing keys are skipped when `allow_missing_keys` is True. + """ + 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_ultrasound_depth_gain(d[key], randomize=True) + return d + + class ShiftIntensityd(MapTransform): """ Dictionary-based wrapper of :py:class:`monai.transforms.ShiftIntensity`. @@ -1987,6 +2168,8 @@ def __call__(self, data: Mapping[Hashable, NdarrayOrTensor]) -> dict[Hashable, N RandGaussianNoiseD = RandGaussianNoiseDict = RandGaussianNoised RandRicianNoiseD = RandRicianNoiseDict = RandRicianNoised +RandSpeckleNoiseD = RandSpeckleNoiseDict = RandSpeckleNoised +RandUltrasoundDepthGainD = RandUltrasoundDepthGainDict = RandUltrasoundDepthGaind ShiftIntensityD = ShiftIntensityDict = ShiftIntensityd RandShiftIntensityD = RandShiftIntensityDict = RandShiftIntensityd StdShiftIntensityD = StdShiftIntensityDict = StdShiftIntensityd diff --git a/tests/transforms/test_rand_speckle_noise.py b/tests/transforms/test_rand_speckle_noise.py new file mode 100644 index 00000000000..15218849367 --- /dev/null +++ b/tests/transforms/test_rand_speckle_noise.py @@ -0,0 +1,91 @@ +# 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 RandSpeckleNoise +from tests.test_utils import TEST_NDARRAYS, NumpyImageTestCase2D + +TESTS = [] +for p in TEST_NDARRAYS: + TESTS.append(("test_sampled_std", p, 0.5, True)) + TESTS.append(("test_fixed_std", p, 0.2, False)) + TESTS.append(("test_zero_std", p, 0.0, False)) + + +class TestRandSpeckleNoise(NumpyImageTestCase2D): + @parameterized.expand(TESTS) + def test_correct_results(self, _, in_type, std, sample_std): + seed = 0 + speckle_fn = RandSpeckleNoise(prob=1.0, std=std, sample_std=sample_std) + speckle_fn.set_random_state(seed) + im = in_type(self.imt) + noised = speckle_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) if sample_std else std + if _std <= 0: + expected = self.imt + else: + expected = self.imt * np.random.gamma(1.0 / _std**2, _std**2, size=self.imt.shape) + if isinstance(noised, torch.Tensor): + noised = noised.cpu() + np.testing.assert_allclose(expected, noised, atol=1e-5) + + def test_prob_zero(self): + speckle_fn = RandSpeckleNoise(prob=0.0, std=0.5) + speckle_fn.set_random_state(0) + out = speckle_fn(self.imt) + np.testing.assert_allclose(self.imt, np.asarray(out)) + + def test_uint8_input_dtype_none(self): + # Fractional speckle factors must not be truncated to integers before multiplication. + img = np.full((1, 4, 4), 100, dtype=np.uint8) + speckle_fn = RandSpeckleNoise(prob=1.0, std=0.5, sample_std=False, dtype=None) + speckle_fn.set_random_state(0) + out = speckle_fn(img) + self.assertEqual(np.asarray(out).dtype, np.uint8) + np.random.seed(0) + np.random.random() + factor = np.random.gamma(1.0 / 0.5**2, 0.5**2, size=img.shape) + expected = (img.astype(np.float64) * factor).astype(np.uint8) + np.testing.assert_array_equal(np.asarray(out), expected) + + @unittest.skipUnless(torch.backends.mps.is_available(), "MPS is not available") + def test_mps_float32_input(self): + # MPS does not support float64, so the transform must compute in float32 on MPS inputs. + img = torch.full((1, 4, 4), 100.0, dtype=torch.float32, device="mps") + speckle_fn = RandSpeckleNoise(prob=1.0, std=0.5, sample_std=False, dtype=None) + speckle_fn.set_random_state(0) + out = speckle_fn(img) + self.assertEqual(out.device.type, "mps") + self.assertEqual(out.dtype, torch.float32) + np.random.seed(0) + np.random.random() + factor = np.random.gamma(1.0 / 0.5**2, 0.5**2, size=img.shape) + expected = img.cpu().numpy().astype(np.float32) * factor.astype(np.float32) + np.testing.assert_allclose(out.cpu().numpy(), expected, atol=1e-4) + + def test_negative_std_raises(self): + with self.assertRaises(ValueError): + RandSpeckleNoise(prob=1.0, std=-0.1) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/transforms/test_rand_speckle_noised.py b/tests/transforms/test_rand_speckle_noised.py new file mode 100644 index 00000000000..6314269e50d --- /dev/null +++ b/tests/transforms/test_rand_speckle_noised.py @@ -0,0 +1,73 @@ +# 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 RandSpeckleNoised +from tests.test_utils import TEST_NDARRAYS, NumpyImageTestCase2D + +TESTS = [] +for p in TEST_NDARRAYS: + TESTS.append(["test_sampled_std", p, ["img1", "img2"], 0.5, True]) + TESTS.append(["test_fixed_std", p, ["img1", "img2"], 0.2, False]) + +seed = 0 + + +class TestRandSpeckleNoisedNumpy(NumpyImageTestCase2D): + @parameterized.expand(TESTS) + def test_correct_results(self, _, in_type, keys, std, sample_std): + speckle_fn = RandSpeckleNoised(keys=keys, prob=1.0, std=std, sample_std=sample_std, dtype=np.float64) + speckle_fn.set_random_state(seed) + noised = speckle_fn({k: in_type(self.imt) for k in keys}) + np.random.seed(seed) + # simulate the `randomize` function of transform, called once so all keys share one factor + np.random.random() + _std = np.random.uniform(0, std) if sample_std else std + if _std <= 0: + expected = self.imt + else: + expected = self.imt * np.random.gamma(1.0 / _std**2, _std**2, size=self.imt.shape) + for k in keys: + if isinstance(noised[k], torch.Tensor): + noised[k] = noised[k].cpu() + np.testing.assert_allclose(expected, noised[k], atol=1e-5, rtol=1e-5) + # identical inputs must get the identical shared speckle factor + np.testing.assert_array_equal(np.asarray(noised[keys[0]]), np.asarray(noised[keys[1]])) + + @unittest.skipUnless(torch.backends.mps.is_available(), "MPS is not available") + def test_mps_float32_input(self): + # MPS does not support float64, so the transform must compute in float32 on MPS inputs. + keys = ["img1", "img2"] + speckle_fn = RandSpeckleNoised(keys=keys, prob=1.0, std=0.5, sample_std=False, dtype=None) + speckle_fn.set_random_state(seed) + img = torch.full((1, 4, 4), 100.0, dtype=torch.float32, device="mps") + noised = speckle_fn({k: img for k in keys}) + np.random.seed(seed) + np.random.random() + factor = np.random.gamma(1.0 / 0.5**2, 0.5**2, size=img.shape) + expected = img.cpu().numpy().astype(np.float32) * factor.astype(np.float32) + for k in keys: + self.assertEqual(noised[k].device.type, "mps") + self.assertEqual(noised[k].dtype, torch.float32) + np.testing.assert_allclose(noised[k].cpu().numpy(), expected, atol=1e-4) + # identical inputs must get the identical shared speckle factor + np.testing.assert_array_equal(np.asarray(noised[keys[0]].cpu()), np.asarray(noised[keys[1]].cpu())) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/transforms/test_rand_ultrasound_depth_gain.py b/tests/transforms/test_rand_ultrasound_depth_gain.py new file mode 100644 index 00000000000..2a86f8ca29a --- /dev/null +++ b/tests/transforms/test_rand_ultrasound_depth_gain.py @@ -0,0 +1,98 @@ +# 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 RandUltrasoundDepthGain +from tests.test_utils import TEST_NDARRAYS, NumpyImageTestCase2D + +TESTS = [] +for p in TEST_NDARRAYS: + TESTS.append(("test_gain_range", p, (-1.0, 1.0), 1)) + TESTS.append(("test_fixed_slope", p, (0.5, 0.5), 1)) + TESTS.append(("test_last_axis", p, (-1.0, 1.0), -1)) + + +class TestRandUltrasoundDepthGain(NumpyImageTestCase2D): + @parameterized.expand(TESTS) + def test_correct_results(self, _, in_type, gain_range, depth_axis): + seed = 0 + gain_fn = RandUltrasoundDepthGain(prob=1.0, gain_range=gain_range, depth_axis=depth_axis) + gain_fn.set_random_state(seed) + im = in_type(self.imt) + out = gain_fn(im) + if isinstance(im, torch.Tensor): + self.assertEqual(im.dtype, out.dtype) + np.random.seed(seed) + np.random.random() + slope = np.random.uniform(gain_range[0], gain_range[1]) + axis = depth_axis if depth_axis >= 0 else self.imt.ndim + depth_axis + gain_shape = [1] * self.imt.ndim + gain_shape[axis] = self.imt.shape[axis] + profile = np.exp(slope * (np.linspace(0.0, 1.0, self.imt.shape[axis]) - 0.5)).reshape(gain_shape) + expected = self.imt * profile + if isinstance(out, torch.Tensor): + out = out.cpu() + np.testing.assert_allclose(expected, out, atol=1e-5) + + def test_gain_increases_with_depth(self): + gain_fn = RandUltrasoundDepthGain(prob=1.0, gain_range=(1.0, 1.0), depth_axis=1) + gain_fn.set_random_state(0) + out = gain_fn(np.ones((1, 8, 4), dtype=np.float32)) + row_means = np.asarray(out).mean(axis=(0, 2)) + self.assertEqual(len(row_means), 8) + self.assertTrue(np.all(np.diff(row_means) > 0)) + + def test_uint8_input_dtype_none(self): + # Fractional gains must not be truncated to integers before multiplication. + img = np.full((1, 8, 4), 100, dtype=np.uint8) + gain_fn = RandUltrasoundDepthGain(prob=1.0, gain_range=(1.0, 1.0), depth_axis=1, dtype=None) + gain_fn.set_random_state(0) + out = gain_fn(img) + self.assertEqual(np.asarray(out).dtype, np.uint8) + profile = np.exp(1.0 * (np.linspace(0.0, 1.0, 8) - 0.5)).reshape((1, 8, 1)) + expected = (img.astype(np.float64) * profile).astype(np.uint8) + np.testing.assert_array_equal(np.asarray(out), expected) + + @unittest.skipUnless(torch.backends.mps.is_available(), "MPS is not available") + def test_mps_float32_input(self): + # MPS does not support float64, so the transform must compute in float32 on MPS inputs. + img = torch.full((1, 8, 4), 100.0, dtype=torch.float32, device="mps") + gain_fn = RandUltrasoundDepthGain(prob=1.0, gain_range=(1.0, 1.0), depth_axis=1, dtype=None) + gain_fn.set_random_state(0) + out = gain_fn(img) + self.assertEqual(out.device.type, "mps") + self.assertEqual(out.dtype, torch.float32) + profile = np.exp(1.0 * (np.linspace(0.0, 1.0, 8) - 0.5)).reshape((1, 8, 1)) + expected = img.cpu().numpy().astype(np.float32) * profile.astype(np.float32) + np.testing.assert_allclose(out.cpu().numpy(), expected, atol=1e-4) + + def test_prob_zero(self): + gain_fn = RandUltrasoundDepthGain(prob=0.0, gain_range=(-1.0, 1.0)) + gain_fn.set_random_state(0) + out = gain_fn(self.imt) + np.testing.assert_allclose(self.imt, np.asarray(out)) + + def test_invalid_depth_axis_raises(self): + gain_fn = RandUltrasoundDepthGain(prob=1.0, gain_range=(0.5, 0.5), depth_axis=5) + gain_fn.set_random_state(0) + with self.assertRaises(ValueError): + gain_fn(self.imt) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/transforms/test_rand_ultrasound_depth_gaind.py b/tests/transforms/test_rand_ultrasound_depth_gaind.py new file mode 100644 index 00000000000..193c3d3fa4d --- /dev/null +++ b/tests/transforms/test_rand_ultrasound_depth_gaind.py @@ -0,0 +1,70 @@ +# 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 RandUltrasoundDepthGaind +from tests.test_utils import TEST_NDARRAYS, NumpyImageTestCase2D + +TESTS = [] +for p in TEST_NDARRAYS: + TESTS.append(["test_gain_range", p, ["img1", "img2"], (-1.0, 1.0), 1]) + TESTS.append(["test_fixed_slope", p, ["img1", "img2"], (0.5, 0.5), 1]) + +seed = 0 + + +class TestRandUltrasoundDepthGaindNumpy(NumpyImageTestCase2D): + @parameterized.expand(TESTS) + def test_correct_results(self, _, in_type, keys, gain_range, depth_axis): + gain_fn = RandUltrasoundDepthGaind( + keys=keys, prob=1.0, gain_range=gain_range, depth_axis=depth_axis, dtype=np.float64 + ) + gain_fn.set_random_state(seed) + noised = gain_fn({k: in_type(self.imt) for k in keys}) + np.random.seed(seed) + for k in keys: + # simulate the `randomize` function of transform + np.random.random() + slope = np.random.uniform(gain_range[0], gain_range[1]) + axis = depth_axis if depth_axis >= 0 else self.imt.ndim + depth_axis + gain_shape = [1] * self.imt.ndim + gain_shape[axis] = self.imt.shape[axis] + profile = np.exp(slope * (np.linspace(0.0, 1.0, self.imt.shape[axis]) - 0.5)).reshape(gain_shape) + expected = self.imt * profile + if isinstance(noised[k], torch.Tensor): + noised[k] = noised[k].cpu() + np.testing.assert_allclose(expected, noised[k], atol=1e-5, rtol=1e-5) + + @unittest.skipUnless(torch.backends.mps.is_available(), "MPS is not available") + def test_mps_float32_input(self): + # MPS does not support float64, so the transform must compute in float32 on MPS inputs. + keys = ["img1", "img2"] + gain_fn = RandUltrasoundDepthGaind(keys=keys, prob=1.0, gain_range=(1.0, 1.0), depth_axis=1, dtype=None) + gain_fn.set_random_state(seed) + img = torch.full((1, 8, 4), 100.0, dtype=torch.float32, device="mps") + noised = gain_fn({k: img for k in keys}) + profile = np.exp(1.0 * (np.linspace(0.0, 1.0, 8) - 0.5)).reshape((1, 8, 1)) + expected = img.cpu().numpy().astype(np.float32) * profile.astype(np.float32) + for k in keys: + self.assertEqual(noised[k].device.type, "mps") + self.assertEqual(noised[k].dtype, torch.float32) + np.testing.assert_allclose(noised[k].cpu().numpy(), expected, atol=1e-4) + + +if __name__ == "__main__": + unittest.main()