Skip to content

3561 Fix new mypy errors for numpy 1.22.0 #3562

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 6 commits into from
Jan 1, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions monai/apps/datasets.py
Original file line number Diff line number Diff line change
Expand Up @@ -122,7 +122,7 @@ def __init__(
copy_cache=copy_cache,
)

def randomize(self, data: List[int]) -> None:
def randomize(self, data: np.ndarray) -> None:
self.R.shuffle(data)

def get_num_classes(self) -> int:
Expand Down Expand Up @@ -331,7 +331,7 @@ def get_indices(self) -> np.ndarray:
"""
return self.indices

def randomize(self, data: List[int]) -> None:
def randomize(self, data: np.ndarray) -> None:
self.R.shuffle(data)

def get_properties(self, keys: Optional[Union[Sequence[str], str]] = None):
Expand Down
2 changes: 1 addition & 1 deletion monai/apps/pathology/transforms/spatial/array.py
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ def __call__(self, image: NdarrayOrTensor) -> NdarrayOrTensor:
if isinstance(image, torch.Tensor):
return torch.stack([image])
elif isinstance(image, np.ndarray):
return np.stack([image])
return np.stack([image]) # type: ignore
else:
raise ValueError(f"Input type [{type(image)}] is not supported.")

Expand Down
2 changes: 1 addition & 1 deletion monai/data/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -539,7 +539,7 @@ def rectify_header_sform_qform(img_nii):
return img_nii


def zoom_affine(affine: np.ndarray, scale: Sequence[float], diagonal: bool = True):
def zoom_affine(affine: np.ndarray, scale: Union[np.ndarray, Sequence[float]], diagonal: bool = True):
"""
To make column norm of `affine` the same as `scale`. If diagonal is False,
returns an affine that combines orthogonal rotation and the new scale.
Expand Down
3 changes: 2 additions & 1 deletion monai/transforms/intensity/array.py
Original file line number Diff line number Diff line change
Expand Up @@ -443,6 +443,7 @@ def __call__(self, img: NdarrayOrTensor) -> NdarrayOrTensor:
ValueError: When ``self.minv=None`` or ``self.maxv=None`` and ``self.factor=None``. Incompatible values.

"""
ret: NdarrayOrTensor
if self.minv is not None or self.maxv is not None:
if self.channel_wise:
out = [rescale_array(d, self.minv, self.maxv, dtype=self.dtype) for d in img]
Expand Down Expand Up @@ -591,7 +592,7 @@ def __call__(self, img: NdarrayOrTensor, randomize: bool = True) -> NdarrayOrTen
axis=0,
)
img_np, *_ = convert_data_type(img, np.ndarray)
out = img_np * np.exp(_bias_fields)
out: NdarrayOrTensor = img_np * np.exp(_bias_fields)
out, *_ = convert_to_dst_type(src=out, dst=img, dtype=self.dtype or img.dtype)
return out

Expand Down
25 changes: 13 additions & 12 deletions monai/transforms/spatial/array.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
https://github.com/Project-MONAI/MONAI/wiki/MONAI_Design
"""
import warnings
from typing import Any, List, Optional, Sequence, Tuple, Union
from typing import Any, Callable, List, Optional, Sequence, Tuple, Union

