Skip to content

Commit 7a8680e

Browse files
authored
Fix mypy issue introduced in 1.11.0 (#7941)
Fixes #7940 . ### Description Refer: https://mypy.readthedocs.io/en/stable/common_issues.html ### 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). - [ ] New tests added to cover the changes. - [ ] Integration tests passed locally by running `./runtests.sh -f -u --net --coverage`. - [ ] 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: YunLiu <[email protected]>
1 parent d020fac commit 7a8680e

File tree

10 files changed

+37
-35
lines changed

10 files changed

+37
-35
lines changed

monai/apps/auto3dseg/hpo_gen.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -53,7 +53,7 @@ def update_params(self, *args, **kwargs):
5353
raise NotImplementedError
5454

5555
@abstractmethod
56-
def set_score(self):
56+
def set_score(self, *args, **kwargs):
5757
"""Report the evaluated results to HPO."""
5858
raise NotImplementedError
5959

monai/apps/pathology/transforms/post/array.py

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@
2828
SobelGradients,
2929
)
3030
from monai.transforms.transform import Transform
31-
from monai.transforms.utils_pytorch_numpy_unification import max, maximum, min, sum, unique
31+
from monai.transforms.utils_pytorch_numpy_unification import max, maximum, min, sum, unique, where
3232
from monai.utils import TransformBackends, convert_to_numpy, optional_import
3333
from monai.utils.misc import ensure_tuple_rep
3434
from monai.utils.type_conversion import convert_to_dst_type, convert_to_tensor
@@ -162,7 +162,8 @@ def __call__(self, prob_map: NdarrayOrTensor) -> NdarrayOrTensor:
162162
pred = label(pred)[0]
163163
if self.remove_small_objects is not None:
164164
pred = self.remove_small_objects(pred)
165-
pred[pred > 0] = 1
165+
pred_indices = np.where(pred > 0)
166+
pred[pred_indices] = 1
166167

167168
return convert_to_dst_type(pred, prob_map, dtype=self.dtype)[0]
168169

@@ -338,7 +339,8 @@ def __call__(self, mask: NdarrayOrTensor, instance_border: NdarrayOrTensor) -> N
338339
instance_border = instance_border >= self.threshold # uncertain area
339340

340341
marker = mask - convert_to_dst_type(instance_border, mask)[0] # certain foreground
341-
marker[marker < 0] = 0
342+
marker_indices = where(marker < 0)
343+
marker[marker_indices] = 0 # type: ignore[index]
342344
marker = self.postprocess_fn(marker)
343345
marker = convert_to_numpy(marker)
344346

