Skip to content

Commit

Permalink
Refactor unnecessary else / elif when if block has a return s…
Browse files Browse the repository at this point in the history
…tatement (#2996)

* Refactor unnecessary `else` / `elif` when `if` block has a `return` statement

* Remove unnecessary lambda expression (#2997)

Co-authored-by: deepsource-autofix[bot] <62050782+deepsource-autofix[bot]@users.noreply.github.com>

* type fixes

Signed-off-by: Wenqi Li <wenqil@nvidia.com>

* remove repeated init

Signed-off-by: Wenqi Li <wenqil@nvidia.com>

* fixes import, unused vars

Signed-off-by: Wenqi Li <wenqil@nvidia.com>

Co-authored-by: deepsource-autofix[bot] <62050782+deepsource-autofix[bot]@users.noreply.github.com>
Co-authored-by: Wenqi Li <wenqil@nvidia.com>
  • Loading branch information
deepsource-autofix[bot] and wyli authored Sep 22, 2021
1 parent f31b55f commit 790fc8f
Show file tree
Hide file tree
Showing 12 changed files with 39 additions and 49 deletions.
12 changes: 6 additions & 6 deletions monai/handlers/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -130,12 +130,12 @@ class mean median max 5percentile 95percentile notnans
if summary_ops is not None:
supported_ops = OrderedDict(
{
"mean": lambda x: np.nanmean(x),
"median": lambda x: np.nanmedian(x),
"max": lambda x: np.nanmax(x),
"min": lambda x: np.nanmin(x),
"mean": np.nanmean,
"median": np.nanmedian,
"max": np.nanmax,
"min": np.nanmin,
"90percentile": lambda x: np.nanpercentile(x[0], x[1]),
"std": lambda x: np.nanstd(x),
"std": np.nanstd,
"notnans": lambda x: (~np.isnan(x)).sum(),
}
)
Expand All @@ -149,7 +149,7 @@ def _compute_op(op: str, d: np.ndarray):
return c_op(d)

threshold = int(op.split("percentile")[0])
return supported_ops["90percentile"]((d, threshold))
return supported_ops["90percentile"]((d, threshold)) # type: ignore

with open(os.path.join(save_dir, f"{k}_summary.csv"), "w") as f:
f.write(f"class{deli}{deli.join(ops)}\n")
Expand Down
34 changes: 16 additions & 18 deletions monai/transforms/compose.py
Original file line number Diff line number Diff line change
Expand Up @@ -204,14 +204,13 @@ def __init__(
def _normalize_probabilities(self, weights):
if len(weights) == 0:
return weights
else:
weights = np.array(weights)
if np.any(weights < 0):
raise AssertionError("Probabilities must be greater than or equal to zero.")
if np.all(weights == 0):
raise AssertionError("At least one probability must be greater than zero.")
weights = weights / weights.sum()
return list(weights)
weights = np.array(weights)
if np.any(weights < 0):
raise AssertionError("Probabilities must be greater than or equal to zero.")
if np.all(weights == 0):
raise AssertionError("At least one probability must be greater than zero.")
weights = weights / weights.sum()
return list(weights)

def flatten(self):
transforms = []
Expand All @@ -232,16 +231,15 @@ def flatten(self):
def __call__(self, data):
if len(self.transforms) == 0:
return data
else:
index = self.R.multinomial(1, self.weights).argmax()
_transform = self.transforms[index]
data = apply_transform(_transform, data, self.map_items, self.unpack_items)
# if the data is a mapping (dictionary), append the OneOf transform to the end
if isinstance(data, Mapping):
for key in data.keys():
if key + InverseKeys.KEY_SUFFIX in data:
self.push_transform(data, key, extra_info={"index": index})
return data
index = self.R.multinomial(1, self.weights).argmax()
_transform = self.transforms[index]
data = apply_transform(_transform, data, self.map_items, self.unpack_items)
# if the data is a mapping (dictionary), append the OneOf transform to the end
if isinstance(data, Mapping):
for key in data.keys():
if key + InverseKeys.KEY_SUFFIX in data:
self.push_transform(data, key, extra_info={"index": index})
return data

def inverse(self, data):
if len(self.transforms) == 0:
Expand Down
1 change: 0 additions & 1 deletion monai/transforms/croppad/dictionary.py
Original file line number Diff line number Diff line change
Expand Up @@ -663,7 +663,6 @@ def __init__(
random_size=random_size,
allow_missing_keys=allow_missing_keys,
)
MapTransform.__init__(self, keys, allow_missing_keys)
self.roi_scale = roi_scale
self.max_roi_scale = max_roi_scale

Expand Down
2 changes: 1 addition & 1 deletion monai/transforms/intensity/array.py
Original file line number Diff line number Diff line change
Expand Up @@ -1457,7 +1457,7 @@ def __call__(self, img: Union[np.ndarray, torch.Tensor]) -> Union[torch.Tensor,
raise RuntimeError("Image needs a channel direction.")
if isinstance(self.loc[0], int) and len(img.shape) == 4 and len(self.loc) == 2:
raise RuntimeError("Input images of dimension 4 need location tuple to be length 3 or 4")
if isinstance(self.loc[0], Sequence) and len(img.shape) == 4 and min(map(lambda x: len(x), self.loc)) == 2:
if isinstance(self.loc[0], Sequence) and len(img.shape) == 4 and min(map(len, self.loc)) == 2:
raise RuntimeError("Input images of dimension 4 need location tuple to be length 3 or 4")

n_dims = len(img.shape[1:])
Expand Down
2 changes: 1 addition & 1 deletion monai/transforms/post/array.py
Original file line number Diff line number Diff line change
Expand Up @@ -205,7 +205,7 @@ def __call__(

rounding = self.rounding if rounding is None else rounding
if rounding is not None:
rounding = look_up_option(rounding, ["torchrounding"])
look_up_option(rounding, ["torchrounding"])
img = torch.round(img)

return img.float()
Expand Down
3 changes: 1 addition & 2 deletions monai/transforms/spatial/array.py
Original file line number Diff line number Diff line change
Expand Up @@ -335,8 +335,7 @@ def __call__(self, img: NdarrayOrTensor) -> NdarrayOrTensor:
"""
if isinstance(img, np.ndarray):
return np.ascontiguousarray(np.flip(img, map_spatial_axes(img.ndim, self.spatial_axis)))
else:
return torch.flip(img, map_spatial_axes(img.ndim, self.spatial_axis))
return torch.flip(img, map_spatial_axes(img.ndim, self.spatial_axis))


class Resize(Transform):
Expand Down
17 changes: 8 additions & 9 deletions monai/transforms/utility/array.py
Original file line number Diff line number Diff line change
Expand Up @@ -391,9 +391,8 @@ def __call__(self, data: NdarrayOrTensor):
if self.data_type == "tensor":
dtype_ = get_equivalent_dtype(self.dtype, torch.Tensor)
return convert_to_tensor(data, dtype=dtype_, device=self.device)
else:
dtype_ = get_equivalent_dtype(self.dtype, np.ndarray)
return convert_to_numpy(data, dtype=dtype_)
dtype_ = get_equivalent_dtype(self.dtype, np.ndarray)
return convert_to_numpy(data, dtype=dtype_)


class ToNumpy(Transform):
Expand Down Expand Up @@ -1091,11 +1090,11 @@ def __call__(
img_ = img[mask]

supported_ops = {
"mean": lambda x: np.nanmean(x),
"median": lambda x: np.nanmedian(x),
"max": lambda x: np.nanmax(x),
"min": lambda x: np.nanmin(x),
"std": lambda x: np.nanstd(x),
"mean": np.nanmean,
"median": np.nanmedian,
"max": np.nanmax,
"min": np.nanmin,
"std": np.nanstd,
}

def _compute(op: Callable, data: np.ndarray):
Expand All @@ -1107,7 +1106,7 @@ def _compute(op: Callable, data: np.ndarray):
for o in self.ops:
if isinstance(o, str):
o = look_up_option(o, supported_ops.keys())
meta_data[self.key_prefix + "_" + o] = _compute(supported_ops[o], img_)
meta_data[self.key_prefix + "_" + o] = _compute(supported_ops[o], img_) # type: ignore
elif callable(o):
meta_data[self.key_prefix + "_custom_" + str(custom_index)] = _compute(o, img_)
custom_index += 1
Expand Down
3 changes: 1 addition & 2 deletions monai/transforms/utility/dictionary.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@
Class names are ended with 'd' to denote dictionary-based transforms.
"""

import copy
import logging
import re
from copy import deepcopy
Expand Down Expand Up @@ -886,7 +885,7 @@ def __call__(self, data: Mapping[Hashable, NdarrayOrTensor]) -> Dict[Hashable, N
if isinstance(val, torch.Tensor):
d[new_key] = val.detach().clone()
else:
d[new_key] = copy.deepcopy(val)
d[new_key] = deepcopy(val)
return d


Expand Down
7 changes: 2 additions & 5 deletions monai/transforms/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,12 +20,11 @@
import torch

import monai
import monai.transforms.transform
from monai.config import DtypeLike, IndexSelection
from monai.config.type_definitions import NdarrayOrTensor
from monai.networks.layers import GaussianFilter
from monai.transforms.compose import Compose, OneOf
from monai.transforms.transform import MapTransform, Transform
from monai.transforms.transform import MapTransform, Transform, apply_transform
from monai.transforms.utils_pytorch_numpy_unification import any_np_pt, nonzero, ravel, unravel_index
from monai.utils import (
GridSampleMode,
Expand Down Expand Up @@ -1330,9 +1329,7 @@ def _get_data(obj, key):
prev_data = _get_data(test_data, key)
prev_type = type(prev_data)
prev_device = prev_data.device if isinstance(prev_data, torch.Tensor) else None
test_data = monai.transforms.transform.apply_transform(
_transform, test_data, transform.map_items, transform.unpack_items
)
test_data = apply_transform(_transform, test_data, transform.map_items, transform.unpack_items)
# every time the type or device changes, increment the counter
curr_data = _get_data(test_data, key)
curr_device = curr_data.device if isinstance(curr_data, torch.Tensor) else None
Expand Down
3 changes: 1 addition & 2 deletions monai/transforms/utils_pytorch_numpy_unification.py
Original file line number Diff line number Diff line change
Expand Up @@ -159,8 +159,7 @@ def floor_divide(a: NdarrayOrTensor, b) -> NdarrayOrTensor:
if is_module_ver_at_least(torch, (1, 8, 0)):
return torch.div(a, b, rounding_mode="floor")
return torch.floor_divide(a, b)
else:
return np.floor_divide(a, b)
return np.floor_divide(a, b)


def unravel_index(idx, shape):
Expand Down
2 changes: 1 addition & 1 deletion tests/test_intensity_stats.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@
]

TEST_CASE_3 = [
{"ops": [lambda x: np.mean(x), "max", lambda x: np.min(x)], "key_prefix": "orig"},
{"ops": [np.mean, "max", np.min], "key_prefix": "orig"},
np.array([[[0.0, 1.0], [2.0, 3.0]]]),
None,
{"orig_custom_0": 1.5, "orig_max": 3.0, "orig_custom_1": 0.0},
Expand Down
2 changes: 1 addition & 1 deletion tests/test_intensity_statsd.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@
]

TEST_CASE_3 = [
{"keys": "img", "ops": [lambda x: np.mean(x), "max", lambda x: np.min(x)], "key_prefix": "orig"},
{"keys": "img", "ops": [np.mean, "max", np.min], "key_prefix": "orig"},
{"img": np.array([[[0.0, 1.0], [2.0, 3.0]]])},
"img_meta_dict",
{"orig_custom_0": 1.5, "orig_max": 3.0, "orig_custom_1": 0.0},
Expand Down

0 comments on commit 790fc8f

Please sign in to comment.