import numpy as np
import torch
Expand Down Expand Up @@ -700,7 +700,7 @@ def __call__(self, img: NdarrayOrTensor) -> NdarrayOrTensor:
Args:
img: channel first array, must have shape: (num_channels, H[, W, ..., ]),
"""
rot90 = torch.rot90 if isinstance(img, torch.Tensor) else np.rot90
rot90: Callable = torch.rot90 if isinstance(img, torch.Tensor) else np.rot90 # type: ignore
out: NdarrayOrTensor = rot90(img, self.k, map_spatial_axes(img.ndim, self.spatial_axes))
out, *_ = convert_data_type(out, dtype=img.dtype)
return out
Expand Down Expand Up @@ -1373,14 +1373,15 @@ def __call__(
raise ValueError("Unknown grid.")
_device = img.device if isinstance(img, torch.Tensor) else self.device
img_t: torch.Tensor
grid_t: torch.Tensor
img_t, *_ = convert_data_type(img, torch.Tensor, device=_device, dtype=torch.float32) # type: ignore
grid, *_ = convert_to_dst_type(grid, img_t)
grid_t, *_ = convert_to_dst_type(grid, img_t) # type: ignore

if USE_COMPILED:
for i, dim in enumerate(img_t.shape[1:]):
grid[i] += (dim - 1.0) / 2.0
grid = grid[:-1] / grid[-1:]
grid = grid.permute(list(range(grid.ndimension()))[1:] + [0])
grid_t[i] += (dim - 1.0) / 2.0
grid_t = grid_t[:-1] / grid_t[-1:]
grid_t = grid_t.permute(list(range(grid_t.ndimension()))[1:] + [0])
_padding_mode = look_up_option(
self.padding_mode if padding_mode is None else padding_mode, GridSamplePadMode
).value
Expand All @@ -1393,21 +1394,21 @@ def __call__(
_interp_mode = look_up_option(self.mode if mode is None else mode, GridSampleMode).value
out = grid_pull(
img_t.unsqueeze(0),
grid.unsqueeze(0),
grid_t.unsqueeze(0),
bound=bound,
extrapolate=True,
interpolation=1 if _interp_mode == "bilinear" else _interp_mode,
)[0]
else:
for i, dim in enumerate(img_t.shape[1:]):
grid[i] = 2.0 * grid[i] / (dim - 1.0)
grid = grid[:-1] / grid[-1:]
grid_t[i] = 2.0 * grid_t[i] / (dim - 1.0)
grid_t = grid_t[:-1] / grid_t[-1:]
index_ordering: List[int] = list(range(img_t.ndimension() - 2, -1, -1))
grid = grid[index_ordering]
grid = grid.permute(list(range(grid.ndimension()))[1:] + [0])
grid_t = grid_t[index_ordering]
grid_t = grid_t.permute(list(range(grid_t.ndimension()))[1:] + [0])
out = torch.nn.functional.grid_sample(
img_t.unsqueeze(0),
grid.unsqueeze(0),
grid_t.unsqueeze(0),
mode=self.mode.value if mode is None else GridSampleMode(mode).value,
padding_mode=self.padding_mode.value if padding_mode is None else GridSamplePadMode(padding_mode).value,
align_corners=True,
Expand Down
2 changes: 1 addition & 1 deletion monai/transforms/utility/array.py
Original file line number Diff line number Diff line change
Expand Up @@ -789,7 +789,7 @@ def __call__(
if img.shape[0] > 1:
data = img[[*select_labels]]
else:
where = np.where if isinstance(img, np.ndarray) else torch.where
where: Callable = np.where if isinstance(img, np.ndarray) else torch.where # type: ignore
if isinstance(img, np.ndarray) or is_module_ver_at_least(torch, (1, 8, 0)):
data = where(in1d(img, select_labels), True, False).reshape(img.shape)
# pre pytorch 1.8.0, need to use 1/0 instead of True/False
Expand Down
4 changes: 2 additions & 2 deletions monai/transforms/utils_pytorch_numpy_unification.py
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,7 @@ def percentile(x: NdarrayOrTensor, q, dim: Optional[int] = None) -> Union[Ndarra
Resulting value (scalar)
"""
if np.isscalar(q):
if not 0 <= q <= 100:
if not 0 <= q <= 100: # type: ignore
raise ValueError
elif any(q < 0) or any(q > 100):
raise ValueError
Expand Down Expand Up @@ -134,7 +134,7 @@ def where(condition: NdarrayOrTensor, x=None, y=None) -> NdarrayOrTensor:
if x is not None:
result = np.where(condition, x, y)
else:
result = np.where(condition)
result = np.where(condition) # type: ignore
else:
if x is not None:
x = torch.as_tensor(x, device=condition.device)
Expand Down