Skip to content

Commit

Permalink
Add SignalFillEmptyd tranform (#7011)
Browse files Browse the repository at this point in the history
As mentioned here
#2637 (comment)
, this transform helps to fix NaN values after the input transforms.
It is basically only a wrapper around `SignalFillEmpty`. 


### Types of changes
<!--- Put an `x` in all the boxes that apply, and remove the not
applicable items -->
- [x] 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).
- [x] 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.

---------

Signed-off-by: Matthias Hadlich <matthiashadlich@posteo.de>
  • Loading branch information
matt3o authored Sep 21, 2023
1 parent f7e46dd commit def73cf
Show file tree
Hide file tree
Showing 5 changed files with 122 additions and 2 deletions.
9 changes: 9 additions & 0 deletions docs/source/transforms.rst
Original file line number Diff line number Diff line change
Expand Up @@ -1713,6 +1713,15 @@ Post-processing (Dict)
:members:
:special-members: __call__

Signal (Dict)
^^^^^^^^^^^^^

`SignalFillEmptyd`
""""""""""""""""""
.. autoclass:: SignalFillEmptyd
:members:
:special-members: __call__


Spatial (Dict)
^^^^^^^^^^^^^^
Expand Down
1 change: 1 addition & 0 deletions monai/transforms/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -345,6 +345,7 @@
SignalRandShift,
SignalRemoveFrequency,
)
from .signal.dictionary import SignalFillEmptyd, SignalFillEmptyD, SignalFillEmptyDict
from .smooth_field.array import (
RandSmoothDeform,
RandSmoothFieldAdjustContrast,
Expand Down
52 changes: 52 additions & 0 deletions monai/transforms/signal/dictionary.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
# 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.
"""
A collection of dictionary-based wrappers around the signal operations defined in :py:class:`monai.transforms.signal.array`.
Class names are ended with 'd' to denote dictionary-based transforms.
"""

from __future__ import annotations

from collections.abc import Hashable, Mapping

from monai.config.type_definitions import KeysCollection, NdarrayOrTensor
from monai.transforms.signal.array import SignalFillEmpty
from monai.transforms.transform import MapTransform

__all__ = ["SignalFillEmptyd", "SignalFillEmptyD", "SignalFillEmptyDict"]


class SignalFillEmptyd(MapTransform):
"""
Applies the SignalFillEmptyd transform on the input. All NaN values will be replaced with the
replacement value.
Args:
keys: keys of the corresponding items to model output.
allow_missing_keys: don't raise exception if key is missing.
replacement: The value that the NaN entries shall be mapped to.
"""

backend = SignalFillEmpty.backend

def __init__(self, keys: KeysCollection = None, allow_missing_keys: bool = False, replacement=0.0):
super().__init__(keys, allow_missing_keys)
self.signal_fill_empty = SignalFillEmpty(replacement=replacement)

def __call__(self, data: Mapping[Hashable, NdarrayOrTensor]) -> Mapping[Hashable, NdarrayOrTensor]:
for key in self.key_iterator(data):
data[key] = self.signal_fill_empty(data[key]) # type: ignore

return data


SignalFillEmptyD = SignalFillEmptyDict = SignalFillEmptyd
4 changes: 2 additions & 2 deletions tests/test_signal_fillempty.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ def test_correct_parameters_multi_channels(self):
sig[:, 123] = np.NAN
fillempty = SignalFillEmpty(replacement=0.0)
fillemptysignal = fillempty(sig)
self.assertTrue(not np.isnan(fillemptysignal.any()))
self.assertTrue(not np.isnan(fillemptysignal).any())


@SkipIfBeforePyTorchVersion((1, 9))
Expand All @@ -43,7 +43,7 @@ def test_correct_parameters_multi_channels(self):
sig[:, 123] = convert_to_tensor(np.NAN)
fillempty = SignalFillEmpty(replacement=0.0)
fillemptysignal = fillempty(sig)
self.assertTrue(not torch.isnan(fillemptysignal.any()))
self.assertTrue(not torch.isnan(fillemptysignal).any())


if __name__ == "__main__":
Expand Down
58 changes: 58 additions & 0 deletions tests/test_signal_fillemptyd.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
# 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 os
import unittest

import numpy as np
import torch

from monai.transforms import SignalFillEmptyd
from monai.utils.type_conversion import convert_to_tensor
from tests.utils import SkipIfBeforePyTorchVersion

TEST_SIGNAL = os.path.join(os.path.dirname(__file__), "testing_data", "signal.npy")


@SkipIfBeforePyTorchVersion((1, 9))
class TestSignalFillEmptyNumpy(unittest.TestCase):
def test_correct_parameters_multi_channels(self):
self.assertIsInstance(SignalFillEmptyd(replacement=0.0), SignalFillEmptyd)
sig = np.load(TEST_SIGNAL)
sig[:, 123] = np.NAN
data = {}
data["signal"] = sig
fillempty = SignalFillEmptyd(keys=("signal",), replacement=0.0)
data_ = fillempty(data)

self.assertTrue(np.isnan(sig).any())
self.assertTrue(not np.isnan(data_["signal"]).any())


@SkipIfBeforePyTorchVersion((1, 9))
class TestSignalFillEmptyTorch(unittest.TestCase):
def test_correct_parameters_multi_channels(self):
self.assertIsInstance(SignalFillEmptyd(replacement=0.0), SignalFillEmptyd)
sig = convert_to_tensor(np.load(TEST_SIGNAL))
sig[:, 123] = convert_to_tensor(np.NAN)
data = {}
data["signal"] = sig
fillempty = SignalFillEmptyd(keys=("signal",), replacement=0.0)
data_ = fillempty(data)

self.assertTrue(np.isnan(sig).any())
self.assertTrue(not torch.isnan(data_["signal"]).any())


if __name__ == "__main__":
unittest.main()

0 comments on commit def73cf

Please sign in to comment.