@@ -635,7 +637,7 @@ def __call__( # type: ignore
635637

636638
seg_map_crop = convert_to_dst_type(seg_map_crop == instance_id, type_map_crop, dtype=bool)[0]
637639

638-
inst_type = type_map_crop[seg_map_crop]
640+
inst_type = type_map_crop[seg_map_crop] # type: ignore[index]
639641
type_list, type_pixels = unique(inst_type, return_counts=True)
640642
type_list = list(zip(type_list, type_pixels))
641643
type_list = sorted(type_list, key=lambda x: x[1], reverse=True)

monai/data/meta_tensor.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -505,7 +505,7 @@ def peek_pending_rank(self):
505505
a = self.pending_operations[-1].get(LazyAttr.AFFINE, None) if self.pending_operations else self.affine
506506
return 1 if a is None else int(max(1, len(a) - 1))
507507

508-
def new_empty(self, size, dtype=None, device=None, requires_grad=False):
508+
def new_empty(self, size, dtype=None, device=None, requires_grad=False): # type: ignore[override]
509509
"""
510510
must be defined for deepcopy to work
511511
@@ -580,7 +580,7 @@ def ensure_torch_and_prune_meta(
580580
img.affine = MetaTensor.get_default_affine()
581581
return img
582582

583-
def __repr__(self):
583+
def __repr__(self): # type: ignore[override]
584584
"""
585585
Prints a representation of the tensor.
586586
Prepends "meta" to ``torch.Tensor.__repr__``.

monai/networks/layers/simplelayers.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -452,7 +452,7 @@ def get_binary_kernel(window_size: Sequence[int], dtype=torch.float, device=None
452452

453453
def median_filter(
454454
in_tensor: torch.Tensor,
455-
kernel_size: Sequence[int] = (3, 3, 3),
455+
kernel_size: Sequence[int] | int = (3, 3, 3),
456456
spatial_dims: int = 3,
457457
kernel: torch.Tensor | None = None,
458458
**kwargs,

monai/networks/nets/quicknat.py

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,7 @@ class SkipConnectionWithIdx(SkipConnection):
4242
Inherits from SkipConnection but provides the indizes with each forward pass.
4343
"""
4444

45-
def forward(self, input, indices):
45+
def forward(self, input, indices): # type: ignore[override]
4646
return super().forward(input), indices
4747

4848

@@ -57,7 +57,7 @@ class SequentialWithIdx(nn.Sequential):
5757
def __init__(self, *args):
5858
super().__init__(*args)
5959

60-
def forward(self, input, indices):
60+
def forward(self, input, indices): # type: ignore[override]
6161
for module in self:
6262
input, indices = module(input, indices)
6363
return input, indices
@@ -165,7 +165,7 @@ def _get_layer(self, in_channels, out_channels, dilation):
165165
)
166166
return nn.Sequential(conv.get_submodule("adn"), conv.get_submodule("conv"))
167167

168-
def forward(self, input, _):
168+
def forward(self, input, _): # type: ignore[override]
169169
i = 0
170170
result = input
171171
result1 = input # this will not stay this value, needed here for pylint/mypy
@@ -215,7 +215,7 @@ def __init__(self, in_channels: int, max_pool, se_layer, dropout, kernel_size, n
215215
super().__init__(in_channels, se_layer, dropout, kernel_size, num_filters)
216216
self.max_pool = max_pool
217217

218-
def forward(self, input, indices=None):
218+
def forward(self, input, indices=None): # type: ignore[override]
219219
input, indices = self.max_pool(input)
220220

221221
out_block, _ = super().forward(input, None)
@@ -243,7 +243,7 @@ def __init__(self, in_channels: int, un_pool, se_layer, dropout, kernel_size, nu
243243
super().__init__(in_channels, se_layer, dropout, kernel_size, num_filters)
244244
self.un_pool = un_pool
245245

246-
def forward(self, input, indices):
246+
def forward(self, input, indices): # type: ignore[override]
247247
out_block, _ = super().forward(input, None)
248248
out_block = self.un_pool(out_block, indices)
249249
return out_block, None
@@ -270,7 +270,7 @@ def __init__(self, in_channels: int, se_layer, dropout, max_pool, un_pool, kerne
270270
self.max_pool = max_pool
271271
self.un_pool = un_pool
272272

273-
def forward(self, input, indices):
273+
def forward(self, input, indices): # type: ignore[override]
274274
out_block, indices = self.max_pool(input)
275275
out_block, _ = super().forward(out_block, None)
276276
out_block = self.un_pool(out_block, indices)

monai/transforms/croppad/array.py

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -362,10 +362,10 @@ def __init__(self, lazy: bool = False):
362362

363363
@staticmethod
364364
def compute_slices(
365-
roi_center: Sequence[int] | NdarrayOrTensor | None = None,
366-
roi_size: Sequence[int] | NdarrayOrTensor | None = None,
367-
roi_start: Sequence[int] | NdarrayOrTensor | None = None,
368-
roi_end: Sequence[int] | NdarrayOrTensor | None = None,
365+
roi_center: Sequence[int] | int | NdarrayOrTensor | None = None,
366+
roi_size: Sequence[int] | int | NdarrayOrTensor | None = None,
367+
roi_start: Sequence[int] | int | NdarrayOrTensor | None = None,
368+
roi_end: Sequence[int] | int | NdarrayOrTensor | None = None,
369369
roi_slices: Sequence[slice] | None = None,
370370
) -> tuple[slice]:
371371
"""
@@ -459,10 +459,10 @@ class SpatialCrop(Crop):
459459

460460
def __init__(
461461
self,
462-
roi_center: Sequence[int] | NdarrayOrTensor | None = None,
463-
roi_size: Sequence[int] | NdarrayOrTensor | None = None,
464-
roi_start: Sequence[int] | NdarrayOrTensor | None = None,
465-
roi_end: Sequence[int] | NdarrayOrTensor | None = None,
462+
roi_center: Sequence[int] | int | NdarrayOrTensor | None = None,
463+
roi_size: Sequence[int] | int | NdarrayOrTensor | None = None,
464+
roi_start: Sequence[int] | int | NdarrayOrTensor | None = None,
465+
roi_end: Sequence[int] | int | NdarrayOrTensor | None = None,
466466
roi_slices: Sequence[slice] | None = None,
467467
lazy: bool = False,
468468
) -> None:

monai/transforms/croppad/dictionary.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -438,10 +438,10 @@ class SpatialCropd(Cropd):
438438
def __init__(
439439
self,
440440
keys: KeysCollection,
441-
roi_center: Sequence[int] | None = None,
442-
roi_size: Sequence[int] | None = None,
443-
roi_start: Sequence[int] | None = None,
444-
roi_end: Sequence[int] | None = None,
441+
roi_center: Sequence[int] | int | None = None,
442+
roi_size: Sequence[int] | int | None = None,
443+
roi_start: Sequence[int] | int | None = None,
444+
roi_end: Sequence[int] | int | None = None,
445445
roi_slices: Sequence[slice] | None = None,
446446
allow_missing_keys: bool = False,
447447
lazy: bool = False,

monai/transforms/spatial/array.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3441,7 +3441,7 @@ def filter_count(self, image_np: NdarrayOrTensor, locations: np.ndarray) -> tupl
34413441
idx = self.R.permutation(image_np.shape[0])
34423442
idx = idx[: self.num_patches]
34433443
idx_np = convert_data_type(idx, np.ndarray)[0]
3444-
image_np = image_np[idx]
3444+
image_np = image_np[idx] # type: ignore[index]
34453445
locations = locations[idx_np]
34463446
return image_np, locations
34473447
elif self.sort_fn not in (None, GridPatchSort.MIN, GridPatchSort.MAX):

monai/visualize/class_activation_maps.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -290,7 +290,7 @@ def __init__(
290290
)
291291
self.fc_layers = fc_layers
292292

293-
def compute_map(self, x, class_idx=None, layer_idx=-1, **kwargs):
293+
def compute_map(self, x, class_idx=None, layer_idx=-1, **kwargs): # type: ignore[override]
294294
logits, acti, _ = self.nn_module(x, **kwargs)
295295
acti = acti[layer_idx]
296296
if class_idx is None:
@@ -302,7 +302,7 @@ def compute_map(self, x, class_idx=None, layer_idx=-1, **kwargs):
302302
output = torch.stack([output[i, b : b + 1] for i, b in enumerate(class_idx)], dim=0)
303303
return output.reshape(b, 1, *spatial) # resume the spatial dims on the selected class
304304

305-
def __call__(self, x, class_idx=None, layer_idx=-1, **kwargs):
305+
def __call__(self, x, class_idx=None, layer_idx=-1, **kwargs): # type: ignore[override]
306306
"""
307307
Compute the activation map with upsampling and postprocessing.
308308
@@ -361,15 +361,15 @@ class GradCAM(CAMBase):
361361
362362
"""
363363

364-
def compute_map(self, x, class_idx=None, retain_graph=False, layer_idx=-1, **kwargs):
364+
def compute_map(self, x, class_idx=None, retain_graph=False, layer_idx=-1, **kwargs): # type: ignore[override]
365365
_, acti, grad = self.nn_module(x, class_idx=class_idx, retain_graph=retain_graph, **kwargs)
366366
acti, grad = acti[layer_idx], grad[layer_idx]
367367
b, c, *spatial = grad.shape
368368
weights = grad.view(b, c, -1).mean(2).view(b, c, *[1] * len(spatial))
369369
acti_map = (weights * acti).sum(1, keepdim=True)
370370
return F.relu(acti_map)
371371

372-
def __call__(self, x, class_idx=None, layer_idx=-1, retain_graph=False, **kwargs):
372+
def __call__(self, x, class_idx=None, layer_idx=-1, retain_graph=False, **kwargs): # type: ignore[override]
373373
"""
374374
Compute the activation map with upsampling and postprocessing.
375375
@@ -401,7 +401,7 @@ class GradCAMpp(GradCAM):
401401
402402
"""
403403

404-
def compute_map(self, x, class_idx=None, retain_graph=False, layer_idx=-1, **kwargs):
404+
def compute_map(self, x, class_idx=None, retain_graph=False, layer_idx=-1, **kwargs): # type: ignore[override]
405405
_, acti, grad = self.nn_module(x, class_idx=class_idx, retain_graph=retain_graph, **kwargs)
406406
acti, grad = acti[layer_idx], grad[layer_idx]
407407
b, c, *spatial = grad.shape

tests/test_subpixel_upsample.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -55,9 +55,9 @@
5555
(2, 1, 32, 16, 8),
5656
]
5757

58-
TEST_CASE_SUBPIXEL.append(TEST_CASE_SUBPIXEL_2D_EXTRA)
59-
TEST_CASE_SUBPIXEL.append(TEST_CASE_SUBPIXEL_3D_EXTRA)
60-
TEST_CASE_SUBPIXEL.append(TEST_CASE_SUBPIXEL_CONV_BLOCK_EXTRA)
58+
TEST_CASE_SUBPIXEL.append(TEST_CASE_SUBPIXEL_2D_EXTRA) # type: ignore
59+
TEST_CASE_SUBPIXEL.append(TEST_CASE_SUBPIXEL_3D_EXTRA) # type: ignore
60+
TEST_CASE_SUBPIXEL.append(TEST_CASE_SUBPIXEL_CONV_BLOCK_EXTRA) # type: ignore
6161

6262
# add every test back with the pad/pool sequential component omitted
6363
for tests in list(TEST_CASE_SUBPIXEL):

0 commit comments

Comments
 (0)