Skip to content

Commit f380cf2

Browse files
Fix missing type annotations (#5655)
Fixes #5605. ### Description Fix missing type annotations so `./runtests.sh --mypy` now finds 0 warnings. ### 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`. - [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: Felix Schnabel <f.schnabel@tum.de> Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
1 parent e8c6247 commit f380cf2

19 files changed

Lines changed: 81 additions & 53 deletions

File tree

monai/apps/auto3dseg/ensemble_builder.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -221,7 +221,7 @@ def __init__(self, n_fold: int = 5):
221221
super().__init__()
222222
self.n_fold = n_fold
223223

224-
def collect_algos(self):
224+
def collect_algos(self) -> None:
225225
"""
226226
Rank the algos by finding the best model in each cross-validation fold
227227
"""

monai/apps/auto3dseg/hpo_gen.py

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@
1212
import os
1313
from abc import abstractmethod
1414
from copy import deepcopy
15+
from typing import Optional
1516
from warnings import warn
1617

1718
from monai.apps.auto3dseg.bundle_gen import BundleAlgo
@@ -96,7 +97,7 @@ class NNIGen(HPOGen):
9697
NNI command manually.
9798
"""
9899

99-
def __init__(self, algo=None, params=None):
100+
def __init__(self, algo: Optional[Algo] = None, params=None):
100101
self.algo: Algo
101102
self.hint = ""
102103
self.obj_filename = ""
@@ -115,7 +116,7 @@ def __init__(self, algo=None, params=None):
115116
else:
116117
self.algo = algo
117118

118-
if isinstance(algo, BundleAlgo):
119+
if isinstance(self.algo, BundleAlgo):
119120
self.obj_filename = algo_to_pickle(self.algo, template_path=self.algo.template_path)
120121
self.print_bundle_algo_instruction()
121122
else:
@@ -271,7 +272,7 @@ class OptunaGen(HPOGen):
271272
272273
"""
273274

274-
def __init__(self, algo=None, params=None):
275+
def __init__(self, algo: Optional[Algo] = None, params=None) -> None:
275276
self.algo: Algo
276277
self.obj_filename = ""
277278

@@ -289,7 +290,7 @@ def __init__(self, algo=None, params=None):
289290
else:
290291
self.algo = algo
291292

292-
if isinstance(algo, BundleAlgo):
293+
if isinstance(self.algo, BundleAlgo):
293294
self.obj_filename = algo_to_pickle(self.algo, template_path=self.algo.template_path)
294295
else:
295296
self.obj_filename = algo_to_pickle(self.algo)

monai/apps/deepgrow/transforms.py

Lines changed: 10 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@
1414
import numpy as np
1515
import torch
1616

17-
from monai.config import IndexSelection, KeysCollection
17+
from monai.config import IndexSelection, KeysCollection, NdarrayOrTensor
1818
from monai.networks.layers import GaussianFilter
1919
from monai.transforms import Resize, SpatialCrop
2020
from monai.transforms.transform import MapTransform, Randomizable, Transform
@@ -50,7 +50,7 @@ def _apply(self, label):
5050
sids.append(sid)
5151
return np.asarray(sids)
5252

53-
def __call__(self, data):
53+
def __call__(self, data) -> Dict:
5454
d: Dict = dict(data)
5555
label = d[self.label].numpy() if isinstance(data[self.label], torch.Tensor) else data[self.label]
5656
if label.shape[0] != 1:
@@ -654,7 +654,7 @@ def bounding_box(self, points, img_shape):
654654
box_start[di], box_end[di] = min_d, max_d
655655
return box_start, box_end
656656

657-
def __call__(self, data):
657+
def __call__(self, data) -> Dict:
658658
d: Dict = dict(data)
659659
first_key: Hashable = self.first_key(d)
660660
if first_key == ():
@@ -741,7 +741,7 @@ def __init__(
741741
self.meta_key_postfix = meta_key_postfix
742742
self.cropped_shape_key = cropped_shape_key
743743

744-
def __call__(self, data):
744+
def __call__(self, data) -> Dict:
745745
d = dict(data)
746746
guidance = d[self.guidance]
747747
meta_dict: Dict = d[self.meta_keys or f"{self.ref_image}_{self.meta_key_postfix}"]
@@ -836,7 +836,7 @@ def __init__(
836836
self.original_shape_key = original_shape_key
837837
self.cropped_shape_key = cropped_shape_key
838838

839-
def __call__(self, data):
839+
def __call__(self, data) -> Dict:
840840
d = dict(data)
841841
meta_dict: Dict = d[f"{self.ref_image}_{self.meta_key_postfix}"]
842842

@@ -857,8 +857,9 @@ def __call__(self, data):
857857
box_end = meta_dict[self.end_coord_key]
858858

859859
spatial_dims = min(len(box_start), len(image.shape[1:]))
860-
slices = [slice(None)] + [slice(s, e) for s, e in zip(box_start[:spatial_dims], box_end[:spatial_dims])]
861-
slices = tuple(slices)
860+
slices = tuple(
861+
[slice(None)] + [slice(s, e) for s, e in zip(box_start[:spatial_dims], box_end[:spatial_dims])]
862+
)
862863
result[slices] = image
863864

864865
# Undo Spacing
@@ -869,10 +870,11 @@ def __call__(self, data):
869870

870871
if np.any(np.not_equal(current_size, spatial_size)):
871872
resizer = Resize(spatial_size=spatial_size, mode=mode)
872-
result = resizer(result, mode=mode, align_corners=align_corners)
873+
result = resizer(result, mode=mode, align_corners=align_corners) # type: ignore
873874

874875
# Undo Slicing
875876
slice_idx = meta_dict.get("slice_idx")
877+
final_result: NdarrayOrTensor
876878
if slice_idx is None or self.slice_only:
877879
final_result = result if len(result.shape) <= 3 else result[0]
878880
else:

monai/auto3dseg/analyzer.py

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@
1212
import time
1313
from abc import ABC, abstractmethod
1414
from copy import deepcopy
15-
from typing import Any, Dict, List, Optional
15+
from typing import Any, Dict, Hashable, List, Mapping, Optional
1616

1717
import numpy as np
1818
import torch
@@ -377,7 +377,7 @@ def __init__(self, image_key: str, label_key: str, stats_name: str = "label_stat
377377
self.label_key = label_key
378378
self.do_ccp = do_ccp
379379

380-
report_format: Dict[str, Any] = {
380+
report_format: Dict[LabelStatsKeys, Any] = {
381381
LabelStatsKeys.LABEL_UID: None,
382382
LabelStatsKeys.IMAGE_INTST: None,
383383
LabelStatsKeys.LABEL: [{LabelStatsKeys.PIXEL_PCT: None, LabelStatsKeys.IMAGE_INTST: None}],
@@ -394,7 +394,7 @@ def __init__(self, image_key: str, label_key: str, stats_name: str = "label_stat
394394
id_seq = ID_SEP_KEY.join([LabelStatsKeys.LABEL, "0", LabelStatsKeys.IMAGE_INTST])
395395
self.update_ops_nested_label(id_seq, SampleOperations())
396396

397-
def __call__(self, data):
397+
def __call__(self, data: Mapping[Hashable, MetaTensor]) -> Dict[Hashable, MetaTensor]:
398398
"""
399399
Callable to execute the pre-defined functions.
400400
@@ -442,7 +442,7 @@ def __call__(self, data):
442442
The stats operation uses numpy and torch to compute max, min, and other
443443
functions. If the input has nan/inf, the stats results will be nan/inf.
444444
"""
445-
d = dict(data)
445+
d: Dict[Hashable, MetaTensor] = dict(data)
446446
start = time.time()
447447
if isinstance(d[self.image_key], (torch.Tensor, MetaTensor)) and d[self.image_key].device.type == "cuda":
448448
using_cuda = True
@@ -451,13 +451,13 @@ def __call__(self, data):
451451
restore_grad_state = torch.is_grad_enabled()
452452
torch.set_grad_enabled(False)
453453

454-
ndas = [d[self.image_key][i] for i in range(d[self.image_key].shape[0])]
455-
ndas_label = d[self.label_key] # (H,W,D)
454+
ndas: List[MetaTensor] = [d[self.image_key][i] for i in range(d[self.image_key].shape[0])] # type: ignore
455+
ndas_label: MetaTensor = d[self.label_key] # (H,W,D)
456456

457457
if ndas_label.shape != ndas[0].shape:
458458
raise ValueError(f"Label shape {ndas_label.shape} is different from image shape {ndas[0].shape}")
459459

460-
nda_foregrounds = [get_foreground_label(nda, ndas_label) for nda in ndas]
460+
nda_foregrounds: List[torch.Tensor] = [get_foreground_label(nda, ndas_label) for nda in ndas]
461461
nda_foregrounds = [nda if nda.numel() > 0 else torch.Tensor([0]) for nda in nda_foregrounds]
462462

463463
unique_label = unique(ndas_label)

monai/data/dataset.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1075,7 +1075,7 @@ def randomize(self, data: Sequence) -> None:
10751075
except TypeError as e:
10761076
warnings.warn(f"input data can't be shuffled in SmartCacheDataset with numpy.random.shuffle(): {e}.")
10771077

1078-
def _compute_data_idx(self):
1078+
def _compute_data_idx(self) -> None:
10791079
"""
10801080
Update the replacement data position in the total data.
10811081
@@ -1209,7 +1209,7 @@ def _try_manage_replacement(self, check_round):
12091209
self._compute_replacements()
12101210
return False, self._round
12111211

1212-
def manage_replacement(self):
1212+
def manage_replacement(self) -> None:
12131213
"""
12141214
Background thread for replacement.
12151215

monai/data/image_reader.py

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -277,7 +277,7 @@ def read(self, data: Union[Sequence[PathLike], PathLike], **kwargs):
277277
img_.append(itk.imread(name, **kwargs_))
278278
return img_ if len(filenames) > 1 else img_[0]
279279

280-
def get_data(self, img):
280+
def get_data(self, img) -> Tuple[np.ndarray, Dict]:
281281
"""
282282
Extract data array and metadata from loaded image and return them.
283283
This function returns two objects, first is numpy array of image data, second is dict of metadata.
@@ -564,7 +564,7 @@ def _combine_dicom_series(self, data):
564564

565565
return stack_array, stack_metadata
566566

567-
def get_data(self, data):
567+
def get_data(self, data) -> Tuple[np.ndarray, Dict]:
568568
"""
569569
Extract data array and metadata from loaded image and return them.
570570
This function returns two objects, first is numpy array of image data, second is dict of metadata.
@@ -929,7 +929,7 @@ def read(self, data: Union[Sequence[PathLike], PathLike], **kwargs):
929929
img_.append(img)
930930
return img_ if len(filenames) > 1 else img_[0]
931931

932-
def get_data(self, img):
932+
def get_data(self, img) -> Tuple[np.ndarray, Dict]:
933933
"""
934934
Extract data array and metadata from loaded image and return them.
935935
This function returns two objects, first is numpy array of image data, second is dict of metadata.
@@ -1095,7 +1095,7 @@ def read(self, data: Union[Sequence[PathLike], PathLike], **kwargs):
10951095

10961096
return img_ if len(img_) > 1 else img_[0]
10971097

1098-
def get_data(self, img):
1098+
def get_data(self, img) -> Tuple[np.ndarray, Dict]:
10991099
"""
11001100
Extract data array and metadata from loaded image and return them.
11011101
This function returns two objects, first is numpy array of image data, second is dict of metadata.
@@ -1113,7 +1113,7 @@ def get_data(self, img):
11131113
img = (img,)
11141114

11151115
for i in ensure_tuple(img):
1116-
header = {}
1116+
header: Dict[MetaKeys, Any] = {}
11171117
if isinstance(i, np.ndarray):
11181118
# if `channel_dim` is None, can not detect the channel dim, use all the dims as spatial_shape
11191119
spatial_shape = np.asarray(i.shape)
@@ -1184,7 +1184,7 @@ def read(self, data: Union[Sequence[PathLike], PathLike, np.ndarray], **kwargs):
11841184

11851185
return img_ if len(filenames) > 1 else img_[0]
11861186

1187-
def get_data(self, img):
1187+
def get_data(self, img) -> Tuple[np.ndarray, Dict]:
11881188
"""
11891189
Extract data array and metadata from loaded image and return them.
11901190
This function returns two objects, first is numpy array of image data, second is dict of metadata.

monai/data/meta_obj.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -79,7 +79,7 @@ class MetaObj:
7979
8080
"""
8181

82-
def __init__(self):
82+
def __init__(self) -> None:
8383
self._meta: dict = MetaObj.get_default_meta()
8484
self._applied_operations: list = MetaObj.get_default_applied_operations()
8585
self._pending_operations: list = MetaObj.get_default_applied_operations() # the same default as applied_ops

monai/data/meta_tensor.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -354,7 +354,7 @@ def get_array(self, output_type=np.ndarray, dtype=None, device=None, *_args, **_
354354
"""
355355
return convert_data_type(self, output_type=output_type, dtype=dtype, device=device, wrap_sequence=True)[0]
356356

357-
def set_array(self, src, non_blocking=False, *_args, **_kwargs):
357+
def set_array(self, src, non_blocking: bool = False, *_args, **_kwargs):
358358
"""
359359
Copies the elements from src into self tensor and returns self.
360360
The src tensor must be broadcastable with the self tensor.
@@ -369,11 +369,11 @@ def set_array(self, src, non_blocking=False, *_args, **_kwargs):
369369
_args: currently unused parameters.
370370
_kwargs: currently unused parameters.
371371
"""
372-
src: torch.Tensor = convert_to_tensor(src, track_meta=False, wrap_sequence=True)
372+
converted: torch.Tensor = convert_to_tensor(src, track_meta=False, wrap_sequence=True)
373373
try:
374-
return self.copy_(src, non_blocking=non_blocking)
374+
return self.copy_(converted, non_blocking=non_blocking)
375375
except RuntimeError: # skip the shape checking
376-
self.data = src
376+
self.data = converted
377377
return self
378378

379379
@property

monai/metrics/metric.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -166,7 +166,7 @@ class Cumulative:
166166
167167
"""
168168

169-
def __init__(self):
169+
def __init__(self) -> None:
170170
"""
171171
Initialize the internal buffers.
172172
`self._buffers` are local buffers, they are not usually used directly.

monai/networks/blocks/warp.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -151,7 +151,7 @@ def __init__(
151151
self.num_steps = num_steps
152152
self.warp_layer = Warp(mode=mode, padding_mode=padding_mode)
153153

154-
def forward(self, dvf):
154+
def forward(self, dvf: torch.Tensor) -> torch.Tensor:
155155
"""
156156
Args:
157157
dvf: dvf to be transformed, in shape (batch, ``spatial_dims``, H, W[,D])

0 commit comments

Comments
 (0)