Skip to content
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
22 changes: 22 additions & 0 deletions .deepsource.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
version = 1

test_patterns = ["tests/**"]

[[analyzers]]
name = "python"
enabled = true

[analyzers.meta]
runtime_version = "3.x.x"

[[analyzers]]
name = "test-coverage"
enabled = true

[[analyzers]]
name = "docker"
enabled = true

[[analyzers]]
name = "shell"
enabled = true
2 changes: 1 addition & 1 deletion monai/apps/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -146,7 +146,7 @@ def download_url(url: str, filepath: str, hash_val: Optional[str] = None, hash_t
if has_tqdm:
pbar.close()
except IOError as e:
logging.debug("IO Error - %s" % e)
logging.debug("IO Error - %s", e)
finally:
if file_size == os.path.getsize(tmp_file_path):
if hash_val and not check_hash(tmp_file_path, hash_val, hash_type):
Expand Down
2 changes: 1 addition & 1 deletion monai/data/dataset.py
Original file line number Diff line number Diff line change
Expand Up @@ -807,7 +807,7 @@ def __getitem__(self, index: int):
def to_list(x):
return list(x) if isinstance(x, (tuple, list)) else [x]

data = list()
data = []
for dataset in self.data:
data.extend(to_list(dataset[index]))
if self.transform is not None:
Expand Down
2 changes: 1 addition & 1 deletion monai/data/decathlon_datalist.py
Original file line number Diff line number Diff line change
Expand Up @@ -136,7 +136,7 @@ def load_decathlon_properties(
with open(data_property_file_path) as json_file:
json_data = json.load(json_file)

properties = dict()
properties = {}
for key in ensure_tuple(property_keys):
if key not in json_data:
raise KeyError(f"key {key} is not in the data property file.")
Expand Down
18 changes: 9 additions & 9 deletions monai/data/image_reader.py
Original file line number Diff line number Diff line change
Expand Up @@ -154,7 +154,7 @@ def read(self, data: Union[Sequence[str], str], **kwargs):
https://github.com/InsightSoftwareConsortium/ITK/blob/master/Wrapping/Generators/Python/itkExtras.py

"""
img_: List[Image] = list()
img_: List[Image] = []

filenames: Sequence[str] = ensure_tuple(data)
kwargs_ = self.kwargs.copy()
Expand Down Expand Up @@ -191,7 +191,7 @@ def get_data(self, img):
img: a ITK image object loaded from a image file or a list of ITK image objects.

"""
img_array: List[np.ndarray] = list()
img_array: List[np.ndarray] = []
compatible_meta: Dict = {}

for i in ensure_tuple(img):
Expand Down Expand Up @@ -325,7 +325,7 @@ def read(self, data: Union[Sequence[str], str], **kwargs):
https://github.com/nipy/nibabel/blob/master/nibabel/loadsave.py

"""
img_: List[Nifti1Image] = list()
img_: List[Nifti1Image] = []

filenames: Sequence[str] = ensure_tuple(data)
kwargs_ = self.kwargs.copy()
Expand All @@ -348,7 +348,7 @@ def get_data(self, img):
img: a Nibabel image object loaded from a image file or a list of Nibabel image objects.

"""
img_array: List[np.ndarray] = list()
img_array: List[np.ndarray] = []
compatible_meta: Dict = {}

for i in ensure_tuple(img):
Expand Down Expand Up @@ -456,7 +456,7 @@ def read(self, data: Union[Sequence[str], str], **kwargs):
https://numpy.org/doc/stable/reference/generated/numpy.load.html

"""
img_: List[Nifti1Image] = list()
img_: List[Nifti1Image] = []

filenames: Sequence[str] = ensure_tuple(data)
kwargs_ = self.kwargs.copy()
Expand Down Expand Up @@ -485,13 +485,13 @@ def get_data(self, img):
img: a Numpy array loaded from a file or a list of Numpy arrays.

"""
img_array: List[np.ndarray] = list()
img_array: List[np.ndarray] = []
compatible_meta: Dict = {}
if isinstance(img, np.ndarray):
img = (img,)

for i in ensure_tuple(img):
header = dict()
header = {}
if isinstance(i, np.ndarray):
header["spatial_shape"] = i.shape
img_array.append(i)
Expand Down Expand Up @@ -540,7 +540,7 @@ def read(self, data: Union[Sequence[str], str, np.ndarray], **kwargs):
https://pillow.readthedocs.io/en/stable/reference/Image.html#PIL.Image.open

"""
img_: List[PILImage.Image] = list()
img_: List[PILImage.Image] = []

filenames: Sequence[str] = ensure_tuple(data)
kwargs_ = self.kwargs.copy()
Expand All @@ -565,7 +565,7 @@ def get_data(self, img):
img: a PIL Image object loaded from a file or a list of PIL Image objects.

"""
img_array: List[np.ndarray] = list()
img_array: List[np.ndarray] = []
compatible_meta: Dict = {}

for i in ensure_tuple(img):
Expand Down
2 changes: 1 addition & 1 deletion monai/data/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -712,7 +712,7 @@ def partition_dataset_classes(
for i, c in enumerate(classes):
class_indices[c].append(i)

class_partition_indices: List[Sequence] = list()
class_partition_indices: List[Sequence] = []
for _, per_class_indices in sorted(class_indices.items()):
per_class_partition_indices = partition_dataset(
data=per_class_indices,
Expand Down
8 changes: 4 additions & 4 deletions monai/engines/evaluator.py
Original file line number Diff line number Diff line change
Expand Up @@ -185,8 +185,8 @@ def _iteration(self, engine: Engine, batchdata: Dict[str, torch.Tensor]) -> Dict
batch = self.prepare_batch(batchdata, engine.state.device, engine.non_blocking)
if len(batch) == 2:
inputs, targets = batch
args: Tuple = tuple()
kwargs: Dict = dict()
args: Tuple = ()
kwargs: Dict = {}
else:
inputs, targets, args, kwargs = batch

Expand Down Expand Up @@ -290,8 +290,8 @@ def _iteration(self, engine: Engine, batchdata: Dict[str, torch.Tensor]) -> Dict
batch = self.prepare_batch(batchdata, engine.state.device, engine.non_blocking)
if len(batch) == 2:
inputs, targets = batch
args: Tuple = tuple()
kwargs: Dict = dict()
args: Tuple = ()
kwargs: Dict = {}
else:
inputs, targets, args, kwargs = batch

Expand Down
4 changes: 2 additions & 2 deletions monai/engines/trainer.py
Original file line number Diff line number Diff line change
Expand Up @@ -143,8 +143,8 @@ def _iteration(self, engine: Engine, batchdata: Dict[str, torch.Tensor]):
batch = self.prepare_batch(batchdata, engine.state.device, engine.non_blocking)
if len(batch) == 2:
inputs, targets = batch
args: Tuple = tuple()
kwargs: Dict = dict()
args: Tuple = ()
kwargs: Dict = {}
else:
inputs, targets, args, kwargs = batch

Expand Down
2 changes: 1 addition & 1 deletion monai/networks/nets/autoencoder.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ def __init__(
self.norm = norm
self.dropout = dropout
self.num_inter_units = num_inter_units
self.inter_channels = inter_channels if inter_channels is not None else list()
self.inter_channels = inter_channels if inter_channels is not None else []
self.inter_dilations = list(inter_dilations or [1] * len(self.inter_channels))

# The number of channels and strides should match
Expand Down
4 changes: 2 additions & 2 deletions monai/optimizers/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -75,8 +75,8 @@ def _filter():

return _filter

params = list()
_layers = list()
params = []
_layers = []
for func, ty, lr in zip(layer_matches, match_types, lr_values):
if ty.lower() == "select":
layer_params = _get_select(func)
Expand Down
2 changes: 1 addition & 1 deletion monai/transforms/adaptors.py
Original file line number Diff line number Diff line change
Expand Up @@ -196,7 +196,7 @@ def _inner(ditems):
if len(ret) != len(outputs):
raise ValueError("'outputs' must have the same length as the number of elements that were returned")

ret = {k: v for k, v in zip(op, ret)}
ret = dict(zip(op, ret))
else:
must_be_types("outputs", op, (str, list, tuple))
if isinstance(op, (list, tuple)):
Expand Down
6 changes: 3 additions & 3 deletions monai/transforms/croppad/array.py
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ def __init__(
def _determine_data_pad_width(self, data_shape: Sequence[int]) -> List[Tuple[int, int]]:
self.spatial_size = fall_back_tuple(self.spatial_size, data_shape)
if self.method == Method.SYMMETRIC:
pad_width = list()
pad_width = []
for i in range(len(self.spatial_size)):
width = max(self.spatial_size[i] - data_shape[i], 0)
pad_width.append((width // 2, width - (width // 2)))
Expand Down Expand Up @@ -601,7 +601,7 @@ def __call__(
else:
fg_indices, bg_indices = map_binary_to_indices(label, image, self.image_threshold)
self.randomize(label, fg_indices, bg_indices, image)
results: List[np.ndarray] = list()
results: List[np.ndarray] = []
if self.centers is not None:
for center in self.centers:
cropper = SpatialCrop(roi_center=tuple(center), roi_size=self.spatial_size)
Expand Down Expand Up @@ -680,7 +680,7 @@ def __call__(self, img: np.ndarray) -> np.ndarray:
"""
See also: :py:class:`monai.transforms.utils.generate_spatial_bounding_box`.
"""
bbox = list()
bbox = []

for channel in range(img.shape[0]):
start_, end_ = generate_spatial_bounding_box(img, select_fn=self.select_fn, channel_indices=channel)
Expand Down
4 changes: 2 additions & 2 deletions monai/transforms/croppad/dictionary.py
Original file line number Diff line number Diff line change
Expand Up @@ -462,7 +462,7 @@ def __call__(self, data: Mapping[Hashable, np.ndarray]) -> List[Dict[Hashable, n
self.randomize(d[self.w_key])
_spatial_size = fall_back_tuple(self.spatial_size, d[self.w_key].shape[1:])

results: List[Dict[Hashable, np.ndarray]] = [dict() for _ in range(self.num_samples)]
results: List[Dict[Hashable, np.ndarray]] = [{} for _ in range(self.num_samples)]
for key in data.keys():
if key in self.keys:
img = d[key]
Expand Down Expand Up @@ -575,7 +575,7 @@ def __call__(self, data: Mapping[Hashable, np.ndarray]) -> List[Dict[Hashable, n
self.randomize(label, fg_indices, bg_indices, image)
assert isinstance(self.spatial_size, tuple)
assert self.centers is not None
results: List[Dict[Hashable, np.ndarray]] = [dict() for _ in range(self.num_samples)]
results: List[Dict[Hashable, np.ndarray]] = [{} for _ in range(self.num_samples)]
for key in data.keys():
if key in self.keys:
img = d[key]
Expand Down
12 changes: 6 additions & 6 deletions monai/transforms/io/array.py
Original file line number Diff line number Diff line change
Expand Up @@ -171,8 +171,8 @@ def __call__(self, filename: Union[Sequence[Union[Path, str]], Path, str]):
filename: path file or file-like object or a list of files.
"""
filename = ensure_tuple(filename)
img_array = list()
compatible_meta: Dict = dict()
img_array = []
compatible_meta: Dict = {}
for name in filename:
img = nib.load(name)
img = correct_nifti_header_if_necessary(img)
Expand Down Expand Up @@ -240,7 +240,7 @@ def __call__(self, filename: Union[Sequence[Union[Path, str]], Path, str]):
filename: path file or file-like object or a list of files.
"""
filename = ensure_tuple(filename)
img_array = list()
img_array = []
compatible_meta = None
for name in filename:
img = Image.open(name)
Expand All @@ -252,7 +252,7 @@ def __call__(self, filename: Union[Sequence[Union[Path, str]], Path, str]):
if self.image_only:
continue

meta = dict()
meta = {}
meta["filename_or_obj"] = name
meta["spatial_shape"] = data.shape[:2]
meta["format"] = img.format
Expand Down Expand Up @@ -314,13 +314,13 @@ def __call__(self, filename: Union[Sequence[Union[Path, str]], Path, str]):
if name.endswith(".npz"):
raise ValueError("Cannot load a sequence of npz files.")
filename = ensure_tuple(filename)
data_array: List = list()
data_array: List = []
compatible_meta = None

def _save_data_meta(data_array, name, data, compatible_meta):
data_array.append(data if self.dtype is None else data.astype(self.dtype))
if not self.data_only:
meta = dict()
meta = {}
meta["filename_or_obj"] = name
meta["spatial_shape"] = data.shape
if not compatible_meta:
Expand Down
4 changes: 2 additions & 2 deletions monai/transforms/spatial/array.py
Original file line number Diff line number Diff line change
Expand Up @@ -299,7 +299,7 @@ def __call__(self, img: np.ndarray) -> np.ndarray:
Args:
img: channel first array, must have shape: (num_channels, H[, W, ..., ]),
"""
flipped = list()
flipped = []
for channel in img:
flipped.append(np.flip(channel, self.spatial_axis))
return np.stack(flipped).astype(img.dtype)
Expand Down Expand Up @@ -584,7 +584,7 @@ def __call__(self, img: np.ndarray) -> np.ndarray:
Args:
img: channel first array, must have shape: (num_channels, H[, W, ..., ]),
"""
rotated = list()
rotated = []
for channel in img:
rotated.append(np.rot90(channel, self.k, self.spatial_axes))
return np.stack(rotated).astype(img.dtype)
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 @@ -189,7 +189,7 @@ def __call__(self, img: Union[np.ndarray, torch.Tensor]) -> List[Union[np.ndarra
if n_classes <= 1:
raise RuntimeError("input image does not contain multiple channels.")

outputs = list()
outputs = []
slices = [slice(None)] * len(img.shape)
for i in range(n_classes):
slices[channel_dim] = slice(i, i + 1)
Expand Down
4 changes: 2 additions & 2 deletions monai/transforms/utility/dictionary.py
Original file line number Diff line number Diff line change
Expand Up @@ -535,7 +535,7 @@ def __call__(self, data):

"""
d = dict(data)
output = list()
output = []
data_type = None
for key in self.keys:
if data_type is None:
Expand Down Expand Up @@ -674,7 +674,7 @@ class ConvertToMultiChannelBasedOnBratsClassesd(MapTransform):
def __call__(self, data: Mapping[Hashable, np.ndarray]) -> Dict[Hashable, np.ndarray]:
d = dict(data)
for key in self.keys:
result = list()
result = []
# merge labels 1 (tumor non-enh) and 4 (tumor enh) to TC
result.append(np.logical_or(d[key] == 1, d[key] == 4))
# merge labels 1 (tumor non-enh) and 4 (tumor enh) and 2 (large edema) to WT
Expand Down
2 changes: 1 addition & 1 deletion monai/utils/misc.py
Original file line number Diff line number Diff line change
Expand Up @@ -265,7 +265,7 @@ def _parse_var(s):
value = items[1].strip(" \n\r\t'")
return key, value

d = dict()
d = {}
if items:
for item in items:
key, value = _parse_var(item)
Expand Down
4 changes: 2 additions & 2 deletions tests/runner.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,15 +18,15 @@

from monai.utils import PerfContext

results: dict = dict()
results: dict = {}


class TimeLoggingTestResult(unittest.TextTestResult):
"""Overload the default results so that we can store the results."""

def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.timed_tests = dict()
self.timed_tests = {}

def startTest(self, test): # noqa: N802
"""Start timer, print test name, do normal test."""
Expand Down
8 changes: 4 additions & 4 deletions tests/test_compute_confusion_matrix.py
Original file line number Diff line number Diff line change
Expand Up @@ -220,7 +220,7 @@ def test_value(self, input_data, expected_value):
@parameterized.expand(TEST_CASES_COMPUTE_SAMPLE)
def test_compute_sample(self, input_data, expected_value):
params = input_data.copy()
vals = dict()
vals = {}
vals["y_pred"] = params.pop("y_pred")
vals["y"] = params.pop("y")
metric = ConfusionMatrixMetric(**params)
Expand All @@ -230,7 +230,7 @@ def test_compute_sample(self, input_data, expected_value):
@parameterized.expand(TEST_CASES_COMPUTE_SAMPLE_MULTI_METRICS)
def test_compute_sample_multiple_metrics(self, input_data, expected_values):
params = input_data.copy()
vals = dict()
vals = {}
vals["y_pred"] = params.pop("y_pred")
vals["y"] = params.pop("y")
metric = ConfusionMatrixMetric(**params)
Expand All @@ -243,7 +243,7 @@ def test_compute_sample_multiple_metrics(self, input_data, expected_values):
@parameterized.expand(TEST_CASES_COMPUTE_SAMPLE_NAN)
def test_compute_sample_with_nan(self, input_data, expected_value, expected_not_nans):
params = input_data.copy()
vals = dict()
vals = {}
vals["y_pred"] = params.pop("y_pred")
vals["y"] = params.pop("y")
metric = ConfusionMatrixMetric(**params)
Expand All @@ -254,7 +254,7 @@ def test_compute_sample_with_nan(self, input_data, expected_value, expected_not_
@parameterized.expand([TEST_CASES_CLF])
def test_clf_with_nan(self, input_data, expected_value):
params = input_data.copy()
vals = dict()
vals = {}
vals["y_pred"] = params.pop("y_pred")
vals["y"] = params.pop("y")
metric = ConfusionMatrixMetric(**params)
Expand Down
Loading