Skip to content

Commit 9b4b84f

Browse files
authored
5251 replace None type metadict content with 'none' (#5252)
Signed-off-by: Wenqi Li <[email protected]> Fixes #5251 ### Description replace `None` with `"none"` in the readers ### 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`. - [x] 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: Wenqi Li <[email protected]>
1 parent e9f48e3 commit 9b4b84f

File tree

4 files changed

+28
-20
lines changed

4 files changed

+28
-20
lines changed

monai/data/image_reader.py

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,16 @@
2828
orientation_ras_lps,
2929
)
3030
from monai.transforms.utility.array import EnsureChannelFirst
31-
from monai.utils import MetaKeys, SpaceKeys, deprecated, ensure_tuple, ensure_tuple_rep, optional_import, require_pkg
31+
from monai.utils import (
32+
MetaKeys,
33+
SpaceKeys,
34+
TraceKeys,
35+
deprecated,
36+
ensure_tuple,
37+
ensure_tuple_rep,
38+
optional_import,
39+
require_pkg,
40+
)
3241

3342
if TYPE_CHECKING:
3443
import itk
@@ -131,7 +140,7 @@ def _copy_compatible_dict(from_dict: Dict, to_dict: Dict):
131140
datum = from_dict[key]
132141
if isinstance(datum, np.ndarray) and np_str_obj_array_pattern.search(datum.dtype.str) is not None:
133142
continue
134-
to_dict[key] = datum
143+
to_dict[key] = str(TraceKeys.NONE) if datum is None else datum # NoneType to string for default_collate
135144
else:
136145
affine_key, shape_key = MetaKeys.AFFINE, MetaKeys.SPATIAL_SHAPE
137146
if affine_key in from_dict and not np.allclose(from_dict[affine_key], to_dict[affine_key]):

monai/metrics/active_learning_metrics.py

Lines changed: 14 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
1515
import torch
1616

1717
from monai.metrics.utils import ignore_background
18+
from monai.utils import MetricReduction
1819

1920
from .metric import Metric
2021

@@ -135,7 +136,7 @@ def compute_variance(
135136

136137
n_len = len(y_pred.shape)
137138

138-
if n_len < 4 and spatial_map is True:
139+
if n_len < 4 and spatial_map:
139140
warnings.warn("Spatial map requires a 2D/3D image with N-repeats and C-channels")
140141
return None
141142

@@ -149,16 +150,14 @@ def compute_variance(
149150
y_reshaped = torch.reshape(y_pred, new_shape)
150151
variance = torch.var(y_reshaped, dim=0, unbiased=False)
151152

152-
if spatial_map is True:
153+
if spatial_map:
153154
return variance
154155

155-
elif spatial_map is False:
156-
if scalar_reduction == "mean":
157-
var_mean = torch.mean(variance)
158-
return var_mean
159-
elif scalar_reduction == "sum":
160-
var_sum = torch.sum(variance)
161-
return var_sum
156+
if scalar_reduction == MetricReduction.MEAN:
157+
return torch.mean(variance)
158+
if scalar_reduction == MetricReduction.SUM:
159+
return torch.sum(variance)
160+
raise ValueError(f"scalar_reduction={scalar_reduction} not supported.")
162161

163162

164163
def label_quality_score(
@@ -196,13 +195,11 @@ def label_quality_score(
196195

197196
abs_diff_map = torch.abs(y_pred - y)
198197

199-
if scalar_reduction == "none":
198+
if scalar_reduction == MetricReduction.NONE:
200199
return abs_diff_map
201200

202-
elif scalar_reduction != "none":
203-
if scalar_reduction == "mean":
204-
lbl_score_mean = torch.mean(abs_diff_map, dim=list(range(1, n_len)))
205-
return lbl_score_mean
206-
elif scalar_reduction == "sum":
207-
lbl_score_sum = torch.sum(abs_diff_map, dim=list(range(1, n_len)))
208-
return lbl_score_sum
201+
if scalar_reduction == MetricReduction.MEAN:
202+
return torch.mean(abs_diff_map, dim=list(range(1, n_len)))
203+
if scalar_reduction == MetricReduction.SUM:
204+
return torch.sum(abs_diff_map, dim=list(range(1, n_len)))
205+
raise ValueError(f"scalar_reduction={scalar_reduction} not supported.")

monai/visualize/occlusion_sensitivity.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -155,7 +155,8 @@ def gaussian_occlusion(x: torch.Tensor, mask_size, sigma=0.25) -> Tuple[torch.Te
155155
[GaussianSmooth(sigma=[b * sigma for b in spatial_shape]), Lambda(lambda x: -x), ScaleIntensity()]
156156
)
157157
# transform and add batch
158-
mul: torch.Tensor = gaussian(kernel)[None] # type: ignore
158+
mul: torch.Tensor = gaussian(kernel)[None]
159+
159160
return mul, 0
160161

161162
@staticmethod

tests/test_pil_reader.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -64,6 +64,7 @@ def test_converter(self, data_shape, filenames, expected_shape, meta_shape):
6464
Image.fromarray(test_image.astype("uint8")).save(filenames[i])
6565
reader = PILReader(converter=lambda image: image.convert("LA"))
6666
result = reader.get_data(reader.read(filenames, mode="r"))
67+
self.assertEqual(result[1]["format"], "none") # project-monai/monai issue#5251
6768
# load image by PIL and compare the result
6869
test_image = np.asarray(Image.open(filenames[0]).convert("LA"))
6970

0 commit comments

Comments
 (0)