Skip to content

Commit 3f452c4

Browse files
authored
2418 Fix mypy errors caused by numpy(1.21.0) (#2419)
* [DLMED] test mypy fix Signed-off-by: Nic Ma <[email protected]> * [DLMED] test commit Signed-off-by: Nic Ma <[email protected]> * [DLMED] fix np.random Signed-off-by: Nic Ma <[email protected]> * [DLMED] fix other numpy data type errors Signed-off-by: Nic Ma <[email protected]>
1 parent 075bccd commit 3f452c4

File tree

8 files changed

+30
-25
lines changed

8 files changed

+30
-25
lines changed

monai/data/synthetic.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,7 @@ def create_test_image_2d(
4848
random_state: the random generator to use. Defaults to `np.random`.
4949
"""
5050
image = np.zeros((width, height))
51-
rs = np.random if random_state is None else random_state
51+
rs: np.random.RandomState = np.random.random.__self__ if random_state is None else random_state # type: ignore
5252

5353
for _ in range(num_objs):
5454
x = rs.randint(rad_max, width - rad_max)
@@ -111,7 +111,7 @@ def create_test_image_3d(
111111
:py:meth:`~create_test_image_2d`
112112
"""
113113
image = np.zeros((width, height, depth))
114-
rs = np.random if random_state is None else random_state
114+
rs: np.random.RandomState = np.random.random.__self__ if random_state is None else random_state # type: ignore
115115

116116
for _ in range(num_objs):
117117
x = rs.randint(rad_max, width - rad_max)

monai/data/utils.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -605,7 +605,7 @@ def to_affine_nd(r: Union[np.ndarray, int], affine: np.ndarray) -> np.ndarray:
605605
raise ValueError(f"affine must have 2 dimensions, got {affine_np.ndim}.")
606606
new_affine = np.array(r, dtype=np.float64, copy=True)
607607
if new_affine.ndim == 0:
608-
sr = new_affine.astype(int)
608+
sr: int = int(new_affine.astype(np.uint))
609609
if not np.isfinite(sr) or sr < 0:
610610
raise ValueError(f"r must be positive, got {sr}.")
611611
new_affine = np.eye(sr + 1, dtype=np.float64)

monai/handlers/utils.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -206,12 +206,12 @@ class mean median max 5percentile 95percentile notnans
206206
if summary_ops is not None:
207207
supported_ops = OrderedDict(
208208
{
209-
"mean": np.nanmean,
210-
"median": np.nanmedian,
211-
"max": np.nanmax,
212-
"min": np.nanmin,
209+
"mean": lambda x: np.nanmean(x),
210+
"median": lambda x: np.nanmedian(x),
211+
"max": lambda x: np.nanmax(x),
212+
"min": lambda x: np.nanmin(x),
213213
"90percentile": lambda x: np.nanpercentile(x[0], x[1]),
214-
"std": np.nanstd,
214+
"std": lambda x: np.nanstd(x),
215215
"notnans": lambda x: (~np.isnan(x)).sum(),
216216
}
217217
)

monai/transforms/intensity/array.py

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -75,7 +75,7 @@ def __init__(self, prob: float = 0.1, mean: Union[Sequence[float], float] = 0.0,
7575
RandomizableTransform.__init__(self, prob)
7676
self.mean = mean
7777
self.std = std
78-
self._noise = None
78+
self._noise: np.ndarray
7979

8080
def randomize(self, im_shape: Sequence[int]) -> None:
8181
super().randomize(None)
@@ -133,8 +133,8 @@ def __init__(
133133
self.channel_wise = channel_wise
134134
self.relative = relative
135135
self.sample_std = sample_std
136-
self._noise1 = None
137-
self._noise2 = None
136+
self._noise1: np.ndarray
137+
self._noise2: np.ndarray
138138

139139
def _add_noise(self, img: Union[torch.Tensor, np.ndarray], mean: float, std: float):
140140
im_shape = img.shape
@@ -463,7 +463,7 @@ def randomize(self, data: np.ndarray) -> None:
463463
self.spatial_shape = data.shape[1:]
464464
self.rank = len(self.spatial_shape)
465465
n_coeff = int(np.prod([(self.degree + k) / k for k in range(1, self.rank + 1)]))
466-
self._coeff = self.R.uniform(*self.coeff_range, n_coeff)
466+
self._coeff = self.R.uniform(*self.coeff_range, n_coeff).tolist()
467467

468468
def __call__(self, img: np.ndarray):
469469
"""
@@ -670,13 +670,13 @@ def __init__(self, prob: float = 0.1, gamma: Union[Sequence[float], float] = (0.
670670
raise AssertionError("gamma should be a number or pair of numbers.")
671671
self.gamma = (min(gamma), max(gamma))
672672

673-
self.gamma_value = None
673+
self.gamma_value: float
674674

675675
def randomize(self, data: Optional[Any] = None) -> None:
676676
super().randomize(None)
677677
self.gamma_value = self.R.uniform(low=self.gamma[0], high=self.gamma[1])
678678

679-
def __call__(self, img: np.ndarray) -> np.ndarray:
679+
def __call__(self, img: np.ndarray):
680680
"""
681681
Apply the transform to `img`.
682682
"""

monai/transforms/spatial/array.py

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -464,7 +464,7 @@ def __call__(
464464
raise ValueError(f"Unsupported img dimension: {input_ndim}, available options are [2, 3].")
465465
_angle = ensure_tuple_rep(self.angle, 1 if input_ndim == 2 else 3)
466466
transform = create_rotate(input_ndim, _angle)
467-
shift = create_translate(input_ndim, (im_shape - 1) / 2)
467+
shift = create_translate(input_ndim, ((im_shape - 1) / 2).tolist())
468468
if self.keep_size:
469469
output_shape = im_shape
470470
else:
@@ -473,7 +473,7 @@ def __call__(
473473
)
474474
corners = transform[:-1, :-1] @ corners
475475
output_shape = np.asarray(corners.ptp(axis=1) + 0.5, dtype=int)
476-
shift_1 = create_translate(input_ndim, -(output_shape - 1) / 2)
476+
shift_1 = create_translate(input_ndim, (-(output_shape - 1) / 2).tolist())
477477
transform = shift @ transform @ shift_1
478478

479479
xform = AffineTransform(
@@ -985,6 +985,7 @@ def __call__(
985985
else:
986986
raise ValueError("Incompatible values: grid=None and spatial_size=None.")
987987

988+
affine: Union[torch.Tensor, np.ndarray]
988989
if self.affine is None:
989990
spatial_dims = len(grid.shape) - 1
990991
affine = np.eye(spatial_dims + 1)
@@ -1138,7 +1139,7 @@ def __init__(
11381139

11391140
self.rand_mag = 1.0
11401141
self.as_tensor_output = as_tensor_output
1141-
self.random_offset = 0.0
1142+
self.random_offset: np.ndarray
11421143
self.device = device
11431144

11441145
def randomize(self, grid_size: Sequence[int]) -> None:
@@ -1694,7 +1695,7 @@ def __init__(
16941695
self.padding_mode: GridSamplePadMode = GridSamplePadMode(padding_mode)
16951696
self.device = device
16961697

1697-
self.rand_offset = None
1698+
self.rand_offset: np.ndarray
16981699
self.magnitude = 1.0
16991700
self.sigma = 1.0
17001701

monai/transforms/spatial/dictionary.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1521,7 +1521,7 @@ def inverse(self, data: Mapping[Hashable, np.ndarray]) -> Dict[Hashable, np.ndar
15211521
transform = self.get_most_recent_transform(d, key)
15221522
# Create inverse transform
15231523
zoom = np.array(self.zoomer.zoom)
1524-
inverse_transform = Zoom(zoom=1 / zoom, keep_size=self.zoomer.keep_size)
1524+
inverse_transform = Zoom(zoom=(1 / zoom).tolist(), keep_size=self.zoomer.keep_size)
15251525
mode = transform[InverseKeys.EXTRA_INFO]["mode"]
15261526
padding_mode = transform[InverseKeys.EXTRA_INFO]["padding_mode"]
15271527
align_corners = transform[InverseKeys.EXTRA_INFO]["align_corners"]
@@ -1649,7 +1649,7 @@ def inverse(self, data: Mapping[Hashable, np.ndarray]) -> Dict[Hashable, np.ndar
16491649
mode = transform[InverseKeys.EXTRA_INFO]["mode"]
16501650
padding_mode = transform[InverseKeys.EXTRA_INFO]["padding_mode"]
16511651
align_corners = transform[InverseKeys.EXTRA_INFO]["align_corners"]
1652-
inverse_transform = Zoom(zoom=1 / zoom, keep_size=self.keep_size)
1652+
inverse_transform = Zoom(zoom=(1 / zoom).tolist(), keep_size=self.keep_size)
16531653
# Apply inverse
16541654
d[key] = inverse_transform(
16551655
d[key],

monai/transforms/utils.py

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -224,8 +224,8 @@ def resize_center(img: np.ndarray, *resize_dims: Optional[int], fill_value: floa
224224

225225
resize_dims = fall_back_tuple(resize_dims, img.shape)
226226

227-
half_img_shape = np.asarray(img.shape) // 2
228-
half_dest_shape = np.asarray(resize_dims) // 2
227+
half_img_shape = (np.asarray(img.shape) // 2).tolist()
228+
half_dest_shape = (np.asarray(resize_dims) // 2).tolist()
229229
srcslices, destslices = copypaste_arrays(img.shape, resize_dims, half_img_shape, half_dest_shape, resize_dims)
230230

231231
if not inplace:
@@ -318,7 +318,7 @@ def generate_pos_neg_label_crop_centers(
318318
label_spatial_shape: Sequence[int],
319319
fg_indices: np.ndarray,
320320
bg_indices: np.ndarray,
321-
rand_state: np.random.RandomState = np.random,
321+
rand_state: Optional[np.random.RandomState] = None,
322322
) -> List[List[np.ndarray]]:
323323
"""
324324
Generate valid sample locations based on the label with option for specifying foreground ratio
@@ -338,6 +338,8 @@ def generate_pos_neg_label_crop_centers(
338338
ValueError: When the foreground and background indices lengths are 0.
339339
340340
"""
341+
if rand_state is None:
342+
rand_state = np.random.random.__self__ # type: ignore
341343
spatial_size = fall_back_tuple(spatial_size, default=label_spatial_shape)
342344
if not (np.subtract(label_spatial_shape, spatial_size) >= 0).all():
343345
raise ValueError("The size of the proposed random crop ROI is larger than the image size.")
@@ -602,7 +604,7 @@ def get_largest_connected_component_mask(img: torch.Tensor, connectivity: Option
602604

603605

604606
def get_extreme_points(
605-
img: np.ndarray, rand_state: np.random.RandomState = np.random, background: int = 0, pert: float = 0.0
607+
img: np.ndarray, rand_state: Optional[np.random.RandomState] = None, background: int = 0, pert: float = 0.0
606608
) -> List[Tuple[int, ...]]:
607609
"""
608610
Generate extreme points from an image. These are used to generate initial segmentation
@@ -624,6 +626,8 @@ def get_extreme_points(
624626
Raises:
625627
ValueError: When the input image does not have any foreground pixel.
626628
"""
629+
if rand_state is None:
630+
rand_state = np.random.random.__self__ # type: ignore
627631
indices = np.where(img != background)
628632
if np.size(indices[0]) == 0:
629633
raise ValueError("get_extreme_points: no foreground object in mask!")

tests/utils.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -158,7 +158,7 @@ def make_nifti_image(array, affine=None):
158158

159159
def make_rand_affine(ndim: int = 3, random_state: Optional[np.random.RandomState] = None):
160160
"""Create random affine transformation (with values == -1, 0 or 1)."""
161-
rs = np.random if random_state is None else random_state
161+
rs = np.random.random.__self__ if random_state is None else random_state # type: ignore
162162

163163
vals = rs.choice([-1, 1], size=ndim)
164164
positions = rs.choice(range(ndim), size=ndim, replace=False)

0 commit comments

Comments
 (0)