From 6a3e30b77e7545ccbf3d28d4757453e71b03e3ea Mon Sep 17 00:00:00 2001 From: Devdutt Shenoi Date: Sun, 10 Jan 2021 23:20:06 +0530 Subject: [PATCH 1/4] Add .deepsource.toml Signed-off-by: Devdutt Shenoi --- .deepsource.toml | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 .deepsource.toml diff --git a/.deepsource.toml b/.deepsource.toml new file mode 100644 index 0000000000..309d06fb8d --- /dev/null +++ b/.deepsource.toml @@ -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 \ No newline at end of file From c320fc12d7270857dbbaa60d27db9ffdbf492f23 Mon Sep 17 00:00:00 2001 From: Devdutt Shenoi Date: Sun, 10 Jan 2021 23:20:47 +0530 Subject: [PATCH 2/4] Remove unnecessary use of comprehension Signed-off-by: Devdutt Shenoi --- monai/transforms/adaptors.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/monai/transforms/adaptors.py b/monai/transforms/adaptors.py index 3aa7f70339..3290a03c80 100644 --- a/monai/transforms/adaptors.py +++ b/monai/transforms/adaptors.py @@ -194,7 +194,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)): From ff5d33d9f3b2cf597259ac6d9c148e680f2804b9 Mon Sep 17 00:00:00 2001 From: Devdutt Shenoi Date: Sun, 10 Jan 2021 23:21:14 +0530 Subject: [PATCH 3/4] Use literal syntax instead of function calls to create data structure Signed-off-by: Devdutt Shenoi --- monai/data/dataset.py | 2 +- monai/data/decathlon_datalist.py | 2 +- monai/data/image_reader.py | 18 +++++++++--------- monai/data/utils.py | 2 +- monai/engines/evaluator.py | 8 ++++---- monai/engines/trainer.py | 4 ++-- monai/networks/nets/autoencoder.py | 2 +- monai/optimizers/utils.py | 4 ++-- monai/transforms/croppad/array.py | 6 +++--- monai/transforms/croppad/dictionary.py | 4 ++-- monai/transforms/io/array.py | 12 ++++++------ monai/transforms/spatial/array.py | 4 ++-- monai/transforms/utility/array.py | 2 +- monai/transforms/utility/dictionary.py | 4 ++-- monai/utils/misc.py | 2 +- tests/runner.py | 4 ++-- tests/test_compute_confusion_matrix.py | 8 ++++---- tests/test_compute_meandice.py | 2 +- tests/test_delete_itemsd.py | 2 +- tests/test_flip.py | 2 +- tests/test_flipd.py | 2 +- tests/test_hilbert_transform.py | 4 ++-- tests/test_identityd.py | 2 +- tests/test_integration_classification_2d.py | 8 ++++---- tests/test_integration_segmentation_3d.py | 4 ++-- tests/test_iterable_dataset.py | 2 +- tests/test_lambdad.py | 6 +++--- tests/test_load_imaged.py | 2 +- tests/test_load_niftid.py | 2 +- tests/test_load_pngd.py | 2 +- tests/test_map_transform.py | 2 +- tests/test_rand_flip.py | 2 +- tests/test_rand_flipd.py | 2 +- tests/test_rand_rotate90.py | 8 ++++---- tests/test_rand_rotate90d.py | 8 ++++---- tests/test_rand_zoom.py | 2 +- tests/test_rand_zoomd.py | 2 +- tests/test_resize.py | 2 +- tests/test_resized.py | 2 +- tests/test_rotate.py | 4 ++-- tests/test_rotate90.py | 8 ++++---- tests/test_rotate90d.py | 8 ++++---- .../test_scale_intensity_range_percentilesd.py | 4 ++-- tests/test_select_itemsd.py | 2 +- tests/test_zoom.py | 2 +- tests/test_zoomd.py | 2 +- 46 files changed, 94 insertions(+), 94 deletions(-) diff --git a/monai/data/dataset.py b/monai/data/dataset.py index 892546b2a4..acd70db00c 100644 --- a/monai/data/dataset.py +++ b/monai/data/dataset.py @@ -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: diff --git a/monai/data/decathlon_datalist.py b/monai/data/decathlon_datalist.py index 96f4fe5324..e4ad4364ef 100644 --- a/monai/data/decathlon_datalist.py +++ b/monai/data/decathlon_datalist.py @@ -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.") diff --git a/monai/data/image_reader.py b/monai/data/image_reader.py index 925772433b..8742bb91e8 100644 --- a/monai/data/image_reader.py +++ b/monai/data/image_reader.py @@ -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() @@ -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): @@ -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() @@ -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): @@ -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() @@ -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) @@ -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() @@ -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): diff --git a/monai/data/utils.py b/monai/data/utils.py index c5fcbf3c86..2f01e17a85 100644 --- a/monai/data/utils.py +++ b/monai/data/utils.py @@ -686,7 +686,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, diff --git a/monai/engines/evaluator.py b/monai/engines/evaluator.py index 0c1c75a1b8..ea04be677d 100644 --- a/monai/engines/evaluator.py +++ b/monai/engines/evaluator.py @@ -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 @@ -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 diff --git a/monai/engines/trainer.py b/monai/engines/trainer.py index 7ab3a47eba..f557096ed0 100644 --- a/monai/engines/trainer.py +++ b/monai/engines/trainer.py @@ -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 diff --git a/monai/networks/nets/autoencoder.py b/monai/networks/nets/autoencoder.py index 8d0aadafd6..6e1e4ad622 100644 --- a/monai/networks/nets/autoencoder.py +++ b/monai/networks/nets/autoencoder.py @@ -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 diff --git a/monai/optimizers/utils.py b/monai/optimizers/utils.py index 4cafa45749..c42f59a538 100644 --- a/monai/optimizers/utils.py +++ b/monai/optimizers/utils.py @@ -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) diff --git a/monai/transforms/croppad/array.py b/monai/transforms/croppad/array.py index 4c69a61b15..590b4f70dd 100644 --- a/monai/transforms/croppad/array.py +++ b/monai/transforms/croppad/array.py @@ -59,7 +59,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))) @@ -586,7 +586,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) @@ -665,7 +665,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) diff --git a/monai/transforms/croppad/dictionary.py b/monai/transforms/croppad/dictionary.py index 8e927eb605..49bf8e12bb 100644 --- a/monai/transforms/croppad/dictionary.py +++ b/monai/transforms/croppad/dictionary.py @@ -422,7 +422,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] @@ -535,7 +535,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] diff --git a/monai/transforms/io/array.py b/monai/transforms/io/array.py index fd44555fa7..8b985c2684 100644 --- a/monai/transforms/io/array.py +++ b/monai/transforms/io/array.py @@ -169,8 +169,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) @@ -238,7 +238,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) @@ -250,7 +250,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 @@ -312,13 +312,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: diff --git a/monai/transforms/spatial/array.py b/monai/transforms/spatial/array.py index 15e22fa8f6..a41424cad1 100644 --- a/monai/transforms/spatial/array.py +++ b/monai/transforms/spatial/array.py @@ -277,7 +277,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) @@ -562,7 +562,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) diff --git a/monai/transforms/utility/array.py b/monai/transforms/utility/array.py index 8daad86dd2..183520bd8a 100644 --- a/monai/transforms/utility/array.py +++ b/monai/transforms/utility/array.py @@ -169,7 +169,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) diff --git a/monai/transforms/utility/dictionary.py b/monai/transforms/utility/dictionary.py index 28d7452e77..d515023f64 100644 --- a/monai/transforms/utility/dictionary.py +++ b/monai/transforms/utility/dictionary.py @@ -511,7 +511,7 @@ def __call__(self, data): """ d = dict(data) - output = list() + output = [] data_type = None for key in self.keys: if data_type is None: @@ -650,7 +650,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 diff --git a/monai/utils/misc.py b/monai/utils/misc.py index 020884bbcc..6804145797 100644 --- a/monai/utils/misc.py +++ b/monai/utils/misc.py @@ -245,7 +245,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) diff --git a/tests/runner.py b/tests/runner.py index 4c249535bf..f7dd282658 100644 --- a/tests/runner.py +++ b/tests/runner.py @@ -18,7 +18,7 @@ from monai.utils import PerfContext -results: dict = dict() +results: dict = {} class TimeLoggingTestResult(unittest.TextTestResult): @@ -26,7 +26,7 @@ class TimeLoggingTestResult(unittest.TextTestResult): 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.""" diff --git a/tests/test_compute_confusion_matrix.py b/tests/test_compute_confusion_matrix.py index 6c322dba9b..6a846bf7c0 100644 --- a/tests/test_compute_confusion_matrix.py +++ b/tests/test_compute_confusion_matrix.py @@ -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) @@ -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) @@ -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) @@ -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) diff --git a/tests/test_compute_meandice.py b/tests/test_compute_meandice.py index 4e4e02622c..f1ca5a0bca 100644 --- a/tests/test_compute_meandice.py +++ b/tests/test_compute_meandice.py @@ -184,7 +184,7 @@ def test_nans(self, input_data, expected_value): def test_value_class(self, input_data, expected_value): # same test as for compute_meandice - vals = dict() + vals = {} vals["y_pred"] = input_data.pop("y_pred") vals["y"] = input_data.pop("y") dice_metric = DiceMetric(**input_data, reduction="none") diff --git a/tests/test_delete_itemsd.py b/tests/test_delete_itemsd.py index c3dbbcbf1c..98146af460 100644 --- a/tests/test_delete_itemsd.py +++ b/tests/test_delete_itemsd.py @@ -23,7 +23,7 @@ class TestDeleteItemsd(unittest.TestCase): @parameterized.expand([TEST_CASE_1]) def test_memory(self, input_param, expected_key_size): - input_data = dict() + input_data = {} for i in range(50): input_data[str(i)] = [time.time()] * 100000 result = DeleteItemsd(**input_param)(input_data) diff --git a/tests/test_flip.py b/tests/test_flip.py index 1f17c36e7a..3bb9bdf158 100644 --- a/tests/test_flip.py +++ b/tests/test_flip.py @@ -32,7 +32,7 @@ def test_invalid_inputs(self, _, spatial_axis, raises): @parameterized.expand(VALID_CASES) def test_correct_results(self, _, spatial_axis): flip = Flip(spatial_axis=spatial_axis) - expected = list() + expected = [] for channel in self.imt[0]: expected.append(np.flip(channel, spatial_axis)) expected = np.stack(expected) diff --git a/tests/test_flipd.py b/tests/test_flipd.py index ec81b78fcc..7148d6995a 100644 --- a/tests/test_flipd.py +++ b/tests/test_flipd.py @@ -32,7 +32,7 @@ def test_invalid_cases(self, _, spatial_axis, raises): @parameterized.expand(VALID_CASES) def test_correct_results(self, _, spatial_axis): flip = Flipd(keys="img", spatial_axis=spatial_axis) - expected = list() + expected = [] for channel in self.imt[0]: expected.append(np.flip(channel, spatial_axis)) expected = np.stack(expected) diff --git a/tests/test_hilbert_transform.py b/tests/test_hilbert_transform.py index 1099468102..45cf5308e3 100644 --- a/tests/test_hilbert_transform.py +++ b/tests/test_hilbert_transform.py @@ -51,7 +51,7 @@ def create_expected_numpy_output(input_datum, **kwargs): # CPU TEST DATA -cpu_input_data = dict() +cpu_input_data = {} cpu_input_data["1D"] = torch.as_tensor(hann_windowed_sine, device=cpu).unsqueeze(0).unsqueeze(0) cpu_input_data["2D"] = ( torch.as_tensor(np.stack([hann_windowed_sine] * 10, axis=1), device=cpu).unsqueeze(0).unsqueeze(0) @@ -110,7 +110,7 @@ def create_expected_numpy_output(input_datum, **kwargs): if torch.cuda.is_available(): gpu = torch.device("cuda") - gpu_input_data = dict() + gpu_input_data = {} gpu_input_data["1D"] = torch.as_tensor(hann_windowed_sine, device=gpu).unsqueeze(0).unsqueeze(0) gpu_input_data["2D"] = ( torch.as_tensor(np.stack([hann_windowed_sine] * 10, axis=1), device=gpu).unsqueeze(0).unsqueeze(0) diff --git a/tests/test_identityd.py b/tests/test_identityd.py index 481cdd45c4..40c7b70359 100644 --- a/tests/test_identityd.py +++ b/tests/test_identityd.py @@ -18,7 +18,7 @@ class TestIdentityd(NumpyImageTestCase2D): def test_identityd(self): img = self.imt - data = dict() + data = {} data["img"] = img identity = Identityd(keys=data.keys()) self.assertEqual(data, identity(data)) diff --git a/tests/test_integration_classification_2d.py b/tests/test_integration_classification_2d.py index d6ac39eb38..d3cb37999d 100644 --- a/tests/test_integration_classification_2d.py +++ b/tests/test_integration_classification_2d.py @@ -80,8 +80,8 @@ def run_training_test(root_dir, train_x, train_y, val_x, val_y, device="cuda:0", # start training validation best_metric = -1 best_metric_epoch = -1 - epoch_loss_values = list() - metric_values = list() + epoch_loss_values = [] + metric_values = [] model_filename = os.path.join(root_dir, "best_metric_model.pth") for epoch in range(epoch_num): print("-" * 10) @@ -137,8 +137,8 @@ def run_inference_test(root_dir, test_x, test_y, device="cuda:0", num_workers=10 model_filename = os.path.join(root_dir, "best_metric_model.pth") model.load_state_dict(torch.load(model_filename)) - y_true = list() - y_pred = list() + y_true = [] + y_pred = [] with eval_mode(model): for test_data in val_loader: test_images, test_labels = test_data[0].to(device), test_data[1].to(device) diff --git a/tests/test_integration_segmentation_3d.py b/tests/test_integration_segmentation_3d.py index 0e1bdbe453..46d6600329 100644 --- a/tests/test_integration_segmentation_3d.py +++ b/tests/test_integration_segmentation_3d.py @@ -112,8 +112,8 @@ def run_training_test(root_dir, device="cuda:0", cachedataset=0): # start a typical PyTorch training val_interval = 2 best_metric, best_metric_epoch = -1, -1 - epoch_loss_values = list() - metric_values = list() + epoch_loss_values = [] + metric_values = [] writer = SummaryWriter(log_dir=os.path.join(root_dir, "runs")) model_filename = os.path.join(root_dir, "best_metric_model.pth") for epoch in range(6): diff --git a/tests/test_iterable_dataset.py b/tests/test_iterable_dataset.py index 56f118b8a2..3849da271a 100644 --- a/tests/test_iterable_dataset.py +++ b/tests/test_iterable_dataset.py @@ -32,7 +32,7 @@ class TestIterableDataset(unittest.TestCase): def test_shape(self): expected_shape = (128, 128, 128) test_image = nib.Nifti1Image(np.random.randint(0, 2, size=[128, 128, 128]), np.eye(4)) - test_data = list() + test_data = [] with tempfile.TemporaryDirectory() as tempdir: for i in range(6): nib.save(test_image, os.path.join(tempdir, f"test_image{str(i)}.nii.gz")) diff --git a/tests/test_lambdad.py b/tests/test_lambdad.py index fbebe081fe..a0c4929e88 100644 --- a/tests/test_lambdad.py +++ b/tests/test_lambdad.py @@ -20,7 +20,7 @@ class TestLambdad(NumpyImageTestCase2D): def test_lambdad_identity(self): img = self.imt - data = dict() + data = {} data["img"] = img def identity_func(x): @@ -33,14 +33,14 @@ def identity_func(x): def test_lambdad_slicing(self): img = self.imt - data = dict() + data = {} data["img"] = img def slice_func(x): return x[:, :, :6, ::-2] lambd = Lambdad(keys=data.keys(), func=slice_func) - expected = dict() + expected = {} expected["img"] = slice_func(data["img"]) self.assertTrue(np.allclose(expected["img"], lambd(data)["img"])) diff --git a/tests/test_load_imaged.py b/tests/test_load_imaged.py index ef733cac2f..f2b918d205 100644 --- a/tests/test_load_imaged.py +++ b/tests/test_load_imaged.py @@ -32,7 +32,7 @@ class TestLoadImaged(unittest.TestCase): @parameterized.expand([TEST_CASE_1, TEST_CASE_2]) def test_shape(self, input_param, expected_shape): test_image = nib.Nifti1Image(np.random.rand(128, 128, 128), np.eye(4)) - test_data = dict() + test_data = {} with tempfile.TemporaryDirectory() as tempdir: for key in KEYS: nib.save(test_image, os.path.join(tempdir, key + ".nii.gz")) diff --git a/tests/test_load_niftid.py b/tests/test_load_niftid.py index 54d816bead..cabc30cb93 100644 --- a/tests/test_load_niftid.py +++ b/tests/test_load_niftid.py @@ -28,7 +28,7 @@ class TestLoadNiftid(unittest.TestCase): @parameterized.expand([TEST_CASE_1]) def test_shape(self, input_param, expected_shape): test_image = nib.Nifti1Image(np.random.randint(0, 2, size=[128, 128, 128]), np.eye(4)) - test_data = dict() + test_data = {} with tempfile.TemporaryDirectory() as tempdir: for key in KEYS: nib.save(test_image, os.path.join(tempdir, key + ".nii.gz")) diff --git a/tests/test_load_pngd.py b/tests/test_load_pngd.py index 6be3197d8f..d88dd44350 100644 --- a/tests/test_load_pngd.py +++ b/tests/test_load_pngd.py @@ -29,7 +29,7 @@ class TestLoadPNGd(unittest.TestCase): def test_shape(self, input_param, expected_shape): test_image = np.random.randint(0, 256, size=[128, 128, 3]) with tempfile.TemporaryDirectory() as tempdir: - test_data = dict() + test_data = {} for key in KEYS: Image.fromarray(test_image.astype("uint8")).save(os.path.join(tempdir, key + ".png")) test_data.update({key: os.path.join(tempdir, key + ".png")}) diff --git a/tests/test_map_transform.py b/tests/test_map_transform.py index 22118202eb..a124927d2a 100644 --- a/tests/test_map_transform.py +++ b/tests/test_map_transform.py @@ -17,7 +17,7 @@ TEST_CASES = [["item", ("item",)], [None, (None,)], [["item1", "item2"], ("item1", "item2")]] -TEST_ILL_CASES = [[ValueError, list()], [ValueError, tuple()], [TypeError, [list()]]] +TEST_ILL_CASES = [[ValueError, []], [ValueError, ()], [TypeError, [[]]]] class MapTest(MapTransform): diff --git a/tests/test_rand_flip.py b/tests/test_rand_flip.py index d9b032b57a..0c347f0165 100644 --- a/tests/test_rand_flip.py +++ b/tests/test_rand_flip.py @@ -32,7 +32,7 @@ def test_invalid_inputs(self, _, spatial_axis, raises): @parameterized.expand(VALID_CASES) def test_correct_results(self, _, spatial_axis): flip = RandFlip(prob=1.0, spatial_axis=spatial_axis) - expected = list() + expected = [] for channel in self.imt[0]: expected.append(np.flip(channel, spatial_axis)) expected = np.stack(expected) diff --git a/tests/test_rand_flipd.py b/tests/test_rand_flipd.py index 5e55f629db..6f075ea80e 100644 --- a/tests/test_rand_flipd.py +++ b/tests/test_rand_flipd.py @@ -25,7 +25,7 @@ class TestRandFlipd(NumpyImageTestCase2D): def test_correct_results(self, _, spatial_axis): flip = RandFlipd(keys="img", prob=1.0, spatial_axis=spatial_axis) res = flip({"img": self.imt[0]}) - expected = list() + expected = [] for channel in self.imt[0]: expected.append(np.flip(channel, spatial_axis)) expected = np.stack(expected) diff --git a/tests/test_rand_rotate90.py b/tests/test_rand_rotate90.py index 20e171f9e8..d23bbb7368 100644 --- a/tests/test_rand_rotate90.py +++ b/tests/test_rand_rotate90.py @@ -22,7 +22,7 @@ def test_default(self): rotate = RandRotate90() rotate.set_random_state(123) rotated = rotate(self.imt[0]) - expected = list() + expected = [] for channel in self.imt[0]: expected.append(np.rot90(channel, 0, (0, 1))) expected = np.stack(expected) @@ -32,7 +32,7 @@ def test_k(self): rotate = RandRotate90(max_k=2) rotate.set_random_state(234) rotated = rotate(self.imt[0]) - expected = list() + expected = [] for channel in self.imt[0]: expected.append(np.rot90(channel, 0, (0, 1))) expected = np.stack(expected) @@ -42,7 +42,7 @@ def test_spatial_axes(self): rotate = RandRotate90(spatial_axes=(0, 1)) rotate.set_random_state(234) rotated = rotate(self.imt[0]) - expected = list() + expected = [] for channel in self.imt[0]: expected.append(np.rot90(channel, 0, (0, 1))) expected = np.stack(expected) @@ -52,7 +52,7 @@ def test_prob_k_spatial_axes(self): rotate = RandRotate90(prob=1.0, max_k=2, spatial_axes=(0, 1)) rotate.set_random_state(234) rotated = rotate(self.imt[0]) - expected = list() + expected = [] for channel in self.imt[0]: expected.append(np.rot90(channel, 1, (0, 1))) expected = np.stack(expected) diff --git a/tests/test_rand_rotate90d.py b/tests/test_rand_rotate90d.py index cd55ff5e3a..5777543c07 100644 --- a/tests/test_rand_rotate90d.py +++ b/tests/test_rand_rotate90d.py @@ -23,7 +23,7 @@ def test_default(self): rotate = RandRotate90d(keys=key) rotate.set_random_state(123) rotated = rotate({key: self.imt[0]}) - expected = list() + expected = [] for channel in self.imt[0]: expected.append(np.rot90(channel, 0, (0, 1))) expected = np.stack(expected) @@ -34,7 +34,7 @@ def test_k(self): rotate = RandRotate90d(keys=key, max_k=2) rotate.set_random_state(234) rotated = rotate({key: self.imt[0]}) - expected = list() + expected = [] for channel in self.imt[0]: expected.append(np.rot90(channel, 0, (0, 1))) expected = np.stack(expected) @@ -45,7 +45,7 @@ def test_spatial_axes(self): rotate = RandRotate90d(keys=key, spatial_axes=(0, 1)) rotate.set_random_state(234) rotated = rotate({key: self.imt[0]}) - expected = list() + expected = [] for channel in self.imt[0]: expected.append(np.rot90(channel, 0, (0, 1))) expected = np.stack(expected) @@ -56,7 +56,7 @@ def test_prob_k_spatial_axes(self): rotate = RandRotate90d(keys=key, prob=1.0, max_k=2, spatial_axes=(0, 1)) rotate.set_random_state(234) rotated = rotate({key: self.imt[0]}) - expected = list() + expected = [] for channel in self.imt[0]: expected.append(np.rot90(channel, 1, (0, 1))) expected = np.stack(expected) diff --git a/tests/test_rand_zoom.py b/tests/test_rand_zoom.py index 3a1f8f08ba..5bb3506a2a 100644 --- a/tests/test_rand_zoom.py +++ b/tests/test_rand_zoom.py @@ -34,7 +34,7 @@ def test_correct_results(self, min_zoom, max_zoom, mode, keep_size): ) random_zoom.set_random_state(1234) zoomed = random_zoom(self.imt[0]) - expected = list() + expected = [] for channel in self.imt[0]: expected.append(zoom_scipy(channel, zoom=random_zoom._zoom, mode="nearest", order=0, prefilter=False)) expected = np.stack(expected).astype(np.float32) diff --git a/tests/test_rand_zoomd.py b/tests/test_rand_zoomd.py index 5daf09d834..537567a8c7 100644 --- a/tests/test_rand_zoomd.py +++ b/tests/test_rand_zoomd.py @@ -37,7 +37,7 @@ def test_correct_results(self, min_zoom, max_zoom, mode, align_corners, keep_siz random_zoom.set_random_state(1234) zoomed = random_zoom({key: self.imt[0]}) - expected = list() + expected = [] for channel in self.imt[0]: expected.append(zoom_scipy(channel, zoom=random_zoom._zoom, mode="nearest", order=0, prefilter=False)) expected = np.stack(expected).astype(np.float32) diff --git a/tests/test_resize.py b/tests/test_resize.py index a4cb1a8d85..50111e90d1 100644 --- a/tests/test_resize.py +++ b/tests/test_resize.py @@ -39,7 +39,7 @@ def test_correct_results(self, spatial_size, mode): _order = 1 if spatial_size == (32, -1): spatial_size = (32, 64) - expected = list() + expected = [] for channel in self.imt[0]: expected.append( skimage.transform.resize( diff --git a/tests/test_resized.py b/tests/test_resized.py index 81a37a65a4..295c5058a3 100644 --- a/tests/test_resized.py +++ b/tests/test_resized.py @@ -37,7 +37,7 @@ def test_correct_results(self, spatial_size, mode): _order = 1 if spatial_size == (32, -1): spatial_size = (32, 64) - expected = list() + expected = [] for channel in self.imt[0]: expected.append( skimage.transform.resize( diff --git a/tests/test_rotate.py b/tests/test_rotate.py index 837f11fe7e..fe9fb334c3 100644 --- a/tests/test_rotate.py +++ b/tests/test_rotate.py @@ -56,7 +56,7 @@ def test_correct_results(self, angle, keep_size, mode, padding_mode, align_corne else: _mode = "constant" - expected = list() + expected = [] for channel in self.imt[0]: expected.append( scipy.ndimage.rotate( @@ -88,7 +88,7 @@ def test_correct_results(self, angle, keep_size, mode, padding_mode, align_corne else: _mode = "constant" - expected = list() + expected = [] for channel in self.imt[0]: expected.append( scipy.ndimage.rotate( diff --git a/tests/test_rotate90.py b/tests/test_rotate90.py index e4eafcc88c..88be9c8968 100644 --- a/tests/test_rotate90.py +++ b/tests/test_rotate90.py @@ -21,7 +21,7 @@ class TestRotate90(NumpyImageTestCase2D): def test_rotate90_default(self): rotate = Rotate90() rotated = rotate(self.imt[0]) - expected = list() + expected = [] for channel in self.imt[0]: expected.append(np.rot90(channel, 1, (0, 1))) expected = np.stack(expected) @@ -30,7 +30,7 @@ def test_rotate90_default(self): def test_k(self): rotate = Rotate90(k=2) rotated = rotate(self.imt[0]) - expected = list() + expected = [] for channel in self.imt[0]: expected.append(np.rot90(channel, 2, (0, 1))) expected = np.stack(expected) @@ -39,7 +39,7 @@ def test_k(self): def test_spatial_axes(self): rotate = Rotate90(spatial_axes=(0, 1)) rotated = rotate(self.imt[0]) - expected = list() + expected = [] for channel in self.imt[0]: expected.append(np.rot90(channel, 1, (0, 1))) expected = np.stack(expected) @@ -48,7 +48,7 @@ def test_spatial_axes(self): def test_prob_k_spatial_axes(self): rotate = Rotate90(k=2, spatial_axes=(0, 1)) rotated = rotate(self.imt[0]) - expected = list() + expected = [] for channel in self.imt[0]: expected.append(np.rot90(channel, 2, (0, 1))) expected = np.stack(expected) diff --git a/tests/test_rotate90d.py b/tests/test_rotate90d.py index 1f85d2fc0a..85aa35a8ee 100644 --- a/tests/test_rotate90d.py +++ b/tests/test_rotate90d.py @@ -22,7 +22,7 @@ def test_rotate90_default(self): key = "test" rotate = Rotate90d(keys=key) rotated = rotate({key: self.imt[0]}) - expected = list() + expected = [] for channel in self.imt[0]: expected.append(np.rot90(channel, 1, (0, 1))) expected = np.stack(expected) @@ -32,7 +32,7 @@ def test_k(self): key = None rotate = Rotate90d(keys=key, k=2) rotated = rotate({key: self.imt[0]}) - expected = list() + expected = [] for channel in self.imt[0]: expected.append(np.rot90(channel, 2, (0, 1))) expected = np.stack(expected) @@ -42,7 +42,7 @@ def test_spatial_axes(self): key = "test" rotate = Rotate90d(keys=key, spatial_axes=(0, 1)) rotated = rotate({key: self.imt[0]}) - expected = list() + expected = [] for channel in self.imt[0]: expected.append(np.rot90(channel, 1, (0, 1))) expected = np.stack(expected) @@ -52,7 +52,7 @@ def test_prob_k_spatial_axes(self): key = "test" rotate = Rotate90d(keys=key, k=2, spatial_axes=(0, 1)) rotated = rotate({key: self.imt[0]}) - expected = list() + expected = [] for channel in self.imt[0]: expected.append(np.rot90(channel, 2, (0, 1))) expected = np.stack(expected) diff --git a/tests/test_scale_intensity_range_percentilesd.py b/tests/test_scale_intensity_range_percentilesd.py index 75e79b7c9b..af84da7dbc 100644 --- a/tests/test_scale_intensity_range_percentilesd.py +++ b/tests/test_scale_intensity_range_percentilesd.py @@ -20,7 +20,7 @@ class TestScaleIntensityRangePercentilesd(NumpyImageTestCase2D): def test_scaling(self): img = self.imt - data = dict() + data = {} data["img"] = img lower = 10 upper = 99 @@ -38,7 +38,7 @@ def test_scaling(self): def test_relative_scaling(self): img = self.imt - data = dict() + data = {} data["img"] = img lower = 10 upper = 99 diff --git a/tests/test_select_itemsd.py b/tests/test_select_itemsd.py index be683ef6a7..9e0a2fcb4b 100644 --- a/tests/test_select_itemsd.py +++ b/tests/test_select_itemsd.py @@ -23,7 +23,7 @@ class TestSelectItemsd(unittest.TestCase): @parameterized.expand([TEST_CASE_1]) def test_memory(self, input_param, expected_key_size): - input_data = dict() + input_data = {} for i in range(50): input_data[str(i)] = [time.time()] * 100000 result = SelectItemsd(**input_param)(input_data) diff --git a/tests/test_zoom.py b/tests/test_zoom.py index edf4fb988e..3b827ea4a6 100644 --- a/tests/test_zoom.py +++ b/tests/test_zoom.py @@ -31,7 +31,7 @@ def test_correct_results(self, zoom, mode): _order = 0 if mode.endswith("linear"): _order = 1 - expected = list() + expected = [] for channel in self.imt[0]: expected.append(zoom_scipy(channel, zoom=zoom, mode="nearest", order=_order, prefilter=False)) expected = np.stack(expected).astype(np.float32) diff --git a/tests/test_zoomd.py b/tests/test_zoomd.py index d9685d259f..a8b24f4abd 100644 --- a/tests/test_zoomd.py +++ b/tests/test_zoomd.py @@ -37,7 +37,7 @@ def test_correct_results(self, zoom, mode, keep_size): _order = 0 if mode.endswith("linear"): _order = 1 - expected = list() + expected = [] for channel in self.imt[0]: expected.append(zoom_scipy(channel, zoom=zoom, mode="nearest", order=_order, prefilter=False)) expected = np.stack(expected).astype(np.float32) From 1022c0c53efe82b1a157dac2abb7f2a7a6435ae5 Mon Sep 17 00:00:00 2001 From: Devdutt Shenoi Date: Sun, 10 Jan 2021 23:21:41 +0530 Subject: [PATCH 4/4] Pass string format arguments as logging method parameters Signed-off-by: Devdutt Shenoi --- monai/apps/utils.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/monai/apps/utils.py b/monai/apps/utils.py index e48dfb63f2..952b57492a 100644 --- a/monai/apps/utils.py +++ b/monai/apps/utils.py @@ -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):