Repository: Project-MONAI/MONAI

Issue:
Add IdentityTransform with configurable delay
Simulating delays in a transform sequence can be useful for simulating delays that may happen
in real data processing scenarios.  For example, a developer may want to simulate network delays by adding an IdentityTransform with a set delay to simulate slow file loading times.

**Describe the solution you'd like**
Add an IdentityTransform with fixed time delay.

**Additional context**
IdentityTransform can be used to simulating behaviors in testing environments.



Discussion:

Resolving patch:
diff --git a/monai/transforms/utility/array.py b/monai/transforms/utility/array.py
--- a/monai/transforms/utility/array.py
+++ b/monai/transforms/utility/array.py
@@ -12,9 +12,11 @@
 A collection of "vanilla" transforms for utility functions
 https://github.com/Project-MONAI/MONAI/wiki/MONAI_Design
 """
+import time
 
 import numpy as np
 import torch
+
 from monai.transforms.compose import Transform
 
 
@@ -162,3 +164,29 @@ def __call__(self, img):
             img (ndarray): numpy arrays with required dimension `dim` removed
         """
         return np.squeeze(img, self.dim)
+
+
+class SimulateDelay(Transform):
+    """
+    This is a pass through transform to be used for testing purposes. It allows
+    adding fake behaviors that are useful for testing purposes to simulate
+    how large datasets behave without needing to test on large data sets.
+
+    For example, simulating slow NFS data transfers, or slow network transfers
+    in testing by adding explicit timing delays. Testing of small test data
+    can lead to incomplete understanding of real world issues, and may lead
+    to sub-optimal design choices.
+    """
+
+    def __init__(self, delay_time=0.0):
+        """
+        Args:
+            delay_time(float): The minimum amount of time, in fractions of seconds,
+                to accomplish this delay task.
+        """
+        super().__init__()
+        self.delay_time: float = delay_time
+
+    def __call__(self, img):
+        time.sleep(self.delay_time)
+        return img
diff --git a/monai/transforms/utility/dictionary.py b/monai/transforms/utility/dictionary.py
--- a/monai/transforms/utility/dictionary.py
+++ b/monai/transforms/utility/dictionary.py
@@ -19,7 +19,7 @@
 
 from monai.transforms.compose import MapTransform
 from monai.transforms.utility.array import AddChannel, AsChannelFirst, ToTensor, \
-    AsChannelLast, CastToType, RepeatChannel, SqueezeDim
+    AsChannelLast, CastToType, RepeatChannel, SqueezeDim, SimulateDelay
 
 
 class AsChannelFirstd(MapTransform):
@@ -193,6 +193,35 @@ def __call__(self, data):
         return d
 
 
+class SimulateDelayd(MapTransform):
+    """
+    dictionary-based wrapper of :py:class:monai.transforms.utility.array.SimulateDelay.
+    """
+
+    def __init__(self, keys, delay_time=0.0):
+        """
+        Args:
+            keys (hashable items): keys of the corresponding items to be transformed.
+                See also: :py:class:`monai.transforms.compose.MapTransform`
+            delay_time(float or list of float): The minimum amount of time, in fractions of seconds,
+                to accomplish this identity task. If a list is provided, it must be of length equal
+                to the keys representing the delay for each key element.
+        """
+        super().__init__(keys)
+
+        if not isinstance(delay_time, (tuple, list)):
+            delay_time = [delay_time] * len(keys)
+        self.converter_dictionary = dict()
+        for key, keyed_default_delay in zip(self.keys, delay_time):
+            self.converter_dictionary[key] = SimulateDelay(delay_time=keyed_default_delay)
+
+    def __call__(self, data):
+        d = dict(data)
+        for key in self.keys:
+            d[key] = self.converter_dictionary[key](d[key])
+        return d
+
+
 AsChannelFirstD = AsChannelFirstDict = AsChannelFirstd
 AsChannelLastD = AsChannelLastDict = AsChannelLastd
 AddChannelD = AddChannelDict = AddChanneld
@@ -201,3 +230,4 @@ def __call__(self, data):
 ToTensorD = ToTensorDict = ToTensord
 DeleteKeysD = DeleteKeysDict = DeleteKeysd
 SqueezeDimD = SqueezeDimDict = SqueezeDimd
+SimulateDelayD = SimulateDelayDict = SimulateDelayd


Test patch:
diff --git a/tests/test_dataset.py b/tests/test_dataset.py
--- a/tests/test_dataset.py
+++ b/tests/test_dataset.py
@@ -17,7 +17,7 @@
 import nibabel as nib
 from parameterized import parameterized
 from monai.data import Dataset
-from monai.transforms import LoadNiftid
+from monai.transforms import Compose, LoadNiftid, SimulateDelayd
 
 TEST_CASE_1 = [
     (128, 128, 128)
@@ -48,7 +48,10 @@ def test_shape(self, expected_shape):
                 'extra': os.path.join(tempdir, 'test_extra2.nii.gz')
             }
         ]
-        dataset = Dataset(data=test_data, transform=LoadNiftid(keys=['image', 'label', 'extra']))
+        test_transform = Compose([LoadNiftid(keys=['image', 'label', 'extra']),
+                                  SimulateDelayd(keys=['image', 'label', 'extra'],
+                                                 delay_time=[1e-7, 1e-6, 1e-5])])
+        dataset = Dataset(data=test_data, transform=test_transform)
         data1 = dataset[0]
         data2 = dataset[1]
         shutil.rmtree(tempdir)
diff --git a/tests/test_simulatedelay.py b/tests/test_simulatedelay.py
new file mode 100644
--- /dev/null
+++ b/tests/test_simulatedelay.py
@@ -0,0 +1,33 @@
+# Copyright 2020 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 unittest
+import time
+import numpy as np
+from parameterized import parameterized
+from monai.transforms.utility.array import SimulateDelay
+from tests.utils import NumpyImageTestCase2D
+
+
+class TestSimulateDelay(NumpyImageTestCase2D):
+
+    @parameterized.expand([(0.45,), (1,)])
+    def test_value(self, delay_test_time: float):
+        resize = SimulateDelay(delay_time=delay_test_time)
+        start: float = time.time()
+        result = resize(self.imt[0])
+        stop: float = time.time()
+        measured_approximate: float = stop - start
+        np.testing.assert_array_less(delay_test_time, measured_approximate)
+
+
+if __name__ == '__main__':
+    unittest.main()
diff --git a/tests/test_simulatedelayd.py b/tests/test_simulatedelayd.py
new file mode 100644
--- /dev/null
+++ b/tests/test_simulatedelayd.py
@@ -0,0 +1,33 @@
+# Copyright 2020 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 unittest
+import time
+import numpy as np
+from parameterized import parameterized
+from monai.transforms.utility.dictionary import SimulateDelayd
+from tests.utils import NumpyImageTestCase2D
+
+
+class TestSimulateDelay(NumpyImageTestCase2D):
+
+    @parameterized.expand([(0.45,), (1,)])
+    def test_value(self, delay_test_time: float):
+        resize = SimulateDelayd(keys='imgd', delay_time=delay_test_time)
+        start: float = time.time()
+        _ = resize({'imgd': self.imt[0]})
+        stop: float = time.time()
+        measured_approximate: float = stop - start
+        np.testing.assert_array_less(delay_test_time, measured_approximate)
+
+
+if __name__ == '__main__':
+    unittest.main()