diff --git a/docs/source/conf.py b/docs/source/conf.py index 324be8a0fd..fe10c546cd 100644 --- a/docs/source/conf.py +++ b/docs/source/conf.py @@ -107,16 +107,8 @@ def generate_apidocs(*args): html_theme_options = { "external_links": [{"url": "https://github.com/Project-MONAI/tutorials", "name": "Tutorials"}], "icon_links": [ - { - "name": "GitHub", - "url": "https://github.com/project-monai/monai", - "icon": "fab fa-github-square", - }, - { - "name": "Twitter", - "url": "https://twitter.com/projectmonai", - "icon": "fab fa-twitter-square", - }, + {"name": "GitHub", "url": "https://github.com/project-monai/monai", "icon": "fab fa-github-square"}, + {"name": "Twitter", "url": "https://twitter.com/projectmonai", "icon": "fab fa-twitter-square"}, ], "collapse_navigation": True, "navigation_depth": 3, diff --git a/monai/__init__.py b/monai/__init__.py index 31cc3503b7..dbe0a0aa03 100644 --- a/monai/__init__.py +++ b/monai/__init__.py @@ -30,7 +30,7 @@ raise RuntimeError( "MONAI requires Python {}.{} or higher. But the current Python is: {}".format( PY_REQUIRED_MAJOR, PY_REQUIRED_MINOR, sys.version - ), + ) ) from .utils.module import load_submodules # noqa: E402 diff --git a/monai/_extensions/loader.py b/monai/_extensions/loader.py index 6c68fe08c7..d7ebca64e3 100644 --- a/monai/_extensions/loader.py +++ b/monai/_extensions/loader.py @@ -84,11 +84,7 @@ def load_module( # This will either run the build or return the existing .so object. name = module_name + platform_str.replace(".", "_") module = load( - name=name, - sources=source, - extra_cflags=define_args, - extra_cuda_cflags=define_args, - verbose=verbose_build, + name=name, sources=source, extra_cflags=define_args, extra_cuda_cflags=define_args, verbose=verbose_build ) return module diff --git a/monai/apps/datasets.py b/monai/apps/datasets.py index cff2df3ac7..d87e635876 100644 --- a/monai/apps/datasets.py +++ b/monai/apps/datasets.py @@ -147,11 +147,7 @@ def _generate_data_list(self, dataset_dir: str) -> List[Dict]: ) return [ - { - "image": image_files_list[i], - "label": image_class[i], - "class_name": class_name[i], - } + {"image": image_files_list[i], "label": image_class[i], "class_name": class_name[i]} for i in section_indices ] @@ -366,13 +362,7 @@ class CrossValidation: """ - def __init__( - self, - dataset_cls, - nfolds: int = 5, - seed: int = 0, - **dataset_params, - ) -> None: + def __init__(self, dataset_cls, nfolds: int = 5, seed: int = 0, **dataset_params) -> None: if not hasattr(dataset_cls, "_split_datalist"): raise ValueError("dataset class must have _split_datalist API.") self.dataset_cls = dataset_cls diff --git a/monai/apps/deepedit/transforms.py b/monai/apps/deepedit/transforms.py index 845e7bd1d0..e0881c7158 100644 --- a/monai/apps/deepedit/transforms.py +++ b/monai/apps/deepedit/transforms.py @@ -15,12 +15,7 @@ class DiscardAddGuidanced(MapTransform): - def __init__( - self, - keys: KeysCollection, - probability: float = 1.0, - allow_missing_keys: bool = False, - ): + def __init__(self, keys: KeysCollection, probability: float = 1.0, allow_missing_keys: bool = False): """ Discard positive and negative points randomly or Add the two channels for inference time @@ -54,11 +49,7 @@ class ResizeGuidanceCustomd(Transform): Resize the guidance based on cropped vs resized image. """ - def __init__( - self, - guidance: str, - ref_image: str, - ) -> None: + def __init__(self, guidance: str, ref_image: str) -> None: self.guidance = guidance self.ref_image = ref_image diff --git a/monai/apps/deepgrow/dataset.py b/monai/apps/deepgrow/dataset.py index a6bf59d243..1dcdc4ec25 100644 --- a/monai/apps/deepgrow/dataset.py +++ b/monai/apps/deepgrow/dataset.py @@ -165,9 +165,7 @@ def _save_data_2d(vol_idx, vol_image, vol_label, dataset_dir, relative_path): # Test Data if vol_label is None: data_list.append( - { - "image": image_file.replace(dataset_dir + os.pathsep, "") if relative_path else image_file, - } + {"image": image_file.replace(dataset_dir + os.pathsep, "") if relative_path else image_file} ) continue @@ -236,11 +234,7 @@ def _save_data_3d(vol_idx, vol_image, vol_label, dataset_dir, relative_path): # Test Data if vol_label is None: - data_list.append( - { - "image": image_file.replace(dataset_dir + os.pathsep, "") if relative_path else image_file, - } - ) + data_list.append({"image": image_file.replace(dataset_dir + os.pathsep, "") if relative_path else image_file}) else: # For all Labels unique_labels = np.unique(vol_label.flatten()) diff --git a/monai/apps/deepgrow/transforms.py b/monai/apps/deepgrow/transforms.py index 7ededcd94c..8c9eb884dd 100644 --- a/monai/apps/deepgrow/transforms.py +++ b/monai/apps/deepgrow/transforms.py @@ -163,13 +163,7 @@ class AddGuidanceSignald(Transform): """ - def __init__( - self, - image: str = "image", - guidance: str = "guidance", - sigma: int = 2, - number_intensity_ch: int = 1, - ): + def __init__(self, image: str = "image", guidance: str = "guidance", sigma: int = 2, number_intensity_ch: int = 1): self.image = image self.guidance = guidance self.sigma = sigma @@ -276,12 +270,7 @@ class AddRandomGuidanced(Randomizable, Transform): """ - def __init__( - self, - guidance: str = "guidance", - discrepancy: str = "discrepancy", - probability: str = "probability", - ): + def __init__(self, guidance: str = "guidance", discrepancy: str = "discrepancy", probability: str = "probability"): self.guidance = guidance self.discrepancy = discrepancy self.probability = probability diff --git a/monai/apps/pathology/data/datasets.py b/monai/apps/pathology/data/datasets.py index d86781f4c5..c9521b1201 100644 --- a/monai/apps/pathology/data/datasets.py +++ b/monai/apps/pathology/data/datasets.py @@ -293,11 +293,7 @@ def _load_a_patch(self, index): location_on_image = sample["image_locations"][patch_num] location_on_mask = sample["mask_locations"][patch_num] - image, _ = self.image_reader.get_data( - img=sample["image"], - location=location_on_image, - size=self.patch_size, - ) + image, _ = self.image_reader.get_data(img=sample["image"], location=location_on_image, size=self.patch_size) processed_sample = {"image": image, "name": sample["name"], "mask_location": location_on_mask} return processed_sample diff --git a/monai/apps/pathology/metrics/lesion_froc.py b/monai/apps/pathology/metrics/lesion_froc.py index 2140de0080..fa4ce422be 100644 --- a/monai/apps/pathology/metrics/lesion_froc.py +++ b/monai/apps/pathology/metrics/lesion_froc.py @@ -78,11 +78,7 @@ def __init__( self.itc_diameter = itc_diameter self.eval_thresholds = eval_thresholds self.image_reader = WSIReader(image_reader_name) - self.nms = PathologyProbNMS( - sigma=nms_sigma, - prob_threshold=nms_prob_threshold, - box_size=nms_box_size, - ) + self.nms = PathologyProbNMS(sigma=nms_sigma, prob_threshold=nms_prob_threshold, box_size=nms_box_size) def prepare_inference_result(self, sample: Dict): """ @@ -151,12 +147,7 @@ def compute_fp_tp(self): total_tp_probs.extend(tp_probs) total_num_targets += num_targets - return ( - np.array(total_fp_probs), - np.array(total_tp_probs), - total_num_targets, - num_images, - ) + return (np.array(total_fp_probs), np.array(total_tp_probs), total_num_targets, num_images) def evaluate(self): """ @@ -168,17 +159,12 @@ def evaluate(self): # compute FROC curve given the evaluation of all images fps_per_image, total_sensitivity = compute_froc_curve_data( - fp_probs=fp_probs, - tp_probs=tp_probs, - num_targets=num_targets, - num_images=num_images, + fp_probs=fp_probs, tp_probs=tp_probs, num_targets=num_targets, num_images=num_images ) # compute FROC score give specific evaluation threshold froc_score = compute_froc_score( - fps_per_image=fps_per_image, - total_sensitivity=total_sensitivity, - eval_thresholds=self.eval_thresholds, + fps_per_image=fps_per_image, total_sensitivity=total_sensitivity, eval_thresholds=self.eval_thresholds ) return froc_score diff --git a/monai/apps/pathology/transforms/spatial/array.py b/monai/apps/pathology/transforms/spatial/array.py index 53e0c63715..b47e6fd015 100644 --- a/monai/apps/pathology/transforms/spatial/array.py +++ b/monai/apps/pathology/transforms/spatial/array.py @@ -34,9 +34,7 @@ class SplitOnGrid(Transform): """ def __init__( - self, - grid_size: Union[int, Tuple[int, int]] = (2, 2), - patch_size: Optional[Union[int, Tuple[int, int]]] = None, + self, grid_size: Union[int, Tuple[int, int]] = (2, 2), patch_size: Optional[Union[int, Tuple[int, int]]] = None ): # Grid size if isinstance(grid_size, int): diff --git a/monai/apps/pathology/utils.py b/monai/apps/pathology/utils.py index 54d49f5717..30bdde91bb 100644 --- a/monai/apps/pathology/utils.py +++ b/monai/apps/pathology/utils.py @@ -62,11 +62,7 @@ class PathologyProbNMS(ProbNMS): Pathology. """ - def __call__( - self, - probs_map: Union[np.ndarray, torch.Tensor], - resolution_level: int = 0, - ): + def __call__(self, probs_map: Union[np.ndarray, torch.Tensor], resolution_level: int = 0): """ probs_map: the input probabilities map, it must have shape (H[, W, ...]). resolution_level: the level at which the probabilities map is made. diff --git a/monai/apps/utils.py b/monai/apps/utils.py index 31cfe1c8ea..16bda628f4 100644 --- a/monai/apps/utils.py +++ b/monai/apps/utils.py @@ -31,12 +31,7 @@ else: tqdm, has_tqdm = optional_import("tqdm", "4.47.0", min_version, "tqdm") -__all__ = [ - "check_hash", - "download_url", - "extractall", - "download_and_extract", -] +__all__ = ["check_hash", "download_url", "extractall", "download_and_extract"] def _basename(p): @@ -69,13 +64,7 @@ def update_to(self, b: int = 1, bsize: int = 1, tsize: Optional[int] = None): self.total = tsize self.update(b * bsize - self.n) # will also set self.n = b * bsize - with TqdmUpTo( - unit="B", - unit_scale=True, - unit_divisor=1024, - miniters=1, - desc=_basename(filepath), - ) as t: + with TqdmUpTo(unit="B", unit_scale=True, unit_divisor=1024, miniters=1, desc=_basename(filepath)) as t: urlretrieve(url, filepath, reporthook=t.update_to) else: if not has_tqdm and progress: diff --git a/monai/data/csv_saver.py b/monai/data/csv_saver.py index 62f407bfd5..f9c814679d 100644 --- a/monai/data/csv_saver.py +++ b/monai/data/csv_saver.py @@ -32,11 +32,7 @@ class CSVSaver: """ def __init__( - self, - output_dir: str = "./", - filename: str = "predictions.csv", - overwrite: bool = True, - flush: bool = False, + self, output_dir: str = "./", filename: str = "predictions.csv", overwrite: bool = True, flush: bool = False ) -> None: """ Args: diff --git a/monai/data/dataloader.py b/monai/data/dataloader.py index 2c9174e9f4..bfb6c01c4e 100644 --- a/monai/data/dataloader.py +++ b/monai/data/dataloader.py @@ -81,8 +81,4 @@ def __init__(self, dataset: Dataset, num_workers: int = 0, **kwargs) -> None: if "worker_init_fn" not in kwargs: kwargs.update({"worker_init_fn": worker_init_fn}) - super().__init__( # type: ignore[call-overload] - dataset=dataset, - num_workers=num_workers, - **kwargs, - ) + super().__init__(dataset=dataset, num_workers=num_workers, **kwargs) # type: ignore[call-overload] diff --git a/monai/data/dataset.py b/monai/data/dataset.py index ae1d88a4fe..474684c4e2 100644 --- a/monai/data/dataset.py +++ b/monai/data/dataset.py @@ -1218,11 +1218,6 @@ def __init__( files = ensure_tuple(filename) dfs = [pd.read_csv(f) for f in files] data = convert_tables_to_dicts( - dfs=dfs, - row_indices=row_indices, - col_names=col_names, - col_types=col_types, - col_groups=col_groups, - **kwargs, + dfs=dfs, row_indices=row_indices, col_names=col_names, col_types=col_types, col_groups=col_groups, **kwargs ) super().__init__(data=data, transform=transform) diff --git a/monai/data/decathlon_datalist.py b/monai/data/decathlon_datalist.py index 663b68a08e..78440fe11c 100644 --- a/monai/data/decathlon_datalist.py +++ b/monai/data/decathlon_datalist.py @@ -126,10 +126,7 @@ def load_decathlon_datalist( return _append_paths(base_dir, is_segmentation, expected_data) -def load_decathlon_properties( - data_property_file_path: str, - property_keys: Union[Sequence[str], str], -) -> Dict: +def load_decathlon_properties(data_property_file_path: str, property_keys: Union[Sequence[str], str]) -> Dict: """Load the properties from the JSON file contains data property with specified `property_keys`. Args: diff --git a/monai/data/image_reader.py b/monai/data/image_reader.py index a2ddb74334..303091f0d8 100644 --- a/monai/data/image_reader.py +++ b/monai/data/image_reader.py @@ -637,12 +637,7 @@ def _get_meta_dict(self, img) -> Dict: img: a PIL Image object loaded from an image file. """ - return { - "format": img.format, - "mode": img.mode, - "width": img.width, - "height": img.height, - } + return {"format": img.format, "mode": img.mode, "width": img.width, "height": img.height} def _get_spatial_shape(self, img): """ @@ -729,10 +724,7 @@ def get_data( if self.reader_lib == "openslide" and size is None: # the maximum size is set to WxH - size = ( - img.shape[0] // (2 ** level) - location[0], - img.shape[1] // (2 ** level) - location[1], - ) + size = (img.shape[0] // (2 ** level) - location[0], img.shape[1] // (2 ** level) - location[1]) region = self._extract_region(img, location=location, size=size, level=level, dtype=dtype) @@ -745,10 +737,7 @@ def get_data( else: tuple_patch_size = ensure_tuple_rep(patch_size, 2) patches = self._extract_patches( - region, - patch_size=tuple_patch_size, # type: ignore - grid_shape=grid_shape, - dtype=dtype, + region, patch_size=tuple_patch_size, grid_shape=grid_shape, dtype=dtype # type: ignore ) return patches, metadata @@ -772,11 +761,7 @@ def _extract_region( region = self.convert_to_rgb_array(region, dtype) return region - def convert_to_rgb_array( - self, - raw_region, - dtype: DtypeLike = np.uint8, - ): + def convert_to_rgb_array(self, raw_region, dtype: DtypeLike = np.uint8): """Convert to RGB mode and numpy array""" if self.reader_lib == "openslide": # convert to RGB diff --git a/monai/data/png_saver.py b/monai/data/png_saver.py index e6fb641cca..609cc8d7be 100644 --- a/monai/data/png_saver.py +++ b/monai/data/png_saver.py @@ -134,11 +134,7 @@ def save(self, data: Union[torch.Tensor, np.ndarray], meta_data: Optional[Dict] raise ValueError(f"Unsupported number of channels: {data.shape[0]}, available options are [1, 3, 4]") write_png( - np.asarray(data), - file_name=path, - output_spatial_shape=spatial_shape, - mode=self.mode, - scale=self.scale, + np.asarray(data), file_name=path, output_spatial_shape=spatial_shape, mode=self.mode, scale=self.scale ) if self.print_log: diff --git a/monai/data/test_time_augmentation.py b/monai/data/test_time_augmentation.py index 33239ea924..0ae004c20f 100644 --- a/monai/data/test_time_augmentation.py +++ b/monai/data/test_time_augmentation.py @@ -184,9 +184,7 @@ def __call__( transform_info = batch_data[transform_key] if self.nearest_interp: transform_info = convert_inverse_interp_mode( - trans_info=deepcopy(transform_info), - mode="nearest", - align_corners=None, + trans_info=deepcopy(transform_info), mode="nearest", align_corners=None ) # create a dictionary containing the inferred batch and their transforms diff --git a/monai/data/thread_buffer.py b/monai/data/thread_buffer.py index da5847465e..8aa5c014c3 100644 --- a/monai/data/thread_buffer.py +++ b/monai/data/thread_buffer.py @@ -92,12 +92,7 @@ class ThreadDataLoader(DataLoader): """ def __init__( - self, - dataset: Dataset, - buffer_size: int = 1, - buffer_timeout: float = 0.01, - num_workers: int = 0, - **kwargs, + self, dataset: Dataset, buffer_size: int = 1, buffer_timeout: float = 0.01, num_workers: int = 0, **kwargs ): super().__init__(dataset, num_workers, **kwargs) self.buffer_size = buffer_size diff --git a/monai/data/utils.py b/monai/data/utils.py index 6b577ebdf7..880ceed7b8 100644 --- a/monai/data/utils.py +++ b/monai/data/utils.py @@ -134,9 +134,7 @@ def iter_patch_slices( def dense_patch_slices( - image_size: Sequence[int], - patch_size: Sequence[int], - scan_interval: Sequence[int], + image_size: Sequence[int], patch_size: Sequence[int], scan_interval: Sequence[int] ) -> List[Tuple[slice, ...]]: """ Enumerate all slices defining ND patches of size `patch_size` from an `image_size` input image. diff --git a/monai/engines/multi_gpu_supervised_trainer.py b/monai/engines/multi_gpu_supervised_trainer.py index b6f516ff99..3736d257cb 100644 --- a/monai/engines/multi_gpu_supervised_trainer.py +++ b/monai/engines/multi_gpu_supervised_trainer.py @@ -34,10 +34,7 @@ Engine, _ = optional_import("ignite.engine", IgniteInfo.OPT_IMPORT_VERSION, min_version, "Engine") Metric, _ = optional_import("ignite.metrics", IgniteInfo.OPT_IMPORT_VERSION, min_version, "Metric") -__all__ = [ - "create_multigpu_supervised_trainer", - "create_multigpu_supervised_evaluator", -] +__all__ = ["create_multigpu_supervised_trainer", "create_multigpu_supervised_evaluator"] def _default_transform(_x: torch.Tensor, _y: torch.Tensor, _y_pred: torch.Tensor, loss: torch.Tensor) -> float: diff --git a/monai/engines/trainer.py b/monai/engines/trainer.py index eeda143def..3f8065f7a3 100644 --- a/monai/engines/trainer.py +++ b/monai/engines/trainer.py @@ -356,9 +356,7 @@ def _iteration( g_output = self.g_inferer(g_input, self.g_network) # Train Discriminator - d_total_loss = torch.zeros( - 1, - ) + d_total_loss = torch.zeros(1) for _ in range(self.d_train_steps): # `set_to_none` only work from PyTorch 1.7.0 if PT_BEFORE_1_7: diff --git a/monai/engines/utils.py b/monai/engines/utils.py index c94cc16916..f075eec492 100644 --- a/monai/engines/utils.py +++ b/monai/engines/utils.py @@ -100,9 +100,7 @@ def get_devices_spec(devices: Optional[Sequence[torch.device]] = None) -> List[t def default_prepare_batch( - batchdata: Dict[str, torch.Tensor], - device: Optional[Union[str, torch.device]] = None, - non_blocking: bool = False, + batchdata: Dict[str, torch.Tensor], device: Optional[Union[str, torch.device]] = None, non_blocking: bool = False ) -> Union[Tuple[torch.Tensor, Optional[torch.Tensor]], torch.Tensor]: """ Default function to prepare the data for current iteration. @@ -126,10 +124,7 @@ def default_prepare_batch( def default_make_latent( - num_latents: int, - latent_size: int, - device: Optional[Union[str, torch.device]] = None, - non_blocking: bool = False, + num_latents: int, latent_size: int, device: Optional[Union[str, torch.device]] = None, non_blocking: bool = False ) -> torch.Tensor: return torch.randn(num_latents, latent_size).to(device=device, non_blocking=non_blocking) diff --git a/monai/engines/workflow.py b/monai/engines/workflow.py index 3454095a02..7f0b65ac28 100644 --- a/monai/engines/workflow.py +++ b/monai/engines/workflow.py @@ -202,9 +202,7 @@ def _register_postprocessing(self, posttrans: Callable): def _run_postprocessing(engine: Engine) -> None: if not isinstance(engine.state.batch, list) or not isinstance(engine.state.output, list): engine.state.batch, engine.state.output = engine_apply_transform( - batch=engine.state.batch, - output=engine.state.output, - transform=posttrans, + batch=engine.state.batch, output=engine.state.output, transform=posttrans ) else: for i, (b, o) in enumerate(zip(engine.state.batch, engine.state.output)): diff --git a/monai/handlers/confusion_matrix.py b/monai/handlers/confusion_matrix.py index 368aacc6cb..44edcae00f 100644 --- a/monai/handlers/confusion_matrix.py +++ b/monai/handlers/confusion_matrix.py @@ -58,8 +58,4 @@ def __init__( reduction=MetricReduction.MEAN, ) self.metric_name = metric_name - super().__init__( - metric_fn=metric_fn, - output_transform=output_transform, - save_details=save_details, - ) + super().__init__(metric_fn=metric_fn, output_transform=output_transform, save_details=save_details) diff --git a/monai/handlers/hausdorff_distance.py b/monai/handlers/hausdorff_distance.py index a25ef04383..ea505ef02e 100644 --- a/monai/handlers/hausdorff_distance.py +++ b/monai/handlers/hausdorff_distance.py @@ -57,8 +57,4 @@ def __init__( directed=directed, reduction=MetricReduction.MEAN, ) - super().__init__( - metric_fn=metric_fn, - output_transform=output_transform, - save_details=save_details, - ) + super().__init__(metric_fn=metric_fn, output_transform=output_transform, save_details=save_details) diff --git a/monai/handlers/ignite_metric.py b/monai/handlers/ignite_metric.py index ea7bcd8eee..cc87842fa5 100644 --- a/monai/handlers/ignite_metric.py +++ b/monai/handlers/ignite_metric.py @@ -49,10 +49,7 @@ class IgniteMetric(Metric): # type: ignore[valid-type, misc] # due to optional_ """ def __init__( - self, - metric_fn: CumulativeIterationMetric, - output_transform: Callable = lambda x: x, - save_details: bool = True, + self, metric_fn: CumulativeIterationMetric, output_transform: Callable = lambda x: x, save_details: bool = True ) -> None: self._is_reduced: bool = False self.metric_fn = metric_fn diff --git a/monai/handlers/mean_dice.py b/monai/handlers/mean_dice.py index ba5805fc19..9d3b95a735 100644 --- a/monai/handlers/mean_dice.py +++ b/monai/handlers/mean_dice.py @@ -22,10 +22,7 @@ class MeanDice(IgniteMetric): """ def __init__( - self, - include_background: bool = True, - output_transform: Callable = lambda x: x, - save_details: bool = True, + self, include_background: bool = True, output_transform: Callable = lambda x: x, save_details: bool = True ) -> None: """ @@ -44,8 +41,4 @@ def __init__( :py:meth:`monai.metrics.meandice.compute_meandice` """ metric_fn = DiceMetric(include_background=include_background, reduction=MetricReduction.MEAN) - super().__init__( - metric_fn=metric_fn, - output_transform=output_transform, - save_details=save_details, - ) + super().__init__(metric_fn=metric_fn, output_transform=output_transform, save_details=save_details) diff --git a/monai/handlers/nvtx_handlers.py b/monai/handlers/nvtx_handlers.py index 847a3c0c47..37bacc7f95 100644 --- a/monai/handlers/nvtx_handlers.py +++ b/monai/handlers/nvtx_handlers.py @@ -50,9 +50,7 @@ class RangeHandler: """ def __init__( - self, - events: Union[str, Tuple[Union[str, Events], Union[str, Events]]], - msg: Optional[str] = None, + self, events: Union[str, Tuple[Union[str, Events], Union[str, Events]]], msg: Optional[str] = None ) -> None: self.events = self.resolve_events(events) if msg is None: @@ -73,10 +71,7 @@ def resolve_events(self, events: Union[str, Tuple]) -> Tuple[Events, Events]: if len(events) == 1: return self.create_paired_events(events[0]) if len(events) == 2: - return ( - self.get_event(events[0]), - self.get_event(events[1]), - ) + return (self.get_event(events[0]), self.get_event(events[1])) raise ValueError(f"Exactly two Ignite events should be provided [received {len(events)}].") def create_paired_events(self, event: str) -> Tuple[Events, Events]: @@ -84,17 +79,8 @@ def create_paired_events(self, event: str) -> Tuple[Events, Events]: Create pair of Ignite events from a event prefix name """ event = event.upper() - event_prefix = { - "": "", - "ENGINE": "", - "EPOCH": "EPOCH_", - "ITERATION": "ITERATION_", - "BATCH": "GET_BATCH_", - } - return ( - self.get_event(event_prefix[event] + "STARTED"), - self.get_event(event_prefix[event] + "COMPLETED"), - ) + event_prefix = {"": "", "ENGINE": "", "EPOCH": "EPOCH_", "ITERATION": "ITERATION_", "BATCH": "GET_BATCH_"} + return (self.get_event(event_prefix[event] + "STARTED"), self.get_event(event_prefix[event] + "COMPLETED")) def get_event(self, event: Union[str, Events]) -> Events: return Events[event.upper()] if isinstance(event, str) else event diff --git a/monai/handlers/postprocessing.py b/monai/handlers/postprocessing.py index 05c6bd414d..29029306d2 100644 --- a/monai/handlers/postprocessing.py +++ b/monai/handlers/postprocessing.py @@ -63,9 +63,7 @@ def __call__(self, engine: Engine) -> None: """ if not isinstance(engine.state.batch, list) or not isinstance(engine.state.output, list): engine.state.batch, engine.state.output = engine_apply_transform( - batch=engine.state.batch, - output=engine.state.output, - transform=self.transform, + batch=engine.state.batch, output=engine.state.output, transform=self.transform ) else: for i, (b, o) in enumerate(zip(engine.state.batch, engine.state.output)): diff --git a/monai/handlers/regression_metrics.py b/monai/handlers/regression_metrics.py index f203439f40..bef3123bd8 100644 --- a/monai/handlers/regression_metrics.py +++ b/monai/handlers/regression_metrics.py @@ -21,11 +21,7 @@ class MeanSquaredError(IgniteMetric): Computes Mean Squared Error from full size Tensor and collects average over batch, iterations. """ - def __init__( - self, - output_transform: Callable = lambda x: x, - save_details: bool = True, - ) -> None: + def __init__(self, output_transform: Callable = lambda x: x, save_details: bool = True) -> None: """ Args: @@ -41,11 +37,7 @@ def __init__( :py:class:`monai.metrics.MSEMetric` """ metric_fn = MSEMetric(reduction=MetricReduction.MEAN) - super().__init__( - metric_fn=metric_fn, - output_transform=output_transform, - save_details=save_details, - ) + super().__init__(metric_fn=metric_fn, output_transform=output_transform, save_details=save_details) class MeanAbsoluteError(IgniteMetric): @@ -53,11 +45,7 @@ class MeanAbsoluteError(IgniteMetric): Computes Mean Absolute Error from full size Tensor and collects average over batch, iterations. """ - def __init__( - self, - output_transform: Callable = lambda x: x, - save_details: bool = True, - ) -> None: + def __init__(self, output_transform: Callable = lambda x: x, save_details: bool = True) -> None: """ Args: @@ -69,11 +57,7 @@ def __init__( :py:class:`monai.metrics.MAEMetric` """ metric_fn = MAEMetric(reduction=MetricReduction.MEAN) - super().__init__( - metric_fn=metric_fn, - output_transform=output_transform, - save_details=save_details, - ) + super().__init__(metric_fn=metric_fn, output_transform=output_transform, save_details=save_details) class RootMeanSquaredError(IgniteMetric): @@ -81,11 +65,7 @@ class RootMeanSquaredError(IgniteMetric): Computes Root Mean Squared Error from full size Tensor and collects average over batch, iterations. """ - def __init__( - self, - output_transform: Callable = lambda x: x, - save_details: bool = True, - ) -> None: + def __init__(self, output_transform: Callable = lambda x: x, save_details: bool = True) -> None: """ Args: @@ -97,11 +77,7 @@ def __init__( :py:class:`monai.metrics.RMSEMetric` """ metric_fn = RMSEMetric(reduction=MetricReduction.MEAN) - super().__init__( - metric_fn=metric_fn, - output_transform=output_transform, - save_details=save_details, - ) + super().__init__(metric_fn=metric_fn, output_transform=output_transform, save_details=save_details) class PeakSignalToNoiseRatio(IgniteMetric): @@ -110,10 +86,7 @@ class PeakSignalToNoiseRatio(IgniteMetric): """ def __init__( - self, - max_val: Union[int, float], - output_transform: Callable = lambda x: x, - save_details: bool = True, + self, max_val: Union[int, float], output_transform: Callable = lambda x: x, save_details: bool = True ) -> None: """ @@ -129,8 +102,4 @@ def __init__( :py:class:`monai.metrics.PSNRMetric` """ metric_fn = PSNRMetric(max_val=max_val, reduction=MetricReduction.MEAN) - super().__init__( - metric_fn=metric_fn, - output_transform=output_transform, - save_details=save_details, - ) + super().__init__(metric_fn=metric_fn, output_transform=output_transform, save_details=save_details) diff --git a/monai/handlers/roc_auc.py b/monai/handlers/roc_auc.py index 98c8c8f8bc..90c5fe2f03 100644 --- a/monai/handlers/roc_auc.py +++ b/monai/handlers/roc_auc.py @@ -45,14 +45,6 @@ class ROCAUC(IgniteMetric): # type: ignore[valid-type, misc] # due to optional """ - def __init__( - self, - average: Union[Average, str] = Average.MACRO, - output_transform: Callable = lambda x: x, - ) -> None: + def __init__(self, average: Union[Average, str] = Average.MACRO, output_transform: Callable = lambda x: x) -> None: metric_fn = ROCAUCMetric(average=Average(average)) - super().__init__( - metric_fn=metric_fn, - output_transform=output_transform, - save_details=False, - ) + super().__init__(metric_fn=metric_fn, output_transform=output_transform, save_details=False) diff --git a/monai/handlers/surface_distance.py b/monai/handlers/surface_distance.py index 4fc5b5a60a..3d010888c1 100644 --- a/monai/handlers/surface_distance.py +++ b/monai/handlers/surface_distance.py @@ -53,8 +53,4 @@ def __init__( distance_metric=distance_metric, reduction=MetricReduction.MEAN, ) - super().__init__( - metric_fn=metric_fn, - output_transform=output_transform, - save_details=save_details, - ) + super().__init__(metric_fn=metric_fn, output_transform=output_transform, save_details=save_details) diff --git a/monai/handlers/utils.py b/monai/handlers/utils.py index 5d72c028f9..3567dbac03 100644 --- a/monai/handlers/utils.py +++ b/monai/handlers/utils.py @@ -25,12 +25,7 @@ else: Engine, _ = optional_import("ignite.engine", IgniteInfo.OPT_IMPORT_VERSION, min_version, "Engine") -__all__ = [ - "stopping_fn_from_metric", - "stopping_fn_from_loss", - "write_metrics_reports", - "from_engine", -] +__all__ = ["stopping_fn_from_metric", "stopping_fn_from_loss", "write_metrics_reports", "from_engine"] def stopping_fn_from_metric(metric_name: str): diff --git a/monai/inferers/inferer.py b/monai/inferers/inferer.py index ecb2c2c178..25d9fd1fb0 100644 --- a/monai/inferers/inferer.py +++ b/monai/inferers/inferer.py @@ -42,13 +42,7 @@ class Inferer(ABC): """ @abstractmethod - def __call__( - self, - inputs: torch.Tensor, - network: Callable[..., torch.Tensor], - *args: Any, - **kwargs: Any, - ): + def __call__(self, inputs: torch.Tensor, network: Callable[..., torch.Tensor], *args: Any, **kwargs: Any): """ Run inference on `inputs` with the `network` model. @@ -75,13 +69,7 @@ class SimpleInferer(Inferer): def __init__(self) -> None: Inferer.__init__(self) - def __call__( - self, - inputs: torch.Tensor, - network: Callable[..., torch.Tensor], - *args: Any, - **kwargs: Any, - ): + def __call__(self, inputs: torch.Tensor, network: Callable[..., torch.Tensor], *args: Any, **kwargs: Any): """Unified callable function API of Inferers. Args: @@ -161,11 +149,7 @@ def __init__( self.device = device def __call__( - self, - inputs: torch.Tensor, - network: Callable[..., torch.Tensor], - *args: Any, - **kwargs: Any, + self, inputs: torch.Tensor, network: Callable[..., torch.Tensor], *args: Any, **kwargs: Any ) -> torch.Tensor: """ @@ -217,13 +201,7 @@ def __init__(self, cam_name: str, target_layers: str, class_idx: Optional[int] = self.args = args self.kwargs = kwargs - def __call__( # type: ignore - self, - inputs: torch.Tensor, - network: nn.Module, - *args: Any, - **kwargs: Any, - ): + def __call__(self, inputs: torch.Tensor, network: nn.Module, *args: Any, **kwargs: Any): # type: ignore """Unified callable function API of Inferers. Args: diff --git a/monai/losses/deform.py b/monai/losses/deform.py index b9eb15f798..fea56010c7 100644 --- a/monai/losses/deform.py +++ b/monai/losses/deform.py @@ -52,10 +52,7 @@ class BendingEnergyLoss(_Loss): DeepReg (https://github.com/DeepRegNet/DeepReg) """ - def __init__( - self, - reduction: Union[LossReduction, str] = LossReduction.MEAN, - ) -> None: + def __init__(self, reduction: Union[LossReduction, str] = LossReduction.MEAN) -> None: """ Args: reduction: {``"none"``, ``"mean"``, ``"sum"``} diff --git a/monai/losses/dice.py b/monai/losses/dice.py index 7917bc6404..09f86a4ebd 100644 --- a/monai/losses/dice.py +++ b/monai/losses/dice.py @@ -536,10 +536,7 @@ def _compute_generalized_true_positive( flat_target_extended = torch.unsqueeze(flat_target, dim=1) alpha_extended = torch.gather(alpha_extended, index=flat_target_extended, dim=1) - return torch.sum( - alpha_extended * (1.0 - wasserstein_distance_map), - dim=[1, 2], - ) + return torch.sum(alpha_extended * (1.0 - wasserstein_distance_map), dim=[1, 2]) def _compute_denominator( self, alpha: torch.Tensor, flat_target: torch.Tensor, wasserstein_distance_map: torch.Tensor @@ -556,10 +553,7 @@ def _compute_denominator( flat_target_extended = torch.unsqueeze(flat_target, dim=1) alpha_extended = torch.gather(alpha_extended, index=flat_target_extended, dim=1) - return torch.sum( - alpha_extended * (2.0 - wasserstein_distance_map), - dim=[1, 2], - ) + return torch.sum(alpha_extended * (2.0 - wasserstein_distance_map), dim=[1, 2]) def _compute_alpha_generalized_true_positives(self, flat_target: torch.Tensor) -> torch.Tensor: """ @@ -657,10 +651,7 @@ def __init__( smooth_dr=smooth_dr, batch=batch, ) - self.cross_entropy = nn.CrossEntropyLoss( - weight=ce_weight, - reduction=reduction, - ) + self.cross_entropy = nn.CrossEntropyLoss(weight=ce_weight, reduction=reduction) if lambda_dice < 0.0: raise ValueError("lambda_dice should be no less than 0.0.") if lambda_ce < 0.0: diff --git a/monai/losses/multi_scale.py b/monai/losses/multi_scale.py index 0e60cda362..182cb2f7a6 100644 --- a/monai/losses/multi_scale.py +++ b/monai/losses/multi_scale.py @@ -21,12 +21,7 @@ def make_gaussian_kernel(sigma: int) -> torch.Tensor: if sigma <= 0: raise ValueError(f"expecting positive sigma, got sigma={sigma}") - return gaussian_1d( - sigma=torch.tensor(sigma), - truncated=3, - approx="sampled", - normalize=False, - ) + return gaussian_1d(sigma=torch.tensor(sigma), truncated=3, approx="sampled", normalize=False) def make_cauchy_kernel(sigma: int) -> torch.Tensor: @@ -39,10 +34,7 @@ def make_cauchy_kernel(sigma: int) -> torch.Tensor: return k -kernel_fn_dict = { - "gaussian": make_gaussian_kernel, - "cauchy": make_cauchy_kernel, -} +kernel_fn_dict = {"gaussian": make_gaussian_kernel, "cauchy": make_cauchy_kernel} class MultiScaleLoss(_Loss): diff --git a/monai/metrics/confusion_matrix.py b/monai/metrics/confusion_matrix.py index 9568cf6028..0a2084c566 100644 --- a/monai/metrics/confusion_matrix.py +++ b/monai/metrics/confusion_matrix.py @@ -99,11 +99,7 @@ def _compute_tensor(self, y_pred: torch.Tensor, y: torch.Tensor): # type: ignor warnings.warn("As for classification task, compute_sample should be False.") self.compute_sample = False - return get_confusion_matrix( - y_pred=y_pred, - y=y, - include_background=self.include_background, - ) + return get_confusion_matrix(y_pred=y_pred, y=y, include_background=self.include_background) def aggregate(self): # type: ignore """ @@ -129,11 +125,7 @@ def aggregate(self): # type: ignore return results -def get_confusion_matrix( - y_pred: torch.Tensor, - y: torch.Tensor, - include_background: bool = True, -): +def get_confusion_matrix(y_pred: torch.Tensor, y: torch.Tensor, include_background: bool = True): """ Compute confusion matrix. A tensor with the shape [BC4] will be returned. Where, the third dimension represents the number of true positive, false positive, true negative and false negative values for @@ -153,10 +145,7 @@ def get_confusion_matrix( """ if not include_background: - y_pred, y = ignore_background( - y_pred=y_pred, - y=y, - ) + y_pred, y = ignore_background(y_pred=y_pred, y=y) y = y.float() y_pred = y_pred.float() diff --git a/monai/metrics/froc.py b/monai/metrics/froc.py index fcf0124afe..011021f33b 100644 --- a/monai/metrics/froc.py +++ b/monai/metrics/froc.py @@ -116,9 +116,7 @@ def compute_froc_curve_data( def compute_froc_score( - fps_per_image: np.ndarray, - total_sensitivity: np.ndarray, - eval_thresholds: Tuple = (0.25, 0.5, 1, 2, 4, 8), + fps_per_image: np.ndarray, total_sensitivity: np.ndarray, eval_thresholds: Tuple = (0.25, 0.5, 1, 2, 4, 8) ): """ This function is modified from the official evaluation code of diff --git a/monai/metrics/hausdorff_distance.py b/monai/metrics/hausdorff_distance.py index 12f3b49d32..ed3639e39e 100644 --- a/monai/metrics/hausdorff_distance.py +++ b/monai/metrics/hausdorff_distance.py @@ -141,10 +141,7 @@ def compute_hausdorff_distance( """ if not include_background: - y_pred, y = ignore_background( - y_pred=y_pred, - y=y, - ) + y_pred, y = ignore_background(y_pred=y_pred, y=y) if isinstance(y, torch.Tensor): y = y.float() if isinstance(y_pred, torch.Tensor): @@ -172,10 +169,7 @@ def compute_hausdorff_distance( def compute_percent_hausdorff_distance( - edges_pred: np.ndarray, - edges_gt: np.ndarray, - distance_metric: str = "euclidean", - percentile: Optional[float] = None, + edges_pred: np.ndarray, edges_gt: np.ndarray, distance_metric: str = "euclidean", percentile: Optional[float] = None ): """ This function is used to compute the directed Hausdorff distance. diff --git a/monai/metrics/meandice.py b/monai/metrics/meandice.py index 226c106f7e..528407cf3c 100644 --- a/monai/metrics/meandice.py +++ b/monai/metrics/meandice.py @@ -77,11 +77,7 @@ def _compute_tensor(self, y_pred: torch.Tensor, y: torch.Tensor): # type: ignor if dims < 3: raise ValueError("y_pred should have at least three dimensions.") # compute dice (BxC) for each channel for each batch - return compute_meandice( - y_pred=y_pred, - y=y, - include_background=self.include_background, - ) + return compute_meandice(y_pred=y_pred, y=y, include_background=self.include_background) def aggregate(self): # type: ignore """ @@ -97,11 +93,7 @@ def aggregate(self): # type: ignore return (f, not_nans) if self.get_not_nans else f -def compute_meandice( - y_pred: torch.Tensor, - y: torch.Tensor, - include_background: bool = True, -) -> torch.Tensor: +def compute_meandice(y_pred: torch.Tensor, y: torch.Tensor, include_background: bool = True) -> torch.Tensor: """Computes Dice score metric from full size Tensor and collects average. Args: @@ -122,10 +114,7 @@ def compute_meandice( """ if not include_background: - y_pred, y = ignore_background( - y_pred=y_pred, - y=y, - ) + y_pred, y = ignore_background(y_pred=y_pred, y=y) y = y.float() y_pred = y_pred.float() @@ -142,8 +131,4 @@ def compute_meandice( y_pred_o = torch.sum(y_pred, dim=reduce_axis) denominator = y_o + y_pred_o - return torch.where( - y_o > 0, - (2.0 * intersection) / denominator, - torch.tensor(float("nan"), device=y_o.device), - ) + return torch.where(y_o > 0, (2.0 * intersection) / denominator, torch.tensor(float("nan"), device=y_o.device)) diff --git a/monai/metrics/regression.py b/monai/metrics/regression.py index 2bf565f543..4b1acb4920 100644 --- a/monai/metrics/regression.py +++ b/monai/metrics/regression.py @@ -39,9 +39,7 @@ class RegressionMetric(CumulativeIterationMetric): """ def __init__( - self, - reduction: Union[MetricReduction, str] = MetricReduction.MEAN, - get_not_nans: bool = False, + self, reduction: Union[MetricReduction, str] = MetricReduction.MEAN, get_not_nans: bool = False ) -> None: super().__init__() self.reduction = reduction @@ -94,9 +92,7 @@ class MSEMetric(RegressionMetric): """ def __init__( - self, - reduction: Union[MetricReduction, str] = MetricReduction.MEAN, - get_not_nans: bool = False, + self, reduction: Union[MetricReduction, str] = MetricReduction.MEAN, get_not_nans: bool = False ) -> None: super().__init__(reduction=reduction, get_not_nans=get_not_nans) self.sq_func = partial(torch.pow, exponent=2.0) @@ -128,9 +124,7 @@ class MAEMetric(RegressionMetric): """ def __init__( - self, - reduction: Union[MetricReduction, str] = MetricReduction.MEAN, - get_not_nans: bool = False, + self, reduction: Union[MetricReduction, str] = MetricReduction.MEAN, get_not_nans: bool = False ) -> None: super().__init__(reduction=reduction, get_not_nans=get_not_nans) self.abs_func = torch.abs @@ -163,9 +157,7 @@ class RMSEMetric(RegressionMetric): """ def __init__( - self, - reduction: Union[MetricReduction, str] = MetricReduction.MEAN, - get_not_nans: bool = False, + self, reduction: Union[MetricReduction, str] = MetricReduction.MEAN, get_not_nans: bool = False ) -> None: super().__init__(reduction=reduction, get_not_nans=get_not_nans) self.sq_func = partial(torch.pow, exponent=2.0) diff --git a/monai/metrics/rocauc.py b/monai/metrics/rocauc.py index d331f01707..4c71fe6374 100644 --- a/monai/metrics/rocauc.py +++ b/monai/metrics/rocauc.py @@ -93,11 +93,7 @@ def _calculate(y_pred: torch.Tensor, y: torch.Tensor) -> float: return auc / (nneg * (n - nneg)) -def compute_roc_auc( - y_pred: torch.Tensor, - y: torch.Tensor, - average: Union[Average, str] = Average.MACRO, -): +def compute_roc_auc(y_pred: torch.Tensor, y: torch.Tensor, average: Union[Average, str] = Average.MACRO): """Computes Area Under the Receiver Operating Characteristic Curve (ROC AUC). Referring to: `sklearn.metrics.roc_auc_score `_. diff --git a/monai/metrics/surface_distance.py b/monai/metrics/surface_distance.py index 6039f1b55e..2c9359ea0c 100644 --- a/monai/metrics/surface_distance.py +++ b/monai/metrics/surface_distance.py @@ -134,10 +134,7 @@ def compute_average_surface_distance( """ if not include_background: - y_pred, y = ignore_background( - y_pred=y_pred, - y=y, - ) + y_pred, y = ignore_background(y_pred=y_pred, y=y) if isinstance(y, torch.Tensor): y = y.float() diff --git a/monai/metrics/utils.py b/monai/metrics/utils.py index 84de834f74..540eda3096 100644 --- a/monai/metrics/utils.py +++ b/monai/metrics/utils.py @@ -25,10 +25,7 @@ __all__ = ["ignore_background", "do_metric_reduction", "get_mask_edges", "get_surface_distance"] -def ignore_background( - y_pred: Union[np.ndarray, torch.Tensor], - y: Union[np.ndarray, torch.Tensor], -): +def ignore_background(y_pred: Union[np.ndarray, torch.Tensor], y: Union[np.ndarray, torch.Tensor]): """ This function is used to remove background (the first channel) for `y_pred` and `y`. Args: @@ -43,10 +40,7 @@ def ignore_background( return y_pred, y -def do_metric_reduction( - f: torch.Tensor, - reduction: Union[MetricReduction, str] = MetricReduction.MEAN, -): +def do_metric_reduction(f: torch.Tensor, reduction: Union[MetricReduction, str] = MetricReduction.MEAN): """ This function is to do the metric reduction for calculated metrics of each example's each class. The function also returns `not_nans`, which counts the number of not nans for the metric. @@ -170,11 +164,7 @@ def get_mask_edges( return (edges_pred, edges_gt) -def get_surface_distance( - seg_pred: np.ndarray, - seg_gt: np.ndarray, - distance_metric: str = "euclidean", -) -> np.ndarray: +def get_surface_distance(seg_pred: np.ndarray, seg_gt: np.ndarray, distance_metric: str = "euclidean") -> np.ndarray: """ This function is used to compute the surface distances from `seg_pred` to `seg_gt`. diff --git a/monai/networks/blocks/dynunet_block.py b/monai/networks/blocks/dynunet_block.py index 24fb16018e..248bc5341c 100644 --- a/monai/networks/blocks/dynunet_block.py +++ b/monai/networks/blocks/dynunet_block.py @@ -58,22 +58,10 @@ def __init__( conv_only=True, ) self.conv2 = get_conv_layer( - spatial_dims, - out_channels, - out_channels, - kernel_size=kernel_size, - stride=1, - dropout=dropout, - conv_only=True, + spatial_dims, out_channels, out_channels, kernel_size=kernel_size, stride=1, dropout=dropout, conv_only=True ) self.conv3 = get_conv_layer( - spatial_dims, - in_channels, - out_channels, - kernel_size=1, - stride=stride, - dropout=dropout, - conv_only=True, + spatial_dims, in_channels, out_channels, kernel_size=1, stride=stride, dropout=dropout, conv_only=True ) self.lrelu = get_act_layer(("leakyrelu", {"inplace": True, "negative_slope": 0.01})) self.norm1 = get_norm_layer(name=norm_name, spatial_dims=spatial_dims, channels=out_channels) @@ -137,13 +125,7 @@ def __init__( conv_only=True, ) self.conv2 = get_conv_layer( - spatial_dims, - out_channels, - out_channels, - kernel_size=kernel_size, - stride=1, - dropout=dropout, - conv_only=True, + spatial_dims, out_channels, out_channels, kernel_size=kernel_size, stride=1, dropout=dropout, conv_only=True ) self.lrelu = get_act_layer(("leakyrelu", {"inplace": True, "negative_slope": 0.01})) self.norm1 = get_norm_layer(name=norm_name, spatial_dims=spatial_dims, channels=out_channels) @@ -266,8 +248,7 @@ def get_conv_layer( def get_padding( - kernel_size: Union[Sequence[int], int], - stride: Union[Sequence[int], int], + kernel_size: Union[Sequence[int], int], stride: Union[Sequence[int], int] ) -> Union[Tuple[int, ...], int]: kernel_size_np = np.atleast_1d(kernel_size) @@ -281,9 +262,7 @@ def get_padding( def get_output_padding( - kernel_size: Union[Sequence[int], int], - stride: Union[Sequence[int], int], - padding: Union[Sequence[int], int], + kernel_size: Union[Sequence[int], int], stride: Union[Sequence[int], int], padding: Union[Sequence[int], int] ) -> Union[Tuple[int, ...], int]: kernel_size_np = np.atleast_1d(kernel_size) stride_np = np.atleast_1d(stride) diff --git a/monai/networks/blocks/dynunet_block_v1.py b/monai/networks/blocks/dynunet_block_v1.py index b5b88dd0df..faf7586be9 100644 --- a/monai/networks/blocks/dynunet_block_v1.py +++ b/monai/networks/blocks/dynunet_block_v1.py @@ -45,22 +45,10 @@ def __init__( conv_only=True, ) self.conv2 = get_conv_layer( - spatial_dims, - out_channels, - out_channels, - kernel_size=kernel_size, - stride=1, - dropout=dropout, - conv_only=True, + spatial_dims, out_channels, out_channels, kernel_size=kernel_size, stride=1, dropout=dropout, conv_only=True ) self.conv3 = get_conv_layer( - spatial_dims, - in_channels, - out_channels, - kernel_size=1, - stride=stride, - dropout=dropout, - conv_only=True, + spatial_dims, in_channels, out_channels, kernel_size=1, stride=stride, dropout=dropout, conv_only=True ) self.lrelu = get_act_layer(("leakyrelu", {"inplace": True, "negative_slope": 0.01})) self.norm1 = _get_norm_layer(spatial_dims, out_channels, norm_name) @@ -98,13 +86,7 @@ def __init__( conv_only=True, ) self.conv2 = get_conv_layer( - spatial_dims, - out_channels, - out_channels, - kernel_size=kernel_size, - stride=1, - dropout=dropout, - conv_only=True, + spatial_dims, out_channels, out_channels, kernel_size=kernel_size, stride=1, dropout=dropout, conv_only=True ) self.lrelu = get_act_layer(("leakyrelu", {"inplace": True, "negative_slope": 0.01})) self.norm1 = _get_norm_layer(spatial_dims, out_channels, norm_name) diff --git a/monai/networks/blocks/fcn.py b/monai/networks/blocks/fcn.py index 1170dfa7e3..09d5d4779e 100644 --- a/monai/networks/blocks/fcn.py +++ b/monai/networks/blocks/fcn.py @@ -154,12 +154,7 @@ def __init__( self.transformer = self.conv2d_type(in_channels=256, out_channels=64, kernel_size=1) if self.upsample_mode == "transpose": - self.up_conv = UpSample( - spatial_dims=2, - in_channels=self.out_channels, - scale_factor=2, - mode="deconv", - ) + self.up_conv = UpSample(spatial_dims=2, in_channels=self.out_channels, scale_factor=2, mode="deconv") def forward(self, x: torch.Tensor): """ @@ -195,14 +190,7 @@ def forward(self, x: torch.Tensor): fs2 = self.refine7(F.interpolate(fs1, fm2.size()[2:], mode=self.upsample_mode, align_corners=True) + gcfm3) fs3 = self.refine8(F.interpolate(fs2, pool_x.size()[2:], mode=self.upsample_mode, align_corners=True) + gcfm4) fs4 = self.refine9(F.interpolate(fs3, conv_x.size()[2:], mode=self.upsample_mode, align_corners=True) + gcfm5) - return self.refine10( - F.interpolate( - fs4, - org_input.size()[2:], - mode=self.upsample_mode, - align_corners=True, - ) - ) + return self.refine10(F.interpolate(fs4, org_input.size()[2:], mode=self.upsample_mode, align_corners=True)) class MCFCN(FCN): diff --git a/monai/networks/blocks/localnet_block.py b/monai/networks/blocks/localnet_block.py index 844c5c0eea..d3b81ff494 100644 --- a/monai/networks/blocks/localnet_block.py +++ b/monai/networks/blocks/localnet_block.py @@ -44,29 +44,16 @@ def get_conv_block( def get_conv_layer( - spatial_dims: int, - in_channels: int, - out_channels: int, - kernel_size: Union[Sequence[int], int] = 3, + spatial_dims: int, in_channels: int, out_channels: int, kernel_size: Union[Sequence[int], int] = 3 ) -> nn.Module: padding = same_padding(kernel_size) mod: nn.Module = Convolution( - spatial_dims, - in_channels, - out_channels, - kernel_size=kernel_size, - bias=False, - conv_only=True, - padding=padding, + spatial_dims, in_channels, out_channels, kernel_size=kernel_size, bias=False, conv_only=True, padding=padding ) return mod -def get_deconv_block( - spatial_dims: int, - in_channels: int, - out_channels: int, -) -> nn.Module: +def get_deconv_block(spatial_dims: int, in_channels: int, out_channels: int) -> nn.Module: mod: nn.Module = Convolution( spatial_dims=spatial_dims, in_channels=in_channels, @@ -84,11 +71,7 @@ def get_deconv_block( class ResidualBlock(nn.Module): def __init__( - self, - spatial_dims: int, - in_channels: int, - out_channels: int, - kernel_size: Union[Sequence[int], int], + self, spatial_dims: int, in_channels: int, out_channels: int, kernel_size: Union[Sequence[int], int] ) -> None: super().__init__() if in_channels != out_channels: @@ -96,10 +79,7 @@ def __init__( f"expecting in_channels == out_channels, " f"got in_channels={in_channels}, out_channels={out_channels}" ) self.conv_block = get_conv_block( - spatial_dims=spatial_dims, - in_channels=in_channels, - out_channels=out_channels, - kernel_size=kernel_size, + spatial_dims=spatial_dims, in_channels=in_channels, out_channels=out_channels, kernel_size=kernel_size ) self.conv = get_conv_layer( spatial_dims=spatial_dims, in_channels=out_channels, out_channels=out_channels, kernel_size=kernel_size @@ -113,22 +93,13 @@ def forward(self, x) -> torch.Tensor: class LocalNetResidualBlock(nn.Module): - def __init__( - self, - spatial_dims: int, - in_channels: int, - out_channels: int, - ) -> None: + def __init__(self, spatial_dims: int, in_channels: int, out_channels: int) -> None: super().__init__() if in_channels != out_channels: raise ValueError( f"expecting in_channels == out_channels, " f"got in_channels={in_channels}, out_channels={out_channels}" ) - self.conv_layer = get_conv_layer( - spatial_dims=spatial_dims, - in_channels=in_channels, - out_channels=out_channels, - ) + self.conv_layer = get_conv_layer(spatial_dims=spatial_dims, in_channels=in_channels, out_channels=out_channels) self.norm = Norm[Norm.BATCH, spatial_dims](out_channels) self.relu = nn.ReLU() @@ -150,11 +121,7 @@ class LocalNetDownSampleBlock(nn.Module): """ def __init__( - self, - spatial_dims: int, - in_channels: int, - out_channels: int, - kernel_size: Union[Sequence[int], int], + self, spatial_dims: int, in_channels: int, out_channels: int, kernel_size: Union[Sequence[int], int] ) -> None: """ Args: @@ -172,9 +139,7 @@ def __init__( self.residual_block = ResidualBlock( spatial_dims=spatial_dims, in_channels=out_channels, out_channels=out_channels, kernel_size=kernel_size ) - self.max_pool = Pool[Pool.MAX, spatial_dims]( - kernel_size=2, - ) + self.max_pool = Pool[Pool.MAX, spatial_dims](kernel_size=2) def forward(self, x) -> Tuple[torch.Tensor, torch.Tensor]: """ @@ -211,12 +176,7 @@ class LocalNetUpSampleBlock(nn.Module): DeepReg (https://github.com/DeepRegNet/DeepReg) """ - def __init__( - self, - spatial_dims: int, - in_channels: int, - out_channels: int, - ) -> None: + def __init__(self, spatial_dims: int, in_channels: int, out_channels: int) -> None: """ Args: spatial_dims: number of spatial dimensions. @@ -227,19 +187,11 @@ def __init__( """ super().__init__() self.deconv_block = get_deconv_block( - spatial_dims=spatial_dims, - in_channels=in_channels, - out_channels=out_channels, - ) - self.conv_block = get_conv_block( - spatial_dims=spatial_dims, - in_channels=out_channels, - out_channels=out_channels, + spatial_dims=spatial_dims, in_channels=in_channels, out_channels=out_channels ) + self.conv_block = get_conv_block(spatial_dims=spatial_dims, in_channels=out_channels, out_channels=out_channels) self.residual_block = LocalNetResidualBlock( - spatial_dims=spatial_dims, - in_channels=out_channels, - out_channels=out_channels, + spatial_dims=spatial_dims, in_channels=out_channels, out_channels=out_channels ) if in_channels / out_channels != 2: raise ValueError( diff --git a/monai/networks/blocks/mlp.py b/monai/networks/blocks/mlp.py index 11b5e6fc15..9f6d12594e 100644 --- a/monai/networks/blocks/mlp.py +++ b/monai/networks/blocks/mlp.py @@ -18,12 +18,7 @@ class MLPBlock(nn.Module): An Image is Worth 16x16 Words: Transformers for Image Recognition at Scale " """ - def __init__( - self, - hidden_size: int, - mlp_dim: int, - dropout_rate: float = 0.0, - ) -> None: + def __init__(self, hidden_size: int, mlp_dim: int, dropout_rate: float = 0.0) -> None: """ Args: hidden_size: dimension of hidden layer. diff --git a/monai/networks/blocks/patchembedding.py b/monai/networks/blocks/patchembedding.py index 8170106dec..492e7bf236 100644 --- a/monai/networks/blocks/patchembedding.py +++ b/monai/networks/blocks/patchembedding.py @@ -94,8 +94,7 @@ def __init__( to_chars = f"b ({' '.join([c[0] for c in chars])}) ({' '.join([c[1] for c in chars])} c)" axes_len = {f"p{i+1}": p for i, p in enumerate(patch_size)} self.patch_embeddings = nn.Sequential( - Rearrange(f"{from_chars} -> {to_chars}", **axes_len), - nn.Linear(self.patch_dim, hidden_size), + Rearrange(f"{from_chars} -> {to_chars}", **axes_len), nn.Linear(self.patch_dim, hidden_size) ) self.position_embeddings = nn.Parameter(torch.zeros(1, self.n_patches, hidden_size)) self.cls_token = nn.Parameter(torch.zeros(1, 1, hidden_size)) diff --git a/monai/networks/blocks/regunet_block.py b/monai/networks/blocks/regunet_block.py index 18770a0d48..b65f08a443 100644 --- a/monai/networks/blocks/regunet_block.py +++ b/monai/networks/blocks/regunet_block.py @@ -59,20 +59,11 @@ def get_conv_block( def get_conv_layer( - spatial_dims: int, - in_channels: int, - out_channels: int, - kernel_size: Union[Sequence[int], int] = 3, + spatial_dims: int, in_channels: int, out_channels: int, kernel_size: Union[Sequence[int], int] = 3 ) -> nn.Module: padding = same_padding(kernel_size) mod: nn.Module = Convolution( - spatial_dims, - in_channels, - out_channels, - kernel_size=kernel_size, - bias=False, - conv_only=True, - padding=padding, + spatial_dims, in_channels, out_channels, kernel_size=kernel_size, bias=False, conv_only=True, padding=padding ) return mod @@ -84,12 +75,7 @@ class RegistrationResidualConvBlock(nn.Module): """ def __init__( - self, - spatial_dims: int, - in_channels: int, - out_channels: int, - num_layers: int = 2, - kernel_size: int = 3, + self, spatial_dims: int, in_channels: int, out_channels: int, num_layers: int = 2, kernel_size: int = 3 ): """ @@ -146,12 +132,7 @@ class RegistrationDownSampleBlock(nn.Module): DeepReg (https://github.com/DeepRegNet/DeepReg) """ - def __init__( - self, - spatial_dims: int, - channels: int, - pooling: bool, - ) -> None: + def __init__(self, spatial_dims: int, channels: int, pooling: bool) -> None: """ Args: spatial_dims: number of spatial dimensions. @@ -189,11 +170,7 @@ def forward(self, x: torch.Tensor) -> torch.Tensor: return out -def get_deconv_block( - spatial_dims: int, - in_channels: int, - out_channels: int, -) -> nn.Module: +def get_deconv_block(spatial_dims: int, in_channels: int, out_channels: int) -> nn.Module: mod: nn.Module = Convolution( spatial_dims=spatial_dims, in_channels=in_channels, @@ -263,10 +240,7 @@ def forward(self, x: List[torch.Tensor], image_size: List[int]) -> torch.Tensor: Tensor of shape (batch, `out_channels`, size1, size2, size3), where (size1, size2, size3) = ``image_size`` """ feature_list = [ - F.interpolate( - layer(x[self.max_level - level]), - size=image_size, - ) + F.interpolate(layer(x[self.max_level - level]), size=image_size) for layer, level in zip(self.layers, self.extract_levels) ] out: torch.Tensor = torch.mean(torch.stack(feature_list, dim=0), dim=0) diff --git a/monai/networks/blocks/segresnet_block.py b/monai/networks/blocks/segresnet_block.py index 4d2a5b0623..aad2278934 100644 --- a/monai/networks/blocks/segresnet_block.py +++ b/monai/networks/blocks/segresnet_block.py @@ -25,13 +25,7 @@ def get_conv_layer( ): return Convolution( - spatial_dims, - in_channels, - out_channels, - strides=stride, - kernel_size=kernel_size, - bias=bias, - conv_only=True, + spatial_dims, in_channels, out_channels, strides=stride, kernel_size=kernel_size, bias=bias, conv_only=True ) @@ -56,13 +50,7 @@ class ResBlock(nn.Module): `_. """ - def __init__( - self, - spatial_dims: int, - in_channels: int, - norm: Union[Tuple, str], - kernel_size: int = 3, - ) -> None: + def __init__(self, spatial_dims: int, in_channels: int, norm: Union[Tuple, str], kernel_size: int = 3) -> None: """ Args: spatial_dims: number of spatial dimensions, could be 1, 2 or 3. diff --git a/monai/networks/blocks/selfattention.py b/monai/networks/blocks/selfattention.py index 649f757bf8..932475b06c 100644 --- a/monai/networks/blocks/selfattention.py +++ b/monai/networks/blocks/selfattention.py @@ -23,12 +23,7 @@ class SABlock(nn.Module): An Image is Worth 16x16 Words: Transformers for Image Recognition at Scale " """ - def __init__( - self, - hidden_size: int, - num_heads: int, - dropout_rate: float = 0.0, - ) -> None: + def __init__(self, hidden_size: int, num_heads: int, dropout_rate: float = 0.0) -> None: """ Args: hidden_size: dimension of hidden layer. diff --git a/monai/networks/blocks/transformerblock.py b/monai/networks/blocks/transformerblock.py index c7a948ed76..5ccc2090b4 100644 --- a/monai/networks/blocks/transformerblock.py +++ b/monai/networks/blocks/transformerblock.py @@ -21,13 +21,7 @@ class TransformerBlock(nn.Module): An Image is Worth 16x16 Words: Transformers for Image Recognition at Scale " """ - def __init__( - self, - hidden_size: int, - mlp_dim: int, - num_heads: int, - dropout_rate: float = 0.0, - ) -> None: + def __init__(self, hidden_size: int, mlp_dim: int, num_heads: int, dropout_rate: float = 0.0) -> None: """ Args: hidden_size: dimension of hidden layer. diff --git a/monai/networks/blocks/warp.py b/monai/networks/blocks/warp.py index ccdfdb964e..e9cc908464 100644 --- a/monai/networks/blocks/warp.py +++ b/monai/networks/blocks/warp.py @@ -30,11 +30,7 @@ class Warp(nn.Module): Warp an image with given dense displacement field (DDF). """ - def __init__( - self, - mode=GridSampleMode.BILINEAR.value, - padding_mode=GridSamplePadMode.BORDER.value, - ): + def __init__(self, mode=GridSampleMode.BILINEAR.value, padding_mode=GridSamplePadMode.BORDER.value): """ For pytorch native APIs, the possible values are: @@ -123,13 +119,7 @@ def forward(self, image: torch.Tensor, ddf: torch.Tensor): ) # using csrc resampling - return grid_pull( - image, - grid, - bound=self._padding_mode, - extrapolate=True, - interpolation=self._interp_mode, - ) + return grid_pull(image, grid, bound=self._padding_mode, extrapolate=True, interpolation=self._interp_mode) class DVF2DDF(nn.Module): @@ -143,10 +133,7 @@ class DVF2DDF(nn.Module): """ def __init__( - self, - num_steps: int = 7, - mode=GridSampleMode.BILINEAR.value, - padding_mode=GridSamplePadMode.ZEROS.value, + self, num_steps: int = 7, mode=GridSampleMode.BILINEAR.value, padding_mode=GridSamplePadMode.ZEROS.value ): super().__init__() if num_steps <= 0: diff --git a/monai/networks/layers/convutils.py b/monai/networks/layers/convutils.py index 994ca05b85..9aa11fa7d0 100644 --- a/monai/networks/layers/convutils.py +++ b/monai/networks/layers/convutils.py @@ -44,8 +44,7 @@ def same_padding( def stride_minus_kernel_padding( - kernel_size: Union[Sequence[int], int], - stride: Union[Sequence[int], int], + kernel_size: Union[Sequence[int], int], stride: Union[Sequence[int], int] ) -> Union[Tuple[int, ...], int]: kernel_size_np = np.atleast_1d(kernel_size) stride_np = np.atleast_1d(stride) diff --git a/monai/networks/nets/ahnet.py b/monai/networks/nets/ahnet.py index 9192b73cbf..21e3c33bf3 100644 --- a/monai/networks/nets/ahnet.py +++ b/monai/networks/nets/ahnet.py @@ -256,13 +256,7 @@ def __init__(self, spatial_dims: int, psp_block_num: int, in_ch: int, upsample_m size = (2 ** (i + 3), 2 ** (i + 3), 1)[-spatial_dims:] self.pool_modules.append(pool_type(kernel_size=size, stride=size)) self.project_modules.append( - conv_type( - in_ch, - 1, - kernel_size=(1, 1, 1)[-spatial_dims:], - stride=1, - padding=(1, 1, 0)[-spatial_dims:], - ) + conv_type(in_ch, 1, kernel_size=(1, 1, 1)[-spatial_dims:], stride=1, padding=(1, 1, 0)[-spatial_dims:]) ) self.spatial_dims = spatial_dims @@ -274,15 +268,7 @@ def __init__(self, spatial_dims: int, psp_block_num: int, in_ch: int, upsample_m for i in range(psp_block_num): size = (2 ** (i + 3), 2 ** (i + 3), 1)[-spatial_dims:] pad_size = (2 ** (i + 3), 2 ** (i + 3), 0)[-spatial_dims:] - self.up_modules.append( - conv_trans_type( - 1, - 1, - kernel_size=size, - stride=size, - padding=pad_size, - ) - ) + self.up_modules.append(conv_trans_type(1, 1, kernel_size=size, stride=size, padding=pad_size)) def forward(self, x): outputs = [] @@ -451,13 +437,7 @@ def __init__( net2d = FCN(pretrained=True, progress=progress) self.copy_from(net2d) - def _make_layer( - self, - block: Type[Bottleneck3x3x1], - planes: int, - blocks: int, - stride: int = 1, - ) -> nn.Sequential: + def _make_layer(self, block: Type[Bottleneck3x3x1], planes: int, blocks: int, stride: int = 1) -> nn.Sequential: downsample = None if stride != 1 or self.inplanes != planes * block.expansion: downsample = nn.Sequential( diff --git a/monai/networks/nets/densenet.py b/monai/networks/nets/densenet.py index 9de9e17b12..59576f5dd4 100644 --- a/monai/networks/nets/densenet.py +++ b/monai/networks/nets/densenet.py @@ -298,12 +298,7 @@ def __init__( progress: bool = True, **kwargs, ) -> None: - super().__init__( - init_features=init_features, - growth_rate=growth_rate, - block_config=block_config, - **kwargs, - ) + super().__init__(init_features=init_features, growth_rate=growth_rate, block_config=block_config, **kwargs) if pretrained: if kwargs["spatial_dims"] > 2: raise NotImplementedError( @@ -325,12 +320,7 @@ def __init__( progress: bool = True, **kwargs, ) -> None: - super().__init__( - init_features=init_features, - growth_rate=growth_rate, - block_config=block_config, - **kwargs, - ) + super().__init__(init_features=init_features, growth_rate=growth_rate, block_config=block_config, **kwargs) if pretrained: if kwargs["spatial_dims"] > 2: raise NotImplementedError( @@ -352,12 +342,7 @@ def __init__( progress: bool = True, **kwargs, ) -> None: - super().__init__( - init_features=init_features, - growth_rate=growth_rate, - block_config=block_config, - **kwargs, - ) + super().__init__(init_features=init_features, growth_rate=growth_rate, block_config=block_config, **kwargs) if pretrained: if kwargs["spatial_dims"] > 2: raise NotImplementedError( @@ -379,12 +364,7 @@ def __init__( progress: bool = True, **kwargs, ) -> None: - super().__init__( - init_features=init_features, - growth_rate=growth_rate, - block_config=block_config, - **kwargs, - ) + super().__init__(init_features=init_features, growth_rate=growth_rate, block_config=block_config, **kwargs) if pretrained: raise NotImplementedError("Currently PyTorch Hub does not provide densenet264 pretrained models.") diff --git a/monai/networks/nets/efficientnet.py b/monai/networks/nets/efficientnet.py index 7de7e4e521..6cd0e83e46 100644 --- a/monai/networks/nets/efficientnet.py +++ b/monai/networks/nets/efficientnet.py @@ -369,10 +369,7 @@ def __init__( ) idx += 1 # increment blocks index counter - self._blocks.add_module( - str(stack_idx), - sub_stack, - ) + self._blocks.add_module(str(stack_idx), sub_stack) # sanity check to see if len(self._blocks) equal expected num_blocks if idx != num_blocks: diff --git a/monai/networks/nets/netadapter.py b/monai/networks/nets/netadapter.py index 13da7698d3..8aaf83f24d 100644 --- a/monai/networks/nets/netadapter.py +++ b/monai/networks/nets/netadapter.py @@ -81,21 +81,12 @@ def __init__( self.fc: Union[torch.nn.Linear, torch.nn.Conv2d, torch.nn.Conv3d] if use_conv: # add 1x1 conv (it behaves like a FC layer) - self.fc = Conv[Conv.CONV, dim]( - in_channels=in_channels_, - out_channels=num_classes, - kernel_size=1, - bias=bias, - ) + self.fc = Conv[Conv.CONV, dim](in_channels=in_channels_, out_channels=num_classes, kernel_size=1, bias=bias) else: # remove the last Linear layer (fully connected) self.features = torch.nn.Sequential(*layers[:-1]) # replace the out_features of FC layer - self.fc = torch.nn.Linear( - in_features=in_channels_, - out_features=num_classes, - bias=bias, - ) + self.fc = torch.nn.Linear(in_features=in_channels_, out_features=num_classes, bias=bias) self.use_conv = use_conv def forward(self, x): diff --git a/monai/networks/nets/regunet.py b/monai/networks/nets/regunet.py index b800364c67..ead12382eb 100644 --- a/monai/networks/nets/regunet.py +++ b/monai/networks/nets/regunet.py @@ -106,9 +106,7 @@ def __init__( # build layers self.build_layers() - def build_layers( - self, - ): + def build_layers(self): self.build_encode_layers() self.build_decode_layers() @@ -125,23 +123,13 @@ def build_encode_layers(self): ] ) self.encode_pools = nn.ModuleList( - [ - self.build_down_sampling_block( - channels=self.num_channels[d], - ) - for d in range(self.depth) - ] + [self.build_down_sampling_block(channels=self.num_channels[d]) for d in range(self.depth)] ) self.bottom_block = self.build_bottom_block( in_channels=self.num_channels[-2], out_channels=self.num_channels[-1] ) - def build_conv_block( - self, - in_channels, - out_channels, - kernel_size, - ): + def build_conv_block(self, in_channels, out_channels, kernel_size): return nn.Sequential( get_conv_block( spatial_dims=self.spatial_dims, @@ -157,10 +145,7 @@ def build_conv_block( ), ) - def build_down_sampling_block( - self, - channels: int, - ): + def build_down_sampling_block(self, channels: int): return RegistrationDownSampleBlock(spatial_dims=self.spatial_dims, channels=channels, pooling=self.pooling) def build_bottom_block(self, in_channels: int, out_channels: int): @@ -203,11 +188,7 @@ def build_decode_layers(self): # extraction self.output_block = self.build_output_block() - def build_up_sampling_block( - self, - in_channels: int, - out_channels: int, - ) -> nn.Module: + def build_up_sampling_block(self, in_channels: int, out_channels: int) -> nn.Module: return get_deconv_block(spatial_dims=self.spatial_dims, in_channels=in_channels, out_channels=out_channels) def build_output_block(self) -> nn.Module: @@ -255,13 +236,7 @@ def forward(self, x): class AffineHead(nn.Module): - def __init__( - self, - spatial_dims: int, - image_size: List[int], - decode_size: List[int], - in_channels: int, - ): + def __init__(self, spatial_dims: int, image_size: List[int], decode_size: List[int], in_channels: int): super().__init__() self.spatial_dims = spatial_dims if spatial_dims == 2: @@ -365,12 +340,7 @@ def build_output_block(self): class AdditiveUpSampleBlock(nn.Module): - def __init__( - self, - spatial_dims: int, - in_channels: int, - out_channels: int, - ): + def __init__(self, spatial_dims: int, in_channels: int, out_channels: int): super().__init__() self.deconv = get_deconv_block(spatial_dims=spatial_dims, in_channels=in_channels, out_channels=out_channels) @@ -435,17 +405,10 @@ def __init__( def build_bottom_block(self, in_channels: int, out_channels: int): kernel_size = self.encode_kernel_sizes[self.depth] return get_conv_block( - spatial_dims=self.spatial_dims, - in_channels=in_channels, - out_channels=out_channels, - kernel_size=kernel_size, + spatial_dims=self.spatial_dims, in_channels=in_channels, out_channels=out_channels, kernel_size=kernel_size ) - def build_up_sampling_block( - self, - in_channels: int, - out_channels: int, - ) -> nn.Module: + def build_up_sampling_block(self, in_channels: int, out_channels: int) -> nn.Module: if self._use_additive_upsampling: return AdditiveUpSampleBlock( spatial_dims=self.spatial_dims, in_channels=in_channels, out_channels=out_channels diff --git a/monai/networks/nets/resnet.py b/monai/networks/nets/resnet.py index 1086a21e46..d859365203 100644 --- a/monai/networks/nets/resnet.py +++ b/monai/networks/nets/resnet.py @@ -276,11 +276,7 @@ def _make_layer( layers = [ block( - in_planes=self.in_planes, - planes=planes, - spatial_dims=spatial_dims, - stride=stride, - downsample=downsample, + in_planes=self.in_planes, planes=planes, spatial_dims=spatial_dims, stride=stride, downsample=downsample ) ] diff --git a/monai/networks/nets/segresnet.py b/monai/networks/nets/segresnet.py index 8604fb82ef..b722e5d70f 100644 --- a/monai/networks/nets/segresnet.py +++ b/monai/networks/nets/segresnet.py @@ -99,12 +99,7 @@ def __init__( def _make_down_layers(self): down_layers = nn.ModuleList() - blocks_down, spatial_dims, filters, norm = ( - self.blocks_down, - self.spatial_dims, - self.init_filters, - self.norm, - ) + blocks_down, spatial_dims, filters, norm = (self.blocks_down, self.spatial_dims, self.init_filters, self.norm) for i in range(len(blocks_down)): layer_in_channels = filters * 2 ** i pre_conv = ( @@ -113,8 +108,7 @@ def _make_down_layers(self): else nn.Identity() ) down_layer = nn.Sequential( - pre_conv, - *[ResBlock(spatial_dims, layer_in_channels, norm=norm) for _ in range(blocks_down[i])], + pre_conv, *[ResBlock(spatial_dims, layer_in_channels, norm=norm) for _ in range(blocks_down[i])] ) down_layers.append(down_layer) return down_layers diff --git a/monai/networks/nets/senet.py b/monai/networks/nets/senet.py index 37da7acc87..a58c2adb51 100644 --- a/monai/networks/nets/senet.py +++ b/monai/networks/nets/senet.py @@ -333,13 +333,7 @@ def __init__( progress: bool = True, **kwargs, ) -> None: - super().__init__( - block=SEBottleneck, - layers=layers, - groups=groups, - reduction=reduction, - **kwargs, - ) + super().__init__(block=SEBottleneck, layers=layers, groups=groups, reduction=reduction, **kwargs) if pretrained: # it only worked when `spatial_dims` is 2 _load_state_dict(self, "senet154", progress) diff --git a/monai/networks/nets/transchex.py b/monai/networks/nets/transchex.py index 2e161cc95f..3e57d868e9 100644 --- a/monai/networks/nets/transchex.py +++ b/monai/networks/nets/transchex.py @@ -27,15 +27,7 @@ BertEmbeddings = optional_import("transformers.models.bert.modeling_bert", name="BertEmbeddings")[0] BertLayer = optional_import("transformers.models.bert.modeling_bert", name="BertLayer")[0] -__all__ = [ - "BertPreTrainedModel", - "BertAttention", - "BertOutput", - "BertMixedLayer", - "Pooler", - "MultiModal", - "Transchex", -] +__all__ = ["BertPreTrainedModel", "BertAttention", "BertOutput", "BertMixedLayer", "Pooler", "MultiModal", "Transchex"] class BertPreTrainedModel(nn.Module): @@ -134,10 +126,7 @@ class BertAttention(nn.Module): https://github.com/huggingface/transformers """ - def __init__( - self, - config, - ) -> None: + def __init__(self, config) -> None: super().__init__() self.num_attention_heads = config.num_attention_heads self.attention_head_size = int(config.hidden_size / config.num_attention_heads) @@ -194,10 +183,7 @@ class BertMixedLayer(nn.Module): https://github.com/huggingface/transformers """ - def __init__( - self, - config, - ) -> None: + def __init__(self, config) -> None: super().__init__() self.att = BertAttention(config) self.output = BertOutput(config) @@ -213,10 +199,7 @@ class Pooler(nn.Module): https://github.com/huggingface/transformers """ - def __init__( - self, - hidden_size, - ) -> None: + def __init__(self, hidden_size) -> None: super().__init__() self.dense = nn.Linear(hidden_size, hidden_size) self.activation = nn.Tanh() @@ -234,11 +217,7 @@ class MultiModal(BertPreTrainedModel): """ def __init__( - self, - num_language_layers: int, - num_vision_layers: int, - num_mixed_layers: int, - bert_config: dict, # type: ignore + self, num_language_layers: int, num_vision_layers: int, num_mixed_layers: int, bert_config: dict # type: ignore ) -> None: """ Args: diff --git a/monai/optimizers/lr_finder.py b/monai/optimizers/lr_finder.py index 08395afb53..d1ab1b44e1 100644 --- a/monai/optimizers/lr_finder.py +++ b/monai/optimizers/lr_finder.py @@ -328,11 +328,7 @@ def range_test( print(f"Computing optimal learning rate, iteration {iteration + 1}/{num_iter}") # Train on batch and retrieve loss - loss = self._train_batch( - train_iter, - accumulation_steps, - non_blocking_transfer=non_blocking_transfer, - ) + loss = self._train_batch(train_iter, accumulation_steps, non_blocking_transfer=non_blocking_transfer) if val_loader: loss = self._validate(val_iter, non_blocking_transfer=non_blocking_transfer) @@ -429,11 +425,7 @@ def _validate(self, val_iter: ValDataLoaderIter, non_blocking_transfer: bool = T return running_loss / len(val_iter.dataset) - def get_lrs_and_losses( - self, - skip_start: int = 0, - skip_end: int = 0, - ) -> Tuple[list, list]: + def get_lrs_and_losses(self, skip_start: int = 0, skip_end: int = 0) -> Tuple[list, list]: """Get learning rates and their corresponding losses Args: @@ -454,9 +446,7 @@ def get_lrs_and_losses( return lrs, losses def get_steepest_gradient( - self, - skip_start: int = 0, - skip_end: int = 0, + self, skip_start: int = 0, skip_end: int = 0 ) -> Union[Tuple[float, float], Tuple[None, None]]: """Get learning rate which has steepest gradient and its corresponding loss @@ -476,14 +466,7 @@ def get_steepest_gradient( print("Failed to compute the gradients, there might not be enough points.") return None, None - def plot( - self, - skip_start: int = 0, - skip_end: int = 0, - log_lr: bool = True, - ax=None, - steepest_lr: bool = True, - ): + def plot(self, skip_start: int = 0, skip_end: int = 0, log_lr: bool = True, ax=None, steepest_lr: bool = True): """Plots the learning rate range test. Args: diff --git a/monai/optimizers/novograd.py b/monai/optimizers/novograd.py index 6ca011d9d4..6d14a055fb 100644 --- a/monai/optimizers/novograd.py +++ b/monai/optimizers/novograd.py @@ -55,12 +55,7 @@ def __init__( if 0.0 > weight_decay: raise ValueError(f"Invalid weight_decay value: {weight_decay}") defaults = dict( - lr=lr, - betas=betas, - eps=eps, - weight_decay=weight_decay, - grad_averaging=grad_averaging, - amsgrad=amsgrad, + lr=lr, betas=betas, eps=eps, weight_decay=weight_decay, grad_averaging=grad_averaging, amsgrad=amsgrad ) super().__init__(params, defaults) diff --git a/monai/transforms/croppad/array.py b/monai/transforms/croppad/array.py index e618fd1481..cc8dd677da 100644 --- a/monai/transforms/croppad/array.py +++ b/monai/transforms/croppad/array.py @@ -108,9 +108,7 @@ def _pt_pad(img: torch.Tensor, all_pad_width, mode, **kwargs) -> torch.Tensor: return pad_pt(img.unsqueeze(0), pt_pad_width, mode=mode, **kwargs).squeeze(0) def __call__( - self, - img: NdarrayOrTensor, - mode: Optional[Union[NumpyPadMode, PytorchPadMode, str]] = None, + self, img: NdarrayOrTensor, mode: Optional[Union[NumpyPadMode, PytorchPadMode, str]] = None ) -> NdarrayOrTensor: """ Args: @@ -186,9 +184,7 @@ def _determine_data_pad_width(self, data_shape: Sequence[int]) -> List[Tuple[int return [(0, max(sp_i - data_shape[i], 0)) for i, sp_i in enumerate(spatial_size)] def __call__( - self, - img: NdarrayOrTensor, - mode: Optional[Union[NumpyPadMode, PytorchPadMode, str]] = None, + self, img: NdarrayOrTensor, mode: Optional[Union[NumpyPadMode, PytorchPadMode, str]] = None ) -> NdarrayOrTensor: """ Args: @@ -251,9 +247,7 @@ def __init__( self.kwargs = kwargs def __call__( - self, - img: NdarrayOrTensor, - mode: Optional[Union[NumpyPadMode, PytorchPadMode, str]] = None, + self, img: NdarrayOrTensor, mode: Optional[Union[NumpyPadMode, PytorchPadMode, str]] = None ) -> NdarrayOrTensor: """ Args: @@ -333,9 +327,7 @@ def __init__( self.kwargs = kwargs def __call__( - self, - img: NdarrayOrTensor, - mode: Optional[Union[NumpyPadMode, PytorchPadMode, str]] = None, + self, img: NdarrayOrTensor, mode: Optional[Union[NumpyPadMode, PytorchPadMode, str]] = None ) -> NdarrayOrTensor: """ Args: @@ -350,12 +342,7 @@ def __call__( """ new_size = compute_divisible_spatial_size(spatial_shape=img.shape[1:], k=self.k) - spatial_pad = SpatialPad( - spatial_size=new_size, - method=self.method, - mode=mode or self.mode, - **self.kwargs, - ) + spatial_pad = SpatialPad(spatial_size=new_size, method=self.method, mode=mode or self.mode, **self.kwargs) return spatial_pad(img) @@ -407,25 +394,18 @@ def __init__( else: if roi_center is not None and roi_size is not None: roi_center, *_ = convert_data_type( - data=roi_center, - output_type=torch.Tensor, - dtype=torch.int16, - wrap_sequence=True, + data=roi_center, output_type=torch.Tensor, dtype=torch.int16, wrap_sequence=True ) roi_size, *_ = convert_to_dst_type(src=roi_size, dst=roi_center, wrap_sequence=True) roi_start_torch = maximum( - roi_center - floor_divide(roi_size, 2), - torch.zeros_like(roi_center), # type: ignore + roi_center - floor_divide(roi_size, 2), torch.zeros_like(roi_center) # type: ignore ) roi_end_torch = maximum(roi_start_torch + roi_size, roi_start_torch) else: if roi_start is None or roi_end is None: raise ValueError("Please specify either roi_center, roi_size or roi_start, roi_end.") roi_start_torch, *_ = convert_data_type( # type: ignore - data=roi_start, - output_type=torch.Tensor, - dtype=torch.int16, - wrap_sequence=True, + data=roi_start, output_type=torch.Tensor, dtype=torch.int16, wrap_sequence=True ) roi_start_torch = maximum(roi_start_torch, torch.zeros_like(roi_start_torch)) # type: ignore roi_end_torch, *_ = convert_to_dst_type(src=roi_end, dst=roi_start_torch, wrap_sequence=True) diff --git a/monai/transforms/croppad/batch.py b/monai/transforms/croppad/batch.py index 956dff7881..42178ec0bc 100644 --- a/monai/transforms/croppad/batch.py +++ b/monai/transforms/croppad/batch.py @@ -26,9 +26,7 @@ from monai.transforms.utility.array import ToTensor from monai.utils.enums import InverseKeys, Method, NumpyPadMode -__all__ = [ - "PadListDataCollate", -] +__all__ = ["PadListDataCollate"] def replace_element(to_replace, batch, idx, key_or_idx): diff --git a/monai/transforms/croppad/dictionary.py b/monai/transforms/croppad/dictionary.py index d44ab3a8d4..b98973d14e 100644 --- a/monai/transforms/croppad/dictionary.py +++ b/monai/transforms/croppad/dictionary.py @@ -855,11 +855,7 @@ def __init__( self.start_coord_key = start_coord_key self.end_coord_key = end_coord_key self.cropper = CropForeground( - select_fn=select_fn, - channel_indices=channel_indices, - margin=margin, - k_divisible=k_divisible, - **np_kwargs, + select_fn=select_fn, channel_indices=channel_indices, margin=margin, k_divisible=k_divisible, **np_kwargs ) self.mode = ensure_tuple_rep(mode, len(self.keys)) @@ -1425,14 +1421,7 @@ def __call__(self, data: Mapping[Hashable, NdarrayOrTensor]) -> Dict[Hashable, N for key, m in self.key_iterator(d, self.mode): orig_size = d[key].shape[1:] d[key] = self.padcropper(d[key], mode=m) - self.push_transform( - d, - key, - orig_size=orig_size, - extra_info={ - "mode": m.value if isinstance(m, Enum) else m, - }, - ) + self.push_transform(d, key, orig_size=orig_size, extra_info={"mode": m.value if isinstance(m, Enum) else m}) return d def inverse(self, data: Mapping[Hashable, NdarrayOrTensor]) -> Dict[Hashable, NdarrayOrTensor]: diff --git a/monai/transforms/intensity/array.py b/monai/transforms/intensity/array.py index c08b61d490..1f131353d2 100644 --- a/monai/transforms/intensity/array.py +++ b/monai/transforms/intensity/array.py @@ -259,12 +259,7 @@ def randomize(self, data: Optional[Any] = None) -> None: return None self._offset = self.R.uniform(low=self.offsets[0], high=self.offsets[1]) - def __call__( - self, - img: NdarrayOrTensor, - factor: Optional[float] = None, - randomize: bool = True, - ) -> NdarrayOrTensor: + def __call__(self, img: NdarrayOrTensor, factor: Optional[float] = None, randomize: bool = True) -> NdarrayOrTensor: """ Apply the transform to `img`. @@ -441,8 +436,7 @@ def __call__(self, img: NdarrayOrTensor) -> NdarrayOrTensor: if self.channel_wise: out = [rescale_array(d, self.minv, self.maxv, dtype=self.dtype) for d in img] return torch.stack(out) if isinstance(img, torch.Tensor) else np.stack(out) # type: ignore - else: - return rescale_array(img, self.minv, self.maxv, dtype=self.dtype) + return rescale_array(img, self.minv, self.maxv, dtype=self.dtype) if self.factor is not None: ret = img * (1 + self.factor) ret, *_ = convert_data_type(ret, dtype=self.dtype) @@ -459,10 +453,7 @@ class RandScaleIntensity(RandomizableTransform): backend = ScaleIntensity.backend def __init__( - self, - factors: Union[Tuple[float, float], float], - prob: float = 0.1, - dtype: DtypeLike = np.float32, + self, factors: Union[Tuple[float, float], float], prob: float = 0.1, dtype: DtypeLike = np.float32 ) -> None: """ Args: @@ -1885,11 +1876,7 @@ def __init__( prob: float = 0.1, ) -> None: super().__init__( - holes=holes, - spatial_size=spatial_size, - max_holes=max_holes, - max_spatial_size=max_spatial_size, - prob=prob, + holes=holes, spatial_size=spatial_size, max_holes=max_holes, max_spatial_size=max_spatial_size, prob=prob ) self.dropout_holes = dropout_holes if isinstance(fill_value, (tuple, list)): diff --git a/monai/transforms/intensity/dictionary.py b/monai/transforms/intensity/dictionary.py index 980674adb8..736ead26c4 100644 --- a/monai/transforms/intensity/dictionary.py +++ b/monai/transforms/intensity/dictionary.py @@ -233,12 +233,7 @@ def __init__( MapTransform.__init__(self, keys, allow_missing_keys) RandomizableTransform.__init__(self, global_prob) self.rand_rician_noise = RandRicianNoise( - prob=1.0, - mean=mean, - std=std, - channel_wise=channel_wise, - relative=relative, - sample_std=sample_std, + prob=1.0, mean=mean, std=std, channel_wise=channel_wise, relative=relative, sample_std=sample_std ) def set_random_state( @@ -460,11 +455,7 @@ def __init__( MapTransform.__init__(self, keys, allow_missing_keys) RandomizableTransform.__init__(self, prob) self.shifter = RandStdShiftIntensity( - factors=factors, - nonzero=nonzero, - channel_wise=channel_wise, - dtype=dtype, - prob=1.0, + factors=factors, nonzero=nonzero, channel_wise=channel_wise, dtype=dtype, prob=1.0 ) def set_random_state( @@ -966,11 +957,7 @@ def __init__( MapTransform.__init__(self, keys, allow_missing_keys) RandomizableTransform.__init__(self, prob) self.rand_smooth = RandGaussianSmooth( - sigma_x=sigma_x, - sigma_y=sigma_y, - sigma_z=sigma_z, - approx=approx, - prob=1.0, + sigma_x=sigma_x, sigma_y=sigma_y, sigma_z=sigma_z, approx=approx, prob=1.0 ) def set_random_state( @@ -1519,11 +1506,7 @@ def __init__( MapTransform.__init__(self, keys, allow_missing_keys) RandomizableTransform.__init__(self, prob=prob) self.shuffle = RandCoarseShuffle( - holes=holes, - spatial_size=spatial_size, - max_holes=max_holes, - max_spatial_size=max_spatial_size, - prob=1.0, + holes=holes, spatial_size=spatial_size, max_holes=max_holes, max_spatial_size=max_spatial_size, prob=1.0 ) def set_random_state( diff --git a/monai/transforms/inverse.py b/monai/transforms/inverse.py index 58f3526086..57a443241b 100644 --- a/monai/transforms/inverse.py +++ b/monai/transforms/inverse.py @@ -64,18 +64,11 @@ class InvertibleTransform(Transform): """ def push_transform( - self, - data: dict, - key: Hashable, - extra_info: Optional[dict] = None, - orig_size: Optional[Tuple] = None, + self, data: dict, key: Hashable, extra_info: Optional[dict] = None, orig_size: Optional[Tuple] = None ) -> None: """Append to list of applied transforms for that key.""" key_transform = str(key) + InverseKeys.KEY_SUFFIX - info = { - InverseKeys.CLASS_NAME: self.__class__.__name__, - InverseKeys.ID: id(self), - } + info = {InverseKeys.CLASS_NAME: self.__class__.__name__, InverseKeys.ID: id(self)} if orig_size is not None: info[InverseKeys.ORIG_SIZE] = orig_size elif hasattr(data[key], "shape"): diff --git a/monai/transforms/inverse_batch_transform.py b/monai/transforms/inverse_batch_transform.py index b485e5bac4..e220d5f350 100644 --- a/monai/transforms/inverse_batch_transform.py +++ b/monai/transforms/inverse_batch_transform.py @@ -27,12 +27,7 @@ class _BatchInverseDataset(Dataset): - def __init__( - self, - data: Sequence[Any], - transform: InvertibleTransform, - pad_collation_used: bool, - ) -> None: + def __init__(self, data: Sequence[Any], transform: InvertibleTransform, pad_collation_used: bool) -> None: self.data = data self.invertible_transform = transform self.pad_collation_used = pad_collation_used @@ -119,10 +114,7 @@ class Decollated(MapTransform): """ def __init__( - self, - keys: Optional[KeysCollection] = None, - detach: bool = True, - allow_missing_keys: bool = False, + self, keys: Optional[KeysCollection] = None, detach: bool = True, allow_missing_keys: bool = False ) -> None: super().__init__(keys, allow_missing_keys) self.detach = detach diff --git a/monai/transforms/io/dictionary.py b/monai/transforms/io/dictionary.py index 764e20f838..f714dd2831 100644 --- a/monai/transforms/io/dictionary.py +++ b/monai/transforms/io/dictionary.py @@ -26,14 +26,7 @@ from monai.transforms.transform import MapTransform from monai.utils import GridSampleMode, GridSamplePadMode, InterpolateMode, ensure_tuple, ensure_tuple_rep -__all__ = [ - "LoadImaged", - "LoadImageD", - "LoadImageDict", - "SaveImaged", - "SaveImageD", - "SaveImageDict", -] +__all__ = ["LoadImaged", "LoadImageD", "LoadImageDict", "SaveImaged", "SaveImageD", "SaveImageDict"] class LoadImaged(MapTransform): diff --git a/monai/transforms/post/array.py b/monai/transforms/post/array.py index eb1860eed1..f0648f6a83 100644 --- a/monai/transforms/post/array.py +++ b/monai/transforms/post/array.py @@ -647,10 +647,7 @@ def __init__( self.box_lower_bd = self.box_size // 2 self.box_upper_bd = self.box_size - self.box_lower_bd - def __call__( - self, - prob_map: Union[np.ndarray, torch.Tensor], - ): + def __call__(self, prob_map: Union[np.ndarray, torch.Tensor]): """ prob_map: the input probabilities map, it must have shape (H[, W, ...]). """ diff --git a/monai/transforms/post/dictionary.py b/monai/transforms/post/dictionary.py index 4ca07da949..a3ebbb6cbe 100644 --- a/monai/transforms/post/dictionary.py +++ b/monai/transforms/post/dictionary.py @@ -183,15 +183,7 @@ def __call__(self, data: Mapping[Hashable, torch.Tensor]) -> Dict[Hashable, torc for key, argmax, to_onehot, num_classes, threshold_values, logit_thresh, rounding in self.key_iterator( d, self.argmax, self.to_onehot, self.num_classes, self.threshold_values, self.logit_thresh, self.rounding ): - d[key] = self.converter( - d[key], - argmax, - to_onehot, - num_classes, - threshold_values, - logit_thresh, - rounding, - ) + d[key] = self.converter(d[key], argmax, to_onehot, num_classes, threshold_values, logit_thresh, rounding) return d @@ -240,10 +232,7 @@ class LabelFilterd(MapTransform): """ def __init__( - self, - keys: KeysCollection, - applied_labels: Union[Sequence[int], int], - allow_missing_keys: bool = False, + self, keys: KeysCollection, applied_labels: Union[Sequence[int], int], allow_missing_keys: bool = False ) -> None: """ Args: @@ -466,10 +455,7 @@ def __init__( ) -> None: super().__init__(keys, allow_missing_keys) self.prob_nms = ProbNMS( - spatial_dims=spatial_dims, - sigma=sigma, - prob_threshold=prob_threshold, - box_size=box_size, + spatial_dims=spatial_dims, sigma=sigma, prob_threshold=prob_threshold, box_size=box_size ) def __call__(self, data: Mapping[Hashable, Union[np.ndarray, torch.Tensor]]): @@ -604,19 +590,14 @@ def __call__(self, data: Mapping[Hashable, Any]) -> Dict[Hashable, Any]: transform_info = d[transform_key] if nearest_interp: transform_info = convert_inverse_interp_mode( - trans_info=deepcopy(transform_info), - mode="nearest", - align_corners=None, + trans_info=deepcopy(transform_info), mode="nearest", align_corners=None ) input = d[key] if isinstance(input, torch.Tensor): input = input.detach() # construct the input dict data for BatchInverseTransform - input_dict = { - orig_key: input, - transform_key: transform_info, - } + input_dict = {orig_key: input, transform_key: transform_info} orig_meta_key = orig_meta_key or f"{orig_key}_{meta_key_postfix}" meta_key = meta_key or f"{key}_{meta_key_postfix}" if orig_meta_key in d: diff --git a/monai/transforms/spatial/array.py b/monai/transforms/spatial/array.py index 4e3f513864..8c7255f632 100644 --- a/monai/transforms/spatial/array.py +++ b/monai/transforms/spatial/array.py @@ -1098,9 +1098,7 @@ def __init__( self.affine = affine def __call__( - self, - spatial_size: Optional[Sequence[int]] = None, - grid: Optional[NdarrayOrTensor] = None, + self, spatial_size: Optional[Sequence[int]] = None, grid: Optional[NdarrayOrTensor] = None ) -> Tuple[NdarrayOrTensor, NdarrayOrTensor]: """ The grid can be initialized with a `spatial_size` parameter, or provided directly as `grid`. @@ -1234,9 +1232,7 @@ def randomize(self, data: Optional[Any] = None) -> None: self.scale_params = self._get_rand_param(self.scale_range, 1.0) def __call__( - self, - spatial_size: Optional[Sequence[int]] = None, - grid: Optional[NdarrayOrTensor] = None, + self, spatial_size: Optional[Sequence[int]] = None, grid: Optional[NdarrayOrTensor] = None ) -> NdarrayOrTensor: """ Args: @@ -2027,10 +2023,7 @@ class AddCoordinateChannels(Transform): backend = [TransformBackends.TORCH, TransformBackends.NUMPY] - def __init__( - self, - spatial_channels: Sequence[int], - ) -> None: + def __init__(self, spatial_channels: Sequence[int]) -> None: """ Args: spatial_channels: the spatial dimensions that are to have their coordinates encoded in a channel and @@ -2187,11 +2180,7 @@ def __init__( self.distort_limit = (min(distort_limit), max(distort_limit)) self.distort_steps: Sequence[Sequence[float]] = ((1.0,),) self.grid_distortion = GridDistortion( - num_cells=num_cells, - distort_steps=self.distort_steps, - mode=mode, - padding_mode=padding_mode, - device=device, + num_cells=num_cells, distort_steps=self.distort_steps, mode=mode, padding_mode=padding_mode, device=device ) def randomize(self, spatial_shape: Sequence[int]) -> None: diff --git a/monai/transforms/spatial/dictionary.py b/monai/transforms/spatial/dictionary.py index b0a5b6b608..df48b1416c 100644 --- a/monai/transforms/spatial/dictionary.py +++ b/monai/transforms/spatial/dictionary.py @@ -381,9 +381,7 @@ def inverse(self, data: Mapping[Hashable, np.ndarray]) -> Dict[Hashable, np.ndar orig_affine = transform[InverseKeys.EXTRA_INFO]["old_affine"] orig_axcodes = nib.orientations.aff2axcodes(orig_affine) inverse_transform = Orientation( - axcodes=orig_axcodes, - as_closest_canonical=False, - labels=self.ornt_transform.labels, + axcodes=orig_axcodes, as_closest_canonical=False, labels=self.ornt_transform.labels ) # Apply inverse d[key], _, new_affine = inverse_transform(d[key], affine=meta_data["affine"]) @@ -576,9 +574,7 @@ def inverse(self, data: Mapping[Hashable, NdarrayOrTensor]) -> Dict[Hashable, Nd align_corners = transform[InverseKeys.EXTRA_INFO]["align_corners"] # Create inverse transform inverse_transform = Resize( - spatial_size=orig_size, - mode=mode, - align_corners=None if align_corners == "none" else align_corners, + spatial_size=orig_size, mode=mode, align_corners=None if align_corners == "none" else align_corners ) # Apply inverse transform d[key] = inverse_transform(d[key]) @@ -1336,11 +1332,7 @@ def __call__(self, data: Mapping[Hashable, NdarrayOrTensor]) -> Dict[Hashable, N ): orig_size = d[key].shape[1:] d[key] = self.rotator( - d[key], - mode=mode, - padding_mode=padding_mode, - align_corners=align_corners, - dtype=dtype, + d[key], mode=mode, padding_mode=padding_mode, align_corners=align_corners, dtype=dtype ) rot_mat = self.rotator.get_rotation_matrix() self.push_transform( @@ -1379,11 +1371,7 @@ def inverse(self, data: Mapping[Hashable, NdarrayOrTensor]) -> Dict[Hashable, Nd transform_t: torch.Tensor transform_t, *_ = convert_to_dst_type(inv_rot_mat, img_t) # type: ignore - output = xform( - img_t.unsqueeze(0), - transform_t, - spatial_size=transform[InverseKeys.ORIG_SIZE], - ) + output = xform(img_t.unsqueeze(0), transform_t, spatial_size=transform[InverseKeys.ORIG_SIZE]) d[key] = output.squeeze(0).detach().float() # Remove the applied transform self.pop_transform(d, key) @@ -1516,11 +1504,7 @@ def inverse(self, data: Mapping[Hashable, NdarrayOrTensor]) -> Dict[Hashable, Nd transform_t: torch.Tensor transform_t, *_ = convert_to_dst_type(inv_rot_mat, img_t) # type: ignore output: torch.Tensor - output = xform( - img_t.unsqueeze(0), - transform_t, - spatial_size=transform[InverseKeys.ORIG_SIZE], - ) + output = xform(img_t.unsqueeze(0), transform_t, spatial_size=transform[InverseKeys.ORIG_SIZE]) d[key] = output.squeeze(0).detach().float() # Remove the applied transform self.pop_transform(d, key) @@ -1592,12 +1576,7 @@ def __call__(self, data: Mapping[Hashable, NdarrayOrTensor]) -> Dict[Hashable, N "align_corners": align_corners if align_corners is not None else "none", }, ) - d[key] = self.zoomer( - d[key], - mode=mode, - padding_mode=padding_mode, - align_corners=align_corners, - ) + d[key] = self.zoomer(d[key], mode=mode, padding_mode=padding_mode, align_corners=align_corners) return d def inverse(self, data: Mapping[Hashable, NdarrayOrTensor]) -> Dict[Hashable, NdarrayOrTensor]: @@ -1704,11 +1683,7 @@ def __call__(self, data: Mapping[Hashable, NdarrayOrTensor]) -> Dict[Hashable, N ): if self._do_transform: d[key] = self.rand_zoom( - d[key], - mode=mode, - padding_mode=padding_mode, - align_corners=align_corners, - randomize=False, + d[key], mode=mode, padding_mode=padding_mode, align_corners=align_corners, randomize=False ) self.push_transform( d, @@ -1814,11 +1789,7 @@ def __init__( """ super().__init__(keys, allow_missing_keys) - self.grid_distortion = GridDistortion( - num_cells=num_cells, - distort_steps=distort_steps, - device=device, - ) + self.grid_distortion = GridDistortion(num_cells=num_cells, distort_steps=distort_steps, device=device) self.mode = ensure_tuple_rep(mode, len(self.keys)) self.padding_mode = ensure_tuple_rep(padding_mode, len(self.keys)) @@ -1870,10 +1841,7 @@ def __init__( MapTransform.__init__(self, keys, allow_missing_keys) RandomizableTransform.__init__(self, prob) self.rand_grid_distortion = RandGridDistortion( - num_cells=num_cells, - prob=1.0, - distort_limit=distort_limit, - device=device, + num_cells=num_cells, prob=1.0, distort_limit=distort_limit, device=device ) self.mode = ensure_tuple_rep(mode, len(self.keys)) self.padding_mode = ensure_tuple_rep(padding_mode, len(self.keys)) diff --git a/monai/transforms/transform.py b/monai/transforms/transform.py index ef49bc706c..3ea2fda136 100644 --- a/monai/transforms/transform.py +++ b/monai/transforms/transform.py @@ -24,14 +24,7 @@ from monai.utils import MAX_SEED, ensure_tuple from monai.utils.enums import TransformBackends -__all__ = [ - "ThreadUnsafe", - "apply_transform", - "Randomizable", - "RandomizableTransform", - "Transform", - "MapTransform", -] +__all__ = ["ThreadUnsafe", "apply_transform", "Randomizable", "RandomizableTransform", "Transform", "MapTransform"] ReturnType = TypeVar("ReturnType") @@ -61,10 +54,7 @@ def _apply_transform( def apply_transform( - transform: Callable[..., ReturnType], - data: Any, - map_items: bool = True, - unpack_items: bool = False, + transform: Callable[..., ReturnType], data: Any, map_items: bool = True, unpack_items: bool = False ) -> Union[List[ReturnType], ReturnType]: """ Transform `data` with `transform`. @@ -355,11 +345,7 @@ def __call__(self, data): """ raise NotImplementedError(f"Subclass {self.__class__.__name__} must implement this method.") - def key_iterator( - self, - data: Dict[Hashable, Any], - *extra_iterables: Optional[Iterable], - ) -> Generator: + def key_iterator(self, data: Dict[Hashable, Any], *extra_iterables: Optional[Iterable]) -> Generator: """ Iterate across keys and optionally extra iterables. If key is missing, exception is raised if `allow_missing_keys==False` (default). If `allow_missing_keys==True`, key is skipped. diff --git a/monai/transforms/utility/array.py b/monai/transforms/utility/array.py index 28ca813b1c..3366f17653 100644 --- a/monai/transforms/utility/array.py +++ b/monai/transforms/utility/array.py @@ -728,9 +728,7 @@ class LabelToMask(Transform): backend = [TransformBackends.TORCH, TransformBackends.NUMPY] def __init__( # pytype: disable=annotation-type-mismatch - self, - select_labels: Union[Sequence[int], int], - merge_channels: bool = False, + self, select_labels: Union[Sequence[int], int], merge_channels: bool = False ) -> None: # pytype: disable=annotation-type-mismatch self.select_labels = ensure_tuple(select_labels) self.merge_channels = merge_channels @@ -1058,10 +1056,7 @@ def __init__(self, ops: Sequence[Union[str, Callable]], key_prefix: str, channel self.channel_wise = channel_wise def __call__( - self, - img: np.ndarray, - meta_data: Optional[Dict] = None, - mask: Optional[np.ndarray] = None, + self, img: np.ndarray, meta_data: Optional[Dict] = None, mask: Optional[np.ndarray] = None ) -> Tuple[np.ndarray, Dict]: """ Compute statistics for the intensity of input image. diff --git a/monai/transforms/utility/dictionary.py b/monai/transforms/utility/dictionary.py index 0db3aeded2..84ff98abf6 100644 --- a/monai/transforms/utility/dictionary.py +++ b/monai/transforms/utility/dictionary.py @@ -550,10 +550,7 @@ class ToNumpyd(MapTransform): backend = ToNumpy.backend def __init__( - self, - keys: KeysCollection, - dtype: Optional[DtypeLike] = None, - allow_missing_keys: bool = False, + self, keys: KeysCollection, dtype: Optional[DtypeLike] = None, allow_missing_keys: bool = False ) -> None: """ Args: @@ -663,12 +660,7 @@ class DeleteItemsd(MapTransform): It will remove the key-values and copy the others to construct a new dictionary. """ - def __init__( - self, - keys: KeysCollection, - sep: str = ".", - use_re: Union[Sequence[bool], bool] = False, - ) -> None: + def __init__(self, keys: KeysCollection, sep: str = ".", use_re: Union[Sequence[bool], bool] = False) -> None: """ Args: keys: keys of the corresponding items to delete, can be "A{sep}B{sep}C" @@ -790,15 +782,7 @@ def __call__(self, data: Mapping[Hashable, NdarrayOrTensor]) -> Dict[Hashable, N for key, prefix, data_type, data_shape, value_range, data_value, additional_info in self.key_iterator( d, self.prefix, self.data_type, self.data_shape, self.value_range, self.data_value, self.additional_info ): - d[key] = self.printer( - d[key], - prefix, - data_type, - data_shape, - value_range, - data_value, - additional_info, - ) + d[key] = self.printer(d[key], prefix, data_type, data_shape, value_range, data_value, additional_info) return d @@ -1292,14 +1276,7 @@ class TorchVisiond(MapTransform): data to be dict of PyTorch Tensors, users can easily call `ToTensord` transform to convert Numpy to Tensor. """ - def __init__( - self, - keys: KeysCollection, - name: str, - allow_missing_keys: bool = False, - *args, - **kwargs, - ) -> None: + def __init__(self, keys: KeysCollection, name: str, allow_missing_keys: bool = False, *args, **kwargs) -> None: """ Args: keys: keys of the corresponding items to be transformed. @@ -1336,14 +1313,7 @@ class RandTorchVisiond(Randomizable, MapTransform): """ - def __init__( - self, - keys: KeysCollection, - name: str, - allow_missing_keys: bool = False, - *args, - **kwargs, - ) -> None: + def __init__(self, keys: KeysCollection, name: str, allow_missing_keys: bool = False, *args, **kwargs) -> None: """ Args: keys: keys of the corresponding items to be transformed. @@ -1458,9 +1428,7 @@ def __call__(self, data) -> Dict[Hashable, np.ndarray]: ): meta_key = meta_key or f"{key}_{meta_key_postfix}" d[key], d[meta_key] = self.stats( - img=d[key], - meta_data=d.get(meta_key), - mask=d.get(mask_key) if mask_key is not None else None, + img=d[key], meta_data=d.get(meta_key), mask=d.get(mask_key) if mask_key is not None else None ) return d @@ -1473,11 +1441,7 @@ class ToDeviced(MapTransform): backend = [TransformBackends.TORCH] def __init__( - self, - keys: KeysCollection, - device: Union[torch.device, str], - allow_missing_keys: bool = False, - **kwargs, + self, keys: KeysCollection, device: Union[torch.device, str], allow_missing_keys: bool = False, **kwargs ) -> None: """ Args: @@ -1516,14 +1480,7 @@ class CuCIMd(MapTransform): Users can call `ToCuPy` transform to convert a numpy array or torch tensor to cupy array. """ - def __init__( - self, - keys: KeysCollection, - name: str, - allow_missing_keys: bool = False, - *args, - **kwargs, - ) -> None: + def __init__(self, keys: KeysCollection, name: str, allow_missing_keys: bool = False, *args, **kwargs) -> None: super().__init__(keys=keys, allow_missing_keys=allow_missing_keys) self.trans = CuCIM(name, *args, **kwargs) @@ -1567,12 +1524,7 @@ class RandCuCIMd(CuCIMd, RandomizableTransform): the results may not be deterministic. See Also: :py:class:`monai.transforms.Randomizable`. """ - def __init__( - self, - apply_prob: float = 1.0, - *args, - **kwargs, - ) -> None: + def __init__(self, apply_prob: float = 1.0, *args, **kwargs) -> None: CuCIMd.__init__(self, *args, **kwargs) RandomizableTransform.__init__(self, prob=apply_prob) diff --git a/monai/transforms/utils.py b/monai/transforms/utils.py index 17dd873b16..68f96b13f5 100644 --- a/monai/transforms/utils.py +++ b/monai/transforms/utils.py @@ -189,11 +189,7 @@ def rescale_array_int_max(arr: np.ndarray, dtype: DtypeLike = np.uint16) -> np.n def copypaste_arrays( - src_shape, - dest_shape, - srccenter: Sequence[int], - destcenter: Sequence[int], - dims: Sequence[Optional[int]], + src_shape, dest_shape, srccenter: Sequence[int], destcenter: Sequence[int], dims: Sequence[Optional[int]] ) -> Tuple[Tuple[slice, ...], Tuple[slice, ...]]: """ Calculate the slices to copy a sliced area of array in `src_shape` into array in `dest_shape`. @@ -270,9 +266,7 @@ def resize_center(img: np.ndarray, *resize_dims: Optional[int], fill_value: floa def map_binary_to_indices( - label: NdarrayOrTensor, - image: Optional[NdarrayOrTensor] = None, - image_threshold: float = 0.0, + label: NdarrayOrTensor, image: Optional[NdarrayOrTensor] = None, image_threshold: float = 0.0 ) -> Tuple[NdarrayOrTensor, NdarrayOrTensor]: """ Compute the foreground and background of input label data, return the indices after fattening. @@ -1100,9 +1094,7 @@ def extreme_points_to_image( def map_spatial_axes( - img_ndim: int, - spatial_axes: Optional[Union[Sequence[int], int]] = None, - channel_first: bool = True, + img_ndim: int, spatial_axes: Optional[Union[Sequence[int], int]] = None, channel_first: bool = True ) -> List[int]: """ Utility to map the spatial axes to real axes in channel first/last shape. @@ -1437,10 +1429,7 @@ def get_transform_backends(): "Transform", ] ): - backends[n] = [ - TransformBackends.TORCH in obj.backend, - TransformBackends.NUMPY in obj.backend, - ] + backends[n] = [TransformBackends.TORCH in obj.backend, TransformBackends.NUMPY in obj.backend] return backends diff --git a/monai/transforms/utils_create_transform_ims.py b/monai/transforms/utils_create_transform_ims.py index dca9615fbf..22e3d5f2d2 100644 --- a/monai/transforms/utils_create_transform_ims.py +++ b/monai/transforms/utils_create_transform_ims.py @@ -190,12 +190,7 @@ def get_data(keys): data = {CommonKeys.IMAGE: image, CommonKeys.LABEL: label} transforms = Compose( - [ - LoadImaged(keys), - AddChanneld(keys), - ScaleIntensityd(CommonKeys.IMAGE), - Rotate90d(keys, spatial_axes=[0, 2]), - ] + [LoadImaged(keys), AddChanneld(keys), ScaleIntensityd(CommonKeys.IMAGE), Rotate90d(keys, spatial_axes=[0, 2])] ) data = transforms(data) max_size = max(data[keys[0]].shape) diff --git a/monai/transforms/utils_pytorch_numpy_unification.py b/monai/transforms/utils_pytorch_numpy_unification.py index 72d1949b16..32da80152e 100644 --- a/monai/transforms/utils_pytorch_numpy_unification.py +++ b/monai/transforms/utils_pytorch_numpy_unification.py @@ -271,38 +271,32 @@ def concatenate(to_cat: Sequence[NdarrayOrTensor], axis: int = 0, out=None) -> N """`np.concatenate` with equivalent implementation for torch (`torch.cat`).""" if isinstance(to_cat[0], np.ndarray): return np.concatenate(to_cat, axis, out) # type: ignore - else: - return torch.cat(to_cat, dim=axis, out=out) # type: ignore + return torch.cat(to_cat, dim=axis, out=out) # type: ignore def cumsum(a: NdarrayOrTensor, axis=None): """`np.cumsum` with equivalent implementation for torch.""" if isinstance(a, np.ndarray): return np.cumsum(a, axis) - else: - if axis is None: - return torch.cumsum(a[:], 0) - else: - return torch.cumsum(a, dim=axis) + if axis is None: + return torch.cumsum(a[:], 0) + return torch.cumsum(a, dim=axis) def isfinite(x): """`np.isfinite` with equivalent implementation for torch.""" if not isinstance(x, torch.Tensor): return np.isfinite(x) - else: - return torch.isfinite(x) + return torch.isfinite(x) def searchsorted(a: NdarrayOrTensor, v: NdarrayOrTensor, right=False, sorter=None): side = "right" if right else "left" if isinstance(a, np.ndarray): return np.searchsorted(a, v, side, sorter) # type: ignore - else: - if hasattr(torch, "searchsorted"): - return torch.searchsorted(a, v, right=right) # type: ignore - else: - # if using old PyTorch, will convert to numpy array then compute - ret = np.searchsorted(a.cpu().numpy(), v.cpu().numpy(), side, sorter) # type: ignore - ret, *_ = convert_to_dst_type(ret, a) - return ret + if hasattr(torch, "searchsorted"): + return torch.searchsorted(a, v, right=right) # type: ignore + # if using old PyTorch, will convert to numpy array then compute + ret = np.searchsorted(a.cpu().numpy(), v.cpu().numpy(), side, sorter) # type: ignore + ret, *_ = convert_to_dst_type(ret, a) + return ret diff --git a/monai/utils/misc.py b/monai/utils/misc.py index a31452f6ae..20466fb91d 100644 --- a/monai/utils/misc.py +++ b/monai/utils/misc.py @@ -302,10 +302,7 @@ def _parse_var(s): def copy_to_device( - obj: Any, - device: Optional[Union[str, torch.device]], - non_blocking: bool = True, - verbose: bool = False, + obj: Any, device: Optional[Union[str, torch.device]], non_blocking: bool = True, verbose: bool = False ) -> Any: """ Copy object or tuple/list/dictionary of objects to ``device``. diff --git a/monai/utils/module.py b/monai/utils/module.py index ef019a8955..130b89493e 100644 --- a/monai/utils/module.py +++ b/monai/utils/module.py @@ -136,9 +136,7 @@ def damerau_levenshtein_distance(s1: str, s2: str): for j, s2j in enumerate(s2): cost = 0 if s1i == s2j else 1 d[(i, j)] = min( - d[(i - 1, j)] + 1, # deletion - d[(i, j - 1)] + 1, # insertion - d[(i - 1, j - 1)] + cost, # substitution + d[(i - 1, j)] + 1, d[(i, j - 1)] + 1, d[(i - 1, j - 1)] + cost # deletion # insertion # substitution ) if i and j and s1i == s2[j - 1] and s1[i - 1] == s2j: d[(i, j)] = min(d[(i, j)], d[i - 2, j - 2] + cost) # transposition diff --git a/monai/utils/state_cacher.py b/monai/utils/state_cacher.py index 94943a8c37..35ac72916e 100644 --- a/monai/utils/state_cacher.py +++ b/monai/utils/state_cacher.py @@ -34,12 +34,7 @@ class StateCacher: >>> model.load_state_dict(state_cacher.retrieve("model")) """ - def __init__( - self, - in_memory: bool, - cache_dir: Optional[str] = None, - allow_overwrite: bool = True, - ) -> None: + def __init__(self, in_memory: bool, cache_dir: Optional[str] = None, allow_overwrite: bool = True) -> None: """Constructor. Args: diff --git a/monai/utils/type_conversion.py b/monai/utils/type_conversion.py index eded35c076..b7f067076c 100644 --- a/monai/utils/type_conversion.py +++ b/monai/utils/type_conversion.py @@ -89,10 +89,7 @@ def get_dtype(data: Any): def convert_to_tensor( - data, - dtype: Optional[torch.dtype] = None, - device: Optional[torch.device] = None, - wrap_sequence: bool = False, + data, dtype: Optional[torch.dtype] = None, device: Optional[torch.device] = None, wrap_sequence: bool = False ): """ Utility to convert the input data to a PyTorch Tensor. If passing a dictionary, list or tuple, @@ -290,10 +287,4 @@ def convert_to_dst_type( output_type = np.ndarray else: output_type = type(dst) - return convert_data_type( - data=src, - output_type=output_type, - device=device, - dtype=dtype, - wrap_sequence=wrap_sequence, - ) + return convert_data_type(data=src, output_type=output_type, device=device, dtype=dtype, wrap_sequence=wrap_sequence) diff --git a/monai/visualize/occlusion_sensitivity.py b/monai/visualize/occlusion_sensitivity.py index 61b84bb406..51bcb1f517 100644 --- a/monai/visualize/occlusion_sensitivity.py +++ b/monai/visualize/occlusion_sensitivity.py @@ -265,9 +265,7 @@ def _compute_occlusion_sensitivity(self, x, b_box): return sensitivity_ims, output_im_shape def __call__( # type: ignore - self, - x: torch.Tensor, - b_box: Optional[Sequence] = None, + self, x: torch.Tensor, b_box: Optional[Sequence] = None ) -> Tuple[torch.Tensor, torch.Tensor]: """ Args: diff --git a/runtests.sh b/runtests.sh index f10e888543..a77f9decd5 100755 --- a/runtests.sh +++ b/runtests.sh @@ -397,9 +397,9 @@ then if [ $doBlackFix = true ] then - ${cmdPrefix}${PY_EXE} -m black "$(pwd)" + ${cmdPrefix}${PY_EXE} -m black --skip-magic-trailing-comma "$(pwd)" else - ${cmdPrefix}${PY_EXE} -m black --check "$(pwd)" + ${cmdPrefix}${PY_EXE} -m black --skip-magic-trailing-comma --check "$(pwd)" fi black_status=$? diff --git a/setup.py b/setup.py index eeaffb7823..95087ce06f 100644 --- a/setup.py +++ b/setup.py @@ -53,11 +53,7 @@ def torch_parallel_backend(): try: - match = re.search( - "^ATen parallel backend: (?P.*)$", - torch._C._parallel_info(), - re.MULTILINE, - ) + match = re.search("^ATen parallel backend: (?P.*)$", torch._C._parallel_info(), re.MULTILINE) if match is None: return None backend = match.group("backend") diff --git a/tests/test_activationsd.py b/tests/test_activationsd.py index 355c50f389..0a981f27e8 100644 --- a/tests/test_activationsd.py +++ b/tests/test_activationsd.py @@ -29,10 +29,7 @@ TEST_CASE_2 = [ {"keys": ["pred", "label"], "sigmoid": False, "softmax": False, "other": [torch.tanh, None]}, {"pred": torch.tensor([[[0.0, 1.0], [2.0, 3.0]]]), "label": torch.tensor([[[0.0, 1.0], [2.0, 3.0]]])}, - { - "pred": torch.tensor([[[0.0000, 0.7616], [0.9640, 0.9951]]]), - "label": torch.tensor([[[0.0, 1.0], [2.0, 3.0]]]), - }, + {"pred": torch.tensor([[[0.0000, 0.7616], [0.9640, 0.9951]]]), "label": torch.tensor([[[0.0, 1.0], [2.0, 3.0]]])}, (1, 2, 2), ] diff --git a/tests/test_affine_grid.py b/tests/test_affine_grid.py index 9bf2bcf90e..c12a395b47 100644 --- a/tests/test_affine_grid.py +++ b/tests/test_affine_grid.py @@ -33,11 +33,7 @@ TESTS.append([{"device": device}, {"grid": p(torch.ones((3, 3, 3)))}, p(np.ones((3, 3, 3)))]) TESTS.append( [ - { - "rotate_params": (1.0, 1.0), - "scale_params": (-20, 10), - "device": device, - }, + {"rotate_params": (1.0, 1.0), "scale_params": (-20, 10), "device": device}, {"grid": p(torch.ones((3, 3, 3)))}, p( torch.tensor( @@ -60,11 +56,7 @@ ) TESTS.append( [ - { - "rotate_params": (1.0, 1.0, 1.0), - "scale_params": (-20, 10), - "device": device, - }, + {"rotate_params": (1.0, 1.0, 1.0), "scale_params": (-20, 10), "device": device}, {"grid": p(torch.ones((4, 3, 3, 3)))}, p( torch.tensor( diff --git a/tests/test_affined.py b/tests/test_affined.py index 142cedc8d9..e9c468e755 100644 --- a/tests/test_affined.py +++ b/tests/test_affined.py @@ -44,13 +44,7 @@ ) TESTS.append( [ - dict( - keys="img", - rotate_params=[np.pi / 2], - padding_mode="zeros", - spatial_size=(4, 4), - device=device, - ), + dict(keys="img", rotate_params=[np.pi / 2], padding_mode="zeros", spatial_size=(4, 4), device=device), {"img": p(np.arange(4).reshape((1, 2, 2)))}, p(np.array([[[0.0, 0.0, 0.0, 0.0], [0.0, 2.0, 0.0, 0.0], [0.0, 3.0, 1.0, 0.0], [0.0, 0.0, 0.0, 0.0]]])), ] @@ -103,11 +97,7 @@ TESTS.append( [ dict( - keys="img", - rotate_params=[np.pi / 2], - padding_mode="zeros", - spatial_size=(4, 4, 4), - device=device, + keys="img", rotate_params=[np.pi / 2], padding_mode="zeros", spatial_size=(4, 4, 4), device=device ), {"img": p(np.arange(8).reshape((1, 2, 2, 2)))}, p( diff --git a/tests/test_ahnet.py b/tests/test_ahnet.py index 777e2637a7..f4bfa555fc 100644 --- a/tests/test_ahnet.py +++ b/tests/test_ahnet.py @@ -162,26 +162,14 @@ def test_mcfcn_shape(self, input_param, input_shape, expected_shape): class TestAHNET(unittest.TestCase): - @parameterized.expand( - [ - TEST_CASE_AHNET_2D_1, - TEST_CASE_AHNET_2D_2, - TEST_CASE_AHNET_2D_3, - ] - ) + @parameterized.expand([TEST_CASE_AHNET_2D_1, TEST_CASE_AHNET_2D_2, TEST_CASE_AHNET_2D_3]) def test_ahnet_shape_2d(self, input_param, input_shape, expected_shape): net = AHNet(**input_param).to(device) with eval_mode(net): result = net.forward(torch.randn(input_shape).to(device)) self.assertEqual(result.shape, expected_shape) - @parameterized.expand( - [ - TEST_CASE_AHNET_3D_1, - TEST_CASE_AHNET_3D_2, - TEST_CASE_AHNET_3D_3, - ] - ) + @parameterized.expand([TEST_CASE_AHNET_3D_1, TEST_CASE_AHNET_3D_2, TEST_CASE_AHNET_3D_3]) @skip_if_quick def test_ahnet_shape_3d(self, input_param, input_shape, expected_shape): net = AHNet(**input_param).to(device) @@ -203,11 +191,7 @@ def test_script(self): class TestAHNETWithPretrain(unittest.TestCase): @parameterized.expand( - [ - TEST_CASE_AHNET_3D_WITH_PRETRAIN_1, - TEST_CASE_AHNET_3D_WITH_PRETRAIN_2, - TEST_CASE_AHNET_3D_WITH_PRETRAIN_3, - ] + [TEST_CASE_AHNET_3D_WITH_PRETRAIN_1, TEST_CASE_AHNET_3D_WITH_PRETRAIN_2, TEST_CASE_AHNET_3D_WITH_PRETRAIN_3] ) def test_ahnet_shape(self, input_param, input_shape, expected_shape, fcn_input_param): net = AHNet(**input_param).to(device) diff --git a/tests/test_autoencoder.py b/tests/test_autoencoder.py index d67964f034..5bc125ba5e 100644 --- a/tests/test_autoencoder.py +++ b/tests/test_autoencoder.py @@ -35,13 +35,7 @@ ] TEST_CASE_1 = [ # single channel 2D, batch 4 - { - "dimensions": 2, - "in_channels": 1, - "out_channels": 1, - "channels": (4, 8, 16), - "strides": (2, 2, 2), - }, + {"dimensions": 2, "in_channels": 1, "out_channels": 1, "channels": (4, 8, 16), "strides": (2, 2, 2)}, (1, 1, 128, 128), (1, 1, 128, 128), ] @@ -60,13 +54,7 @@ ] TEST_CASE_3 = [ # 4-channel 3D, batch 4 - { - "dimensions": 3, - "in_channels": 4, - "out_channels": 3, - "channels": (4, 8, 16), - "strides": (2, 2, 2), - }, + {"dimensions": 3, "in_channels": 4, "out_channels": 3, "channels": (4, 8, 16), "strides": (2, 2, 2)}, (1, 4, 128, 128, 128), (1, 3, 128, 128, 128), ] diff --git a/tests/test_basic_unet.py b/tests/test_basic_unet.py index 1e553b363b..6a1bca858b 100644 --- a/tests/test_basic_unet.py +++ b/tests/test_basic_unet.py @@ -20,20 +20,10 @@ CASES_1D = [] for mode in ["pixelshuffle", "nontrainable", "deconv", None]: - kwargs = { - "dimensions": 1, - "in_channels": 5, - "out_channels": 8, - } + kwargs = {"dimensions": 1, "in_channels": 5, "out_channels": 8} if mode is not None: kwargs["upsample"] = mode # type: ignore - CASES_1D.append( - [ - kwargs, - (10, 5, 33), - (10, 8, 33), - ] - ) + CASES_1D.append([kwargs, (10, 5, 33), (10, 8, 33)]) CASES_2D = [] for mode in ["pixelshuffle", "nontrainable", "deconv"]: diff --git a/tests/test_bending_energy.py b/tests/test_bending_energy.py index 8f1fb43535..f254b9624c 100644 --- a/tests/test_bending_energy.py +++ b/tests/test_bending_energy.py @@ -20,31 +20,11 @@ device = "cuda" if torch.cuda.is_available() else "cpu" TEST_CASES = [ - [ - {}, - {"pred": torch.ones((1, 3, 5, 5, 5), device=device)}, - 0.0, - ], - [ - {}, - {"pred": torch.arange(0, 5, device=device)[None, None, None, None, :].expand(1, 3, 5, 5, 5)}, - 0.0, - ], - [ - {}, - {"pred": torch.arange(0, 5, device=device)[None, None, None, None, :].expand(1, 3, 5, 5, 5) ** 2}, - 4.0, - ], - [ - {}, - {"pred": torch.arange(0, 5, device=device)[None, None, None, :].expand(1, 3, 5, 5) ** 2}, - 4.0, - ], - [ - {}, - {"pred": torch.arange(0, 5, device=device)[None, None, :].expand(1, 3, 5) ** 2}, - 4.0, - ], + [{}, {"pred": torch.ones((1, 3, 5, 5, 5), device=device)}, 0.0], + [{}, {"pred": torch.arange(0, 5, device=device)[None, None, None, None, :].expand(1, 3, 5, 5, 5)}, 0.0], + [{}, {"pred": torch.arange(0, 5, device=device)[None, None, None, None, :].expand(1, 3, 5, 5, 5) ** 2}, 4.0], + [{}, {"pred": torch.arange(0, 5, device=device)[None, None, None, :].expand(1, 3, 5, 5) ** 2}, 4.0], + [{}, {"pred": torch.arange(0, 5, device=device)[None, None, :].expand(1, 3, 5) ** 2}, 4.0], ] diff --git a/tests/test_bilateral_approx_cpu.py b/tests/test_bilateral_approx_cpu.py index 7960f76591..d55a6ff5b3 100644 --- a/tests/test_bilateral_approx_cpu.py +++ b/tests/test_bilateral_approx_cpu.py @@ -306,7 +306,7 @@ # Frame 4 [[1, 0, 0, 0, 1], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [1, 0, 0, 0, 1]], ] - ], + ] ], # Expected [ diff --git a/tests/test_bilateral_approx_cuda.py b/tests/test_bilateral_approx_cuda.py index 345a920f3c..bc7defdc4e 100644 --- a/tests/test_bilateral_approx_cuda.py +++ b/tests/test_bilateral_approx_cuda.py @@ -306,7 +306,7 @@ # Frame 4 [[1, 0, 0, 0, 1], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [1, 0, 0, 0, 1]], ] - ], + ] ], # Expected [ diff --git a/tests/test_bilateral_precise.py b/tests/test_bilateral_precise.py index dfa3ca107d..3b8f6194cf 100644 --- a/tests/test_bilateral_precise.py +++ b/tests/test_bilateral_precise.py @@ -306,7 +306,7 @@ # Frame 4 [[1, 0, 0, 0, 1], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [1, 0, 0, 0, 1]], ] - ], + ] ], # Expected [ diff --git a/tests/test_border_pad.py b/tests/test_border_pad.py index 9e6a8a6a08..7bd3f36c20 100644 --- a/tests/test_border_pad.py +++ b/tests/test_border_pad.py @@ -18,17 +18,9 @@ from monai.utils import NumpyPadMode from tests.utils import TEST_NDARRAYS -TEST_CASE_1 = [ - {"spatial_border": 2, "mode": "constant"}, - np.zeros((3, 8, 8, 4)), - np.zeros((3, 12, 12, 8)), -] +TEST_CASE_1 = [{"spatial_border": 2, "mode": "constant"}, np.zeros((3, 8, 8, 4)), np.zeros((3, 12, 12, 8))] -TEST_CASE_2 = [ - {"spatial_border": [1, 2, 3], "mode": "constant"}, - np.zeros((3, 8, 8, 4)), - np.zeros((3, 10, 12, 10)), -] +TEST_CASE_2 = [{"spatial_border": [1, 2, 3], "mode": "constant"}, np.zeros((3, 8, 8, 4)), np.zeros((3, 10, 12, 10))] TEST_CASE_3 = [ {"spatial_border": [1, 2, 3, 4, 5, 6], "mode": "constant"}, diff --git a/tests/test_cachedataset.py b/tests/test_cachedataset.py index e5bb1b9a90..b7d2e97590 100644 --- a/tests/test_cachedataset.py +++ b/tests/test_cachedataset.py @@ -84,12 +84,7 @@ def test_shape(self, transform, expected_shape): def test_set_data(self): data_list1 = list(range(10)) - transform = Compose( - [ - Lambda(func=lambda x: np.array([x * 10])), - RandLambda(func=lambda x: x + 1), - ] - ) + transform = Compose([Lambda(func=lambda x: np.array([x * 10])), RandLambda(func=lambda x: x + 1)]) dataset = CacheDataset( data=data_list1, @@ -142,11 +137,7 @@ def test_thread_safe(self, persistent_workers, cache_workers, loader_workers): _kwg = {"persistent_workers": persistent_workers} if get_torch_version_tuple() > (1, 7) else {} data_list = list(range(1, 11)) dataset = CacheDataset( - data=data_list, - transform=_StatefulTransform(), - cache_rate=1.0, - num_workers=cache_workers, - progress=False, + data=data_list, transform=_StatefulTransform(), cache_rate=1.0, num_workers=cache_workers, progress=False ) self.assertListEqual(expected, list(dataset)) loader = DataLoader( diff --git a/tests/test_cachedataset_parallel.py b/tests/test_cachedataset_parallel.py index 0be3ba085b..96aadd9614 100644 --- a/tests/test_cachedataset_parallel.py +++ b/tests/test_cachedataset_parallel.py @@ -42,12 +42,7 @@ def test_shape(self, num_workers, dataset_size, transform): "extra": os.path.join(tempdir, "test_extra1.nii.gz"), } ] * dataset_size - dataset = CacheDataset( - data=test_data, - transform=transform, - cache_rate=1, - num_workers=num_workers, - ) + dataset = CacheDataset(data=test_data, transform=transform, cache_rate=1, num_workers=num_workers) self.assertEqual(len(dataset._cache), dataset.cache_num) for i in range(dataset.cache_num): diff --git a/tests/test_cachedataset_persistent_workers.py b/tests/test_cachedataset_persistent_workers.py index 584a053614..d727074bf9 100644 --- a/tests/test_cachedataset_persistent_workers.py +++ b/tests/test_cachedataset_persistent_workers.py @@ -23,12 +23,7 @@ def test_duplicate_transforms(self): data = [{"img": im} for _ in range(2)] # at least 1 deterministic followed by at least 1 random - transform = Compose( - [ - Spacingd("img", pixdim=(1, 1)), - RandAffined("img", prob=1.0), - ] - ) + transform = Compose([Spacingd("img", pixdim=(1, 1)), RandAffined("img", prob=1.0)]) # cachedataset and data loader w persistent_workers train_ds = CacheDataset(data, transform, cache_num=1) diff --git a/tests/test_cachentransdataset.py b/tests/test_cachentransdataset.py index 492db8b16f..13c1e1c68e 100644 --- a/tests/test_cachentransdataset.py +++ b/tests/test_cachentransdataset.py @@ -42,19 +42,13 @@ def test_n_trans(self, transform, expected_shape): cache_dir = os.path.join(os.path.join(tempdir, "cache"), "data") dataset_precached = CacheNTransDataset( - data=test_data, - transform=transform, - cache_dir=cache_dir, - cache_n_trans=2, + data=test_data, transform=transform, cache_dir=cache_dir, cache_n_trans=2 ) data_precached = dataset_precached[0] self.assertTupleEqual(data_precached["image"].shape, expected_shape) dataset_postcached = CacheNTransDataset( - data=test_data, - transform=transform, - cache_dir=cache_dir, - cache_n_trans=2, + data=test_data, transform=transform, cache_dir=cache_dir, cache_n_trans=2 ) data_postcached = dataset_postcached[0] self.assertTupleEqual(data_postcached["image"].shape, expected_shape) diff --git a/tests/test_cast_to_typed.py b/tests/test_cast_to_typed.py index 342a677ce1..007598c200 100644 --- a/tests/test_cast_to_typed.py +++ b/tests/test_cast_to_typed.py @@ -39,18 +39,12 @@ TESTS_CUPY = [ [ {"keys": "image", "dtype": np.uint8}, - { - "image": np.array([[0, 1], [1, 2]], dtype=np.float32), - "label": np.array([[0, 1], [1, 1]], dtype=np.float32), - }, + {"image": np.array([[0, 1], [1, 2]], dtype=np.float32), "label": np.array([[0, 1], [1, 1]], dtype=np.float32)}, {"image": np.uint8, "label": np.float32}, ], [ {"keys": ["image", "label"], "dtype": np.float32}, - { - "image": np.array([[0, 1], [1, 2]], dtype=np.uint8), - "label": np.array([[0, 1], [1, 1]], dtype=np.uint8), - }, + {"image": np.array([[0, 1], [1, 2]], dtype=np.uint8), "label": np.array([[0, 1], [1, 1]], dtype=np.uint8)}, {"image": np.float32, "label": np.float32}, ], ] diff --git a/tests/test_center_spatial_cropd.py b/tests/test_center_spatial_cropd.py index 8ffcdf4387..be44468987 100644 --- a/tests/test_center_spatial_cropd.py +++ b/tests/test_center_spatial_cropd.py @@ -20,19 +20,11 @@ TEST_SHAPES = [] for p in TEST_NDARRAYS: TEST_SHAPES.append( - [ - {"keys": "img", "roi_size": [2, -1, -1]}, - {"img": p(np.random.randint(0, 2, size=[3, 3, 3, 3]))}, - (3, 2, 3, 3), - ] + [{"keys": "img", "roi_size": [2, -1, -1]}, {"img": p(np.random.randint(0, 2, size=[3, 3, 3, 3]))}, (3, 2, 3, 3)] ) TEST_SHAPES.append( - [ - {"keys": "img", "roi_size": [2, 2, 2]}, - {"img": p(np.random.randint(0, 2, size=[3, 3, 3, 3]))}, - (3, 2, 2, 2), - ] + [{"keys": "img", "roi_size": [2, 2, 2]}, {"img": p(np.random.randint(0, 2, size=[3, 3, 3, 3]))}, (3, 2, 2, 2)] ) TEST_CASES = [] diff --git a/tests/test_compute_confusion_matrix.py b/tests/test_compute_confusion_matrix.py index 69a95e0c8b..ef65c474c8 100644 --- a/tests/test_compute_confusion_matrix.py +++ b/tests/test_compute_confusion_matrix.py @@ -174,22 +174,10 @@ # 3. test metric with compute_sample, denominator may have zeros TEST_CASES_COMPUTE_SAMPLE_NAN = [] metric_names = ["tpr", "tnr"] -result_sum = [ - torch.tensor([0.5000]), - torch.tensor([4.8333]), -] -not_nans_sum = [ - torch.tensor([6]), - torch.tensor([8]), -] -result_sum_batch = [ - torch.tensor([0.0000, 0.5000, 0.0000]), - torch.tensor([1.6667, 2.5000, 0.6667]), -] -not_nans_sum_batch = [ - torch.tensor([3.0, 2.0, 1.0]), - torch.tensor([2.0, 3.0, 3.0]), -] +result_sum = [torch.tensor([0.5000]), torch.tensor([4.8333])] +not_nans_sum = [torch.tensor([6]), torch.tensor([8])] +result_sum_batch = [torch.tensor([0.0000, 0.5000, 0.0000]), torch.tensor([1.6667, 2.5000, 0.6667])] +not_nans_sum_batch = [torch.tensor([3.0, 2.0, 1.0]), torch.tensor([2.0, 3.0, 3.0])] for idx in range(2): for reduction in ["sum", "sum_batch"]: TEST_CASE = [data_nan.copy()] diff --git a/tests/test_compute_meandice.py b/tests/test_compute_meandice.py index f9e494efc7..f96563e22e 100644 --- a/tests/test_compute_meandice.py +++ b/tests/test_compute_meandice.py @@ -168,10 +168,7 @@ ] TEST_CASE_10 = [ - { - "y": [torch.ones((2, 3, 3)), torch.ones((2, 3, 3))], - "y_pred": [torch.ones((2, 3, 3)), torch.ones((2, 3, 3))], - }, + {"y": [torch.ones((2, 3, 3)), torch.ones((2, 3, 3))], "y_pred": [torch.ones((2, 3, 3)), torch.ones((2, 3, 3))]}, [[1.0000, 1.0000], [1.0000, 1.0000]], ] diff --git a/tests/test_compute_roc_auc.py b/tests/test_compute_roc_auc.py index 1cec357b93..bfecb4ce5b 100644 --- a/tests/test_compute_roc_auc.py +++ b/tests/test_compute_roc_auc.py @@ -37,23 +37,9 @@ 0.875, ] -TEST_CASE_3 = [ - torch.tensor([[0.5], [0.5], [0.2], [8.3]]), - torch.tensor([0, 1, 0, 1]), - False, - False, - "macro", - 0.875, -] +TEST_CASE_3 = [torch.tensor([[0.5], [0.5], [0.2], [8.3]]), torch.tensor([0, 1, 0, 1]), False, False, "macro", 0.875] -TEST_CASE_4 = [ - torch.tensor([0.5, 0.5, 0.2, 8.3]), - torch.tensor([0, 1, 0, 1]), - False, - False, - "macro", - 0.875, -] +TEST_CASE_4 = [torch.tensor([0.5, 0.5, 0.2, 8.3]), torch.tensor([0, 1, 0, 1]), False, False, "macro", 0.875] TEST_CASE_5 = [ torch.tensor([[0.1, 0.9], [0.3, 1.4], [0.2, 0.1], [0.1, 0.5]]), diff --git a/tests/test_convert_data_type.py b/tests/test_convert_data_type.py index c3d5622245..aba10fd717 100644 --- a/tests/test_convert_data_type.py +++ b/tests/test_convert_data_type.py @@ -28,7 +28,7 @@ for in_type in TEST_NDARRAYS + (int, float): for out_type in TEST_NDARRAYS: TESTS_LIST.append( - ([in_type(np.array(1.0)), in_type(np.array(1.0))], out_type(np.array([1.0, 1.0])), True), # type: ignore + ([in_type(np.array(1.0)), in_type(np.array(1.0))], out_type(np.array([1.0, 1.0])), True) # type: ignore ) TESTS_LIST.append( ( diff --git a/tests/test_correct_crop_centers.py b/tests/test_correct_crop_centers.py index 853b3d41d3..8804223719 100644 --- a/tests/test_correct_crop_centers.py +++ b/tests/test_correct_crop_centers.py @@ -17,13 +17,7 @@ from monai.transforms.utils import correct_crop_centers from tests.utils import assert_allclose -TESTS = [ - [ - [1, 5, 0], - [2, 2, 2], - [10, 10, 10], - ], -] +TESTS = [[[1, 5, 0], [2, 2, 2], [10, 10, 10]]] class TestCorrectCropCenters(unittest.TestCase): diff --git a/tests/test_crf_cpu.py b/tests/test_crf_cpu.py index ed1860943f..6f9864e934 100644 --- a/tests/test_crf_cpu.py +++ b/tests/test_crf_cpu.py @@ -55,12 +55,12 @@ # Batch 0 [ # Channel 0 - [1, 1, 1, 0.5, 0], + [1, 1, 1, 0.5, 0] ], # Batch 1 [ # Channel 0 - [1, 1, 0.5, 0, 0], + [1, 1, 0.5, 0, 0] ], ], # Expected @@ -117,12 +117,12 @@ # Batch 0 [ # Channel 0 - [1, 1, 1, 0.5, 0], + [1, 1, 1, 0.5, 0] ], # Batch 1 [ # Channel 0 - [1, 1, 0.5, 0, 0], + [1, 1, 0.5, 0, 0] ], ], # Expected @@ -185,7 +185,7 @@ [1.0, 1.0, 1.0, 0.0, 0.0], [1.0, 1.0, 0.0, 0.0, 0.0], ], - ], + ] ], # Features [ @@ -207,7 +207,7 @@ [0.0, 0.0, 0.0, 1.0, 1.0], [0.0, 0.0, 0.0, 1.0, 1.0], ], - ], + ] ], # Expected [ @@ -237,7 +237,7 @@ [0.688815, 0.687855, 0.687076, 0.228579, 0.227552], [0.687434, 0.686453, 0.445019, 0.229047, 0.227588], ], - ], + ] ], ], [ @@ -344,7 +344,7 @@ [0.0, 0.0, 0.0, 1.0, 1.0], ], ], - ], + ] ], # Features [ @@ -392,8 +392,8 @@ [0.0, 0.0, 1.0, 1.0, 1.0], [0.0, 0.0, 1.0, 1.0, 1.0], ], - ], - ], + ] + ] ], # Expected [ @@ -485,7 +485,7 @@ [0.500533, 0.500745, 0.553344, 0.771576, 0.772222], ], ], - ], + ] ], ], ] diff --git a/tests/test_crf_cuda.py b/tests/test_crf_cuda.py index adf8c440c0..8881b9aec5 100644 --- a/tests/test_crf_cuda.py +++ b/tests/test_crf_cuda.py @@ -55,12 +55,12 @@ # Batch 0 [ # Channel 0 - [1, 1, 1, 0.5, 0], + [1, 1, 1, 0.5, 0] ], # Batch 1 [ # Channel 0 - [1, 1, 0.5, 0, 0], + [1, 1, 0.5, 0, 0] ], ], # Expected @@ -117,12 +117,12 @@ # Batch 0 [ # Channel 0 - [1, 1, 1, 0.5, 0], + [1, 1, 1, 0.5, 0] ], # Batch 1 [ # Channel 0 - [1, 1, 0.5, 0, 0], + [1, 1, 0.5, 0, 0] ], ], # Expected @@ -185,7 +185,7 @@ [0.5, 1.0, 0.5, 0.0, 0.0], [1.0, 0.5, 0.0, 0.0, 0.0], ], - ], + ] ], # Features [ @@ -207,7 +207,7 @@ [0.0, 0.0, 0.0, 1.0, 1.0], [0.0, 0.0, 0.0, 1.0, 1.0], ], - ], + ] ], # Expected [ @@ -237,7 +237,7 @@ [0.492602, 0.609557, 0.480947, 0.161909, 0.161476], [0.610678, 0.480516, 0.352479, 0.159380, 0.158274], ], - ], + ] ], ], [ @@ -344,7 +344,7 @@ [0.0, 0.0, 0.0, 1.0, 1.0], ], ], - ], + ] ], # Features [ @@ -392,8 +392,8 @@ [0.0, 0.0, 1.0, 1.0, 1.0], [0.0, 0.0, 1.0, 1.0, 1.0], ], - ], - ], + ] + ] ], # Expected [ @@ -485,7 +485,7 @@ [0.500663, 0.500887, 0.556332, 0.773597, 0.775210], ], ], - ], + ] ], ], ] diff --git a/tests/test_cuimage_reader.py b/tests/test_cuimage_reader.py index 34df4b5fe4..c8391939f1 100644 --- a/tests/test_cuimage_reader.py +++ b/tests/test_cuimage_reader.py @@ -47,13 +47,7 @@ TEST_CASE_3 = [ FILE_PATH, - { - "location": (0, 0), - "size": (8, 8), - "level": 2, - "grid_shape": (2, 1), - "patch_size": 2, - }, + {"location": (0, 0), "size": (8, 8), "level": 2, "grid_shape": (2, 1), "patch_size": 2}, np.array( [ [[[239, 239], [239, 239]], [[239, 239], [239, 239]], [[239, 239], [239, 239]]], @@ -64,23 +58,13 @@ TEST_CASE_4 = [ FILE_PATH, - { - "location": (0, 0), - "size": (8, 8), - "level": 2, - "grid_shape": (2, 1), - "patch_size": 1, - }, + {"location": (0, 0), "size": (8, 8), "level": 2, "grid_shape": (2, 1), "patch_size": 1}, np.array([[[[239]], [[239]], [[239]]], [[[243]], [[243]], [[243]]]]), ] -TEST_CASE_RGB_0 = [ - np.ones((3, 2, 2), dtype=np.uint8), # CHW -] +TEST_CASE_RGB_0 = [np.ones((3, 2, 2), dtype=np.uint8)] # CHW -TEST_CASE_RGB_1 = [ - np.ones((3, 100, 100), dtype=np.uint8), # CHW -] +TEST_CASE_RGB_1 = [np.ones((3, 100, 100), dtype=np.uint8)] # CHW class TestCuCIMReader(unittest.TestCase): diff --git a/tests/test_data_statsd.py b/tests/test_data_statsd.py index 686d23c4f9..4c33a82b67 100644 --- a/tests/test_data_statsd.py +++ b/tests/test_data_statsd.py @@ -155,16 +155,7 @@ class TestDataStatsd(unittest.TestCase): @parameterized.expand( - [ - TEST_CASE_1, - TEST_CASE_2, - TEST_CASE_3, - TEST_CASE_4, - TEST_CASE_5, - TEST_CASE_6, - TEST_CASE_7, - TEST_CASE_8, - ] + [TEST_CASE_1, TEST_CASE_2, TEST_CASE_3, TEST_CASE_4, TEST_CASE_5, TEST_CASE_6, TEST_CASE_7, TEST_CASE_8] ) def test_value(self, input_param, input_data, expected_print): transform = DataStatsd(**input_param) diff --git a/tests/test_dataloader.py b/tests/test_dataloader.py index 3b159fb5b8..035f145c9a 100644 --- a/tests/test_dataloader.py +++ b/tests/test_dataloader.py @@ -20,19 +20,9 @@ from monai.transforms import Compose, DataStatsd, Randomizable, SimulateDelayd from monai.utils import set_determinism -TEST_CASE_1 = [ - [ - {"image": np.asarray([1, 2, 3])}, - {"image": np.asarray([4, 5])}, - ] -] - -TEST_CASE_2 = [ - [ - {"label": torch.as_tensor([[3], [2]])}, - {"label": np.asarray([[1], [2]])}, - ] -] +TEST_CASE_1 = [[{"image": np.asarray([1, 2, 3])}, {"image": np.asarray([4, 5])}]] + +TEST_CASE_2 = [[{"label": torch.as_tensor([[3], [2]])}, {"label": np.asarray([[1], [2]])}]] class TestDataLoader(unittest.TestCase): diff --git a/tests/test_dataset_summary.py b/tests/test_dataset_summary.py index 5307bc7e66..172d4980dd 100644 --- a/tests/test_dataset_summary.py +++ b/tests/test_dataset_summary.py @@ -56,13 +56,7 @@ def test_spacing_intensity(self): def test_anisotropic_spacing(self): with tempfile.TemporaryDirectory() as tempdir: - pixdims = [ - [1.0, 1.0, 5.0], - [1.0, 1.0, 4.0], - [1.0, 1.0, 4.5], - [1.0, 1.0, 2.0], - [1.0, 1.0, 1.0], - ] + pixdims = [[1.0, 1.0, 5.0], [1.0, 1.0, 4.0], [1.0, 1.0, 4.5], [1.0, 1.0, 2.0], [1.0, 1.0, 1.0]] for i in range(5): im, seg = create_test_image_3d(32, 32, 32, num_seg_classes=1, num_objs=3, rad_max=6, channel_dim=0) n = nib.Nifti1Image(im, np.eye(4)) diff --git a/tests/test_decathlondataset.py b/tests/test_decathlondataset.py index 15dbceb8ad..db07d361db 100644 --- a/tests/test_decathlondataset.py +++ b/tests/test_decathlondataset.py @@ -68,12 +68,7 @@ def _test_dataset(dataset): self.assertEqual(len(data), 208) # test dataset properties - data = DecathlonDataset( - root_dir=testing_dir, - task="Task04_Hippocampus", - section="validation", - download=False, - ) + data = DecathlonDataset(root_dir=testing_dir, task="Task04_Hippocampus", section="validation", download=False) properties = data.get_properties(keys="labels") self.assertDictEqual(properties["labels"], {"0": "background", "1": "Anterior", "2": "Posterior"}) diff --git a/tests/test_decollate.py b/tests/test_decollate.py index 521d263663..9bc3c3b470 100644 --- a/tests/test_decollate.py +++ b/tests/test_decollate.py @@ -170,10 +170,7 @@ def test_decollation_examples(self, input_val, expected_out): self.assertListEqual(expected_out, out) def test_dict_examples(self): - test_case = { - "meta": {"out": ["test", "test"]}, - "image_meta_dict": {"scl_slope": torch.Tensor((0.0, 0.0))}, - } + test_case = {"meta": {"out": ["test", "test"]}, "image_meta_dict": {"scl_slope": torch.Tensor((0.0, 0.0))}} out = decollate_batch(test_case) self.assertEqual(out[0]["meta"]["out"], "test") self.assertEqual(out[0]["image_meta_dict"]["scl_slope"], 0.0) diff --git a/tests/test_deepedit_transforms.py b/tests/test_deepedit_transforms.py index c2b11e8ee7..391b724da9 100644 --- a/tests/test_deepedit_transforms.py +++ b/tests/test_deepedit_transforms.py @@ -28,11 +28,7 @@ "background": [0, 0, 0], } -DISCARD_ADD_GUIDANCE_TEST_CASE = [ - {"image": IMAGE, "label": LABEL}, - DATA_1, - (3, 1, 5, 5), -] +DISCARD_ADD_GUIDANCE_TEST_CASE = [{"image": IMAGE, "label": LABEL}, DATA_1, (3, 1, 5, 5)] DATA_2 = { "image": IMAGE, diff --git a/tests/test_deepgrow_transforms.py b/tests/test_deepgrow_transforms.py index f50e92d146..3085309bdc 100644 --- a/tests/test_deepgrow_transforms.py +++ b/tests/test_deepgrow_transforms.py @@ -31,12 +31,7 @@ IMAGE = np.array([[[[1, 0, 2, 0, 1], [0, 1, 2, 1, 0], [2, 2, 3, 2, 2], [0, 1, 2, 1, 0], [1, 0, 2, 0, 1]]]]) LABEL = np.array([[[[0, 0, 0, 0, 0], [0, 1, 0, 1, 0], [0, 0, 1, 0, 0], [0, 1, 0, 1, 0], [0, 0, 0, 0, 0]]]]) -DATA_1 = { - "image": IMAGE, - "label": LABEL, - "image_meta_dict": {}, - "label_meta_dict": {}, -} +DATA_1 = {"image": IMAGE, "label": LABEL, "image_meta_dict": {}, "label_meta_dict": {}} DATA_2 = { "image": np.array( @@ -141,23 +136,11 @@ "pred": np.array([[[[1, 2], [3, 4]], [[5, 6], [7, 8]]]]), } -DATA_12 = { - "image": np.arange(27).reshape(3, 3, 3), - "image_meta_dict": {}, - "guidance": [[0, 0, 0], [0, 1, 1], 1], -} +DATA_12 = {"image": np.arange(27).reshape(3, 3, 3), "image_meta_dict": {}, "guidance": [[0, 0, 0], [0, 1, 1], 1]} -FIND_SLICE_TEST_CASE_1 = [ - {"label": "label", "sids": "sids"}, - DATA_1, - [0], -] +FIND_SLICE_TEST_CASE_1 = [{"label": "label", "sids": "sids"}, DATA_1, [0]] -FIND_SLICE_TEST_CASE_2 = [ - {"label": "label", "sids": "sids"}, - DATA_2, - [0, 1], -] +FIND_SLICE_TEST_CASE_2 = [{"label": "label", "sids": "sids"}, DATA_2, [0, 1]] CROP_TEST_CASE_1 = [ { @@ -338,14 +321,10 @@ [[1.0, 1.0, 2.0, 2.0], [1.0, 1.0, 2.0, 2.0], [3.0, 3.0, 4.0, 4.0], [3.0, 3.0, 4.0, 4.0]], [[5.0, 5.0, 6.0, 6.0], [5.0, 5.0, 6.0, 6.0], [7.0, 7.0, 8.0, 8.0], [7.0, 7.0, 8.0, 8.0]], [[5.0, 5.0, 6.0, 6.0], [5.0, 5.0, 6.0, 6.0], [7.0, 7.0, 8.0, 8.0], [7.0, 7.0, 8.0, 8.0]], - ], + ] ) -RESTORE_LABEL_TEST_CASE_2 = [ - {"keys": ["pred"], "ref_image": "image", "mode": "nearest"}, - DATA_11, - RESULT, -] +RESTORE_LABEL_TEST_CASE_2 = [{"keys": ["pred"], "ref_image": "image", "mode": "nearest"}, DATA_11, RESULT] FETCH_2D_SLICE_TEST_CASE_1 = [ {"keys": ["image"], "guidance": "guidance"}, diff --git a/tests/test_dice_focal_loss.py b/tests/test_dice_focal_loss.py index 920994f8de..a69df21693 100644 --- a/tests/test_dice_focal_loss.py +++ b/tests/test_dice_focal_loss.py @@ -24,11 +24,7 @@ def test_result_onehot_target_include_bg(self): label = torch.randint(low=0, high=2, size=size) pred = torch.randn(size) for reduction in ["sum", "mean", "none"]: - common_params = { - "include_background": True, - "to_onehot_y": False, - "reduction": reduction, - } + common_params = {"include_background": True, "to_onehot_y": False, "reduction": reduction} for focal_weight in [None, torch.tensor([1.0, 1.0, 2.0]), (3, 2.0, 1)]: for lambda_focal in [0.5, 1.0, 1.5]: dice_focal = DiceFocalLoss( @@ -46,11 +42,7 @@ def test_result_no_onehot_no_bg(self): label = torch.argmax(label, dim=1, keepdim=True) pred = torch.randn(size) for reduction in ["sum", "mean", "none"]: - common_params = { - "include_background": False, - "to_onehot_y": True, - "reduction": reduction, - } + common_params = {"include_background": False, "to_onehot_y": True, "reduction": reduction} for focal_weight in [2.0, torch.tensor([1.0, 2.0]), (2.0, 1)]: for lambda_focal in [0.5, 1.0, 1.5]: dice_focal = DiceFocalLoss(focal_weight=focal_weight, lambda_focal=lambda_focal, **common_params) diff --git a/tests/test_dice_loss.py b/tests/test_dice_loss.py index ef0a51eb15..32d8ae694d 100644 --- a/tests/test_dice_loss.py +++ b/tests/test_dice_loss.py @@ -21,10 +21,7 @@ TEST_CASES = [ [ # shape: (1, 1, 2, 2), (1, 1, 2, 2) {"include_background": True, "sigmoid": True, "smooth_nr": 1e-6, "smooth_dr": 1e-6}, - { - "input": torch.tensor([[[[1.0, -1.0], [-1.0, 1.0]]]]), - "target": torch.tensor([[[[1.0, 0.0], [1.0, 1.0]]]]), - }, + {"input": torch.tensor([[[[1.0, -1.0], [-1.0, 1.0]]]]), "target": torch.tensor([[[[1.0, 0.0], [1.0, 1.0]]]])}, 0.307576, ], [ # shape: (2, 1, 2, 2), (2, 1, 2, 2) @@ -91,26 +88,17 @@ ], [ # shape: (1, 1, 2, 2), (1, 1, 2, 2) {"include_background": True, "sigmoid": True, "smooth_nr": 1e-6, "smooth_dr": 1e-6}, - { - "input": torch.tensor([[[[1.0, -1.0], [-1.0, 1.0]]]]), - "target": torch.tensor([[[[1.0, 0.0], [1.0, 1.0]]]]), - }, + {"input": torch.tensor([[[[1.0, -1.0], [-1.0, 1.0]]]]), "target": torch.tensor([[[[1.0, 0.0], [1.0, 1.0]]]])}, 0.307576, ], [ # shape: (1, 1, 2, 2), (1, 1, 2, 2) {"include_background": True, "sigmoid": True, "squared_pred": True}, - { - "input": torch.tensor([[[[1.0, -1.0], [-1.0, 1.0]]]]), - "target": torch.tensor([[[[1.0, 0.0], [1.0, 1.0]]]]), - }, + {"input": torch.tensor([[[[1.0, -1.0], [-1.0, 1.0]]]]), "target": torch.tensor([[[[1.0, 0.0], [1.0, 1.0]]]])}, 0.178337, ], [ # shape: (1, 1, 2, 2), (1, 1, 2, 2) {"include_background": True, "sigmoid": True, "jaccard": True}, - { - "input": torch.tensor([[[[1.0, -1.0], [-1.0, 1.0]]]]), - "target": torch.tensor([[[[1.0, 0.0], [1.0, 1.0]]]]), - }, + {"input": torch.tensor([[[[1.0, -1.0], [-1.0, 1.0]]]]), "target": torch.tensor([[[[1.0, 0.0], [1.0, 1.0]]]])}, 0.470451, ], [ # shape: (2, 1, 2, 2), (2, 1, 2, 2) diff --git a/tests/test_distributed_weighted_random_sampler.py b/tests/test_distributed_weighted_random_sampler.py index b8e088fdcf..23574e5121 100644 --- a/tests/test_distributed_weighted_random_sampler.py +++ b/tests/test_distributed_weighted_random_sampler.py @@ -25,10 +25,7 @@ def test_sampling(self): data = [1, 2, 3, 4, 5] weights = [1, 2, 3, 4, 5] sampler = DistributedWeightedRandomSampler( - weights=weights, - dataset=data, - shuffle=False, - generator=torch.Generator().manual_seed(0), + weights=weights, dataset=data, shuffle=False, generator=torch.Generator().manual_seed(0) ) samples = np.array([data[i] for i in list(sampler)]) diff --git a/tests/test_divisible_pad.py b/tests/test_divisible_pad.py index 810d08252c..bb58668908 100644 --- a/tests/test_divisible_pad.py +++ b/tests/test_divisible_pad.py @@ -22,21 +22,11 @@ for p in TEST_NDARRAYS: # pad first dim to be divisible by 7, the second unchanged. - TESTS.append( - [ - {"k": (7, -1), "mode": "constant"}, - p(np.zeros((3, 8, 7))), - p(np.zeros((3, 14, 7))), - ] - ) + TESTS.append([{"k": (7, -1), "mode": "constant"}, p(np.zeros((3, 8, 7))), p(np.zeros((3, 14, 7)))]) # pad all dimensions to be divisible by 5 TESTS.append( - [ - {"k": 5, "mode": "constant", "method": "end"}, - p(np.zeros((3, 10, 5, 17))), - p(np.zeros((3, 10, 5, 20))), - ] + [{"k": 5, "mode": "constant", "method": "end"}, p(np.zeros((3, 10, 5, 17))), p(np.zeros((3, 10, 5, 20)))] ) diff --git a/tests/test_divisible_padd.py b/tests/test_divisible_padd.py index c834adac6d..44faeced7b 100644 --- a/tests/test_divisible_padd.py +++ b/tests/test_divisible_padd.py @@ -28,11 +28,7 @@ np.zeros((3, 14, 7)), ] -TEST_CASE_3 = [ - {"keys": ["img"], "k": 0, "mode": {"constant"}}, - {"img": np.zeros((3, 8))}, - np.zeros((3, 8)), -] +TEST_CASE_3 = [{"keys": ["img"], "k": 0, "mode": {"constant"}}, {"img": np.zeros((3, 8))}, np.zeros((3, 8))] class TestDivisiblePadd(unittest.TestCase): diff --git a/tests/test_downsample_block.py b/tests/test_downsample_block.py index f4ae30198f..d35218c6d7 100644 --- a/tests/test_downsample_block.py +++ b/tests/test_downsample_block.py @@ -20,11 +20,7 @@ TEST_CASES = [ [{"spatial_dims": 2, "kernel_size": 2}, (7, 4, 64, 48), (7, 8, 32, 24)], # 4-channel 2D, batch 7 [{"spatial_dims": 1, "kernel_size": 4}, (16, 4, 63), (16, 8, 15)], # 4-channel 1D, batch 16 - [ # 4-channel 1D, batch 16 - {"spatial_dims": 1, "kernel_size": 4, "padding": 1}, - (16, 4, 63), - (16, 8, 16), - ], + [{"spatial_dims": 1, "kernel_size": 4, "padding": 1}, (16, 4, 63), (16, 8, 16)], # 4-channel 1D, batch 16 [ # 4-channel 3D, batch 16 {"spatial_dims": 3, "kernel_size": 3, "ceil_mode": True}, (16, 4, 32, 24, 48), diff --git a/tests/test_efficientnet.py b/tests/test_efficientnet.py index 667d3cd09b..ac23a68792 100644 --- a/tests/test_efficientnet.py +++ b/tests/test_efficientnet.py @@ -107,11 +107,7 @@ def make_shape_cases( ret_tests.append( [ kwargs, - ( - batch, - in_channels, - ) - + (get_expected_model_shape(model),) * spatial_dim, + (batch, in_channels) + (get_expected_model_shape(model),) * spatial_dim, (batch, num_classes), ] ) @@ -245,7 +241,7 @@ def make_shape_cases( }, [1, 2, 224, 224], ([1, 32, 112, 112], [1, 56, 56, 56], [1, 88, 28, 28], [1, 248, 14, 14], [1, 704, 7, 7]), - ), + ) ] diff --git a/tests/test_ensure_channel_first.py b/tests/test_ensure_channel_first.py index 23126d326f..0fb7759219 100644 --- a/tests/test_ensure_channel_first.py +++ b/tests/test_ensure_channel_first.py @@ -27,11 +27,7 @@ TEST_CASE_2 = [{"image_only": False}, ["test_image.nii.gz"], -1] -TEST_CASE_3 = [ - {"image_only": False}, - ["test_image.nii.gz", "test_image2.nii.gz", "test_image3.nii.gz"], - None, -] +TEST_CASE_3 = [{"image_only": False}, ["test_image.nii.gz", "test_image2.nii.gz", "test_image3.nii.gz"], None] TEST_CASE_4 = [{"reader": ITKReader(), "image_only": False}, ["test_image.nii.gz"], None] @@ -43,11 +39,7 @@ None, ] -TEST_CASE_7 = [ - {"image_only": False, "reader": ITKReader(pixel_type=itk.UC)}, - "tests/testing_data/CT_DICOM", - None, -] +TEST_CASE_7 = [{"image_only": False, "reader": ITKReader(pixel_type=itk.UC)}, "tests/testing_data/CT_DICOM", None] class TestEnsureChannelFirst(unittest.TestCase): diff --git a/tests/test_ensure_channel_firstd.py b/tests/test_ensure_channel_firstd.py index b4cde02a8f..b5e1abe4ca 100644 --- a/tests/test_ensure_channel_firstd.py +++ b/tests/test_ensure_channel_firstd.py @@ -25,11 +25,7 @@ TEST_CASE_2 = [{"keys": "img"}, ["test_image.nii.gz"], -1] -TEST_CASE_3 = [ - {"keys": "img"}, - ["test_image.nii.gz", "test_image2.nii.gz", "test_image3.nii.gz"], - None, -] +TEST_CASE_3 = [{"keys": "img"}, ["test_image.nii.gz", "test_image2.nii.gz", "test_image3.nii.gz"], None] class TestEnsureChannelFirstd(unittest.TestCase): diff --git a/tests/test_ensure_typed.py b/tests/test_ensure_typed.py index a78df6cb3f..283f3fa730 100644 --- a/tests/test_ensure_typed.py +++ b/tests/test_ensure_typed.py @@ -26,10 +26,7 @@ def test_array_input(self): for test_data in test_datas: for dtype in ("tensor", "NUMPY"): result = EnsureTyped( - keys="data", - data_type=dtype, - dtype=np.float32 if dtype == "NUMPY" else None, - device="cpu", + keys="data", data_type=dtype, dtype=np.float32 if dtype == "NUMPY" else None, device="cpu" )({"data": test_data})["data"] if dtype == "NUMPY": self.assertTrue(result.dtype == np.float32) diff --git a/tests/test_fill_holes.py b/tests/test_fill_holes.py index 6ea83c239b..c6ad202587 100644 --- a/tests/test_fill_holes.py +++ b/tests/test_fill_holes.py @@ -18,29 +18,13 @@ from monai.transforms import FillHoles from tests.utils import assert_allclose, clone -grid_1_raw = [ - [1, 1, 1], - [1, 0, 1], - [1, 1, 1], -] +grid_1_raw = [[1, 1, 1], [1, 0, 1], [1, 1, 1]] -grid_2_raw = [ - [0, 1, 0], - [1, 0, 1], - [0, 1, 0], -] +grid_2_raw = [[0, 1, 0], [1, 0, 1], [0, 1, 0]] -grid_3_raw = [ - [1, 1, 1], - [1, 1, 1], - [1, 1, 1], -] +grid_3_raw = [[1, 1, 1], [1, 1, 1], [1, 1, 1]] -grid_4_raw = [ - [0, 1, 0], - [1, 1, 1], - [0, 1, 0], -] +grid_4_raw = [[0, 1, 0], [1, 1, 1], [0, 1, 0]] grid_1 = torch.tensor([grid_1_raw]) @@ -50,49 +34,15 @@ grid_4 = torch.tensor([grid_4_raw]) -grid_5 = torch.tensor( - [ - [ - [1, 1, 1], - [1, 0, 0], - [1, 1, 1], - ] - ] -) - -grid_6 = torch.tensor( - [ - [ - [1, 1, 2, 2, 2], - [1, 0, 2, 0, 2], - [1, 1, 2, 2, 2], - ] - ] -) - -grid_7 = torch.tensor( - [ - [ - [1, 1, 2, 2, 2], - [1, 0, 2, 2, 2], - [1, 1, 2, 2, 2], - ] - ] -) - -TEST_CASE_0 = [ - "enclosed_default_full_connectivity_default_applied_labels", - {}, - grid_1, - grid_3, -] +grid_5 = torch.tensor([[[1, 1, 1], [1, 0, 0], [1, 1, 1]]]) -TEST_CASE_1 = [ - "enclosed_full_connectivity_default_applied_labels", - {"connectivity": 2}, - grid_1, - grid_3, -] +grid_6 = torch.tensor([[[1, 1, 2, 2, 2], [1, 0, 2, 0, 2], [1, 1, 2, 2, 2]]]) + +grid_7 = torch.tensor([[[1, 1, 2, 2, 2], [1, 0, 2, 2, 2], [1, 1, 2, 2, 2]]]) + +TEST_CASE_0 = ["enclosed_default_full_connectivity_default_applied_labels", {}, grid_1, grid_3] + +TEST_CASE_1 = ["enclosed_full_connectivity_default_applied_labels", {"connectivity": 2}, grid_1, grid_3] TEST_CASE_2 = [ "enclosed_full_connectivity_applied_labels_same_single", @@ -129,40 +79,15 @@ grid_3, ] -TEST_CASE_7 = [ - "enclosed_connectivity_1_default_applied_labels", - {"connectivity": 1}, - grid_1, - grid_3, -] +TEST_CASE_7 = ["enclosed_connectivity_1_default_applied_labels", {"connectivity": 1}, grid_1, grid_3] -TEST_CASE_8 = [ - "enclosed_connectivity_1_default_applied_labels", - {"connectivity": 1}, - grid_2, - grid_4, -] +TEST_CASE_8 = ["enclosed_connectivity_1_default_applied_labels", {"connectivity": 1}, grid_2, grid_4] -TEST_CASE_9 = [ - "open_full_connectivity_default_applied_labels", - {"connectivity": 2}, - grid_2, - grid_2, -] +TEST_CASE_9 = ["open_full_connectivity_default_applied_labels", {"connectivity": 2}, grid_2, grid_2] -TEST_CASE_10 = [ - "open_to_edge_connectivity_1_default_applied_labels", - {"connectivity": 1}, - grid_5, - grid_5, -] +TEST_CASE_10 = ["open_to_edge_connectivity_1_default_applied_labels", {"connectivity": 1}, grid_5, grid_5] -TEST_CASE_11 = [ - "open_to_other_label_connectivity_1_default_applied_labels", - {"connectivity": 1}, - grid_6, - grid_7, -] +TEST_CASE_11 = ["open_to_other_label_connectivity_1_default_applied_labels", {"connectivity": 1}, grid_6, grid_7] TEST_CASE_12 = [ "open_to_other_label_connectivity_1_applied_labels_other", diff --git a/tests/test_gaussian.py b/tests/test_gaussian.py index e2659abb0c..b17663652b 100644 --- a/tests/test_gaussian.py +++ b/tests/test_gaussian.py @@ -241,16 +241,8 @@ def test_gaussian(self): rtol=1e-4, ) - np.testing.assert_allclose( - gaussian_1d(1, 1), - torch.tensor([0.24173, 0.382925, 0.24173]), - rtol=1e-4, - ) - np.testing.assert_allclose( - gaussian_1d(1, 1, normalize=True), - torch.tensor([0.2790, 0.4420, 0.2790]), - rtol=1e-4, - ) + np.testing.assert_allclose(gaussian_1d(1, 1), torch.tensor([0.24173, 0.382925, 0.24173]), rtol=1e-4) + np.testing.assert_allclose(gaussian_1d(1, 1, normalize=True), torch.tensor([0.2790, 0.4420, 0.2790]), rtol=1e-4) def test_scalespace_gaussian(self): np.testing.assert_allclose( @@ -272,15 +264,11 @@ def test_scalespace_gaussian(self): ) np.testing.assert_allclose( - gaussian_1d(1, 1, "scalespace"), - torch.tensor([0.20791, 0.46576, 0.20791]), - rtol=1e-3, + gaussian_1d(1, 1, "scalespace"), torch.tensor([0.20791, 0.46576, 0.20791]), rtol=1e-3 ) np.testing.assert_allclose( - gaussian_1d(1, 1, "scalespace", normalize=True), - torch.tensor([0.2358, 0.5283, 0.2358]), - rtol=1e-3, + gaussian_1d(1, 1, "scalespace", normalize=True), torch.tensor([0.2358, 0.5283, 0.2358]), rtol=1e-3 ) np.testing.assert_allclose( diff --git a/tests/test_gaussian_filter.py b/tests/test_gaussian_filter.py index 7636aa5459..62aea524b8 100644 --- a/tests/test_gaussian_filter.py +++ b/tests/test_gaussian_filter.py @@ -19,10 +19,7 @@ from tests.utils import SkipIfBeforePyTorchVersion, skip_if_quick TEST_CASES = [[{"type": "erf", "gt": 2.0}], [{"type": "scalespace", "gt": 3.0}], [{"type": "sampled", "gt": 5.0}]] -TEST_CASES_GPU = [ - [{"type": "erf", "gt": 0.8, "device": "cuda"}], - [{"type": "sampled", "gt": 5.0, "device": "cuda"}], -] +TEST_CASES_GPU = [[{"type": "erf", "gt": 0.8, "device": "cuda"}], [{"type": "sampled", "gt": 5.0, "device": "cuda"}]] TEST_CASES_3d = [ [{"type": "scalespace", "gt": 0.5, "dims": (2, 3, 8, 9, 10), "lr": 0.01, "device": "cuda"}], [{"type": "erf", "gt": 3.8, "dims": (2, 3, 8, 9, 10), "lr": 0.1, "device": "cuda"}], diff --git a/tests/test_generalized_dice_loss.py b/tests/test_generalized_dice_loss.py index 06446204fb..7285f01a41 100644 --- a/tests/test_generalized_dice_loss.py +++ b/tests/test_generalized_dice_loss.py @@ -21,10 +21,7 @@ TEST_CASES = [ [ # shape: (1, 1, 2, 2), (1, 1, 2, 2) {"include_background": True, "sigmoid": True, "smooth_nr": 1e-6, "smooth_dr": 1e-6}, - { - "input": torch.tensor([[[[1.0, -1.0], [-1.0, 1.0]]]]), - "target": torch.tensor([[[[1.0, 0.0], [1.0, 1.0]]]]), - }, + {"input": torch.tensor([[[[1.0, -1.0], [-1.0, 1.0]]]]), "target": torch.tensor([[[[1.0, 0.0], [1.0, 1.0]]]])}, 0.307576, ], [ # shape: (2, 1, 2, 2), (2, 1, 2, 2) @@ -99,10 +96,7 @@ ], [ # shape: (1, 1, 2, 2), (1, 1, 2, 2) {"include_background": True, "sigmoid": True, "smooth_nr": 1e-6, "smooth_dr": 1e-6}, - { - "input": torch.tensor([[[[1.0, -1.0], [-1.0, 1.0]]]]), - "target": torch.tensor([[[[1.0, 0.0], [1.0, 1.0]]]]), - }, + {"input": torch.tensor([[[[1.0, -1.0], [-1.0, 1.0]]]]), "target": torch.tensor([[[[1.0, 0.0], [1.0, 1.0]]]])}, 0.307576, ], [ # shape: (1, 2, 4), (1, 1, 4) diff --git a/tests/test_generate_param_groups.py b/tests/test_generate_param_groups.py index ea1fad44f9..0fe94ba218 100644 --- a/tests/test_generate_param_groups.py +++ b/tests/test_generate_param_groups.py @@ -18,15 +18,7 @@ from monai.optimizers import generate_param_groups from monai.utils import ensure_tuple -TEST_CASE_1 = [ - { - "layer_matches": [lambda x: x.model[-1]], - "match_types": "select", - "lr_values": [1], - }, - (1, 100), - [5, 21], -] +TEST_CASE_1 = [{"layer_matches": [lambda x: x.model[-1]], "match_types": "select", "lr_values": [1]}, (1, 100), [5, 21]] TEST_CASE_2 = [ { @@ -39,11 +31,7 @@ ] TEST_CASE_3 = [ - { - "layer_matches": [lambda x: x.model[2][1].conv[0].conv], - "match_types": ["select"], - "lr_values": [1], - }, + {"layer_matches": [lambda x: x.model[2][1].conv[0].conv], "match_types": ["select"], "lr_values": [1]}, (1, 100), [2, 24], ] @@ -59,12 +47,7 @@ ] TEST_CASE_5 = [ - { - "layer_matches": [lambda x: x.model[-1]], - "match_types": ["select"], - "lr_values": [1], - "include_others": False, - }, + {"layer_matches": [lambda x: x.model[-1]], "match_types": ["select"], "lr_values": [1], "include_others": False}, (1), [5], ] @@ -86,12 +69,7 @@ class TestGenerateParamGroups(unittest.TestCase): def test_lr_values(self, input_param, expected_values, expected_groups): device = "cuda" if torch.cuda.is_available() else "cpu" net = Unet( - dimensions=3, - in_channels=1, - out_channels=3, - channels=(16, 32, 64), - strides=(2, 2), - num_res_units=1, + dimensions=3, in_channels=1, out_channels=3, channels=(16, 32, 64), strides=(2, 2), num_res_units=1 ).to(device) params = generate_param_groups(network=net, **input_param) @@ -107,12 +85,7 @@ def test_wrong(self): """overlapped""" device = "cuda" if torch.cuda.is_available() else "cpu" net = Unet( - dimensions=3, - in_channels=1, - out_channels=3, - channels=(16, 32, 64), - strides=(2, 2), - num_res_units=1, + dimensions=3, in_channels=1, out_channels=3, channels=(16, 32, 64), strides=(2, 2), num_res_units=1 ).to(device) params = generate_param_groups( diff --git a/tests/test_gmm.py b/tests/test_gmm.py index 0e2401b452..641f6b998b 100644 --- a/tests/test_gmm.py +++ b/tests/test_gmm.py @@ -47,12 +47,12 @@ # Batch 0 [ # Channel 0 - [1, -1, 0, -1, 1], + [1, -1, 0, -1, 1] ], # Batch 1 [ # Channel 0 - [1, 1, 0, 0, -1], + [1, 1, 0, 0, -1] ], ], # Expected @@ -94,15 +94,15 @@ [0.7, 0.9, 0.0, 0.0, 0.0], # Channel 4 [0.2, 0.1, 0.2, 0.2, 0.1], - ], + ] ], # Labels [ # Batch 0 [ # Channel 0 - [0, 0, -1, 1, 1], - ], + [0, 0, -1, 1, 1] + ] ], # Expected [ @@ -112,7 +112,7 @@ [1, 1, 0, 0, 0], # Channel 1 [0, 0, 1, 1, 1], - ], + ] ], ], [ @@ -142,21 +142,15 @@ [0.4, 0.5, 0.0, 0.0, 0.0], [0.7, 0.6, 0.0, 0.0, 0.0], ], - ], + ] ], # Labels [ # Batch 0 [ # Channel 0 - [ - [-1, 1, -1, 0, -1], - [1, -1, -1, -1, -1], - [-1, -1, 0, -1, -1], - [2, 2, -1, 3, -1], - [-1, -1, -1, -1, 3], - ], - ], + [[-1, 1, -1, 0, -1], [1, -1, -1, -1, -1], [-1, -1, 0, -1, -1], [2, 2, -1, 3, -1], [-1, -1, -1, -1, 3]] + ] ], # Expected [ @@ -194,7 +188,7 @@ [0.0, 0.0, 0.0, 1.0, 1.0], [0.0, 0.0, 0.0, 1.0, 1.0], ], - ], + ] ], ], [ @@ -211,25 +205,13 @@ # Channel 0 [ # Slice 0 - [ - [0.7, 0.6, 0.0], - [0.5, 0.4, 0.0], - [0.0, 0.0, 0.0], - ], + [[0.7, 0.6, 0.0], [0.5, 0.4, 0.0], [0.0, 0.0, 0.0]], # Slice 1 - [ - [0.5, 0.6, 0.0], - [0.4, 0.3, 0.0], - [0.0, 0.0, 0.0], - ], + [[0.5, 0.6, 0.0], [0.4, 0.3, 0.0], [0.0, 0.0, 0.0]], # Slice 2 - [ - [0.3, 0.3, 0.0], - [0.2, 0.1, 0.0], - [0.0, 0.0, 0.0], - ], - ], - ], + [[0.3, 0.3, 0.0], [0.2, 0.1, 0.0], [0.0, 0.0, 0.0]], + ] + ] ], # Labels [ @@ -238,25 +220,13 @@ # Channel 0 [ # Slice 0 - [ - [0, -1, -1], - [0, -1, -1], - [-1, -1, 1], - ], + [[0, -1, -1], [0, -1, -1], [-1, -1, 1]], # Slice 1 - [ - [0, 0, -1], - [-1, -1, 1], - [-1, 1, 1], - ], + [[0, 0, -1], [-1, -1, 1], [-1, 1, 1]], # Slice 2 - [ - [0, -1, -1], - [-1, -1, -1], - [-1, -1, -1], - ], - ], - ], + [[0, -1, -1], [-1, -1, -1], [-1, -1, -1]], + ] + ] ], # Expected [ @@ -265,46 +235,22 @@ # Channel 0 [ # Slice 0 - [ - [1.0, 1.0, 0.0], - [1.0, 1.0, 0.0], - [0.0, 0.0, 0.0], - ], + [[1.0, 1.0, 0.0], [1.0, 1.0, 0.0], [0.0, 0.0, 0.0]], # Slice 1 - [ - [1.0, 1.0, 0.0], - [1.0, 1.0, 0.0], - [0.0, 0.0, 0.0], - ], + [[1.0, 1.0, 0.0], [1.0, 1.0, 0.0], [0.0, 0.0, 0.0]], # Slice 2 - [ - [1.0, 1.0, 0.0], - [1.0, 1.0, 0.0], - [0.0, 0.0, 0.0], - ], + [[1.0, 1.0, 0.0], [1.0, 1.0, 0.0], [0.0, 0.0, 0.0]], ], # Channel 1 [ # Slice 0 - [ - [0.0, 0.0, 1.0], - [0.0, 0.0, 1.0], - [1.0, 1.0, 1.0], - ], + [[0.0, 0.0, 1.0], [0.0, 0.0, 1.0], [1.0, 1.0, 1.0]], # Slice 1 - [ - [0.0, 0.0, 1.0], - [0.0, 0.0, 1.0], - [1.0, 1.0, 1.0], - ], + [[0.0, 0.0, 1.0], [0.0, 0.0, 1.0], [1.0, 1.0, 1.0]], # Slice 2 - [ - [0.0, 0.0, 1.0], - [0.0, 0.0, 1.0], - [1.0, 1.0, 1.0], - ], + [[0.0, 0.0, 1.0], [0.0, 0.0, 1.0], [1.0, 1.0, 1.0]], ], - ], + ] ], ], ] diff --git a/tests/test_grid_dataset.py b/tests/test_grid_dataset.py index 0f4065a30b..3c5c5bd4fa 100644 --- a/tests/test_grid_dataset.py +++ b/tests/test_grid_dataset.py @@ -59,11 +59,7 @@ def test_loading_array(self): np.array([[[[2.0577, 3.0577], [6.0577, 7.0577]]], [[[10.5540, 11.5540], [14.5540, 15.5540]]]]), rtol=1e-5, ) - np.testing.assert_allclose( - item[1], - np.array([[[0, 1], [0, 2], [2, 4]], [[0, 1], [2, 4], [2, 4]]]), - rtol=1e-5, - ) + np.testing.assert_allclose(item[1], np.array([[[0, 1], [0, 2], [2, 4]], [[0, 1], [2, 4], [2, 4]]]), rtol=1e-5) if sys.platform != "win32": for item in DataLoader(ds, batch_size=2, shuffle=False, num_workers=2): np.testing.assert_equal(tuple(item[0].shape), (2, 1, 2, 2)) @@ -73,9 +69,7 @@ def test_loading_array(self): rtol=1e-3, ) np.testing.assert_allclose( - item[1], - np.array([[[0, 1], [0, 2], [2, 4]], [[0, 1], [2, 4], [2, 4]]]), - rtol=1e-5, + item[1], np.array([[[0, 1], [0, 2], [2, 4]], [[0, 1], [2, 4], [2, 4]]]), rtol=1e-5 ) diff --git a/tests/test_grid_distortion.py b/tests/test_grid_distortion.py index 75f8bb06bc..09fcb856f3 100644 --- a/tests/test_grid_distortion.py +++ b/tests/test_grid_distortion.py @@ -21,12 +21,7 @@ for p in TEST_NDARRAYS: TESTS.append( [ - dict( - num_cells=3, - distort_steps=[(1.5,) * 4] * 2, - mode="nearest", - padding_mode="zeros", - ), + dict(num_cells=3, distort_steps=[(1.5,) * 4] * 2, mode="nearest", padding_mode="zeros"), p(np.indices([6, 6]).astype(np.float32)), p( np.array( @@ -56,12 +51,7 @@ distort_steps = [(1.5,) * (1 + num_cells[0]), (1.0,) * (1 + num_cells[1])] TESTS.append( [ - dict( - num_cells=num_cells, - distort_steps=distort_steps, - mode="bilinear", - padding_mode="reflection", - ), + dict(num_cells=num_cells, distort_steps=distort_steps, mode="bilinear", padding_mode="reflection"), p(np.indices([6, 6]).astype(np.float32)), p( np.array( @@ -89,12 +79,7 @@ ) TESTS.append( [ - dict( - num_cells=2, - distort_steps=[(1.25,) * 3] * 3, - mode="nearest", - padding_mode="zeros", - ), + dict(num_cells=2, distort_steps=[(1.25,) * 3] * 3, mode="nearest", padding_mode="zeros"), p(np.indices([3, 3, 3])[:1].astype(np.float32)), p( np.array( diff --git a/tests/test_grid_pull.py b/tests/test_grid_pull.py index cbfd8a9590..25e1d7c1d8 100644 --- a/tests/test_grid_pull.py +++ b/tests/test_grid_pull.py @@ -53,11 +53,7 @@ def make_grid(shape, dtype=None, device=None, requires_grad=True): "interpolation": interp, "bound": bound, }, - { - "val": torch.tensor([[expected_val]]), - "device": device, - "grad": torch.tensor(expected_grad), - }, + {"val": torch.tensor([[expected_val]]), "device": device, "grad": torch.tensor(expected_grad)}, ] TEST_1D_GP.append(test_case) diff --git a/tests/test_handler_checkpoint_saver.py b/tests/test_handler_checkpoint_saver.py index bcab49f12b..86544e5321 100644 --- a/tests/test_handler_checkpoint_saver.py +++ b/tests/test_handler_checkpoint_saver.py @@ -112,16 +112,7 @@ class TestHandlerCheckpointSaver(unittest.TestCase): @parameterized.expand( - [ - TEST_CASE_1, - TEST_CASE_2, - TEST_CASE_3, - TEST_CASE_4, - TEST_CASE_5, - TEST_CASE_6, - TEST_CASE_7, - TEST_CASE_8, - ] + [TEST_CASE_1, TEST_CASE_2, TEST_CASE_3, TEST_CASE_4, TEST_CASE_5, TEST_CASE_6, TEST_CASE_7, TEST_CASE_8] ) def test_file( self, diff --git a/tests/test_handler_confusion_matrix.py b/tests/test_handler_confusion_matrix.py index 0c6e36066b..2765bf6799 100644 --- a/tests/test_handler_confusion_matrix.py +++ b/tests/test_handler_confusion_matrix.py @@ -39,16 +39,8 @@ } data_2: Dict[Any, Any] = { - "y_pred": torch.tensor( - [ - [[[0.0, 1.0], [1.0, 0.0]], [[1.0, 0.0], [1.0, 1.0]], [[0.0, 1.0], [0.0, 0.0]]], - ] - ), - "y": torch.tensor( - [ - [[[1.0, 1.0], [1.0, 1.0]], [[1.0, 1.0], [1.0, 1.0]], [[1.0, 1.0], [1.0, 1.0]]], - ] - ), + "y_pred": torch.tensor([[[[0.0, 1.0], [1.0, 0.0]], [[1.0, 0.0], [1.0, 1.0]], [[0.0, 1.0], [0.0, 0.0]]]]), + "y": torch.tensor([[[[1.0, 1.0], [1.0, 1.0]], [[1.0, 1.0], [1.0, 1.0]], [[1.0, 1.0], [1.0, 1.0]]]]), } diff --git a/tests/test_handler_confusion_matrix_dist.py b/tests/test_handler_confusion_matrix_dist.py index 40245bce2e..31e853cd00 100644 --- a/tests/test_handler_confusion_matrix_dist.py +++ b/tests/test_handler_confusion_matrix_dist.py @@ -54,12 +54,10 @@ def _val_func(engine, batch): if dist.get_rank() == 1: y_pred = torch.tensor( - [[[[0.0, 1.0], [1.0, 0.0]], [[1.0, 0.0], [1.0, 1.0]], [[0.0, 1.0], [0.0, 0.0]]]], - device=device, + [[[[0.0, 1.0], [1.0, 0.0]], [[1.0, 0.0], [1.0, 1.0]], [[0.0, 1.0], [0.0, 0.0]]]], device=device ) y = torch.tensor( - [[[[1.0, 1.0], [1.0, 1.0]], [[1.0, 1.0], [1.0, 1.0]], [[1.0, 1.0], [1.0, 1.0]]]], - device=device, + [[[[1.0, 1.0], [1.0, 1.0]], [[1.0, 1.0], [1.0, 1.0]], [[1.0, 1.0], [1.0, 1.0]]]], device=device ) metric.update([y_pred, y]) diff --git a/tests/test_handler_early_stop.py b/tests/test_handler_early_stop.py index efe8e89825..4707a8b3cc 100644 --- a/tests/test_handler_early_stop.py +++ b/tests/test_handler_early_stop.py @@ -23,10 +23,7 @@ def _train_func(engine, batch): trainer = Engine(_train_func) EarlyStopHandler( - patience=5, - score_function=lambda x: x.state.output["loss"], - trainer=trainer, - epoch_level=False, + patience=5, score_function=lambda x: x.state.output["loss"], trainer=trainer, epoch_level=False ).attach(trainer) trainer.run(range(4), max_epochs=2) diff --git a/tests/test_handler_garbage_collector.py b/tests/test_handler_garbage_collector.py index 75ab9ceb99..23ecfbbf37 100644 --- a/tests/test_handler_garbage_collector.py +++ b/tests/test_handler_garbage_collector.py @@ -34,13 +34,7 @@ class TestHandlerGarbageCollector(unittest.TestCase): @skipUnless(has_ignite, "Requires ignite") - @parameterized.expand( - [ - TEST_CASE_0, - TEST_CASE_1, - TEST_CASE_2, - ] - ) + @parameterized.expand([TEST_CASE_0, TEST_CASE_1, TEST_CASE_2]) def test_content(self, data, trigger_event): # set up engine gb_count_dict = {} diff --git a/tests/test_handler_hausdorff_distance.py b/tests/test_handler_hausdorff_distance.py index bbc36cc2b5..ced9503499 100644 --- a/tests/test_handler_hausdorff_distance.py +++ b/tests/test_handler_hausdorff_distance.py @@ -20,9 +20,7 @@ def create_spherical_seg_3d( - radius: float = 20.0, - centre: Tuple[int, int, int] = (49, 49, 49), - im_shape: Tuple[int, int, int] = (99, 99, 99), + radius: float = 20.0, centre: Tuple[int, int, int] = (49, 49, 49), im_shape: Tuple[int, int, int] = (99, 99, 99) ) -> np.ndarray: """ Return a 3D image with a sphere inside. Voxel values will be diff --git a/tests/test_handler_metrics_saver_dist.py b/tests/test_handler_metrics_saver_dist.py index 0a36a19c66..0b65b14886 100644 --- a/tests/test_handler_metrics_saver_dist.py +++ b/tests/test_handler_metrics_saver_dist.py @@ -52,10 +52,7 @@ def _val_func(engine, batch): @engine.on(Events.EPOCH_COMPLETED) def _save_metrics0(engine): engine.state.metrics = {"metric1": 1, "metric2": 2} - engine.state.metric_details = { - "metric3": torch.tensor([[1, 2]]), - "metric4": torch.tensor([[5, 6]]), - } + engine.state.metric_details = {"metric3": torch.tensor([[1, 2]]), "metric4": torch.tensor([[5, 6]])} if dist.get_rank() == 1: # different ranks have different data length diff --git a/tests/test_handler_nvtx.py b/tests/test_handler_nvtx.py index fee29af344..6723e55892 100644 --- a/tests/test_handler_nvtx.py +++ b/tests/test_handler_nvtx.py @@ -22,42 +22,18 @@ _, has_nvtx = optional_import("torch._C._nvtx", descriptor="NVTX is not installed. Are you sure you have a CUDA build?") -TENSOR_0 = torch.tensor( - [ - [ - [[1.0], [2.0]], - [[3.0], [4.0]], - ] - ] -) +TENSOR_0 = torch.tensor([[[[1.0], [2.0]], [[3.0], [4.0]]]]) -TENSOR_1 = torch.tensor( - [ - [ - [[0.0], [-2.0]], - [[-3.0], [4.0]], - ] - ] -) +TENSOR_1 = torch.tensor([[[[0.0], [-2.0]], [[-3.0], [4.0]]]]) -TENSOR_1_EXPECTED = torch.tensor( - [ - [[1.0], [0.5]], - [[0.25], [5.0]], - ] -) +TENSOR_1_EXPECTED = torch.tensor([[[1.0], [0.5]], [[0.25], [5.0]]]) TEST_CASE_0 = [[{"image": TENSOR_0}], TENSOR_0[0] + 1.0] TEST_CASE_1 = [[{"image": TENSOR_1}], TENSOR_1_EXPECTED] class TestHandlerDecollateBatch(unittest.TestCase): - @parameterized.expand( - [ - TEST_CASE_0, - TEST_CASE_1, - ] - ) + @parameterized.expand([TEST_CASE_0, TEST_CASE_1]) @unittest.skipUnless(has_nvtx, "CUDA is required for NVTX!") def test_compute(self, data, expected): # Set up handlers diff --git a/tests/test_handler_prob_map_producer.py b/tests/test_handler_prob_map_producer.py index b21cf03171..316cd6f70a 100644 --- a/tests/test_handler_prob_map_producer.py +++ b/tests/test_handler_prob_map_producer.py @@ -32,12 +32,7 @@ class TestDataset(Dataset): def __init__(self, name, size): super().__init__( data=[ - { - "name": name, - "mask_shape": (size, size), - "mask_locations": [[i, i] for i in range(size)], - "level": 0, - } + {"name": name, "mask_shape": (size, size), "mask_locations": [[i, i] for i in range(size)], "level": 0} ] ) self.len = size @@ -46,11 +41,7 @@ def __len__(self): return self.len def __getitem__(self, index): - return { - "name": self.data[0]["name"], - "mask_location": self.data[0]["mask_locations"][index], - "pred": index + 1, - } + return {"name": self.data[0]["name"], "mask_location": self.data[0]["mask_locations"][index], "pred": index + 1} class TestEvaluator(Evaluator): @@ -59,13 +50,7 @@ def _iteration(self, engine, batchdata): class TestHandlerProbMapGenerator(unittest.TestCase): - @parameterized.expand( - [ - TEST_CASE_0, - TEST_CASE_1, - TEST_CASE_2, - ] - ) + @parameterized.expand([TEST_CASE_0, TEST_CASE_1, TEST_CASE_2]) def test_prob_map_generator(self, name, size): # set up dataset dataset = TestDataset(name, size) diff --git a/tests/test_handler_smartcache.py b/tests/test_handler_smartcache.py index b67f1226cd..23a6aa7500 100644 --- a/tests/test_handler_smartcache.py +++ b/tests/test_handler_smartcache.py @@ -24,13 +24,7 @@ class TestHandlerSmartCache(unittest.TestCase): def test_content(self): data = [0, 1, 2, 3, 4, 5, 6, 7, 8] - expected = [ - [0, 1, 2, 3, 4], - [1, 2, 3, 4, 5], - [2, 3, 4, 5, 6], - [3, 4, 5, 6, 7], - [4, 5, 6, 7, 8], - ] + expected = [[0, 1, 2, 3, 4], [1, 2, 3, 4, 5], [2, 3, 4, 5, 6], [3, 4, 5, 6, 7], [4, 5, 6, 7, 8]] # set up engine def _train_func(engine, batch): diff --git a/tests/test_handler_stats.py b/tests/test_handler_stats.py index e5d71bcc8a..49433195c8 100644 --- a/tests/test_handler_stats.py +++ b/tests/test_handler_stats.py @@ -187,9 +187,7 @@ def _update_metric(engine): # set up testing handler stats_handler = StatsHandler( - name=key_to_handler, - state_attributes=["test1", "test2", "test3"], - logger_handler=log_handler, + name=key_to_handler, state_attributes=["test1", "test2", "test3"], logger_handler=log_handler ) stats_handler.attach(engine) diff --git a/tests/test_handler_surface_distance.py b/tests/test_handler_surface_distance.py index 82cdb50d90..076f84eca9 100644 --- a/tests/test_handler_surface_distance.py +++ b/tests/test_handler_surface_distance.py @@ -20,9 +20,7 @@ def create_spherical_seg_3d( - radius: float = 20.0, - centre: Tuple[int, int, int] = (49, 49, 49), - im_shape: Tuple[int, int, int] = (99, 99, 99), + radius: float = 20.0, centre: Tuple[int, int, int] = (49, 49, 49), im_shape: Tuple[int, int, int] = (99, 99, 99) ) -> np.ndarray: """ Return a 3D image with a sphere inside. Voxel values will be diff --git a/tests/test_hausdorff_distance.py b/tests/test_hausdorff_distance.py index 0b313f722f..182c8cdaca 100644 --- a/tests/test_hausdorff_distance.py +++ b/tests/test_hausdorff_distance.py @@ -20,9 +20,7 @@ def create_spherical_seg_3d( - radius: float = 20.0, - centre: Tuple[int, int, int] = (49, 49, 49), - im_shape: Tuple[int, int, int] = (99, 99, 99), + radius: float = 20.0, centre: Tuple[int, int, int] = (49, 49, 49), im_shape: Tuple[int, int, int] = (99, 99, 99) ) -> np.ndarray: """ Return a 3D image with a sphere inside. Voxel values will be @@ -49,10 +47,7 @@ def create_spherical_seg_3d( TEST_CASES = [ - [ - [create_spherical_seg_3d(), create_spherical_seg_3d(), 1], - [0, 0, 0, 0, 0, 0], - ], + [[create_spherical_seg_3d(), create_spherical_seg_3d(), 1], [0, 0, 0, 0, 0, 0]], [ [ create_spherical_seg_3d(radius=20, centre=(20, 20, 20)), @@ -106,8 +101,8 @@ def create_spherical_seg_3d( # both pred and gt do not have foreground, metric and not_nans should be 0 np.zeros([99, 99, 99]), np.zeros([99, 99, 99]), - ], - ], + ] + ] ] diff --git a/tests/test_hilbert_transform.py b/tests/test_hilbert_transform.py index 82454c34d0..ffe5824034 100644 --- a/tests/test_hilbert_transform.py +++ b/tests/test_hilbert_transform.py @@ -28,10 +28,7 @@ def create_expected_numpy_output(input_datum, **kwargs): - x = np.fft.fft( - input_datum.cpu().numpy() if input_datum.device.type == "cuda" else input_datum.numpy(), - **kwargs, - ) + x = np.fft.fft(input_datum.cpu().numpy() if input_datum.device.type == "cuda" else input_datum.numpy(), **kwargs) f = np.fft.fftfreq(x.shape[kwargs["axis"]]) u = np.heaviside(f, 0.5) new_dims_before = kwargs["axis"] diff --git a/tests/test_integration_workflows.py b/tests/test_integration_workflows.py index 4a3e027993..0ffef2935b 100644 --- a/tests/test_integration_workflows.py +++ b/tests/test_integration_workflows.py @@ -245,12 +245,7 @@ def run_inference_test(root_dir, model_file, device="cuda:0", amp=False, num_wor AsDiscreted(keys="pred", threshold_values=True), KeepLargestConnectedComponentd(keys="pred", applied_labels=[1]), # test the case that `pred` in `engine.state.output`, while `image_meta_dict` in `engine.state.batch` - SaveImaged( - keys="pred", - meta_keys="image_meta_dict", - output_dir=root_dir, - output_postfix="seg_transform", - ), + SaveImaged(keys="pred", meta_keys="image_meta_dict", output_dir=root_dir, output_postfix="seg_transform"), ] ) val_handlers = [ @@ -357,11 +352,7 @@ def test_training(self): repeated.append(results) np.testing.assert_allclose(repeated[0], repeated[1]) - @TimedCall( - seconds=300, - skip_timing=not torch.cuda.is_available(), - daemon=False, - ) + @TimedCall(seconds=300, skip_timing=not torch.cuda.is_available(), daemon=False) def test_timing(self): if monai.utils.module.get_torch_version_tuple() >= (1, 6): self.train_and_infer(idx=2) diff --git a/tests/test_integration_workflows_gan.py b/tests/test_integration_workflows_gan.py index c54e8b01f2..d4b7d99b62 100644 --- a/tests/test_integration_workflows_gan.py +++ b/tests/test_integration_workflows_gan.py @@ -90,8 +90,7 @@ def generator_loss(gen_images): train_handlers = [ StatsHandler( - name="training_loss", - output_transform=lambda x: {Keys.GLOSS: x[Keys.GLOSS], Keys.DLOSS: x[Keys.DLOSS]}, + name="training_loss", output_transform=lambda x: {Keys.GLOSS: x[Keys.GLOSS], Keys.DLOSS: x[Keys.DLOSS]} ), TensorBoardStatsHandler( log_dir=root_dir, diff --git a/tests/test_intensity_stats.py b/tests/test_intensity_stats.py index 92a2c04585..2647efd7c2 100644 --- a/tests/test_intensity_stats.py +++ b/tests/test_intensity_stats.py @@ -23,12 +23,7 @@ {"orig_max": 3.0, "orig_mean": 1.5}, ] -TEST_CASE_2 = [ - {"ops": "std", "key_prefix": "orig"}, - np.array([[[0.0, 1.0], [2.0, 3.0]]]), - None, - {"orig_std": 1.118034}, -] +TEST_CASE_2 = [{"ops": "std", "key_prefix": "orig"}, np.array([[[0.0, 1.0], [2.0, 3.0]]]), None, {"orig_std": 1.118034}] TEST_CASE_3 = [ {"ops": [np.mean, "max", np.min], "key_prefix": "orig"}, diff --git a/tests/test_inverse.py b/tests/test_inverse.py index b09f532fd1..d547fe7595 100644 --- a/tests/test_inverse.py +++ b/tests/test_inverse.py @@ -122,23 +122,9 @@ ) ) -TESTS.append( - ( - "SpatialPadd 3d", - "3D", - 0, - SpatialPadd(KEYS, spatial_size=[112, 113, 116]), - ) -) +TESTS.append(("SpatialPadd 3d", "3D", 0, SpatialPadd(KEYS, spatial_size=[112, 113, 116]))) -TESTS.append( - ( - "SpatialCropd 2d", - "2D", - 0, - SpatialCropd(KEYS, [49, 51], [90, 89]), - ) -) +TESTS.append(("SpatialCropd 2d", "2D", 0, SpatialCropd(KEYS, [49, 51], [90, 89]))) TESTS.append( ( @@ -149,91 +135,28 @@ ) ) -TESTS.append( - ( - "SpatialCropd 2d", - "2D", - 0, - SpatialCropd(KEYS, [49, 51], [390, 89]), - ) -) +TESTS.append(("SpatialCropd 2d", "2D", 0, SpatialCropd(KEYS, [49, 51], [390, 89]))) -TESTS.append( - ( - "SpatialCropd 3d", - "3D", - 0, - SpatialCropd(KEYS, [49, 51, 44], [90, 89, 93]), - ) -) +TESTS.append(("SpatialCropd 3d", "3D", 0, SpatialCropd(KEYS, [49, 51, 44], [90, 89, 93]))) TESTS.append(("RandSpatialCropd 2d", "2D", 0, RandSpatialCropd(KEYS, [96, 93], None, True, False))) TESTS.append(("RandSpatialCropd 3d", "3D", 0, RandSpatialCropd(KEYS, [96, 93, 92], None, False, False))) -TESTS.append( - ( - "BorderPadd 2d", - "2D", - 0, - BorderPadd(KEYS, [3, 7, 2, 5]), - ) -) +TESTS.append(("BorderPadd 2d", "2D", 0, BorderPadd(KEYS, [3, 7, 2, 5]))) -TESTS.append( - ( - "BorderPadd 2d", - "2D", - 0, - BorderPadd(KEYS, [3, 7]), - ) -) +TESTS.append(("BorderPadd 2d", "2D", 0, BorderPadd(KEYS, [3, 7]))) -TESTS.append( - ( - "BorderPadd 3d", - "3D", - 0, - BorderPadd(KEYS, [4]), - ) -) +TESTS.append(("BorderPadd 3d", "3D", 0, BorderPadd(KEYS, [4]))) -TESTS.append( - ( - "DivisiblePadd 2d", - "2D", - 0, - DivisiblePadd(KEYS, k=4), - ) -) +TESTS.append(("DivisiblePadd 2d", "2D", 0, DivisiblePadd(KEYS, k=4))) -TESTS.append( - ( - "DivisiblePadd 3d", - "3D", - 0, - DivisiblePadd(KEYS, k=[4, 8, 11]), - ) -) +TESTS.append(("DivisiblePadd 3d", "3D", 0, DivisiblePadd(KEYS, k=[4, 8, 11]))) -TESTS.append( - ( - "CenterSpatialCropd 2d", - "2D", - 0, - CenterSpatialCropd(KEYS, roi_size=95), - ) -) +TESTS.append(("CenterSpatialCropd 2d", "2D", 0, CenterSpatialCropd(KEYS, roi_size=95))) -TESTS.append( - ( - "CenterSpatialCropd 3d", - "3D", - 0, - CenterSpatialCropd(KEYS, roi_size=[95, 97, 98]), - ) -) +TESTS.append(("CenterSpatialCropd 3d", "3D", 0, CenterSpatialCropd(KEYS, roi_size=[95, 97, 98]))) TESTS.append(("CropForegroundd 2d", "2D", 0, CropForegroundd(KEYS, source_key="label", margin=2))) @@ -242,69 +165,20 @@ TESTS.append(("ResizeWithPadOrCropd 3d", "3D", 0, ResizeWithPadOrCropd(KEYS, [201, 150, 105]))) -TESTS.append( - ( - "Flipd 3d", - "3D", - 0, - Flipd(KEYS, [1, 2]), - ) -) +TESTS.append(("Flipd 3d", "3D", 0, Flipd(KEYS, [1, 2]))) -TESTS.append( - ( - "RandFlipd 3d", - "3D", - 0, - RandFlipd(KEYS, 1, [1, 2]), - ) -) +TESTS.append(("RandFlipd 3d", "3D", 0, RandFlipd(KEYS, 1, [1, 2]))) -TESTS.append( - ( - "RandAxisFlipd 3d", - "3D", - 0, - RandAxisFlipd(KEYS, 1), - ) -) +TESTS.append(("RandAxisFlipd 3d", "3D", 0, RandAxisFlipd(KEYS, 1))) for acc in [True, False]: - TESTS.append( - ( - "Orientationd 3d", - "3D", - 0, - Orientationd(KEYS, "RAS", as_closest_canonical=acc), - ) - ) + TESTS.append(("Orientationd 3d", "3D", 0, Orientationd(KEYS, "RAS", as_closest_canonical=acc))) -TESTS.append( - ( - "Rotate90d 2d", - "2D", - 0, - Rotate90d(KEYS), - ) -) +TESTS.append(("Rotate90d 2d", "2D", 0, Rotate90d(KEYS))) -TESTS.append( - ( - "Rotate90d 3d", - "3D", - 0, - Rotate90d(KEYS, k=2, spatial_axes=(1, 2)), - ) -) +TESTS.append(("Rotate90d 3d", "3D", 0, Rotate90d(KEYS, k=2, spatial_axes=(1, 2)))) -TESTS.append( - ( - "RandRotate90d 3d", - "3D", - 0, - RandRotate90d(KEYS, prob=1, spatial_axes=(1, 2)), - ) -) +TESTS.append(("RandRotate90d 3d", "3D", 0, RandRotate90d(KEYS, prob=1, spatial_axes=(1, 2)))) TESTS.append(("Spacingd 3d", "3D", 3e-2, Spacingd(KEYS, [0.5, 0.7, 0.9], diagonal=False))) @@ -327,51 +201,18 @@ ) ) -TESTS.append( - ( - "Zoomd 1d", - "1D odd", - 0, - Zoomd(KEYS, zoom=2, keep_size=False), - ) -) +TESTS.append(("Zoomd 1d", "1D odd", 0, Zoomd(KEYS, zoom=2, keep_size=False))) -TESTS.append( - ( - "Zoomd 2d", - "2D", - 2e-1, - Zoomd(KEYS, zoom=0.9), - ) -) +TESTS.append(("Zoomd 2d", "2D", 2e-1, Zoomd(KEYS, zoom=0.9))) -TESTS.append( - ( - "Zoomd 3d", - "3D", - 3e-2, - Zoomd(KEYS, zoom=[2.5, 1, 3], keep_size=False), - ) -) +TESTS.append(("Zoomd 3d", "3D", 3e-2, Zoomd(KEYS, zoom=[2.5, 1, 3], keep_size=False))) TESTS.append(("RandZoom 3d", "3D", 9e-2, RandZoomd(KEYS, 1, [0.5, 0.6, 0.9], [1.1, 1, 1.05], keep_size=True))) -TESTS.append( - ( - "RandRotated, prob 0", - "2D", - 0, - RandRotated(KEYS, prob=0), - ) -) +TESTS.append(("RandRotated, prob 0", "2D", 0, RandRotated(KEYS, prob=0))) TESTS.append( - ( - "Rotated 2d", - "2D", - 8e-2, - Rotated(KEYS, random.uniform(np.pi / 6, np.pi), keep_size=True, align_corners=False), - ) + ("Rotated 2d", "2D", 8e-2, Rotated(KEYS, random.uniform(np.pi / 6, np.pi), keep_size=True, align_corners=False)) ) TESTS.append( @@ -392,23 +233,9 @@ ) ) -TESTS.append( - ( - "Transposed 2d", - "2D", - 0, - Transposed(KEYS, [0, 2, 1]), # channel=0 - ) -) +TESTS.append(("Transposed 2d", "2D", 0, Transposed(KEYS, [0, 2, 1]))) # channel=0 -TESTS.append( - ( - "Transposed 3d", - "3D", - 0, - Transposed(KEYS, [0, 3, 1, 2]), # channel=0 - ) -) +TESTS.append(("Transposed 3d", "3D", 0, Transposed(KEYS, [0, 3, 1, 2]))) # channel=0 TESTS.append( ( @@ -444,14 +271,7 @@ ) ) -TESTS.append( - ( - "RandAffine 3d", - "3D", - 0, - RandAffined(KEYS, spatial_size=None, prob=0), - ) -) +TESTS.append(("RandAffine 3d", "3D", 0, RandAffined(KEYS, spatial_size=None, prob=0))) TESTS.append( ( @@ -462,32 +282,11 @@ ) ) -TESTS.append( - ( - "RandCropByPosNegLabeld 2d", - "2D", - 1e-7, - RandCropByPosNegLabeld(KEYS, "label", (99, 96), num_samples=10), - ) -) +TESTS.append(("RandCropByPosNegLabeld 2d", "2D", 1e-7, RandCropByPosNegLabeld(KEYS, "label", (99, 96), num_samples=10))) -TESTS.append( - ( - "RandSpatialCropSamplesd 2d", - "2D", - 1e-7, - RandSpatialCropSamplesd(KEYS, (90, 91), num_samples=10), - ) -) +TESTS.append(("RandSpatialCropSamplesd 2d", "2D", 1e-7, RandSpatialCropSamplesd(KEYS, (90, 91), num_samples=10))) -TESTS.append( - ( - "RandWeightedCropd 2d", - "2D", - 1e-7, - RandWeightedCropd(KEYS, "label", (90, 91), num_samples=10), - ) -) +TESTS.append(("RandWeightedCropd 2d", "2D", 1e-7, RandWeightedCropd(KEYS, "label", (90, 91), num_samples=10))) TESTS_COMPOSE_X2 = [(t[0] + " Compose", t[1], t[2], Compose(Compose(t[3:]))) for t in TESTS] @@ -652,26 +451,14 @@ def test_inverse_inferred_seg(self, extra_transform): batch_size = 10 # num workers = 0 for mac num_workers = 2 if sys.platform != "darwin" else 0 - transforms = Compose( - [ - AddChanneld(KEYS), - SpatialPadd(KEYS, (150, 153)), - extra_transform, - ] - ) + transforms = Compose([AddChanneld(KEYS), SpatialPadd(KEYS, (150, 153)), extra_transform]) num_invertible_transforms = sum(1 for i in transforms.transforms if isinstance(i, InvertibleTransform)) dataset = CacheDataset(test_data, transform=transforms, progress=False) loader = DataLoader(dataset, batch_size=batch_size, shuffle=False, num_workers=num_workers) device = "cuda" if torch.cuda.is_available() else "cpu" - model = UNet( - spatial_dims=2, - in_channels=1, - out_channels=1, - channels=(2, 4), - strides=(2,), - ).to(device) + model = UNet(spatial_dims=2, in_channels=1, out_channels=1, channels=(2, 4), strides=(2,)).to(device) data = first(loader) self.assertEqual(len(data["label_transforms"]), num_invertible_transforms) diff --git a/tests/test_inverse_collation.py b/tests/test_inverse_collation.py index b986f21bce..f0a87c2b9d 100644 --- a/tests/test_inverse_collation.py +++ b/tests/test_inverse_collation.py @@ -48,19 +48,11 @@ for t in [ RandFlipd(keys=KEYS, prob=0.5, spatial_axis=[1, 2]), RandAxisFlipd(keys=KEYS, prob=0.5), - Compose( - [ - RandRotate90d(keys=KEYS, spatial_axes=(1, 2)), - ToTensord(keys=KEYS), - ] - ), + Compose([RandRotate90d(keys=KEYS, spatial_axes=(1, 2)), ToTensord(keys=KEYS)]), RandZoomd(keys=KEYS, prob=0.5, min_zoom=0.5, max_zoom=1.1, keep_size=True), RandRotated(keys=KEYS, prob=0.5, range_x=np.pi), RandAffined( - keys=KEYS, - prob=0.5, - rotate_range=np.pi, - device=torch.device("cuda" if torch.cuda.is_available() else "cpu"), + keys=KEYS, prob=0.5, rotate_range=np.pi, device=torch.device("cuda" if torch.cuda.is_available() else "cpu") ), ] ] @@ -71,19 +63,11 @@ for t in [ RandFlipd(keys=KEYS, prob=0.5, spatial_axis=[1]), RandAxisFlipd(keys=KEYS, prob=0.5), - Compose( - [ - RandRotate90d(keys=KEYS, prob=0.5, spatial_axes=(0, 1)), - ToTensord(keys=KEYS), - ] - ), + Compose([RandRotate90d(keys=KEYS, prob=0.5, spatial_axes=(0, 1)), ToTensord(keys=KEYS)]), RandZoomd(keys=KEYS, prob=0.5, min_zoom=0.5, max_zoom=1.1, keep_size=True), RandRotated(keys=KEYS, prob=0.5, range_x=np.pi), RandAffined( - keys=KEYS, - prob=0.5, - rotate_range=np.pi, - device=torch.device("cuda" if torch.cuda.is_available() else "cpu"), + keys=KEYS, prob=0.5, rotate_range=np.pi, device=torch.device("cuda" if torch.cuda.is_available() else "cpu") ), ] ] diff --git a/tests/test_is_supported_format.py b/tests/test_is_supported_format.py index c0af8f4395..0008712f96 100644 --- a/tests/test_is_supported_format.py +++ b/tests/test_is_supported_format.py @@ -15,35 +15,17 @@ from monai.data import is_supported_format -TEST_CASE_1 = [ - {"filename": "testfile.nii.gz", "suffixes": ["nii", "nii.gz"]}, - True, -] - -TEST_CASE_2 = [ - {"filename": "./testfile.nii.gz", "suffixes": ["nii", "nii.gz"]}, - True, -] - -TEST_CASE_3 = [ - {"filename": "./test.data/file.nii.gz", "suffixes": ["nii", "nii.gz"]}, - True, -] - -TEST_CASE_4 = [ - {"filename": "./test.data/file.nii", "suffixes": ["nii", "nii.gz"]}, - True, -] - -TEST_CASE_5 = [ - {"filename": "C:\\documents\\testfile.nii.gz", "suffixes": ["nii", "nii.gz"]}, - True, -] - -TEST_CASE_6 = [ - {"filename": "1.3.12.2.1107.5.4.4.145.nii.gz", "suffixes": ["nii.gz"]}, - True, -] +TEST_CASE_1 = [{"filename": "testfile.nii.gz", "suffixes": ["nii", "nii.gz"]}, True] + +TEST_CASE_2 = [{"filename": "./testfile.nii.gz", "suffixes": ["nii", "nii.gz"]}, True] + +TEST_CASE_3 = [{"filename": "./test.data/file.nii.gz", "suffixes": ["nii", "nii.gz"]}, True] + +TEST_CASE_4 = [{"filename": "./test.data/file.nii", "suffixes": ["nii", "nii.gz"]}, True] + +TEST_CASE_5 = [{"filename": "C:\\documents\\testfile.nii.gz", "suffixes": ["nii", "nii.gz"]}, True] + +TEST_CASE_6 = [{"filename": "1.3.12.2.1107.5.4.4.145.nii.gz", "suffixes": ["nii.gz"]}, True] class TestIsSupportedFormat(unittest.TestCase): diff --git a/tests/test_iterable_dataset.py b/tests/test_iterable_dataset.py index 7b16eaf594..bf6946101e 100644 --- a/tests/test_iterable_dataset.py +++ b/tests/test_iterable_dataset.py @@ -38,12 +38,7 @@ def test_shape(self): nib.save(test_image, os.path.join(tempdir, f"test_image{str(i)}.nii.gz")) test_data.append({"image": os.path.join(tempdir, f"test_image{str(i)}.nii.gz")}) - test_transform = Compose( - [ - LoadImaged(keys="image"), - SimulateDelayd(keys="image", delay_time=1e-7), - ] - ) + test_transform = Compose([LoadImaged(keys="image"), SimulateDelayd(keys="image", delay_time=1e-7)]) data_iterator = _Stream(test_data) with self.assertRaises(TypeError): # Dataset doesn't work diff --git a/tests/test_keep_largest_connected_component.py b/tests/test_keep_largest_connected_component.py index 527d986614..50caa0bb31 100644 --- a/tests/test_keep_largest_connected_component.py +++ b/tests/test_keep_largest_connected_component.py @@ -42,7 +42,7 @@ [0.0, 1.0, 0.0, 0.0, 0.0], [1.0, 1.0, 0.0, 0.0, 1.0], ], - ], + ] ) grid_4 = torch.tensor( [ @@ -67,7 +67,7 @@ [0.0, 0.0, 0.0, 1.0, 1.0], [0.0, 0.0, 0.0, 0.0, 0.0], ], - ], + ] ) @@ -168,7 +168,7 @@ [0.0, 1.0, 0.0, 0.0, 0.0], [1.0, 1.0, 0.0, 0.0, 1.0], ], - ], + ] ), ] @@ -199,7 +199,7 @@ [0.0, 1.0, 0.0, 0.0, 0.0], [1.0, 1.0, 0.0, 0.0, 1.0], ], - ], + ] ), ] @@ -230,7 +230,7 @@ [0.0, 1.0, 0.0, 0.0, 0.0], [1.0, 1.0, 0.0, 0.0, 0.0], ], - ], + ] ), ] @@ -261,7 +261,7 @@ [0.0, 0.0, 0.0, 1.0, 1.0], [0.0, 0.0, 0.0, 0.0, 0.0], ], - ], + ] ), ] @@ -292,7 +292,7 @@ [0.0, 0.0, 0.0, 1.0, 1.0], [0.0, 0.0, 0.0, 0.0, 0.0], ], - ], + ] ), ] diff --git a/tests/test_keep_largest_connected_componentd.py b/tests/test_keep_largest_connected_componentd.py index 9478cfb965..96a8154b65 100644 --- a/tests/test_keep_largest_connected_componentd.py +++ b/tests/test_keep_largest_connected_componentd.py @@ -42,7 +42,7 @@ [0.0, 1.0, 0.0, 0.0, 0.0], [1.0, 1.0, 0.0, 0.0, 1.0], ], - ], + ] ) } grid_4 = { @@ -69,7 +69,7 @@ [0.0, 0.0, 0.0, 1.0, 1.0], [0.0, 0.0, 0.0, 0.0, 0.0], ], - ], + ] ) } @@ -170,7 +170,7 @@ [0.0, 1.0, 0.0, 0.0, 0.0], [1.0, 1.0, 0.0, 0.0, 1.0], ], - ], + ] ), ] @@ -201,7 +201,7 @@ [0.0, 1.0, 0.0, 0.0, 0.0], [1.0, 1.0, 0.0, 0.0, 1.0], ], - ], + ] ), ] @@ -232,7 +232,7 @@ [0.0, 1.0, 0.0, 0.0, 0.0], [1.0, 1.0, 0.0, 0.0, 0.0], ], - ], + ] ), ] @@ -263,7 +263,7 @@ [0.0, 0.0, 0.0, 1.0, 1.0], [0.0, 0.0, 0.0, 0.0, 0.0], ], - ], + ] ), ] @@ -294,7 +294,7 @@ [0.0, 0.0, 0.0, 1.0, 1.0], [0.0, 0.0, 0.0, 0.0, 0.0], ], - ], + ] ), ] diff --git a/tests/test_label_filter.py b/tests/test_label_filter.py index c699fb31fd..05f64a5fd9 100644 --- a/tests/test_label_filter.py +++ b/tests/test_label_filter.py @@ -18,34 +18,14 @@ from monai.transforms import LabelFilter from tests.utils import assert_allclose, clone -grid_1 = torch.tensor( - [ - [ - [ - [1, 2, 3], - [4, 5, 6], - [7, 8, 9], - ] - ] - ] -) +grid_1 = torch.tensor([[[[1, 2, 3], [4, 5, 6], [7, 8, 9]]]]) TEST_CASE_0 = [ "filter_single_label", {"applied_labels": 3}, grid_1, - torch.tensor( - [ - [ - [ - [0, 0, 3], - [0, 0, 0], - [0, 0, 0], - ] - ] - ] - ), + torch.tensor([[[[0, 0, 3], [0, 0, 0], [0, 0, 0]]]]), ] @@ -53,49 +33,19 @@ "filter_single_label_list", {"applied_labels": [3]}, grid_1, - torch.tensor( - [ - [ - [ - [0, 0, 3], - [0, 0, 0], - [0, 0, 0], - ] - ] - ] - ), + torch.tensor([[[[0, 0, 3], [0, 0, 0], [0, 0, 0]]]]), ] TEST_CASE_2 = [ "filter_multi_label", {"applied_labels": [3, 5, 8]}, grid_1, - torch.tensor( - [ - [ - [ - [0, 0, 3], - [0, 5, 0], - [0, 8, 0], - ] - ] - ] - ), + torch.tensor([[[[0, 0, 3], [0, 5, 0], [0, 8, 0]]]]), ] -TEST_CASE_3 = [ - "filter_all", - {"applied_labels": [1, 2, 3, 4, 5, 6, 7, 8, 9]}, - grid_1, - grid_1, -] +TEST_CASE_3 = ["filter_all", {"applied_labels": [1, 2, 3, 4, 5, 6, 7, 8, 9]}, grid_1, grid_1] -VALID_CASES = [ - TEST_CASE_0, - TEST_CASE_1, - TEST_CASE_2, - TEST_CASE_3, -] +VALID_CASES = [TEST_CASE_0, TEST_CASE_1, TEST_CASE_2, TEST_CASE_3] ITEST_CASE_1 = ["invalid_image_data_type", {"applied_labels": 1}, [[[[1, 1, 1]]]], NotImplementedError] diff --git a/tests/test_list_to_dict.py b/tests/test_list_to_dict.py index 2f026f3e29..c366e8f3bd 100644 --- a/tests/test_list_to_dict.py +++ b/tests/test_list_to_dict.py @@ -15,25 +15,13 @@ from monai.utils import list_to_dict -TEST_CASE_1 = [ - ["a=1", "b=2", "c=3", "d=4"], - {"a": 1, "b": 2, "c": 3, "d": 4}, -] +TEST_CASE_1 = [["a=1", "b=2", "c=3", "d=4"], {"a": 1, "b": 2, "c": 3, "d": 4}] -TEST_CASE_2 = [ - ["a=a", "b=b", "c=c", "d=d"], - {"a": "a", "b": "b", "c": "c", "d": "d"}, -] +TEST_CASE_2 = [["a=a", "b=b", "c=c", "d=d"], {"a": "a", "b": "b", "c": "c", "d": "d"}] -TEST_CASE_3 = [ - ["a=0.1", "b=0.2", "c=0.3", "d=0.4"], - {"a": 0.1, "b": 0.2, "c": 0.3, "d": 0.4}, -] +TEST_CASE_3 = [["a=0.1", "b=0.2", "c=0.3", "d=0.4"], {"a": 0.1, "b": 0.2, "c": 0.3, "d": 0.4}] -TEST_CASE_4 = [ - ["a=True", "b=TRUE", "c=false", "d=FALSE"], - {"a": True, "b": True, "c": False, "d": False}, -] +TEST_CASE_4 = [["a=True", "b=TRUE", "c=false", "d=FALSE"], {"a": True, "b": True, "c": False, "d": False}] TEST_CASE_5 = [ ["a='1'", "b=2 ", " c = 3", "d='test'", "'e'=0", "f", "g=None"], diff --git a/tests/test_load_image.py b/tests/test_load_image.py index 2aa6eced65..3f78d3892d 100644 --- a/tests/test_load_image.py +++ b/tests/test_load_image.py @@ -68,11 +68,7 @@ def get_data(self, _obj): (3, 128, 128, 128), ] -TEST_CASE_5 = [ - {"reader": NibabelReader(mmap=False), "image_only": False}, - ["test_image.nii.gz"], - (128, 128, 128), -] +TEST_CASE_5 = [{"reader": NibabelReader(mmap=False), "image_only": False}, ["test_image.nii.gz"], (128, 128, 128)] TEST_CASE_6 = [{"reader": ITKReader(), "image_only": True}, ["test_image.nii.gz"], (128, 128, 128)] diff --git a/tests/test_load_imaged.py b/tests/test_load_imaged.py index ca5b56a7d9..cfe85c7c9c 100644 --- a/tests/test_load_imaged.py +++ b/tests/test_load_imaged.py @@ -81,12 +81,7 @@ class TestConsistency(unittest.TestCase): def _cmp(self, filename, shape, ch_shape, reader_1, reader_2, outname, ext): data_dict = {"img": filename} keys = data_dict.keys() - xforms = Compose( - [ - LoadImaged(keys, reader=reader_1), - EnsureChannelFirstD(keys), - ] - ) + xforms = Compose([LoadImaged(keys, reader=reader_1), EnsureChannelFirstD(keys)]) img_dict = xforms(data_dict) # load dicom with itk self.assertTupleEqual(img_dict["img"].shape, ch_shape) self.assertTupleEqual(tuple(img_dict["img_meta_dict"]["spatial_shape"]), shape) @@ -97,12 +92,7 @@ def _cmp(self, filename, shape, ch_shape, reader_1, reader_2, outname, ext): ) save_xform(img_dict) # save to nifti - new_xforms = Compose( - [ - LoadImaged(keys, reader=reader_2), - EnsureChannelFirstD(keys), - ] - ) + new_xforms = Compose([LoadImaged(keys, reader=reader_2), EnsureChannelFirstD(keys)]) out = new_xforms({"img": os.path.join(tempdir, outname)}) # load nifti with itk self.assertTupleEqual(out["img"].shape, ch_shape) self.assertTupleEqual(tuple(out["img_meta_dict"]["spatial_shape"]), shape) diff --git a/tests/test_lr_scheduler.py b/tests/test_lr_scheduler.py index 20fd7ca8cf..acafc87131 100644 --- a/tests/test_lr_scheduler.py +++ b/tests/test_lr_scheduler.py @@ -28,13 +28,7 @@ def forward(self, x): TEST_CASE_LRSCHEDULER = [ - [ - { - "warmup_steps": 2, - "t_total": 10, - }, - [0.000, 0.500, 1.00, 0.962, 0.854, 0.691, 0.500, 0.309, 0.146, 0.038], - ] + [{"warmup_steps": 2, "t_total": 10}, [0.000, 0.500, 1.00, 0.962, 0.854, 0.691, 0.500, 0.309, 0.146, 0.038]] ] diff --git a/tests/test_map_classes_to_indices.py b/tests/test_map_classes_to_indices.py index a585bd006b..ae75b90c16 100644 --- a/tests/test_map_classes_to_indices.py +++ b/tests/test_map_classes_to_indices.py @@ -28,11 +28,7 @@ "image": None, "image_threshold": 0.0, }, - [ - np.array([0, 4, 8]), - np.array([1, 5, 6]), - np.array([2, 3, 7]), - ], + [np.array([0, 4, 8]), np.array([1, 5, 6]), np.array([2, 3, 7])], ] ) @@ -44,11 +40,7 @@ "image": p(np.array([[[132, 1434, 51], [61, 0, 133], [523, 44, 232]]])), "image_threshold": 60, }, - [ - np.array([0, 8]), - np.array([1, 5, 6]), - np.array([3]), - ], + [np.array([0, 8]), np.array([1, 5, 6]), np.array([3])], ] ) @@ -68,11 +60,7 @@ "image": None, "image_threshold": 0.0, }, - [ - np.array([0, 4, 8]), - np.array([1, 5, 6]), - np.array([2, 3, 7]), - ], + [np.array([0, 4, 8]), np.array([1, 5, 6]), np.array([2, 3, 7])], ] ) @@ -92,11 +80,7 @@ "image": p(np.array([[[132, 1434, 51], [61, 0, 133], [523, 44, 232]]])), "image_threshold": 60, }, - [ - np.array([0, 8]), - np.array([1, 5, 6]), - np.array([3]), - ], + [np.array([0, 8]), np.array([1, 5, 6]), np.array([3])], ] ) @@ -109,13 +93,7 @@ "image": None, "image_threshold": 0.0, }, - [ - np.array([0, 4, 8]), - np.array([1, 5, 6]), - np.array([2, 3, 7]), - np.array([]), - np.array([]), - ], + [np.array([0, 4, 8]), np.array([1, 5, 6]), np.array([2, 3, 7]), np.array([]), np.array([])], ] ) @@ -137,13 +115,7 @@ "image": None, "image_threshold": 0.0, }, - [ - np.array([0, 4, 8]), - np.array([1, 5, 6]), - np.array([2, 3, 7]), - np.array([]), - np.array([]), - ], + [np.array([0, 4, 8]), np.array([1, 5, 6]), np.array([2, 3, 7]), np.array([]), np.array([])], ] ) diff --git a/tests/test_map_label_value.py b/tests/test_map_label_value.py index ff1d7d1eef..388b6db973 100644 --- a/tests/test_map_label_value.py +++ b/tests/test_map_label_value.py @@ -28,11 +28,7 @@ np.array([[[0], [1], [1], [2]]]), ] -TEST_CASE_3 = [ - {"orig_labels": [1, 2, 3], "target_labels": [0, 1, 2]}, - np.array([3, 1, 1, 2]), - np.array([2, 0, 0, 1]), -] +TEST_CASE_3 = [{"orig_labels": [1, 2, 3], "target_labels": [0, 1, 2]}, np.array([3, 1, 1, 2]), np.array([2, 0, 0, 1])] TEST_CASE_4 = [ {"orig_labels": [1, 2, 3], "target_labels": [0.5, 1.5, 2.5]}, @@ -67,16 +63,7 @@ class TestMapLabelValue(unittest.TestCase): @parameterized.expand( - [ - TEST_CASE_1, - TEST_CASE_2, - TEST_CASE_3, - TEST_CASE_4, - TEST_CASE_5, - TEST_CASE_6, - TEST_CASE_7, - TEST_CASE_8, - ] + [TEST_CASE_1, TEST_CASE_2, TEST_CASE_3, TEST_CASE_4, TEST_CASE_5, TEST_CASE_6, TEST_CASE_7, TEST_CASE_8] ) def test_shape(self, input_param, input_data, expected_value): result = MapLabelValue(**input_param)(input_data) diff --git a/tests/test_masked_dice_loss.py b/tests/test_masked_dice_loss.py index b8d69bc8f9..acfdb60ab0 100644 --- a/tests/test_masked_dice_loss.py +++ b/tests/test_masked_dice_loss.py @@ -94,26 +94,17 @@ ], [ # shape: (1, 1, 2, 2), (1, 1, 2, 2) {"include_background": True, "sigmoid": True, "smooth_nr": 1e-6, "smooth_dr": 1e-6}, - { - "input": torch.tensor([[[[1.0, -1.0], [-1.0, 1.0]]]]), - "target": torch.tensor([[[[1.0, 0.0], [1.0, 1.0]]]]), - }, + {"input": torch.tensor([[[[1.0, -1.0], [-1.0, 1.0]]]]), "target": torch.tensor([[[[1.0, 0.0], [1.0, 1.0]]]])}, 0.307576, ], [ # shape: (1, 1, 2, 2), (1, 1, 2, 2) {"include_background": True, "sigmoid": True, "squared_pred": True, "smooth_nr": 1e-5, "smooth_dr": 1e-5}, - { - "input": torch.tensor([[[[1.0, -1.0], [-1.0, 1.0]]]]), - "target": torch.tensor([[[[1.0, 0.0], [1.0, 1.0]]]]), - }, + {"input": torch.tensor([[[[1.0, -1.0], [-1.0, 1.0]]]]), "target": torch.tensor([[[[1.0, 0.0], [1.0, 1.0]]]])}, 0.178337, ], [ # shape: (1, 1, 2, 2), (1, 1, 2, 2) {"include_background": True, "sigmoid": True, "jaccard": True, "smooth_nr": 1e-5, "smooth_dr": 1e-5}, - { - "input": torch.tensor([[[[1.0, -1.0], [-1.0, 1.0]]]]), - "target": torch.tensor([[[[1.0, 0.0], [1.0, 1.0]]]]), - }, + {"input": torch.tensor([[[[1.0, -1.0], [-1.0, 1.0]]]]), "target": torch.tensor([[[[1.0, 0.0], [1.0, 1.0]]]])}, 0.470451, ], ] diff --git a/tests/test_masked_inference_wsi_dataset.py b/tests/test_masked_inference_wsi_dataset.py index 927ba9de5f..f5b2611fd9 100644 --- a/tests/test_masked_inference_wsi_dataset.py +++ b/tests/test_masked_inference_wsi_dataset.py @@ -50,28 +50,12 @@ def prepare_data(): TEST_CASE_0 = [ - { - "data": [ - {"image": FILE_PATH, "mask": MASK1}, - ], - "patch_size": 1, - "image_reader_name": "cuCIM", - }, - [ - { - "image": np.array([[[243]], [[243]], [[243]]], dtype=np.uint8), - "name": FILE_NAME, - "mask_location": [100, 100], - }, - ], + {"data": [{"image": FILE_PATH, "mask": MASK1}], "patch_size": 1, "image_reader_name": "cuCIM"}, + [{"image": np.array([[[243]], [[243]], [[243]]], dtype=np.uint8), "name": FILE_NAME, "mask_location": [100, 100]}], ] TEST_CASE_1 = [ - { - "data": [{"image": FILE_PATH, "mask": MASK2}], - "patch_size": 1, - "image_reader_name": "cuCIM", - }, + {"data": [{"image": FILE_PATH, "mask": MASK2}], "patch_size": 1, "image_reader_name": "cuCIM"}, [ { "image": np.array([[[243]], [[243]], [[243]]], dtype=np.uint8), @@ -87,11 +71,7 @@ def prepare_data(): ] TEST_CASE_2 = [ - { - "data": [{"image": FILE_PATH, "mask": MASK4}], - "patch_size": 1, - "image_reader_name": "cuCIM", - }, + {"data": [{"image": FILE_PATH, "mask": MASK4}], "patch_size": 1, "image_reader_name": "cuCIM"}, [ { "image": np.array([[[243]], [[243]], [[243]]], dtype=np.uint8), @@ -117,35 +97,21 @@ def prepare_data(): ] TEST_CASE_3 = [ - { - "data": [ - {"image": FILE_PATH, "mask": MASK1}, - ], - "patch_size": 2, - "image_reader_name": "cuCIM", - }, + {"data": [{"image": FILE_PATH, "mask": MASK1}], "patch_size": 2, "image_reader_name": "cuCIM"}, [ { "image": np.array( - [ - [[243, 243], [243, 243]], - [[243, 243], [243, 243]], - [[243, 243], [243, 243]], - ], - dtype=np.uint8, + [[[243, 243], [243, 243]], [[243, 243], [243, 243]], [[243, 243], [243, 243]]], dtype=np.uint8 ), "name": FILE_NAME, "mask_location": [100, 100], - }, + } ], ] TEST_CASE_4 = [ { - "data": [ - {"image": FILE_PATH, "mask": MASK1}, - {"image": FILE_PATH, "mask": MASK2}, - ], + "data": [{"image": FILE_PATH, "mask": MASK1}, {"image": FILE_PATH, "mask": MASK2}], "patch_size": 1, "image_reader_name": "cuCIM", }, @@ -170,28 +136,12 @@ def prepare_data(): TEST_CASE_OPENSLIDE_0 = [ - { - "data": [ - {"image": FILE_PATH, "mask": MASK1}, - ], - "patch_size": 1, - "image_reader_name": "OpenSlide", - }, - [ - { - "image": np.array([[[243]], [[243]], [[243]]], dtype=np.uint8), - "name": FILE_NAME, - "mask_location": [100, 100], - }, - ], + {"data": [{"image": FILE_PATH, "mask": MASK1}], "patch_size": 1, "image_reader_name": "OpenSlide"}, + [{"image": np.array([[[243]], [[243]], [[243]]], dtype=np.uint8), "name": FILE_NAME, "mask_location": [100, 100]}], ] TEST_CASE_OPENSLIDE_1 = [ - { - "data": [{"image": FILE_PATH, "mask": MASK2}], - "patch_size": 1, - "image_reader_name": "OpenSlide", - }, + {"data": [{"image": FILE_PATH, "mask": MASK2}], "patch_size": 1, "image_reader_name": "OpenSlide"}, [ { "image": np.array([[[243]], [[243]], [[243]]], dtype=np.uint8), @@ -212,27 +162,14 @@ def setUp(self): prepare_data() download_url(FILE_URL, FILE_PATH, "5a3cfd4fd725c50578ddb80b517b759f") - @parameterized.expand( - [ - TEST_CASE_0, - TEST_CASE_1, - TEST_CASE_2, - TEST_CASE_3, - TEST_CASE_4, - ] - ) + @parameterized.expand([TEST_CASE_0, TEST_CASE_1, TEST_CASE_2, TEST_CASE_3, TEST_CASE_4]) @skipUnless(has_cim, "Requires CuCIM") @skip_if_quick def test_read_patches_cucim(self, input_parameters, expected): dataset = MaskedInferenceWSIDataset(**input_parameters) self.compare_samples_expected(dataset, expected) - @parameterized.expand( - [ - TEST_CASE_OPENSLIDE_0, - TEST_CASE_OPENSLIDE_1, - ] - ) + @parameterized.expand([TEST_CASE_OPENSLIDE_0, TEST_CASE_OPENSLIDE_1]) @skipUnless(has_osl, "Requires OpenSlide") @skip_if_quick def test_read_patches_openslide(self, input_parameters, expected): diff --git a/tests/test_masked_loss.py b/tests/test_masked_loss.py index 225e3d9668..b56fcbbcdb 100644 --- a/tests/test_masked_loss.py +++ b/tests/test_masked_loss.py @@ -33,7 +33,7 @@ "reduction": "sum", }, [(14.538666, 20.191753), (13.17672, 8.251623)], - ], + ] ] diff --git a/tests/test_mean_ensemble.py b/tests/test_mean_ensemble.py index 7e08846beb..532a6c21c4 100644 --- a/tests/test_mean_ensemble.py +++ b/tests/test_mean_ensemble.py @@ -17,23 +17,11 @@ from monai.transforms import MeanEnsemble -TEST_CASE_1 = [ - {"weights": None}, - [torch.ones(2, 2, 2), torch.ones(2, 2, 2) + 2], - torch.ones(2, 2, 2) + 1, -] +TEST_CASE_1 = [{"weights": None}, [torch.ones(2, 2, 2), torch.ones(2, 2, 2) + 2], torch.ones(2, 2, 2) + 1] -TEST_CASE_2 = [ - {"weights": None}, - torch.stack([torch.ones(2, 2, 2), torch.ones(2, 2, 2) + 2]), - torch.ones(2, 2, 2) + 1, -] +TEST_CASE_2 = [{"weights": None}, torch.stack([torch.ones(2, 2, 2), torch.ones(2, 2, 2) + 2]), torch.ones(2, 2, 2) + 1] -TEST_CASE_3 = [ - {"weights": [1, 3]}, - [torch.ones(2, 2, 2), torch.ones(2, 2, 2) + 2], - torch.ones(2, 2, 2) * 2.5, -] +TEST_CASE_3 = [{"weights": [1, 3]}, [torch.ones(2, 2, 2), torch.ones(2, 2, 2) + 2], torch.ones(2, 2, 2) * 2.5] TEST_CASE_4 = [ {"weights": [[1, 3], [3, 1]]}, diff --git a/tests/test_mlp.py b/tests/test_mlp.py index 7a93f81ec3..b6e78c9a66 100644 --- a/tests/test_mlp.py +++ b/tests/test_mlp.py @@ -24,11 +24,7 @@ for mlp_dim in [512, 1028, 2048, 3072]: test_case = [ - { - "hidden_size": hidden_size, - "mlp_dim": mlp_dim, - "dropout_rate": dropout_rate, - }, + {"hidden_size": hidden_size, "mlp_dim": mlp_dim, "dropout_rate": dropout_rate}, (2, 512, hidden_size), (2, 512, hidden_size), ] diff --git a/tests/test_net_adapter.py b/tests/test_net_adapter.py index b2d55129a7..198de8d142 100644 --- a/tests/test_net_adapter.py +++ b/tests/test_net_adapter.py @@ -19,23 +19,11 @@ device = "cuda" if torch.cuda.is_available() else "cpu" -TEST_CASE_0 = [ - {"num_classes": 1, "use_conv": True, "dim": 2}, - (2, 3, 224, 224), - (2, 1, 8, 1), -] +TEST_CASE_0 = [{"num_classes": 1, "use_conv": True, "dim": 2}, (2, 3, 224, 224), (2, 1, 8, 1)] -TEST_CASE_1 = [ - {"num_classes": 1, "use_conv": True, "dim": 3, "pool": None}, - (2, 3, 32, 32, 32), - (2, 1, 1, 1, 1), -] +TEST_CASE_1 = [{"num_classes": 1, "use_conv": True, "dim": 3, "pool": None}, (2, 3, 32, 32, 32), (2, 1, 1, 1, 1)] -TEST_CASE_2 = [ - {"num_classes": 5, "use_conv": True, "dim": 3, "pool": None}, - (2, 3, 32, 32, 32), - (2, 5, 1, 1, 1), -] +TEST_CASE_2 = [{"num_classes": 5, "use_conv": True, "dim": 3, "pool": None}, (2, 3, 32, 32, 32), (2, 5, 1, 1, 1)] TEST_CASE_3 = [ {"num_classes": 5, "use_conv": True, "pool": ("avg", {"kernel_size": 4, "stride": 1}), "dim": 3}, diff --git a/tests/test_nifti_saver.py b/tests/test_nifti_saver.py index c07084172f..e22a6e6620 100644 --- a/tests/test_nifti_saver.py +++ b/tests/test_nifti_saver.py @@ -36,12 +36,7 @@ def test_saved_content(self): def test_saved_resize_content(self): with tempfile.TemporaryDirectory() as tempdir: - saver = NiftiSaver( - output_dir=tempdir, - output_postfix="seg", - output_ext=".nii.gz", - dtype=np.float32, - ) + saver = NiftiSaver(output_dir=tempdir, output_postfix="seg", output_ext=".nii.gz", dtype=np.float32) meta_data = { "filename_or_obj": ["testfile" + str(i) + ".nii" for i in range(8)], @@ -56,12 +51,7 @@ def test_saved_resize_content(self): def test_saved_3d_resize_content(self): with tempfile.TemporaryDirectory() as tempdir: - saver = NiftiSaver( - output_dir=tempdir, - output_postfix="seg", - output_ext=".nii.gz", - dtype=np.float32, - ) + saver = NiftiSaver(output_dir=tempdir, output_postfix="seg", output_ext=".nii.gz", dtype=np.float32) meta_data = { "filename_or_obj": ["testfile" + str(i) + ".nii.gz" for i in range(8)], diff --git a/tests/test_nvtx_decorator.py b/tests/test_nvtx_decorator.py index e2a9ad67b8..0955fbb712 100644 --- a/tests/test_nvtx_decorator.py +++ b/tests/test_nvtx_decorator.py @@ -31,38 +31,21 @@ _, has_nvtx = optional_import("torch._C._nvtx", descriptor="NVTX is not installed. Are you sure you have a CUDA build?") -TEST_CASE_ARRAY_0 = [ - np.random.randn(3, 3), -] -TEST_CASE_ARRAY_1 = [ - np.random.randn(3, 10, 10), -] - -TEST_CASE_DICT_0 = [ - {"image": np.random.randn(3, 3)}, -] -TEST_CASE_DICT_1 = [ - {"image": np.random.randn(3, 10, 10)}, -] - -TEST_CASE_TORCH_0 = [ - torch.randn(3, 3), -] -TEST_CASE_TORCH_1 = [ - torch.randn(3, 10, 10), -] +TEST_CASE_ARRAY_0 = [np.random.randn(3, 3)] +TEST_CASE_ARRAY_1 = [np.random.randn(3, 10, 10)] + +TEST_CASE_DICT_0 = [{"image": np.random.randn(3, 3)}] +TEST_CASE_DICT_1 = [{"image": np.random.randn(3, 10, 10)}] + +TEST_CASE_TORCH_0 = [torch.randn(3, 3)] +TEST_CASE_TORCH_1 = [torch.randn(3, 10, 10)] class TestNVTXRangeDecorator(unittest.TestCase): @parameterized.expand([TEST_CASE_ARRAY_0, TEST_CASE_ARRAY_1]) @unittest.skipUnless(has_nvtx, "CUDA is required for NVTX Range!") def test_tranform_array(self, input): - transforms = Compose( - [ - Range("random flip")(Flip()), - Range()(ToTensor()), - ] - ) + transforms = Compose([Range("random flip")(Flip()), Range()(ToTensor())]) # Apply transforms output = transforms(input) @@ -88,12 +71,7 @@ def test_tranform_array(self, input): @parameterized.expand([TEST_CASE_DICT_0, TEST_CASE_DICT_1]) @unittest.skipUnless(has_nvtx, "CUDA is required for NVTX Range!") def test_tranform_dict(self, input): - transforms = Compose( - [ - Range("random flip dict")(FlipD(keys="image")), - Range()(ToTensorD("image")), - ] - ) + transforms = Compose([Range("random flip dict")(FlipD(keys="image")), Range()(ToTensorD("image"))]) # Apply transforms output = transforms(input)["image"] @@ -161,10 +139,7 @@ def test_tranform_randomized(self, input): @unittest.skipUnless(has_nvtx, "CUDA is required for NVTX Range!") def test_network(self, input): # Create a network - model = torch.nn.Sequential( - torch.nn.ReLU(), - torch.nn.Sigmoid(), - ) + model = torch.nn.Sequential(torch.nn.ReLU(), torch.nn.Sigmoid()) # Forward output = model(input) diff --git a/tests/test_nvtx_transform.py b/tests/test_nvtx_transform.py index 6bcfe00078..36a924dd1c 100644 --- a/tests/test_nvtx_transform.py +++ b/tests/test_nvtx_transform.py @@ -35,29 +35,14 @@ _, has_nvtx = optional_import("torch._C._nvtx", descriptor="NVTX is not installed. Are you sure you have a CUDA build?") -TEST_CASE_ARRAY_0 = [ - np.random.randn(3, 3), -] -TEST_CASE_ARRAY_1 = [ - np.random.randn(3, 10, 10), -] -TEST_CASE_DICT_0 = [ - {"image": np.random.randn(3, 3)}, -] -TEST_CASE_DICT_1 = [ - {"image": np.random.randn(3, 10, 10)}, -] +TEST_CASE_ARRAY_0 = [np.random.randn(3, 3)] +TEST_CASE_ARRAY_1 = [np.random.randn(3, 10, 10)] +TEST_CASE_DICT_0 = [{"image": np.random.randn(3, 3)}] +TEST_CASE_DICT_1 = [{"image": np.random.randn(3, 10, 10)}] class TestNVTXTransforms(unittest.TestCase): - @parameterized.expand( - [ - TEST_CASE_ARRAY_0, - TEST_CASE_ARRAY_1, - TEST_CASE_DICT_0, - TEST_CASE_DICT_1, - ] - ) + @parameterized.expand([TEST_CASE_ARRAY_0, TEST_CASE_ARRAY_1, TEST_CASE_DICT_0, TEST_CASE_DICT_1]) @unittest.skipUnless(has_nvtx, "CUDA is required for NVTX!") def test_nvtx_transfroms_alone(self, input): transforms = Compose( diff --git a/tests/test_occlusion_sensitivity.py b/tests/test_occlusion_sensitivity.py index d58359a598..18da4057ab 100644 --- a/tests/test_occlusion_sensitivity.py +++ b/tests/test_occlusion_sensitivity.py @@ -29,47 +29,27 @@ # 2D w/ bounding box TEST_CASE_0 = [ - { - "nn_module": model_2d, - }, - { - "x": torch.rand(1, 1, 48, 64).to(device), - "b_box": [-1, -1, 2, 40, 1, 62], - }, + {"nn_module": model_2d}, + {"x": torch.rand(1, 1, 48, 64).to(device), "b_box": [-1, -1, 2, 40, 1, 62]}, (1, 1, 39, 62, out_channels_2d), (1, 1, 39, 62), ] # 3D w/ bounding box and stride TEST_CASE_1 = [ {"nn_module": model_3d, "n_batch": 10, "stride": (2, 1, 2), "mask_size": (16, 15, 14)}, - { - "x": torch.rand(1, 1, 6, 6, 6).to(device), - "b_box": [-1, -1, 2, 3, -1, -1, -1, -1], - }, + {"x": torch.rand(1, 1, 6, 6, 6).to(device), "b_box": [-1, -1, 2, 3, -1, -1, -1, -1]}, (1, 1, 2, 6, 6, out_channels_3d), (1, 1, 2, 6, 6), ] TEST_CASE_FAIL_0 = [ # 2D should fail, since 3 stride values given - { - "nn_module": model_2d, - "n_batch": 10, - "stride": (2, 2, 2), - }, - { - "x": torch.rand(1, 1, 48, 64).to(device), - "b_box": [-1, -1, 2, 3, -1, -1], - }, + {"nn_module": model_2d, "n_batch": 10, "stride": (2, 2, 2)}, + {"x": torch.rand(1, 1, 48, 64).to(device), "b_box": [-1, -1, 2, 3, -1, -1]}, ] TEST_CASE_FAIL_1 = [ # 2D should fail, since stride is not a factor of image size - { - "nn_module": model_2d, - "stride": 3, - }, - { - "x": torch.rand(1, 1, 48, 64).to(device), - }, + {"nn_module": model_2d, "stride": 3}, + {"x": torch.rand(1, 1, 48, 64).to(device)}, ] diff --git a/tests/test_one_of.py b/tests/test_one_of.py index d45d0f3f61..9fe9f193a3 100644 --- a/tests/test_one_of.py +++ b/tests/test_one_of.py @@ -93,9 +93,7 @@ def __init__(self, keys): self.inv_fn = lambda x: x - 100 -TESTS = [ - ((X(), Y(), X()), (1, 2, 1), (0.25, 0.5, 0.25)), -] +TESTS = [((X(), Y(), X()), (1, 2, 1), (0.25, 0.5, 0.25))] KEYS = ["x", "y"] TEST_INVERSES = [ diff --git a/tests/test_openslide_reader.py b/tests/test_openslide_reader.py index efbd611579..cf092158f2 100644 --- a/tests/test_openslide_reader.py +++ b/tests/test_openslide_reader.py @@ -46,13 +46,7 @@ TEST_CASE_3 = [ FILE_PATH, - { - "location": (0, 0), - "size": (8, 8), - "level": 2, - "grid_shape": (2, 1), - "patch_size": 2, - }, + {"location": (0, 0), "size": (8, 8), "level": 2, "grid_shape": (2, 1), "patch_size": 2}, np.array( [ [[[239, 239], [239, 239]], [[239, 239], [239, 239]], [[239, 239], [239, 239]]], @@ -63,13 +57,7 @@ TEST_CASE_4 = [ FILE_PATH, - { - "location": (0, 0), - "size": (8, 8), - "level": 2, - "grid_shape": (2, 1), - "patch_size": 1, - }, + {"location": (0, 0), "size": (8, 8), "level": 2, "grid_shape": (2, 1), "patch_size": 1}, np.array([[[[239]], [[239]], [[239]]], [[[243]], [[243]], [[243]]]]), ] diff --git a/tests/test_optim_novograd.py b/tests/test_optim_novograd.py index c76501cd6f..35f54d67ae 100644 --- a/tests/test_optim_novograd.py +++ b/tests/test_optim_novograd.py @@ -38,37 +38,19 @@ def build_test_cases(data): return test_cases -TEST_CASES_ALL = build_test_cases( # normal parameters - [ - torch.randn(10, 5), - torch.randn(10), - torch.randn(5), - ] -) +TEST_CASES_ALL = build_test_cases([torch.randn(10, 5), torch.randn(10), torch.randn(5)]) # normal parameters TEST_CASES_ALL += build_test_cases( # non-contiguous parameters - [ - torch.randn(10, 5, 2)[..., 0], - torch.randn(10, 2)[..., 0], - torch.randn(5), - ] + [torch.randn(10, 5, 2)[..., 0], torch.randn(10, 2)[..., 0], torch.randn(5)] ) if torch.cuda.is_available(): TEST_CASES_ALL += build_test_cases( # gpu parameters - [ - torch.randn(10, 5).cuda(), - torch.randn(10).cuda(), - torch.randn(5).cuda(), - ] + [torch.randn(10, 5).cuda(), torch.randn(10).cuda(), torch.randn(5).cuda()] ) if torch.cuda.device_count() > 1: TEST_CASES_ALL += build_test_cases( # multi-gpu parameters - [ - torch.randn(10, 5).cuda(0), - torch.randn(10).cuda(1), - torch.randn(5).cuda(0), - ] + [torch.randn(10, 5).cuda(0), torch.randn(10).cuda(1), torch.randn(5).cuda(0)] ) diff --git a/tests/test_partition_dataset.py b/tests/test_partition_dataset.py index a954bfae91..b036cd6827 100644 --- a/tests/test_partition_dataset.py +++ b/tests/test_partition_dataset.py @@ -117,16 +117,7 @@ class TestPartitionDataset(unittest.TestCase): @parameterized.expand( - [ - TEST_CASE_1, - TEST_CASE_2, - TEST_CASE_3, - TEST_CASE_4, - TEST_CASE_5, - TEST_CASE_6, - TEST_CASE_7, - TEST_CASE_8, - ] + [TEST_CASE_1, TEST_CASE_2, TEST_CASE_3, TEST_CASE_4, TEST_CASE_5, TEST_CASE_6, TEST_CASE_7, TEST_CASE_8] ) def test_value(self, input_param, result): self.assertListEqual(partition_dataset(**input_param), result) diff --git a/tests/test_patch_dataset.py b/tests/test_patch_dataset.py index 7bb39bc969..40e8bbb20a 100644 --- a/tests/test_patch_dataset.py +++ b/tests/test_patch_dataset.py @@ -74,8 +74,8 @@ def test_loading_array(self): [4.957847, 5.957847, 6.957847], [8.957847, 9.957847, 10.957847], [12.957847, 13.957847, 14.957847], - ], - ], + ] + ] ), rtol=1e-5, ) diff --git a/tests/test_patch_wsi_dataset.py b/tests/test_patch_wsi_dataset.py index 50b0e13859..9259cd0e7b 100644 --- a/tests/test_patch_wsi_dataset.py +++ b/tests/test_patch_wsi_dataset.py @@ -30,17 +30,13 @@ TEST_CASE_0 = [ { - "data": [ - {"image": FILE_PATH, "location": [0, 0], "label": [1]}, - ], + "data": [{"image": FILE_PATH, "location": [0, 0], "label": [1]}], "region_size": (1, 1), "grid_shape": (1, 1), "patch_size": 1, "image_reader_name": "cuCIM", }, - [ - {"image": np.array([[[239]], [[239]], [[239]]], dtype=np.uint8), "label": np.array([[[1]]])}, - ], + [{"image": np.array([[[239]], [[239]], [[239]]], dtype=np.uint8), "label": np.array([[[1]]])}], ] TEST_CASE_1 = [ @@ -61,47 +57,35 @@ TEST_CASE_2 = [ { - "data": [ - {"image": FILE_PATH, "location": [0, 0], "label": [1]}, - ], + "data": [{"image": FILE_PATH, "location": [0, 0], "label": [1]}], "region_size": 1, "grid_shape": 1, "patch_size": 1, "image_reader_name": "cuCIM", }, - [ - {"image": np.array([[[239]], [[239]], [[239]]], dtype=np.uint8), "label": np.array([[[1]]])}, - ], + [{"image": np.array([[[239]], [[239]], [[239]]], dtype=np.uint8), "label": np.array([[[1]]])}], ] TEST_CASE_3 = [ { - "data": [ - {"image": FILE_PATH, "location": [0, 0], "label": [[[0, 1], [1, 0]]]}, - ], + "data": [{"image": FILE_PATH, "location": [0, 0], "label": [[[0, 1], [1, 0]]]}], "region_size": 1, "grid_shape": 1, "patch_size": 1, "image_reader_name": "cuCIM", }, - [ - {"image": np.array([[[239]], [[239]], [[239]]], dtype=np.uint8), "label": np.array([[[0, 1], [1, 0]]])}, - ], + [{"image": np.array([[[239]], [[239]], [[239]]], dtype=np.uint8), "label": np.array([[[0, 1], [1, 0]]])}], ] TEST_CASE_OPENSLIDE_0 = [ { - "data": [ - {"image": FILE_PATH, "location": [0, 0], "label": [1]}, - ], + "data": [{"image": FILE_PATH, "location": [0, 0], "label": [1]}], "region_size": (1, 1), "grid_shape": (1, 1), "patch_size": 1, "image_reader_name": "OpenSlide", }, - [ - {"image": np.array([[[239]], [[239]], [[239]]], dtype=np.uint8), "label": np.array([[[1]]])}, - ], + [{"image": np.array([[[239]], [[239]], [[239]]], dtype=np.uint8), "label": np.array([[[1]]])}], ] TEST_CASE_OPENSLIDE_1 = [ @@ -125,14 +109,7 @@ class TestPatchWSIDataset(unittest.TestCase): def setUp(self): download_url(FILE_URL, FILE_PATH, "5a3cfd4fd725c50578ddb80b517b759f") - @parameterized.expand( - [ - TEST_CASE_0, - TEST_CASE_1, - TEST_CASE_2, - TEST_CASE_3, - ] - ) + @parameterized.expand([TEST_CASE_0, TEST_CASE_1, TEST_CASE_2, TEST_CASE_3]) @skipUnless(has_cim, "Requires CuCIM") def test_read_patches_cucim(self, input_parameters, expected): dataset = PatchWSIDataset(**input_parameters) @@ -143,12 +120,7 @@ def test_read_patches_cucim(self, input_parameters, expected): self.assertIsNone(assert_array_equal(samples[i]["label"], expected[i]["label"])) self.assertIsNone(assert_array_equal(samples[i]["image"], expected[i]["image"])) - @parameterized.expand( - [ - TEST_CASE_OPENSLIDE_0, - TEST_CASE_OPENSLIDE_1, - ] - ) + @parameterized.expand([TEST_CASE_OPENSLIDE_0, TEST_CASE_OPENSLIDE_1]) @skipUnless(has_osl, "Requires OpenSlide") def test_read_patches_openslide(self, input_parameters, expected): dataset = PatchWSIDataset(**input_parameters) diff --git a/tests/test_pathology_he_stain.py b/tests/test_pathology_he_stain.py index 1d74f485e9..7f76c3f03e 100644 --- a/tests/test_pathology_he_stain.py +++ b/tests/test_pathology_he_stain.py @@ -73,12 +73,7 @@ class TestExtractHEStains(unittest.TestCase): @parameterized.expand( - [ - NEGATIVE_VALUE_TEST_CASE, - INVALID_VALUE_TEST_CASE, - EXTRACT_STAINS_TEST_CASE_0, - EXTRACT_STAINS_TEST_CASE_1, - ] + [NEGATIVE_VALUE_TEST_CASE, INVALID_VALUE_TEST_CASE, EXTRACT_STAINS_TEST_CASE_0, EXTRACT_STAINS_TEST_CASE_1] ) def test_transparent_image(self, image): """ @@ -112,13 +107,7 @@ def test_identical_result_vectors(self, image): result = ExtractHEStains()(image) np.testing.assert_array_equal(result[:, 0], result[:, 1]) - @parameterized.expand( - [ - EXTRACT_STAINS_TEST_CASE_00, - EXTRACT_STAINS_TEST_CASE_4, - EXTRACT_STAINS_TEST_CASE_5, - ] - ) + @parameterized.expand([EXTRACT_STAINS_TEST_CASE_00, EXTRACT_STAINS_TEST_CASE_4, EXTRACT_STAINS_TEST_CASE_5]) def test_result_value(self, image, expected_data): """ Test that an input image returns an expected stain matrix. @@ -156,12 +145,7 @@ def test_result_value(self, image, expected_data): class TestNormalizeHEStains(unittest.TestCase): @parameterized.expand( - [ - NEGATIVE_VALUE_TEST_CASE, - INVALID_VALUE_TEST_CASE, - NORMALIZE_STAINS_TEST_CASE_0, - NORMALIZE_STAINS_TEST_CASE_1, - ] + [NEGATIVE_VALUE_TEST_CASE, INVALID_VALUE_TEST_CASE, NORMALIZE_STAINS_TEST_CASE_0, NORMALIZE_STAINS_TEST_CASE_1] ) def test_transparent_image(self, image): """ diff --git a/tests/test_pathology_he_stain_dict.py b/tests/test_pathology_he_stain_dict.py index 8d51579cb2..2ba2c3f71b 100644 --- a/tests/test_pathology_he_stain_dict.py +++ b/tests/test_pathology_he_stain_dict.py @@ -100,13 +100,7 @@ def test_identical_result_vectors(self, image): result = ExtractHEStainsD([key])({key: image}) np.testing.assert_array_equal(result[key][:, 0], result[key][:, 1]) - @parameterized.expand( - [ - EXTRACT_STAINS_TEST_CASE_00, - EXTRACT_STAINS_TEST_CASE_4, - EXTRACT_STAINS_TEST_CASE_5, - ] - ) + @parameterized.expand([EXTRACT_STAINS_TEST_CASE_00, EXTRACT_STAINS_TEST_CASE_4, EXTRACT_STAINS_TEST_CASE_5]) def test_result_value(self, image, expected_data): """ Test that an input image returns an expected stain matrix. diff --git a/tests/test_pathology_prob_nms.py b/tests/test_pathology_prob_nms.py index 223b136ea7..879ca88821 100644 --- a/tests/test_pathology_prob_nms.py +++ b/tests/test_pathology_prob_nms.py @@ -41,12 +41,7 @@ class TestPathologyProbNMS(unittest.TestCase): - @parameterized.expand( - [ - TEST_CASES_2D, - TEST_CASES_3D, - ] - ) + @parameterized.expand([TEST_CASES_2D, TEST_CASES_3D]) def test_output(self, class_args, call_args, probs_map, expected): nms = PathologyProbNMS(**class_args) output = nms(probs_map, **call_args) diff --git a/tests/test_phl_cpu.py b/tests/test_phl_cpu.py index 31e28bd39d..3583c4e996 100644 --- a/tests/test_phl_cpu.py +++ b/tests/test_phl_cpu.py @@ -42,7 +42,7 @@ # Batch 0 [ # Channel 0 - [1, 0.2, 0.5, 0, 1], + [1, 0.2, 0.5, 0, 1] ], # Batch 1 [ @@ -79,15 +79,15 @@ [0, 0, 0, 0, 1], # Channel 2 [0, 0, 1, 0, 0], - ], + ] ], # Features [ # Batch 0 [ # Channel 0 - [1, 0.2, 0.5, 0.2, 1], - ], + [1, 0.2, 0.5, 0.2, 1] + ] ], # Expected [ @@ -99,7 +99,7 @@ [0.229572, 0.182884, 0.202637, 0.182884, 0.229572], # Channel 2 [0.201235, 0.208194, 0.205409, 0.208194, 0.201235], - ], + ] ], ], [ @@ -113,7 +113,7 @@ [ # Channel 0 [[9, 9, 0, 0, 0], [9, 9, 0, 0, 0], [9, 9, 0, 0, 0], [9, 9, 6, 6, 6], [9, 9, 6, 6, 6]] - ], + ] ], # Features [ @@ -125,7 +125,7 @@ [[0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4]], # Channel 2 [[0, 0, 0, 0, 0], [1, 1, 1, 1, 1], [2, 2, 2, 2, 2], [3, 3, 3, 3, 3], [4, 4, 4, 4, 4]], - ], + ] ], # Expected [ @@ -139,7 +139,7 @@ [7.613517, 7.359183, 5.846500, 5.638952, 5.350098], [7.598255, 7.458446, 5.912375, 5.583625, 5.233126], ] - ], + ] ], ], [ @@ -164,7 +164,7 @@ # Frame 4 [[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]], ] - ], + ] ], # Features [ @@ -183,7 +183,7 @@ # Frame 4 [[0, 0, 5, 5, 5], [0, 0, 5, 5, 5], [0, 0, 5, 5, 5], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]], ] - ], + ] ], # Expected [ @@ -232,7 +232,7 @@ [0.284234, 0.284234, 0.284234, 0.284234, 0.284234], ], ] - ], + ] ], ], ] diff --git a/tests/test_phl_cuda.py b/tests/test_phl_cuda.py index 8f7fc6fc3d..4ba47e4fca 100644 --- a/tests/test_phl_cuda.py +++ b/tests/test_phl_cuda.py @@ -42,7 +42,7 @@ # Batch 0 [ # Channel 0 - [1, 0.2, 0.5, 0, 1], + [1, 0.2, 0.5, 0, 1] ], # Batch 1 [ @@ -79,15 +79,15 @@ [0, 0, 0, 0, 1], # Channel 2 [0, 0, 1, 0, 0], - ], + ] ], # Features [ # Batch 0 [ # Channel 0 - [1, 0.2, 0.5, 0.2, 1], - ], + [1, 0.2, 0.5, 0.2, 1] + ] ], # Expected [ @@ -99,7 +99,7 @@ [0.229572, 0.182884, 0.202637, 0.182884, 0.229572], # Channel 2 [0.201235, 0.208194, 0.205409, 0.208194, 0.201235], - ], + ] ], ], [ @@ -113,7 +113,7 @@ [ # Channel 0 [[9, 9, 0, 0, 0], [9, 9, 0, 0, 0], [9, 9, 0, 0, 0], [9, 9, 6, 6, 6], [9, 9, 6, 6, 6]] - ], + ] ], # Features [ @@ -125,7 +125,7 @@ [[0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4]], # Channel 2 [[0, 0, 0, 0, 0], [1, 1, 1, 1, 1], [2, 2, 2, 2, 2], [3, 3, 3, 3, 3], [4, 4, 4, 4, 4]], - ], + ] ], # Expected [ @@ -139,7 +139,7 @@ [7.712976, 7.429060, 5.789552, 5.594258, 5.371737], [7.701185, 7.492719, 5.860026, 5.538241, 5.281656], ] - ], + ] ], ], ] diff --git a/tests/test_png_saver.py b/tests/test_png_saver.py index f8ea1df54b..e807cf2927 100644 --- a/tests/test_png_saver.py +++ b/tests/test_png_saver.py @@ -60,11 +60,7 @@ def test_saved_specified_root(self): with tempfile.TemporaryDirectory() as tempdir: saver = PNGSaver( - output_dir=tempdir, - output_postfix="seg", - output_ext=".png", - scale=255, - data_root_dir="test", + output_dir=tempdir, output_postfix="seg", output_ext=".png", scale=255, data_root_dir="test" ) meta_data = { diff --git a/tests/test_probnms.py b/tests/test_probnms.py index e51d1017d8..cc055d883c 100644 --- a/tests/test_probnms.py +++ b/tests/test_probnms.py @@ -24,32 +24,20 @@ probs_map_2[33, 33] = 0.7 probs_map_2[66, 66] = 0.9 expected_2 = [[0.9, 66, 66], [0.7, 33, 33]] -TEST_CASES_2D_2 = [ - {"spatial_dims": 2, "prob_threshold": 0.5, "box_size": [10, 10]}, - probs_map_2, - expected_2, -] +TEST_CASES_2D_2 = [{"spatial_dims": 2, "prob_threshold": 0.5, "box_size": [10, 10]}, probs_map_2, expected_2] probs_map_3 = np.random.rand(100, 100).clip(0, 0.5) probs_map_3[56, 58] = 0.7 probs_map_3[60, 66] = 0.8 probs_map_3[66, 66] = 0.9 expected_3 = [[0.9, 66, 66], [0.8, 60, 66]] -TEST_CASES_2D_3 = [ - {"spatial_dims": 2, "prob_threshold": 0.5, "box_size": (10, 20)}, - probs_map_3, - expected_3, -] +TEST_CASES_2D_3 = [{"spatial_dims": 2, "prob_threshold": 0.5, "box_size": (10, 20)}, probs_map_3, expected_3] probs_map_4 = np.random.rand(100, 100).clip(0, 0.5) probs_map_4[33, 33] = 0.7 probs_map_4[66, 66] = 0.9 expected_4 = [[0.9, 66, 66]] -TEST_CASES_2D_4 = [ - {"spatial_dims": 2, "prob_threshold": 0.8, "box_size": 10}, - probs_map_4, - expected_4, -] +TEST_CASES_2D_4 = [{"spatial_dims": 2, "prob_threshold": 0.8, "box_size": 10}, probs_map_4, expected_4] probs_map_5 = np.random.rand(100, 100).clip(0, 0.5) TEST_CASES_2D_5 = [{"spatial_dims": 2, "prob_threshold": 0.5, "sigma": 0.1}, probs_map_5, []] @@ -63,21 +51,13 @@ if torch.cuda.is_available(): probs_map_7 = probs_map_7.cuda() expected_7 = [[0.9, 66, 66], [0.7, 33, 33]] -TEST_CASES_2D_7 = [ - {"spatial_dims": 2, "prob_threshold": 0.5, "sigma": 0.1}, - probs_map_7, - expected_7, -] +TEST_CASES_2D_7 = [{"spatial_dims": 2, "prob_threshold": 0.5, "sigma": 0.1}, probs_map_7, expected_7] probs_map_3d = torch.rand([50, 50, 50]).uniform_(0, 0.5) probs_map_3d[25, 25, 25] = 0.7 probs_map_3d[45, 45, 45] = 0.9 expected_3d = [[0.9, 45, 45, 45], [0.7, 25, 25, 25]] -TEST_CASES_3D = [ - {"spatial_dims": 3, "prob_threshold": 0.5, "box_size": (10, 10, 10)}, - probs_map_3d, - expected_3d, -] +TEST_CASES_3D = [{"spatial_dims": 3, "prob_threshold": 0.5, "box_size": (10, 10, 10)}, probs_map_3d, expected_3d] class TestProbNMS(unittest.TestCase): diff --git a/tests/test_probnmsd.py b/tests/test_probnmsd.py index 5b75d4310f..b0b3227531 100644 --- a/tests/test_probnmsd.py +++ b/tests/test_probnmsd.py @@ -45,11 +45,7 @@ probs_map_4[33, 33] = 0.7 probs_map_4[66, 66] = 0.9 expected_4 = [[0.9, 66, 66]] -TEST_CASES_2D_4 = [ - {"spatial_dims": 2, "prob_threshold": 0.8, "box_size": 10}, - {"prob_map": probs_map_4}, - expected_4, -] +TEST_CASES_2D_4 = [{"spatial_dims": 2, "prob_threshold": 0.8, "box_size": 10}, {"prob_map": probs_map_4}, expected_4] probs_map_5 = np.random.rand(100, 100).clip(0, 0.5) TEST_CASES_2D_5 = [{"spatial_dims": 2, "prob_threshold": 0.5, "sigma": 0.1}, {"prob_map": probs_map_5}, []] @@ -63,11 +59,7 @@ if torch.cuda.is_available(): probs_map_7 = probs_map_7.cuda() expected_7 = [[0.9, 66, 66], [0.7, 33, 33]] -TEST_CASES_2D_7 = [ - {"spatial_dims": 2, "prob_threshold": 0.5, "sigma": 0.1}, - {"prob_map": probs_map_7}, - expected_7, -] +TEST_CASES_2D_7 = [{"spatial_dims": 2, "prob_threshold": 0.5, "sigma": 0.1}, {"prob_map": probs_map_7}, expected_7] probs_map_3d = torch.rand([50, 50, 50]).uniform_(0, 0.5) probs_map_3d[25, 25, 25] = 0.7 diff --git a/tests/test_rand_affine.py b/tests/test_rand_affine.py index 96322813c9..4cef6b4d44 100644 --- a/tests/test_rand_affine.py +++ b/tests/test_rand_affine.py @@ -25,11 +25,7 @@ for p in TEST_NDARRAYS: for device in [None, "cpu", "cuda"] if torch.cuda.is_available() else [None, "cpu"]: TESTS.append( - [ - dict(device=device), - {"img": p(torch.arange(27).reshape((3, 3, 3)))}, - p(np.arange(27).reshape((3, 3, 3))), - ] + [dict(device=device), {"img": p(torch.arange(27).reshape((3, 3, 3)))}, p(np.arange(27).reshape((3, 3, 3)))] ) TESTS.append( [ diff --git a/tests/test_rand_affined.py b/tests/test_rand_affined.py index 651452ab07..e59a345d0d 100644 --- a/tests/test_rand_affined.py +++ b/tests/test_rand_affined.py @@ -224,13 +224,7 @@ def test_ill_cache(self): RandAffined(device=device, spatial_size=None, prob=1.0, cache_grid=True, keys=("img", "seg")) with self.assertWarns(UserWarning): # spatial size is dynamic - RandAffined( - device=device, - spatial_size=(2, -1), - prob=1.0, - cache_grid=True, - keys=("img", "seg"), - ) + RandAffined(device=device, spatial_size=(2, -1), prob=1.0, cache_grid=True, keys=("img", "seg")) if __name__ == "__main__": diff --git a/tests/test_rand_coarse_dropout.py b/tests/test_rand_coarse_dropout.py index 3f46799de2..db26ea3c7a 100644 --- a/tests/test_rand_coarse_dropout.py +++ b/tests/test_rand_coarse_dropout.py @@ -61,16 +61,7 @@ class TestRandCoarseDropout(unittest.TestCase): @parameterized.expand( - [ - TEST_CASE_0, - TEST_CASE_1, - TEST_CASE_2, - TEST_CASE_3, - TEST_CASE_4, - TEST_CASE_5, - TEST_CASE_6, - TEST_CASE_7, - ] + [TEST_CASE_0, TEST_CASE_1, TEST_CASE_2, TEST_CASE_3, TEST_CASE_4, TEST_CASE_5, TEST_CASE_6, TEST_CASE_7] ) def test_value(self, input_param, input_data): dropout = RandCoarseDropout(**input_param) diff --git a/tests/test_rand_coarse_dropoutd.py b/tests/test_rand_coarse_dropoutd.py index fc898a9fca..ebb090e378 100644 --- a/tests/test_rand_coarse_dropoutd.py +++ b/tests/test_rand_coarse_dropoutd.py @@ -28,14 +28,7 @@ ] TEST_CASE_2 = [ - { - "keys": "img", - "holes": 2, - "spatial_size": [2, 2, 2], - "fill_value": 5, - "max_spatial_size": [4, 4, 3], - "prob": 1.0, - }, + {"keys": "img", "holes": 2, "spatial_size": [2, 2, 2], "fill_value": 5, "max_spatial_size": [4, 4, 3], "prob": 1.0}, {"img": np.random.randint(0, 2, size=[3, 3, 3, 4])}, ] diff --git a/tests/test_rand_coarse_shuffle.py b/tests/test_rand_coarse_shuffle.py index e6d721e264..0262fe2b3a 100644 --- a/tests/test_rand_coarse_shuffle.py +++ b/tests/test_rand_coarse_shuffle.py @@ -32,8 +32,8 @@ [[8, 19, 26], [24, 6, 15], [0, 13, 25]], [[17, 3, 5], [10, 1, 12], [22, 4, 11]], [[21, 20, 23], [14, 2, 16], [18, 9, 7]], - ], - ], + ] + ] ), ], [ diff --git a/tests/test_rand_coarse_shuffled.py b/tests/test_rand_coarse_shuffled.py index 775fdae07e..ad49c8d02d 100644 --- a/tests/test_rand_coarse_shuffled.py +++ b/tests/test_rand_coarse_shuffled.py @@ -31,8 +31,8 @@ [[8, 19, 26], [24, 6, 15], [0, 13, 25]], [[17, 3, 5], [10, 1, 12], [22, 4, 11]], [[21, 20, 23], [14, 2, 16], [18, 9, 7]], - ], - ], + ] + ] ), ], [ diff --git a/tests/test_rand_elastic_3d.py b/tests/test_rand_elastic_3d.py index d44324746f..712049ec1a 100644 --- a/tests/test_rand_elastic_3d.py +++ b/tests/test_rand_elastic_3d.py @@ -36,24 +36,14 @@ ) TESTS.append( [ - { - "magnitude_range": (0.3, 2.3), - "sigma_range": (1.0, 20.0), - "prob": 0.0, - "device": device, - }, + {"magnitude_range": (0.3, 2.3), "sigma_range": (1.0, 20.0), "prob": 0.0, "device": device}, {"img": p(torch.ones((2, 3, 3, 3))), "spatial_size": (2, 2, 2)}, p(np.ones((2, 2, 2, 2))), ] ) TESTS.append( [ - { - "magnitude_range": (0.3, 0.3), - "sigma_range": (1.0, 2.0), - "prob": 0.9, - "device": device, - }, + {"magnitude_range": (0.3, 0.3), "sigma_range": (1.0, 2.0), "prob": 0.9, "device": device}, {"img": p(torch.arange(27).reshape((1, 3, 3, 3))), "spatial_size": (2, 2, 2)}, p( np.array( diff --git a/tests/test_rand_grid_distortion.py b/tests/test_rand_grid_distortion.py index c01a36e73d..eabe6d34a1 100644 --- a/tests/test_rand_grid_distortion.py +++ b/tests/test_rand_grid_distortion.py @@ -22,13 +22,7 @@ seed = 0 TESTS.append( [ - dict( - num_cells=2, - prob=1.0, - distort_limit=0.5, - mode="nearest", - padding_mode="zeros", - ), + dict(num_cells=2, prob=1.0, distort_limit=0.5, mode="nearest", padding_mode="zeros"), seed, p(np.indices([6, 6]).astype(np.float32)), p( @@ -58,13 +52,7 @@ seed = 1 TESTS.append( [ - dict( - num_cells=(2, 2), - prob=1.0, - distort_limit=0.1, - mode="bilinear", - padding_mode="reflection", - ), + dict(num_cells=(2, 2), prob=1.0, distort_limit=0.1, mode="bilinear", padding_mode="reflection"), seed, p(np.indices([6, 6]).astype(np.float32)), p( diff --git a/tests/test_rand_k_space_spike_noised.py b/tests/test_rand_k_space_spike_noised.py index e41ba19a5c..9036166b61 100644 --- a/tests/test_rand_k_space_spike_noised.py +++ b/tests/test_rand_k_space_spike_noised.py @@ -49,12 +49,7 @@ def test_same_result(self, im_shape, im_type): data = self.get_data(im_shape, im_type) - t = RandKSpaceSpikeNoised( - KEYS, - prob=1.0, - intensity_range=(13, 15), - channel_wise=True, - ) + t = RandKSpaceSpikeNoised(KEYS, prob=1.0, intensity_range=(13, 15), channel_wise=True) t.set_random_state(42) out1 = t(deepcopy(data)) @@ -73,19 +68,9 @@ def test_same_result(self, im_shape, im_type): def test_0_prob(self, im_shape, im_type): data = self.get_data(im_shape, im_type) - t1 = RandKSpaceSpikeNoised( - KEYS, - prob=0.0, - intensity_range=(13, 15), - channel_wise=True, - ) - - t2 = RandKSpaceSpikeNoised( - KEYS, - prob=0.0, - intensity_range=(13, 15), - channel_wise=True, - ) + t1 = RandKSpaceSpikeNoised(KEYS, prob=0.0, intensity_range=(13, 15), channel_wise=True) + + t2 = RandKSpaceSpikeNoised(KEYS, prob=0.0, intensity_range=(13, 15), channel_wise=True) out1 = t1(data) out2 = t2(data) diff --git a/tests/test_rand_spatial_crop_samplesd.py b/tests/test_rand_spatial_crop_samplesd.py index 4b41ce3344..a4e8bdb2e6 100644 --- a/tests/test_rand_spatial_crop_samplesd.py +++ b/tests/test_rand_spatial_crop_samplesd.py @@ -98,11 +98,7 @@ def test_deep_copy(self): data = {"img": np.ones((1, 10, 11, 12))} num_samples = 3 sampler = RandSpatialCropSamplesd( - keys=["img"], - roi_size=(3, 3, 3), - num_samples=num_samples, - random_center=True, - random_size=False, + keys=["img"], roi_size=(3, 3, 3), num_samples=num_samples, random_center=True, random_size=False ) transform = Compose([ToTensord(keys="img"), sampler]) samples = transform(data) diff --git a/tests/test_rand_zoom.py b/tests/test_rand_zoom.py index 6ccb265cca..da630853fe 100644 --- a/tests/test_rand_zoom.py +++ b/tests/test_rand_zoom.py @@ -26,13 +26,7 @@ class TestRandZoom(NumpyImageTestCase2D): @parameterized.expand(VALID_CASES) def test_correct_results(self, min_zoom, max_zoom, mode, keep_size): for p in TEST_NDARRAYS: - random_zoom = RandZoom( - prob=1.0, - min_zoom=min_zoom, - max_zoom=max_zoom, - mode=mode, - keep_size=keep_size, - ) + random_zoom = RandZoom(prob=1.0, min_zoom=min_zoom, max_zoom=max_zoom, mode=mode, keep_size=keep_size) random_zoom.set_random_state(1234) zoomed = random_zoom(p(self.imt[0])) expected = [ @@ -69,13 +63,7 @@ def test_invalid_inputs(self, _, min_zoom, max_zoom, mode, raises): def test_auto_expand_3d(self): for p in TEST_NDARRAYS: - random_zoom = RandZoom( - prob=1.0, - min_zoom=[0.8, 0.7], - max_zoom=[1.2, 1.3], - mode="nearest", - keep_size=False, - ) + random_zoom = RandZoom(prob=1.0, min_zoom=[0.8, 0.7], max_zoom=[1.2, 1.3], mode="nearest", keep_size=False) random_zoom.set_random_state(1234) test_data = p(np.random.randint(0, 2, size=[2, 2, 3, 4])) zoomed = random_zoom(test_data) diff --git a/tests/test_rand_zoomd.py b/tests/test_rand_zoomd.py index 8cc770cc21..89a997e925 100644 --- a/tests/test_rand_zoomd.py +++ b/tests/test_rand_zoomd.py @@ -49,13 +49,7 @@ def test_correct_results(self, min_zoom, max_zoom, mode, align_corners, keep_siz def test_keep_size(self): key = "img" random_zoom = RandZoomd( - keys=key, - prob=1.0, - min_zoom=0.6, - max_zoom=0.7, - keep_size=True, - padding_mode="constant", - constant_values=2, + keys=key, prob=1.0, min_zoom=0.6, max_zoom=0.7, keep_size=True, padding_mode="constant", constant_values=2 ) for p in TEST_NDARRAYS: zoomed = random_zoom({key: p(self.imt[0])}) @@ -73,12 +67,7 @@ def test_invalid_inputs(self, _, min_zoom, max_zoom, mode, raises): def test_auto_expand_3d(self): random_zoom = RandZoomd( - keys="img", - prob=1.0, - min_zoom=[0.8, 0.7], - max_zoom=[1.2, 1.3], - mode="nearest", - keep_size=False, + keys="img", prob=1.0, min_zoom=[0.8, 0.7], max_zoom=[1.2, 1.3], mode="nearest", keep_size=False ) for p in TEST_NDARRAYS: random_zoom.set_random_state(1234) diff --git a/tests/test_randtorchvisiond.py b/tests/test_randtorchvisiond.py index d0485ce405..2dffe67994 100644 --- a/tests/test_randtorchvisiond.py +++ b/tests/test_randtorchvisiond.py @@ -29,19 +29,10 @@ {"img": torch.tensor([[[0.0, 1.0], [1.0, 2.0]], [[0.0, 1.0], [1.0, 2.0]], [[0.0, 1.0], [1.0, 2.0]]])}, torch.tensor( [ - [ - [0.1090, 0.6193], - [0.6193, 0.9164], - ], - [ - [0.1090, 0.6193], - [0.6193, 0.9164], - ], - [ - [0.1090, 0.6193], - [0.6193, 0.9164], - ], - ], + [[0.1090, 0.6193], [0.6193, 0.9164]], + [[0.1090, 0.6193], [0.6193, 0.9164]], + [[0.1090, 0.6193], [0.6193, 0.9164]], + ] ), ] @@ -50,24 +41,9 @@ {"img": torch.tensor([[[0.0, 1.0], [1.0, 2.0]], [[0.0, 1.0], [1.0, 2.0]], [[0.0, 1.0], [1.0, 2.0]]])}, torch.tensor( [ - [ - [0.0, 0.0, 0.0, 0.0], - [0.0, 0.0, 1.0, 0.0], - [0.0, 1.0, 2.0, 0.0], - [0.0, 0.0, 0.0, 0.0], - ], - [ - [0.0, 0.0, 0.0, 0.0], - [0.0, 0.0, 1.0, 0.0], - [0.0, 1.0, 2.0, 0.0], - [0.0, 0.0, 0.0, 0.0], - ], - [ - [0.0, 0.0, 0.0, 0.0], - [0.0, 0.0, 1.0, 0.0], - [0.0, 1.0, 2.0, 0.0], - [0.0, 0.0, 0.0, 0.0], - ], + [[0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], [0.0, 1.0, 2.0, 0.0], [0.0, 0.0, 0.0, 0.0]], + [[0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], [0.0, 1.0, 2.0, 0.0], [0.0, 0.0, 0.0, 0.0]], + [[0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], [0.0, 1.0, 2.0, 0.0], [0.0, 0.0, 0.0, 0.0]], ] ), ] diff --git a/tests/test_reg_loss_integration.py b/tests/test_reg_loss_integration.py index 1578aa4888..2949ee1519 100644 --- a/tests/test_reg_loss_integration.py +++ b/tests/test_reg_loss_integration.py @@ -21,21 +21,9 @@ TEST_CASES = [ [BendingEnergyLoss, {}, ["pred"]], - [ - LocalNormalizedCrossCorrelationLoss, - {"kernel_size": 7, "kernel_type": "rectangular"}, - ["pred", "target"], - ], - [ - LocalNormalizedCrossCorrelationLoss, - {"kernel_size": 5, "kernel_type": "triangular"}, - ["pred", "target"], - ], - [ - LocalNormalizedCrossCorrelationLoss, - {"kernel_size": 3, "kernel_type": "gaussian"}, - ["pred", "target"], - ], + [LocalNormalizedCrossCorrelationLoss, {"kernel_size": 7, "kernel_type": "rectangular"}, ["pred", "target"]], + [LocalNormalizedCrossCorrelationLoss, {"kernel_size": 5, "kernel_type": "triangular"}, ["pred", "target"]], + [LocalNormalizedCrossCorrelationLoss, {"kernel_size": 3, "kernel_type": "gaussian"}, ["pred", "target"]], [GlobalMutualInformationLoss, {"num_bins": 10}, ["pred", "target"]], [GlobalMutualInformationLoss, {"kernel_type": "b-spline", "num_bins": 10}, ["pred", "target"]], ] diff --git a/tests/test_resize.py b/tests/test_resize.py index f6c4a8b14b..65d934afe6 100644 --- a/tests/test_resize.py +++ b/tests/test_resize.py @@ -47,12 +47,7 @@ def test_correct_results(self, spatial_size, mode): spatial_size = (32, 64) expected = [ skimage.transform.resize( - channel, - spatial_size, - order=_order, - clip=False, - preserve_range=False, - anti_aliasing=False, + channel, spatial_size, order=_order, clip=False, preserve_range=False, anti_aliasing=False ) for channel in self.imt[0] ] diff --git a/tests/test_resize_with_pad_or_crop.py b/tests/test_resize_with_pad_or_crop.py index 2162a0bb1b..262cd2ffdb 100644 --- a/tests/test_resize_with_pad_or_crop.py +++ b/tests/test_resize_with_pad_or_crop.py @@ -19,31 +19,15 @@ from tests.utils import TEST_NDARRAYS TEST_CASES = [ - [ - {"spatial_size": [15, 8, 8], "mode": "constant"}, - (3, 8, 8, 4), - (3, 15, 8, 8), - ], + [{"spatial_size": [15, 8, 8], "mode": "constant"}, (3, 8, 8, 4), (3, 15, 8, 8)], [ {"spatial_size": [15, 4, 8], "mode": "constant", "method": "end", "constant_values": 1}, (3, 8, 8, 4), (3, 15, 4, 8), ], - [ - {"spatial_size": [15, 4, -1], "mode": "constant"}, - (3, 8, 8, 4), - (3, 15, 4, 4), - ], - [ - {"spatial_size": [15, 4, -1], "mode": "reflect"}, - (3, 8, 8, 4), - (3, 15, 4, 4), - ], - [ - {"spatial_size": [-1, -1, -1], "mode": "reflect"}, - (3, 8, 8, 4), - (3, 8, 8, 4), - ], + [{"spatial_size": [15, 4, -1], "mode": "constant"}, (3, 8, 8, 4), (3, 15, 4, 4)], + [{"spatial_size": [15, 4, -1], "mode": "reflect"}, (3, 8, 8, 4), (3, 15, 4, 4)], + [{"spatial_size": [-1, -1, -1], "mode": "reflect"}, (3, 8, 8, 4), (3, 8, 8, 4)], ] diff --git a/tests/test_resize_with_pad_or_cropd.py b/tests/test_resize_with_pad_or_cropd.py index 58f6c92a8f..91201bba53 100644 --- a/tests/test_resize_with_pad_or_cropd.py +++ b/tests/test_resize_with_pad_or_cropd.py @@ -19,31 +19,15 @@ from tests.utils import TEST_NDARRAYS TEST_CASES = [ - [ - {"keys": "img", "spatial_size": [15, 8, 8], "mode": "constant"}, - {"img": np.zeros((3, 8, 8, 4))}, - (3, 15, 8, 8), - ], + [{"keys": "img", "spatial_size": [15, 8, 8], "mode": "constant"}, {"img": np.zeros((3, 8, 8, 4))}, (3, 15, 8, 8)], [ {"keys": "img", "spatial_size": [15, 4, 8], "mode": "constant", "method": "end", "constant_values": 1}, {"img": np.zeros((3, 8, 8, 4))}, (3, 15, 4, 8), ], - [ - {"keys": "img", "spatial_size": [15, 4, -1], "mode": "constant"}, - {"img": np.zeros((3, 8, 8, 4))}, - (3, 15, 4, 4), - ], - [ - {"keys": "img", "spatial_size": [15, 4, -1], "mode": "reflect"}, - {"img": np.zeros((3, 8, 8, 4))}, - (3, 15, 4, 4), - ], - [ - {"keys": "img", "spatial_size": [-1, -1, -1], "mode": "reflect"}, - {"img": np.zeros((3, 8, 8, 4))}, - (3, 8, 8, 4), - ], + [{"keys": "img", "spatial_size": [15, 4, -1], "mode": "constant"}, {"img": np.zeros((3, 8, 8, 4))}, (3, 15, 4, 4)], + [{"keys": "img", "spatial_size": [15, 4, -1], "mode": "reflect"}, {"img": np.zeros((3, 8, 8, 4))}, (3, 15, 4, 4)], + [{"keys": "img", "spatial_size": [-1, -1, -1], "mode": "reflect"}, {"img": np.zeros((3, 8, 8, 4))}, (3, 8, 8, 4)], ] diff --git a/tests/test_resized.py b/tests/test_resized.py index 47b8e8a704..7d09f13bad 100644 --- a/tests/test_resized.py +++ b/tests/test_resized.py @@ -50,12 +50,7 @@ def test_correct_results(self, spatial_size, mode): spatial_size = (32, 64) expected = [ skimage.transform.resize( - channel, - spatial_size, - order=_order, - clip=False, - preserve_range=False, - anti_aliasing=False, + channel, spatial_size, order=_order, clip=False, preserve_range=False, anti_aliasing=False ) for channel in self.imt[0] ] diff --git a/tests/test_rotate.py b/tests/test_rotate.py index 16a9c6d124..411fed3d1d 100644 --- a/tests/test_rotate.py +++ b/tests/test_rotate.py @@ -62,13 +62,7 @@ def test_correct_results(self, im_type, angle, keep_size, mode, padding_mode, al for channel in self.imt[0]: expected.append( scipy.ndimage.rotate( - channel, - -np.rad2deg(angle), - (0, 1), - not keep_size, - order=_order, - mode=_mode, - prefilter=False, + channel, -np.rad2deg(angle), (0, 1), not keep_size, order=_order, mode=_mode, prefilter=False ) ) expected = np.stack(expected).astype(np.float32) @@ -96,13 +90,7 @@ def test_correct_results(self, im_type, angle, keep_size, mode, padding_mode, al for channel in self.imt[0]: expected.append( scipy.ndimage.rotate( - channel, - -np.rad2deg(angle), - (1, 2), - not keep_size, - order=_order, - mode=_mode, - prefilter=False, + channel, -np.rad2deg(angle), (1, 2), not keep_size, order=_order, mode=_mode, prefilter=False ) ) expected = np.stack(expected).astype(np.float32) diff --git a/tests/test_save_image.py b/tests/test_save_image.py index f7c8e07f06..be77b12b8e 100644 --- a/tests/test_save_image.py +++ b/tests/test_save_image.py @@ -18,19 +18,9 @@ from monai.transforms import SaveImage -TEST_CASE_1 = [ - torch.randint(0, 255, (1, 2, 3, 4)), - {"filename_or_obj": "testfile0.nii.gz"}, - ".nii.gz", - False, -] - -TEST_CASE_2 = [ - torch.randint(0, 255, (1, 2, 3, 4)), - None, - ".nii.gz", - False, -] +TEST_CASE_1 = [torch.randint(0, 255, (1, 2, 3, 4)), {"filename_or_obj": "testfile0.nii.gz"}, ".nii.gz", False] + +TEST_CASE_2 = [torch.randint(0, 255, (1, 2, 3, 4)), None, ".nii.gz", False] class TestSaveImage(unittest.TestCase): diff --git a/tests/test_save_imaged.py b/tests/test_save_imaged.py index 35bbea9628..f05a83dd9a 100644 --- a/tests/test_save_imaged.py +++ b/tests/test_save_imaged.py @@ -19,10 +19,7 @@ from monai.transforms import SaveImaged TEST_CASE_1 = [ - { - "img": torch.randint(0, 255, (1, 2, 3, 4)), - "img_meta_dict": {"filename_or_obj": "testfile0.nii.gz"}, - }, + {"img": torch.randint(0, 255, (1, 2, 3, 4)), "img_meta_dict": {"filename_or_obj": "testfile0.nii.gz"}}, ".nii.gz", False, ] diff --git a/tests/test_savitzky_golay_filter.py b/tests/test_savitzky_golay_filter.py index c9bcd9687e..fa38659acb 100644 --- a/tests/test_savitzky_golay_filter.py +++ b/tests/test_savitzky_golay_filter.py @@ -99,13 +99,7 @@ class TestSavitzkyGolayCPU(unittest.TestCase): @parameterized.expand( - [ - TEST_CASE_SINGLE_VALUE, - TEST_CASE_1D, - TEST_CASE_2D_AXIS_2, - TEST_CASE_2D_AXIS_3, - TEST_CASE_SINE_SMOOTH, - ] + [TEST_CASE_SINGLE_VALUE, TEST_CASE_1D, TEST_CASE_2D_AXIS_2, TEST_CASE_2D_AXIS_3, TEST_CASE_SINE_SMOOTH] ) def test_value(self, arguments, image, expected_data, atol): result = SavitzkyGolayFilter(**arguments)(image) @@ -124,13 +118,7 @@ def test_value(self, arguments, image, expected_data, atol): @skip_if_no_cuda class TestSavitzkyGolayGPU(unittest.TestCase): @parameterized.expand( - [ - TEST_CASE_SINGLE_VALUE, - TEST_CASE_1D, - TEST_CASE_2D_AXIS_2, - TEST_CASE_2D_AXIS_3, - TEST_CASE_SINE_SMOOTH, - ] + [TEST_CASE_SINGLE_VALUE, TEST_CASE_1D, TEST_CASE_2D_AXIS_2, TEST_CASE_2D_AXIS_3, TEST_CASE_SINE_SMOOTH] ) def test_value(self, arguments, image, expected_data, atol): result = SavitzkyGolayFilter(**arguments)(image.to(device="cuda")) @@ -140,12 +128,7 @@ def test_value(self, arguments, image, expected_data, atol): @skip_if_no_cuda class TestSavitzkyGolayGPUREP(unittest.TestCase): @parameterized.expand( - [ - TEST_CASE_SINGLE_VALUE_REP, - TEST_CASE_1D_REP, - TEST_CASE_2D_AXIS_2_REP, - TEST_CASE_2D_AXIS_3_REP, - ] + [TEST_CASE_SINGLE_VALUE_REP, TEST_CASE_1D_REP, TEST_CASE_2D_AXIS_2_REP, TEST_CASE_2D_AXIS_3_REP] ) def test_value(self, arguments, image, expected_data, atol): result = SavitzkyGolayFilter(**arguments)(image.to(device="cuda")) diff --git a/tests/test_selfattention.py b/tests/test_selfattention.py index 3d561aac2f..559e86487b 100644 --- a/tests/test_selfattention.py +++ b/tests/test_selfattention.py @@ -28,11 +28,7 @@ for num_heads in [4, 6, 8, 12]: test_case = [ - { - "hidden_size": hidden_size, - "num_heads": num_heads, - "dropout_rate": dropout_rate, - }, + {"hidden_size": hidden_size, "num_heads": num_heads, "dropout_rate": dropout_rate}, (2, 512, hidden_size), (2, 512, hidden_size), ] diff --git a/tests/test_skip_connection.py b/tests/test_skip_connection.py index 2118842ed0..462acd9242 100644 --- a/tests/test_skip_connection.py +++ b/tests/test_skip_connection.py @@ -24,11 +24,7 @@ result_shape = (input_shape[0] * 2, *input_shape[1:]) else: result_shape = input_shape - test_case = [ - {"dim": 0, "mode": type_1}, - input_shape, - result_shape, - ] + test_case = [{"dim": 0, "mode": type_1}, input_shape, result_shape] TEST_CASES_3D.append(test_case) diff --git a/tests/test_sliding_window_inference.py b/tests/test_sliding_window_inference.py index a22e5990bf..c5b941bf3d 100644 --- a/tests/test_sliding_window_inference.py +++ b/tests/test_sliding_window_inference.py @@ -33,14 +33,7 @@ [(1, 3, 16, 7), (80, 50), 7, 0.5, "gaussian", torch.device("cpu:0")], # 2D large overlap, gaussian [(1, 3, 16, 15, 7), (4, 10, 7), 3, 0.25, "gaussian", torch.device("cpu:0")], # 3D small roi, gaussian [(3, 3, 16, 15, 7), (4, 10, 7), 3, 0.25, "gaussian", torch.device("cpu:0")], # 3D small roi, gaussian - [ - (1, 3, 16, 15, 7), - (4, 10, 7), - 3, - 0.25, - "gaussian", - torch.device("cuda:0"), - ], # test inference on gpu if availabe + [(1, 3, 16, 15, 7), (4, 10, 7), 3, 0.25, "gaussian", torch.device("cuda:0")], # test inference on gpu if availabe [(1, 3, 16, 15, 7), (4, 1, 7), 3, 0.25, "constant", torch.device("cpu:0")], # 3D small roi [(5, 3, 16, 15, 7), (4, 1, 7), 3, 0.25, "constant", torch.device("cpu:0")], # 3D small roi ] diff --git a/tests/test_smartcache_patch_wsi_dataset.py b/tests/test_smartcache_patch_wsi_dataset.py index a2605ec525..317b6cba63 100644 --- a/tests/test_smartcache_patch_wsi_dataset.py +++ b/tests/test_smartcache_patch_wsi_dataset.py @@ -134,13 +134,7 @@ class TestSmartCachePatchWSIDataset(unittest.TestCase): def setUp(self): download_url(FILE_URL, FILE_PATH, "5a3cfd4fd725c50578ddb80b517b759f") - @parameterized.expand( - [ - TEST_CASE_0, - TEST_CASE_1, - TEST_CASE_2, - ] - ) + @parameterized.expand([TEST_CASE_0, TEST_CASE_1, TEST_CASE_2]) @skipUnless(has_cim, "Requires CuCIM") def test_read_patches(self, input_parameters, expected): dataset = SmartCachePatchWSIDataset(**input_parameters) diff --git a/tests/test_smartcachedataset.py b/tests/test_smartcachedataset.py index e2675f4d8c..f390a9127e 100644 --- a/tests/test_smartcachedataset.py +++ b/tests/test_smartcachedataset.py @@ -174,13 +174,7 @@ def test_datalist(self): data_list = [np.array([i]) for i in range(5)] data_list_backup = copy.copy(data_list) - SmartCacheDataset( - data=data_list, - transform=None, - cache_rate=0.5, - replace_rate=0.4, - shuffle=True, - ) + SmartCacheDataset(data=data_list, transform=None, cache_rate=0.5, replace_rate=0.4, shuffle=True) np.testing.assert_allclose(data_list, data_list_backup) diff --git a/tests/test_spacingd.py b/tests/test_spacingd.py index fd1ee7fd54..ab40976caf 100644 --- a/tests/test_spacingd.py +++ b/tests/test_spacingd.py @@ -60,14 +60,7 @@ "image_meta_dict": {"affine": np.eye(4)}, "seg_meta_dict": {"affine": np.eye(4)}, }, - dict( - keys=("image", "seg"), - mode="nearest", - pixdim=( - 1, - 0.2, - ), - ), + dict(keys=("image", "seg"), mode="nearest", pixdim=(1, 0.2)), ("image", "image_meta_dict", "image_transforms", "seg", "seg_meta_dict", "seg_transforms"), (2, 1, 46), np.diag((1, 0.2, 1, 1)), diff --git a/tests/test_spatial_crop.py b/tests/test_spatial_crop.py index c18dd86e46..652c420a4d 100644 --- a/tests/test_spatial_crop.py +++ b/tests/test_spatial_crop.py @@ -19,38 +19,16 @@ from tests.utils import TEST_NDARRAYS, assert_allclose TESTS = [ - [ - {"roi_center": [1, 1, 1], "roi_size": [2, 2, 2]}, - (3, 3, 3, 3), - (3, 2, 2, 2), - ], + [{"roi_center": [1, 1, 1], "roi_size": [2, 2, 2]}, (3, 3, 3, 3), (3, 2, 2, 2)], [{"roi_start": [0, 0, 0], "roi_end": [2, 2, 2]}, (3, 3, 3, 3), (3, 2, 2, 2)], [{"roi_start": [0, 0], "roi_end": [2, 2]}, (3, 3, 3, 3), (3, 2, 2, 3)], - [ - {"roi_start": [0, 0, 0, 0, 0], "roi_end": [2, 2, 2, 2, 2]}, - (3, 3, 3, 3), - (3, 2, 2, 2), - ], - [ - {"roi_start": [0, 0, 0, 0, 0], "roi_end": [8, 8, 8, 2, 2]}, - (3, 3, 3, 3), - (3, 3, 3, 3), - ], - [ - {"roi_start": [1, 0, 0], "roi_end": [1, 8, 8]}, - (3, 3, 3, 3), - (3, 0, 3, 3), - ], - [ - {"roi_slices": [slice(s, e) for s, e in zip([-1, -2, 0], [None, None, 2])]}, - (3, 3, 3, 3), - (3, 1, 2, 2), - ], + [{"roi_start": [0, 0, 0, 0, 0], "roi_end": [2, 2, 2, 2, 2]}, (3, 3, 3, 3), (3, 2, 2, 2)], + [{"roi_start": [0, 0, 0, 0, 0], "roi_end": [8, 8, 8, 2, 2]}, (3, 3, 3, 3), (3, 3, 3, 3)], + [{"roi_start": [1, 0, 0], "roi_end": [1, 8, 8]}, (3, 3, 3, 3), (3, 0, 3, 3)], + [{"roi_slices": [slice(s, e) for s, e in zip([-1, -2, 0], [None, None, 2])]}, (3, 3, 3, 3), (3, 1, 2, 2)], ] -TEST_ERRORS = [ - [{"roi_slices": [slice(s, e, 2) for s, e in zip([-1, -2, 0], [None, None, 2])]}], -] +TEST_ERRORS = [[{"roi_slices": [slice(s, e, 2) for s, e in zip([-1, -2, 0], [None, None, 2])]}]] class TestSpatialCrop(unittest.TestCase): diff --git a/tests/test_spatial_pad.py b/tests/test_spatial_pad.py index 3d237c6681..83a261138e 100644 --- a/tests/test_spatial_pad.py +++ b/tests/test_spatial_pad.py @@ -47,21 +47,9 @@ MODES += [PytorchPadMode(i) for i in PT_MODES] for mode in MODES: - TESTS.append( - [ - {"spatial_size": [3, 4], "method": "end", "mode": mode}, - (1, 2, 3), - (1, 3, 4), - ] - ) - - TESTS.append( - [ - {"spatial_size": [15, 4, -1], "method": "symmetric", "mode": mode}, - (3, 8, 8, 4), - (3, 15, 8, 4), - ] - ) + TESTS.append([{"spatial_size": [3, 4], "method": "end", "mode": mode}, (1, 2, 3), (1, 3, 4)]) + + TESTS.append([{"spatial_size": [15, 4, -1], "method": "symmetric", "mode": mode}, (3, 8, 8, 4), (3, 15, 8, 4)]) class TestSpatialPad(unittest.TestCase): diff --git a/tests/test_split_channeld.py b/tests/test_split_channeld.py index f1df24364d..344f206c86 100644 --- a/tests/test_split_channeld.py +++ b/tests/test_split_channeld.py @@ -51,13 +51,7 @@ ] ) - TESTS.append( - [ - {"keys": "pred", "channel_dim": 1}, - {"pred": p(np.random.randint(2, size=(3, 2, 4)))}, - (3, 1, 4), - ] - ) + TESTS.append([{"keys": "pred", "channel_dim": 1}, {"pred": p(np.random.randint(2, size=(3, 2, 4)))}, (3, 1, 4)]) class TestSplitChanneld(unittest.TestCase): diff --git a/tests/test_split_on_grid.py b/tests/test_split_on_grid.py index a187835e7b..4893c4c78a 100644 --- a/tests/test_split_on_grid.py +++ b/tests/test_split_on_grid.py @@ -26,100 +26,41 @@ A2 = torch.cat([A21, A22], 2) A = torch.cat([A1, A2], 1) -TEST_CASE_0 = [ - {"grid_size": (2, 2)}, - A, - torch.stack([A11, A12, A21, A22]), -] - -TEST_CASE_1 = [ - {"grid_size": (2, 1)}, - A, - torch.stack([A1, A2]), -] - -TEST_CASE_2 = [ - {"grid_size": (1, 2)}, - A1, - torch.stack([A11, A12]), -] - -TEST_CASE_3 = [ - {"grid_size": (1, 2)}, - A2, - torch.stack([A21, A22]), -] - -TEST_CASE_4 = [ - {"grid_size": (1, 1), "patch_size": (2, 2)}, - A, - torch.stack([A11]), -] - -TEST_CASE_5 = [ - {"grid_size": 1, "patch_size": 4}, - A, - torch.stack([A]), -] - -TEST_CASE_6 = [ - {"grid_size": 2, "patch_size": 2}, - A, - torch.stack([A11, A12, A21, A22]), -] - -TEST_CASE_7 = [ - {"grid_size": 1}, - A, - torch.stack([A]), -] - -TEST_CASE_MC_0 = [ - {"grid_size": (2, 2)}, - [A, A], - [torch.stack([A11, A12, A21, A22]), torch.stack([A11, A12, A21, A22])], -] - - -TEST_CASE_MC_1 = [ - {"grid_size": (2, 1)}, - [A] * 5, - [torch.stack([A1, A2])] * 5, -] - - -TEST_CASE_MC_2 = [ - {"grid_size": (1, 2)}, - [A1, A2], - [torch.stack([A11, A12]), torch.stack([A21, A22])], -] +TEST_CASE_0 = [{"grid_size": (2, 2)}, A, torch.stack([A11, A12, A21, A22])] + +TEST_CASE_1 = [{"grid_size": (2, 1)}, A, torch.stack([A1, A2])] + +TEST_CASE_2 = [{"grid_size": (1, 2)}, A1, torch.stack([A11, A12])] + +TEST_CASE_3 = [{"grid_size": (1, 2)}, A2, torch.stack([A21, A22])] + +TEST_CASE_4 = [{"grid_size": (1, 1), "patch_size": (2, 2)}, A, torch.stack([A11])] + +TEST_CASE_5 = [{"grid_size": 1, "patch_size": 4}, A, torch.stack([A])] + +TEST_CASE_6 = [{"grid_size": 2, "patch_size": 2}, A, torch.stack([A11, A12, A21, A22])] + +TEST_CASE_7 = [{"grid_size": 1}, A, torch.stack([A])] + +TEST_CASE_MC_0 = [{"grid_size": (2, 2)}, [A, A], [torch.stack([A11, A12, A21, A22]), torch.stack([A11, A12, A21, A22])]] + + +TEST_CASE_MC_1 = [{"grid_size": (2, 1)}, [A] * 5, [torch.stack([A1, A2])] * 5] + + +TEST_CASE_MC_2 = [{"grid_size": (1, 2)}, [A1, A2], [torch.stack([A11, A12]), torch.stack([A21, A22])]] class TestSplitOnGrid(unittest.TestCase): @parameterized.expand( - [ - TEST_CASE_0, - TEST_CASE_1, - TEST_CASE_2, - TEST_CASE_3, - TEST_CASE_4, - TEST_CASE_5, - TEST_CASE_6, - TEST_CASE_7, - ] + [TEST_CASE_0, TEST_CASE_1, TEST_CASE_2, TEST_CASE_3, TEST_CASE_4, TEST_CASE_5, TEST_CASE_6, TEST_CASE_7] ) def test_split_pathce_single_call(self, input_parameters, img, expected): splitter = SplitOnGrid(**input_parameters) output = splitter(img) np.testing.assert_equal(output.numpy(), expected.numpy()) - @parameterized.expand( - [ - TEST_CASE_MC_0, - TEST_CASE_MC_1, - TEST_CASE_MC_2, - ] - ) + @parameterized.expand([TEST_CASE_MC_0, TEST_CASE_MC_1, TEST_CASE_MC_2]) def test_split_pathce_multiple_call(self, input_parameters, img_list, expected_list): splitter = SplitOnGrid(**input_parameters) for img, expected in zip(img_list, expected_list): diff --git a/tests/test_split_on_grid_dict.py b/tests/test_split_on_grid_dict.py index 96ec095423..f22e58515f 100644 --- a/tests/test_split_on_grid_dict.py +++ b/tests/test_split_on_grid_dict.py @@ -26,53 +26,21 @@ A2 = torch.cat([A21, A22], 2) A = torch.cat([A1, A2], 1) -TEST_CASE_0 = [ - {"keys": "image", "grid_size": (2, 2)}, - {"image": A}, - torch.stack([A11, A12, A21, A22]), -] +TEST_CASE_0 = [{"keys": "image", "grid_size": (2, 2)}, {"image": A}, torch.stack([A11, A12, A21, A22])] -TEST_CASE_1 = [ - {"keys": "image", "grid_size": (2, 1)}, - {"image": A}, - torch.stack([A1, A2]), -] +TEST_CASE_1 = [{"keys": "image", "grid_size": (2, 1)}, {"image": A}, torch.stack([A1, A2])] -TEST_CASE_2 = [ - {"keys": "image", "grid_size": (1, 2)}, - {"image": A1}, - torch.stack([A11, A12]), -] +TEST_CASE_2 = [{"keys": "image", "grid_size": (1, 2)}, {"image": A1}, torch.stack([A11, A12])] -TEST_CASE_3 = [ - {"keys": "image", "grid_size": (1, 2)}, - {"image": A2}, - torch.stack([A21, A22]), -] +TEST_CASE_3 = [{"keys": "image", "grid_size": (1, 2)}, {"image": A2}, torch.stack([A21, A22])] -TEST_CASE_4 = [ - {"keys": "image", "grid_size": (1, 1), "patch_size": (2, 2)}, - {"image": A}, - torch.stack([A11]), -] +TEST_CASE_4 = [{"keys": "image", "grid_size": (1, 1), "patch_size": (2, 2)}, {"image": A}, torch.stack([A11])] -TEST_CASE_5 = [ - {"keys": "image", "grid_size": 1, "patch_size": 4}, - {"image": A}, - torch.stack([A]), -] +TEST_CASE_5 = [{"keys": "image", "grid_size": 1, "patch_size": 4}, {"image": A}, torch.stack([A])] -TEST_CASE_6 = [ - {"keys": "image", "grid_size": 2, "patch_size": 2}, - {"image": A}, - torch.stack([A11, A12, A21, A22]), -] +TEST_CASE_6 = [{"keys": "image", "grid_size": 2, "patch_size": 2}, {"image": A}, torch.stack([A11, A12, A21, A22])] -TEST_CASE_7 = [ - {"keys": "image", "grid_size": 1}, - {"image": A}, - torch.stack([A]), -] +TEST_CASE_7 = [{"keys": "image", "grid_size": 1}, {"image": A}, torch.stack([A])] TEST_CASE_MC_0 = [ {"keys": "image", "grid_size": (2, 2)}, @@ -81,11 +49,7 @@ ] -TEST_CASE_MC_1 = [ - {"keys": "image", "grid_size": (2, 1)}, - [{"image": A}] * 5, - [torch.stack([A1, A2])] * 5, -] +TEST_CASE_MC_1 = [{"keys": "image", "grid_size": (2, 1)}, [{"image": A}] * 5, [torch.stack([A1, A2])] * 5] TEST_CASE_MC_2 = [ @@ -97,29 +61,14 @@ class TestSplitOnGridDict(unittest.TestCase): @parameterized.expand( - [ - TEST_CASE_0, - TEST_CASE_1, - TEST_CASE_2, - TEST_CASE_3, - TEST_CASE_4, - TEST_CASE_5, - TEST_CASE_6, - TEST_CASE_7, - ] + [TEST_CASE_0, TEST_CASE_1, TEST_CASE_2, TEST_CASE_3, TEST_CASE_4, TEST_CASE_5, TEST_CASE_6, TEST_CASE_7] ) def test_split_pathce_single_call(self, input_parameters, img_dict, expected): splitter = SplitOnGridDict(**input_parameters) output = splitter(img_dict)[input_parameters["keys"]] np.testing.assert_equal(output.numpy(), expected.numpy()) - @parameterized.expand( - [ - TEST_CASE_MC_0, - TEST_CASE_MC_1, - TEST_CASE_MC_2, - ] - ) + @parameterized.expand([TEST_CASE_MC_0, TEST_CASE_MC_1, TEST_CASE_MC_2]) def test_split_pathce_multiple_call(self, input_parameters, img_list, expected_list): splitter = SplitOnGridDict(**input_parameters) for img_dict, expected in zip(img_list, expected_list): diff --git a/tests/test_state_cacher.py b/tests/test_state_cacher.py index 139e7b8374..5835bfdb5c 100644 --- a/tests/test_state_cacher.py +++ b/tests/test_state_cacher.py @@ -20,18 +20,9 @@ DEVICE = "cuda:0" if torch.cuda.is_available() else "cpu" -TEST_CASE_0 = [ - torch.Tensor([1]).to(DEVICE), - {"in_memory": True}, -] -TEST_CASE_1 = [ - torch.Tensor([1]).to(DEVICE), - {"in_memory": False, "cache_dir": gettempdir()}, -] -TEST_CASE_2 = [ - torch.Tensor([1]).to(DEVICE), - {"in_memory": False, "allow_overwrite": False}, -] +TEST_CASE_0 = [torch.Tensor([1]).to(DEVICE), {"in_memory": True}] +TEST_CASE_1 = [torch.Tensor([1]).to(DEVICE), {"in_memory": False, "cache_dir": gettempdir()}] +TEST_CASE_2 = [torch.Tensor([1]).to(DEVICE), {"in_memory": False, "allow_overwrite": False}] TEST_CASES = [TEST_CASE_0, TEST_CASE_1, TEST_CASE_2] diff --git a/tests/test_subpixel_upsample.py b/tests/test_subpixel_upsample.py index 07e110d7a7..8a4336dbd5 100644 --- a/tests/test_subpixel_upsample.py +++ b/tests/test_subpixel_upsample.py @@ -43,14 +43,7 @@ ] conv_block = nn.Sequential( - Conv[Conv.CONV, 3](1, 4, kernel_size=1), - Conv[Conv.CONV, 3]( - 4, - 8, - kernel_size=3, - stride=1, - padding=1, - ), + Conv[Conv.CONV, 3](1, 4, kernel_size=1), Conv[Conv.CONV, 3](4, 8, kernel_size=3, stride=1, padding=1) ) TEST_CASE_SUBPIXEL_CONV_BLOCK_EXTRA = [ diff --git a/tests/test_surface_distance.py b/tests/test_surface_distance.py index e5d2145a1f..8f09218f57 100644 --- a/tests/test_surface_distance.py +++ b/tests/test_surface_distance.py @@ -20,9 +20,7 @@ def create_spherical_seg_3d( - radius: float = 20.0, - centre: Tuple[int, int, int] = (49, 49, 49), - im_shape: Tuple[int, int, int] = (99, 99, 99), + radius: float = 20.0, centre: Tuple[int, int, int] = (49, 49, 49), im_shape: Tuple[int, int, int] = (99, 99, 99) ) -> np.ndarray: """ Return a 3D image with a sphere inside. Voxel values will be @@ -49,10 +47,7 @@ def create_spherical_seg_3d( TEST_CASES = [ - [ - [create_spherical_seg_3d(), create_spherical_seg_3d()], - [0, 0], - ], + [[create_spherical_seg_3d(), create_spherical_seg_3d()], [0, 0]], [ [ create_spherical_seg_3d(radius=20, centre=(20, 20, 20)), @@ -91,21 +86,8 @@ def create_spherical_seg_3d( ], [17.32691760951026, 12.432687531048186], ], - [ - [ - np.zeros([99, 99, 99]), - create_spherical_seg_3d(radius=40, centre=(20, 33, 22)), - ], - [np.inf, np.inf], - ], - [ - [ - create_spherical_seg_3d(), - np.zeros([99, 99, 99]), - "taxicab", - ], - [np.inf, np.inf], - ], + [[np.zeros([99, 99, 99]), create_spherical_seg_3d(radius=40, centre=(20, 33, 22))], [np.inf, np.inf]], + [[create_spherical_seg_3d(), np.zeros([99, 99, 99]), "taxicab"], [np.inf, np.inf]], ] TEST_CASES_NANS = [ @@ -114,8 +96,8 @@ def create_spherical_seg_3d( # both pred and gt do not have foreground, metric and not_nans should be 0 np.zeros([99, 99, 99]), np.zeros([99, 99, 99]), - ], - ], + ] + ] ] diff --git a/tests/test_synthetic.py b/tests/test_synthetic.py index 97ab12a588..6b08df8b00 100644 --- a/tests/test_synthetic.py +++ b/tests/test_synthetic.py @@ -18,29 +18,10 @@ from monai.utils import set_determinism TEST_CASES = [ + [2, {"width": 64, "height": 64, "rad_max": 10, "rad_min": 4}, 0.1479004, 0.739502, (64, 64), 5], [ 2, - { - "width": 64, - "height": 64, - "rad_max": 10, - "rad_min": 4, - }, - 0.1479004, - 0.739502, - (64, 64), - 5, - ], - [ - 2, - { - "width": 32, - "height": 28, - "num_objs": 3, - "rad_max": 5, - "rad_min": 1, - "noise_max": 0.2, - }, + {"width": 32, "height": 28, "num_objs": 3, "rad_max": 5, "rad_min": 1, "noise_max": 0.2}, 0.1709315, 0.4040179, (32, 28), @@ -48,15 +29,7 @@ ], [ 3, - { - "width": 64, - "height": 64, - "depth": 45, - "num_seg_classes": 3, - "channel_dim": -1, - "rad_max": 10, - "rad_min": 4, - }, + {"width": 64, "height": 64, "depth": 45, "num_seg_classes": 3, "channel_dim": -1, "rad_max": 10, "rad_min": 4}, 0.025132, 0.0753961, (64, 64, 45, 1), diff --git a/tests/test_testtimeaugmentation.py b/tests/test_testtimeaugmentation.py index a07d59703d..6303abf8dd 100644 --- a/tests/test_testtimeaugmentation.py +++ b/tests/test_testtimeaugmentation.py @@ -113,12 +113,7 @@ def test_test_time_augmentation(self): epoch_loss /= len(train_loader) - post_trans = Compose( - [ - Activations(sigmoid=True), - AsDiscrete(threshold_values=True), - ] - ) + post_trans = Compose([Activations(sigmoid=True), AsDiscrete(threshold_values=True)]) def inferrer_fn(x): return post_trans(model(x)) diff --git a/tests/test_to_deviced.py b/tests/test_to_deviced.py index 0d5d1d1cdc..3b3a7a2e8f 100644 --- a/tests/test_to_deviced.py +++ b/tests/test_to_deviced.py @@ -24,9 +24,7 @@ def test_value(self): device = "cuda:0" data = [{"img": torch.tensor(i)} for i in range(4)] dataset = CacheDataset( - data=data, - transform=ToDeviced(keys="img", device=device, non_blocking=True), - cache_rate=1.0, + data=data, transform=ToDeviced(keys="img", device=device, non_blocking=True), cache_rate=1.0 ) dataloader = ThreadDataLoader(dataset=dataset, num_workers=0, batch_size=1) for i, d in enumerate(dataloader): diff --git a/tests/test_torchvision.py b/tests/test_torchvision.py index 0846b7f6b6..58e7d9295f 100644 --- a/tests/test_torchvision.py +++ b/tests/test_torchvision.py @@ -29,19 +29,10 @@ torch.tensor([[[0.0, 1.0], [1.0, 2.0]], [[0.0, 1.0], [1.0, 2.0]], [[0.0, 1.0], [1.0, 2.0]]]), torch.tensor( [ - [ - [0.1090, 0.6193], - [0.6193, 0.9164], - ], - [ - [0.1090, 0.6193], - [0.6193, 0.9164], - ], - [ - [0.1090, 0.6193], - [0.6193, 0.9164], - ], - ], + [[0.1090, 0.6193], [0.6193, 0.9164]], + [[0.1090, 0.6193], [0.6193, 0.9164]], + [[0.1090, 0.6193], [0.6193, 0.9164]], + ] ), ] @@ -50,24 +41,9 @@ torch.tensor([[[0.0, 1.0], [1.0, 2.0]], [[0.0, 1.0], [1.0, 2.0]], [[0.0, 1.0], [1.0, 2.0]]]), torch.tensor( [ - [ - [0.0, 0.0, 0.0, 0.0], - [0.0, 0.0, 1.0, 0.0], - [0.0, 1.0, 2.0, 0.0], - [0.0, 0.0, 0.0, 0.0], - ], - [ - [0.0, 0.0, 0.0, 0.0], - [0.0, 0.0, 1.0, 0.0], - [0.0, 1.0, 2.0, 0.0], - [0.0, 0.0, 0.0, 0.0], - ], - [ - [0.0, 0.0, 0.0, 0.0], - [0.0, 0.0, 1.0, 0.0], - [0.0, 1.0, 2.0, 0.0], - [0.0, 0.0, 0.0, 0.0], - ], + [[0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], [0.0, 1.0, 2.0, 0.0], [0.0, 0.0, 0.0, 0.0]], + [[0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], [0.0, 1.0, 2.0, 0.0], [0.0, 0.0, 0.0, 0.0]], + [[0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], [0.0, 1.0, 2.0, 0.0], [0.0, 0.0, 0.0, 0.0]], ] ), ] diff --git a/tests/test_torchvision_fc_model.py b/tests/test_torchvision_fc_model.py index d6d3ea69c9..cc603e2585 100644 --- a/tests/test_torchvision_fc_model.py +++ b/tests/test_torchvision_fc_model.py @@ -115,17 +115,7 @@ class TestTorchVisionFCModel(unittest.TestCase): - @parameterized.expand( - [ - TEST_CASE_0, - TEST_CASE_1, - TEST_CASE_2, - TEST_CASE_3, - TEST_CASE_4, - TEST_CASE_5, - TEST_CASE_6, - ] - ) + @parameterized.expand([TEST_CASE_0, TEST_CASE_1, TEST_CASE_2, TEST_CASE_3, TEST_CASE_4, TEST_CASE_5, TEST_CASE_6]) @skipUnless(has_tv, "Requires TorchVision.") def test_without_pretrained(self, input_param, input_shape, expected_shape): net = TorchVisionFCModel(**input_param).to(device) diff --git a/tests/test_torchvision_fully_conv_model.py b/tests/test_torchvision_fully_conv_model.py index af2c1458d3..444e871c45 100644 --- a/tests/test_torchvision_fully_conv_model.py +++ b/tests/test_torchvision_fully_conv_model.py @@ -23,23 +23,11 @@ device = "cuda" if torch.cuda.is_available() else "cpu" -TEST_CASE_0 = [ - {"model_name": "resnet18", "num_classes": 1, "pretrained": False}, - (2, 3, 224, 224), - (2, 1, 1, 1), -] +TEST_CASE_0 = [{"model_name": "resnet18", "num_classes": 1, "pretrained": False}, (2, 3, 224, 224), (2, 1, 1, 1)] -TEST_CASE_1 = [ - {"model_name": "resnet18", "num_classes": 1, "pretrained": False}, - (2, 3, 256, 256), - (2, 1, 2, 2), -] +TEST_CASE_1 = [{"model_name": "resnet18", "num_classes": 1, "pretrained": False}, (2, 3, 256, 256), (2, 1, 2, 2)] -TEST_CASE_2 = [ - {"model_name": "resnet101", "num_classes": 5, "pretrained": False}, - (2, 3, 256, 256), - (2, 5, 2, 2), -] +TEST_CASE_2 = [{"model_name": "resnet101", "num_classes": 5, "pretrained": False}, (2, 3, 256, 256), (2, 5, 2, 2)] TEST_CASE_3 = [ {"model_name": "resnet101", "num_classes": 5, "pool_size": 6, "pretrained": False}, @@ -70,14 +58,7 @@ class TestTorchVisionFullyConvModel(unittest.TestCase): - @parameterized.expand( - [ - TEST_CASE_0, - TEST_CASE_1, - TEST_CASE_2, - TEST_CASE_3, - ] - ) + @parameterized.expand([TEST_CASE_0, TEST_CASE_1, TEST_CASE_2, TEST_CASE_3]) @skipUnless(has_tv, "Requires TorchVision.") def test_without_pretrained(self, input_param, input_shape, expected_shape): net = TorchVisionFullyConvModel(**input_param).to(device) @@ -85,13 +66,7 @@ def test_without_pretrained(self, input_param, input_shape, expected_shape): result = net.forward(torch.randn(input_shape).to(device)) self.assertEqual(result.shape, expected_shape) - @parameterized.expand( - [ - TEST_CASE_PRETRAINED_0, - TEST_CASE_PRETRAINED_1, - TEST_CASE_PRETRAINED_2, - ] - ) + @parameterized.expand([TEST_CASE_PRETRAINED_0, TEST_CASE_PRETRAINED_1, TEST_CASE_PRETRAINED_2]) @skipUnless(has_tv, "Requires TorchVision.") def test_with_pretrained(self, input_param, input_shape, expected_shape, expected_value): net = TorchVisionFullyConvModel(**input_param).to(device) diff --git a/tests/test_torchvisiond.py b/tests/test_torchvisiond.py index 4f42bc95f7..1530691824 100644 --- a/tests/test_torchvisiond.py +++ b/tests/test_torchvisiond.py @@ -29,19 +29,10 @@ {"img": torch.tensor([[[0.0, 1.0], [1.0, 2.0]], [[0.0, 1.0], [1.0, 2.0]], [[0.0, 1.0], [1.0, 2.0]]])}, torch.tensor( [ - [ - [0.1090, 0.6193], - [0.6193, 0.9164], - ], - [ - [0.1090, 0.6193], - [0.6193, 0.9164], - ], - [ - [0.1090, 0.6193], - [0.6193, 0.9164], - ], - ], + [[0.1090, 0.6193], [0.6193, 0.9164]], + [[0.1090, 0.6193], [0.6193, 0.9164]], + [[0.1090, 0.6193], [0.6193, 0.9164]], + ] ), ] @@ -50,24 +41,9 @@ {"img": torch.tensor([[[0.0, 1.0], [1.0, 2.0]], [[0.0, 1.0], [1.0, 2.0]], [[0.0, 1.0], [1.0, 2.0]]])}, torch.tensor( [ - [ - [0.0, 0.0, 0.0, 0.0], - [0.0, 0.0, 1.0, 0.0], - [0.0, 1.0, 2.0, 0.0], - [0.0, 0.0, 0.0, 0.0], - ], - [ - [0.0, 0.0, 0.0, 0.0], - [0.0, 0.0, 1.0, 0.0], - [0.0, 1.0, 2.0, 0.0], - [0.0, 0.0, 0.0, 0.0], - ], - [ - [0.0, 0.0, 0.0, 0.0], - [0.0, 0.0, 1.0, 0.0], - [0.0, 1.0, 2.0, 0.0], - [0.0, 0.0, 0.0, 0.0], - ], + [[0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], [0.0, 1.0, 2.0, 0.0], [0.0, 0.0, 0.0, 0.0]], + [[0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], [0.0, 1.0, 2.0, 0.0], [0.0, 0.0, 0.0, 0.0]], + [[0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], [0.0, 1.0, 2.0, 0.0], [0.0, 0.0, 0.0, 0.0]], ] ), ] diff --git a/tests/test_transpose.py b/tests/test_transpose.py index 16cca49e1c..176fa6f10e 100644 --- a/tests/test_transpose.py +++ b/tests/test_transpose.py @@ -20,18 +20,8 @@ TESTS = [] for p in TEST_NDARRAYS: - TESTS.append( - [ - p(np.arange(5 * 4).reshape(5, 4)), - None, - ] - ) - TESTS.append( - [ - p(np.arange(5 * 4 * 3).reshape(5, 4, 3)), - [2, 0, 1], - ] - ) + TESTS.append([p(np.arange(5 * 4).reshape(5, 4)), None]) + TESTS.append([p(np.arange(5 * 4 * 3).reshape(5, 4, 3)), [2, 0, 1]]) class TestTranspose(unittest.TestCase): diff --git a/tests/test_transposed.py b/tests/test_transposed.py index 2f9558b74e..719efea4c3 100644 --- a/tests/test_transposed.py +++ b/tests/test_transposed.py @@ -21,30 +21,10 @@ TESTS = [] for p in TEST_NDARRAYS: - TESTS.append( - [ - p(np.arange(5 * 4).reshape(5, 4)), - [1, 0], - ] - ) - TESTS.append( - [ - p(np.arange(5 * 4).reshape(5, 4)), - None, - ] - ) - TESTS.append( - [ - p(np.arange(5 * 4 * 3).reshape(5, 4, 3)), - [2, 0, 1], - ] - ) - TESTS.append( - [ - p(np.arange(5 * 4 * 3).reshape(5, 4, 3)), - None, - ] - ) + TESTS.append([p(np.arange(5 * 4).reshape(5, 4)), [1, 0]]) + TESTS.append([p(np.arange(5 * 4).reshape(5, 4)), None]) + TESTS.append([p(np.arange(5 * 4 * 3).reshape(5, 4, 3)), [2, 0, 1]]) + TESTS.append([p(np.arange(5 * 4 * 3).reshape(5, 4, 3)), None]) class TestTranspose(unittest.TestCase): diff --git a/tests/test_tversky_loss.py b/tests/test_tversky_loss.py index 0bc2ca2e70..57e887d3f0 100644 --- a/tests/test_tversky_loss.py +++ b/tests/test_tversky_loss.py @@ -21,10 +21,7 @@ TEST_CASES = [ [ # shape: (1, 1, 2, 2), (1, 1, 2, 2) {"include_background": True, "sigmoid": True, "smooth_nr": 1e-6, "smooth_dr": 1e-6}, - { - "input": torch.tensor([[[[1.0, -1.0], [-1.0, 1.0]]]]), - "target": torch.tensor([[[[1.0, 0.0], [1.0, 1.0]]]]), - }, + {"input": torch.tensor([[[[1.0, -1.0], [-1.0, 1.0]]]]), "target": torch.tensor([[[[1.0, 0.0], [1.0, 1.0]]]])}, 0.307576, ], [ # shape: (2, 1, 2, 2), (2, 1, 2, 2) @@ -107,18 +104,12 @@ ], [ # shape: (1, 1, 2, 2), (1, 1, 2, 2) {"include_background": True, "sigmoid": True, "alpha": 0.3, "beta": 0.7, "smooth_nr": 1e-6, "smooth_dr": 1e-6}, - { - "input": torch.tensor([[[[1.0, -1.0], [-1.0, 1.0]]]]), - "target": torch.tensor([[[[1.0, 0.0], [1.0, 1.0]]]]), - }, + {"input": torch.tensor([[[[1.0, -1.0], [-1.0, 1.0]]]]), "target": torch.tensor([[[[1.0, 0.0], [1.0, 1.0]]]])}, 0.3589, ], [ # shape: (1, 1, 2, 2), (1, 1, 2, 2) {"include_background": True, "sigmoid": True, "alpha": 0.7, "beta": 0.3, "smooth_nr": 1e-6, "smooth_dr": 1e-6}, - { - "input": torch.tensor([[[[1.0, -1.0], [-1.0, 1.0]]]]), - "target": torch.tensor([[[[1.0, 0.0], [1.0, 1.0]]]]), - }, + {"input": torch.tensor([[[[1.0, -1.0], [-1.0, 1.0]]]]), "target": torch.tensor([[[[1.0, 0.0], [1.0, 1.0]]]])}, 0.247366, ], [ # shape: (2, 1, 2, 2), (2, 1, 2, 2) diff --git a/tests/test_unet.py b/tests/test_unet.py index 94077dad14..edc3ce35fe 100644 --- a/tests/test_unet.py +++ b/tests/test_unet.py @@ -190,13 +190,7 @@ def test_script_without_running_stats(self): test_script_save(net, test_data) def test_ill_input_shape(self): - net = UNet( - spatial_dims=2, - in_channels=1, - out_channels=3, - channels=(16, 32, 64), - strides=(2, 2), - ) + net = UNet(spatial_dims=2, in_channels=1, out_channels=3, channels=(16, 32, 64), strides=(2, 2)) with eval_mode(net): with self.assertRaisesRegex(RuntimeError, "Sizes of tensors must match"): net.forward(torch.randn(2, 1, 16, 5)) diff --git a/tests/test_upsample_block.py b/tests/test_upsample_block.py index 7b8ada399c..02dbaacdc6 100644 --- a/tests/test_upsample_block.py +++ b/tests/test_upsample_block.py @@ -20,11 +20,7 @@ TEST_CASES = [ [{"dimensions": 2, "in_channels": 4}, (7, 4, 32, 48), (7, 4, 64, 96)], # 4-channel 2D, batch 7 - [ - {"dimensions": 1, "in_channels": 4, "out_channels": 3}, - (16, 4, 63), - (16, 3, 126), - ], # 4-channel 1D, batch 16 + [{"dimensions": 1, "in_channels": 4, "out_channels": 3}, (16, 4, 63), (16, 3, 126)], # 4-channel 1D, batch 16 [ {"dimensions": 1, "in_channels": 4, "out_channels": 8, "mode": "deconv", "align_corners": False}, (16, 4, 20), @@ -78,14 +74,7 @@ expected_shape = (16, 5, 4 * s, 5 * s, 6 * s) for t in UpsampleMode: test_case = [ - { - "dimensions": 3, - "in_channels": 3, - "out_channels": 5, - "mode": t, - "scale_factor": s, - "align_corners": True, - }, + {"dimensions": 3, "in_channels": 3, "out_channels": 5, "mode": t, "scale_factor": s, "align_corners": True}, (16, 3, 4, 5, 6), ] test_case.append(expected_shape) diff --git a/tests/test_vis_gradcam.py b/tests/test_vis_gradcam.py index ecd62badcc..72385a37a7 100644 --- a/tests/test_vis_gradcam.py +++ b/tests/test_vis_gradcam.py @@ -40,23 +40,13 @@ ] # 2D TEST_CASE_2 = [ - { - "model": "senet2d", - "shape": (2, 3, 64, 64), - "feature_shape": (2, 1, 2, 2), - "target_layers": "layer4", - }, + {"model": "senet2d", "shape": (2, 3, 64, 64), "feature_shape": (2, 1, 2, 2), "target_layers": "layer4"}, (2, 1, 64, 64), ] # 3D TEST_CASE_3 = [ - { - "model": "senet3d", - "shape": (2, 3, 8, 8, 48), - "feature_shape": (2, 1, 1, 1, 2), - "target_layers": "layer4", - }, + {"model": "senet3d", "shape": (2, 3, 8, 8, 48), "feature_shape": (2, 1, 1, 1, 2), "target_layers": "layer4"}, (2, 1, 8, 8, 48), ] diff --git a/tests/test_vis_gradcampp.py b/tests/test_vis_gradcampp.py index 92a4b2ac7b..5f801dce45 100644 --- a/tests/test_vis_gradcampp.py +++ b/tests/test_vis_gradcampp.py @@ -39,23 +39,13 @@ ] # 2D TEST_CASE_2 = [ - { - "model": "senet2d", - "shape": (2, 3, 64, 64), - "feature_shape": (2, 1, 2, 2), - "target_layers": "layer4", - }, + {"model": "senet2d", "shape": (2, 3, 64, 64), "feature_shape": (2, 1, 2, 2), "target_layers": "layer4"}, (2, 1, 64, 64), ] # 3D TEST_CASE_3 = [ - { - "model": "senet3d", - "shape": (2, 3, 8, 8, 48), - "feature_shape": (2, 1, 1, 1, 2), - "target_layers": "layer4", - }, + {"model": "senet3d", "shape": (2, 3, 8, 8, 48), "feature_shape": (2, 1, 1, 1, 2), "target_layers": "layer4"}, (2, 1, 8, 8, 48), ] diff --git a/tests/test_vote_ensemble.py b/tests/test_vote_ensemble.py index 74c19d5f48..434f0079dd 100644 --- a/tests/test_vote_ensemble.py +++ b/tests/test_vote_ensemble.py @@ -45,18 +45,10 @@ ] # shape: [1] -TEST_CASE_5 = [ - {"num_classes": 3}, - [torch.tensor([2]), torch.tensor([2]), torch.tensor([1])], - torch.tensor([2]), -] +TEST_CASE_5 = [{"num_classes": 3}, [torch.tensor([2]), torch.tensor([2]), torch.tensor([1])], torch.tensor([2])] # shape: 1 -TEST_CASE_6 = [ - {"num_classes": 3}, - [torch.tensor(2), torch.tensor(2), torch.tensor(1)], - torch.tensor(2), -] +TEST_CASE_6 = [{"num_classes": 3}, [torch.tensor(2), torch.tensor(2), torch.tensor(1)], torch.tensor(2)] class TestVoteEnsemble(unittest.TestCase): diff --git a/tests/test_vote_ensembled.py b/tests/test_vote_ensembled.py index e94213733f..1c2ac8a339 100644 --- a/tests/test_vote_ensembled.py +++ b/tests/test_vote_ensembled.py @@ -41,22 +41,14 @@ # shape: [1, 2, 1] TEST_CASE_3 = [ {"keys": ["pred0", "pred1", "pred2"], "output_key": "output", "num_classes": 3}, - { - "pred0": torch.tensor([[[0], [2]]]), - "pred1": torch.tensor([[[0], [2]]]), - "pred2": torch.tensor([[[1], [1]]]), - }, + {"pred0": torch.tensor([[[0], [2]]]), "pred1": torch.tensor([[[0], [2]]]), "pred2": torch.tensor([[[1], [1]]])}, torch.tensor([[[0], [2]]]), ] # shape: [1, 2, 1] TEST_CASE_4 = [ {"keys": ["pred0", "pred1", "pred2"], "output_key": "output", "num_classes": 5}, - { - "pred0": torch.tensor([[[0], [2]]]), - "pred1": torch.tensor([[[0], [2]]]), - "pred2": torch.tensor([[[1], [1]]]), - }, + {"pred0": torch.tensor([[[0], [2]]]), "pred1": torch.tensor([[[0], [2]]]), "pred2": torch.tensor([[[1], [1]]])}, torch.tensor([[[0], [2]]]), ] diff --git a/tests/testing_data/integration_answers.py b/tests/testing_data/integration_answers.py index ccb4293a40..6932ee6e71 100644 --- a/tests/testing_data/integration_answers.py +++ b/tests/testing_data/integration_answers.py @@ -418,7 +418,7 @@ 0.17794132232666016, 0.18584394454956055, 0.03577899932861328, - ], + ] }, "integration_segmentation_3d": { # for the mixed readers "losses": [