Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 11 additions & 6 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -22,12 +22,17 @@ repos:
args: ['--maxkb=1024']
- id: detect-private-key

#- repo: https://github.com/asottile/pyupgrade
# rev: v2.23.2
# hooks:
# - id: pyupgrade
# args: [--py36-plus]
# name: Upgrade code
- repo: https://github.com/asottile/pyupgrade
rev: v2.27.0
hooks:
- id: pyupgrade
args: [--py36-plus]
name: Upgrade code
exclude: |
(?x)^(
versioneer.py|
monai/_version.py
)$

#- repo: https://github.com/asottile/yesqa
# rev: v1.2.3
Expand Down
2 changes: 1 addition & 1 deletion monai/apps/datasets.py
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,7 @@ def _generate_data_list(self, dataset_dir: str) -> List[Dict]:
ValueError: When ``section`` is not one of ["training", "validation", "test"].

"""
class_names = sorted((x for x in os.listdir(dataset_dir) if os.path.isdir(os.path.join(dataset_dir, x))))
class_names = sorted(x for x in os.listdir(dataset_dir) if os.path.isdir(os.path.join(dataset_dir, x)))
self.num_class = len(class_names)
image_files = [
[
Expand Down
10 changes: 5 additions & 5 deletions monai/apps/deepgrow/dataset.py
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,7 @@ def create_dataset(
image = os.path.abspath(image)
label = os.path.abspath(label) if label else None

logging.info("Image: {}; Label: {}".format(image, label if label else None))
logging.info(f"Image: {image}; Label: {label if label else None}")
data = transforms({image_key: image, label_key: label})
if dimension == 2:
data = _save_data_2d(
Expand Down Expand Up @@ -154,7 +154,7 @@ def _save_data_2d(vol_idx, vol_image, vol_label, dataset_dir, relative_path):
if vol_label is not None and np.sum(label) == 0:
continue

image_file_prefix = "vol_idx_{:0>4d}_slice_{:0>3d}".format(vol_idx, sid)
image_file_prefix = f"vol_idx_{vol_idx:0>4d}_slice_{sid:0>3d}"
image_file = os.path.join(dataset_dir, "images", image_file_prefix)
image_file += ".npy"

Expand All @@ -177,7 +177,7 @@ def _save_data_2d(vol_idx, vol_image, vol_label, dataset_dir, relative_path):
unique_labels_count = max(unique_labels_count, len(unique_labels))

for idx in unique_labels:
label_file_prefix = "{}_region_{:0>2d}".format(image_file_prefix, int(idx))
label_file_prefix = f"{image_file_prefix}_region_{int(idx):0>2d}"
label_file = os.path.join(dataset_dir, "labels", label_file_prefix)
label_file += ".npy"

Expand Down Expand Up @@ -226,7 +226,7 @@ def _save_data_3d(vol_idx, vol_image, vol_label, dataset_dir, relative_path):
label_count = 0
unique_labels_count = 0

image_file_prefix = "vol_idx_{:0>4d}".format(vol_idx)
image_file_prefix = f"vol_idx_{vol_idx:0>4d}"
image_file = os.path.join(dataset_dir, "images", image_file_prefix)
image_file += ".npy"

Expand All @@ -248,7 +248,7 @@ def _save_data_3d(vol_idx, vol_image, vol_label, dataset_dir, relative_path):
unique_labels_count = max(unique_labels_count, len(unique_labels))

for idx in unique_labels:
label_file_prefix = "{}_region_{:0>2d}".format(image_file_prefix, int(idx))
label_file_prefix = f"{image_file_prefix}_region_{int(idx):0>2d}"
label_file = os.path.join(dataset_dir, "labels", label_file_prefix)
label_file += ".npy"

Expand Down
2 changes: 1 addition & 1 deletion monai/apps/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ def update_to(self, b: int = 1, bsize: int = 1, tsize: Optional[int] = None):
if not has_tqdm and progress:
warnings.warn("tqdm is not installed, will not show the downloading progress bar.")
urlretrieve(url, filepath)
except (URLError, HTTPError, ContentTooShortError, IOError) as e:
except (URLError, HTTPError, ContentTooShortError, OSError) as e:
print(f"Download failed from {url} to {filepath}.")
raise e

Expand Down
2 changes: 1 addition & 1 deletion monai/config/deviceconfig.py
Original file line number Diff line number Diff line change
Expand Up @@ -122,7 +122,7 @@ def get_system_info() -> OrderedDict:
elif output["System"] == "Darwin":
_dict_append(output, "Mac version", lambda: platform.mac_ver()[0])
else:
with open("/etc/os-release", "r") as rel_f:
with open("/etc/os-release") as rel_f:
linux_ver = re.search(r'PRETTY_NAME="(.*)"', rel_f.read())
if linux_ver:
_dict_append(output, "Linux version", lambda: linux_ver.group(1))
Expand Down
2 changes: 1 addition & 1 deletion monai/data/dataset.py
Original file line number Diff line number Diff line change
Expand Up @@ -989,7 +989,7 @@ def __init__(self, datasets: Sequence, transform: Optional[Callable] = None) ->
super().__init__(list(datasets), transform=transform)

def __len__(self) -> int:
return min((len(dataset) for dataset in self.data))
return min(len(dataset) for dataset in self.data)

def _transform(self, index: int):
def to_list(x):
Expand Down
2 changes: 1 addition & 1 deletion monai/data/dataset_summary.py
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ def __init__(
self.image_key = image_key
self.label_key = label_key
if image_key:
self.meta_key = "{}_{}".format(image_key, meta_key_postfix)
self.meta_key = f"{image_key}_{meta_key_postfix}"
self.all_meta_data: List = []

def collect_meta_data(self):
Expand Down
4 changes: 2 additions & 2 deletions monai/data/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -1029,7 +1029,7 @@ def json_hashing(item) -> bytes:
"""
# TODO: Find way to hash transforms content as part of the cache
cache_key = hashlib.md5(json.dumps(item, sort_keys=True).encode("utf-8")).hexdigest()
return f"{cache_key}".encode("utf-8")
return f"{cache_key}".encode()


def pickle_hashing(item, protocol=pickle.HIGHEST_PROTOCOL) -> bytes:
Expand All @@ -1044,7 +1044,7 @@ def pickle_hashing(item, protocol=pickle.HIGHEST_PROTOCOL) -> bytes:

"""
cache_key = hashlib.md5(pickle.dumps(sorted_dict(item), protocol=protocol)).hexdigest()
return f"{cache_key}".encode("utf-8")
return f"{cache_key}".encode()


def sorted_dict(item, key=None, reverse=False):
Expand Down
2 changes: 1 addition & 1 deletion monai/losses/deform.py
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ def __init__(
- ``"mean"``: the sum of the output will be divided by the number of elements in the output.
- ``"sum"``: the output will be summed.
"""
super(BendingEnergyLoss, self).__init__(reduction=LossReduction(reduction).value)
super().__init__(reduction=LossReduction(reduction).value)

def forward(self, pred: torch.Tensor) -> torch.Tensor:
"""
Expand Down
2 changes: 1 addition & 1 deletion monai/losses/dice.py
Original file line number Diff line number Diff line change
Expand Up @@ -419,7 +419,7 @@ def __init__(
wass_loss(pred_score, grnd) # 0

"""
super(GeneralizedWassersteinDiceLoss, self).__init__(reduction=LossReduction(reduction).value)
super().__init__(reduction=LossReduction(reduction).value)

if dist_matrix.shape[0] != dist_matrix.shape[1]:
raise ValueError(f"dist_matrix must be C x C, got {dist_matrix.shape[0]} x {dist_matrix.shape[1]}.")
Expand Down
2 changes: 1 addition & 1 deletion monai/losses/focal_loss.py
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ def __init__(
fl(pred, grnd)

"""
super(FocalLoss, self).__init__(reduction=LossReduction(reduction).value)
super().__init__(reduction=LossReduction(reduction).value)
self.include_background = include_background
self.to_onehot_y = to_onehot_y
self.gamma = gamma
Expand Down
4 changes: 2 additions & 2 deletions monai/losses/image_dissimilarity.py
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,7 @@ def __init__(
.. deprecated:: 0.6.0
``ndim`` is deprecated, use ``spatial_dims``.
"""
super(LocalNormalizedCrossCorrelationLoss, self).__init__(reduction=LossReduction(reduction).value)
super().__init__(reduction=LossReduction(reduction).value)

if ndim is not None:
spatial_dims = ndim
Expand Down Expand Up @@ -196,7 +196,7 @@ def __init__(
smooth_nr: a small constant added to the numerator to avoid nan.
smooth_dr: a small constant added to the denominator to avoid nan.
"""
super(GlobalMutualInformationLoss, self).__init__(reduction=LossReduction(reduction).value)
super().__init__(reduction=LossReduction(reduction).value)
if num_bins <= 0:
raise ValueError("num_bins must > 0, got {num_bins}")
bin_centers = torch.linspace(0.0, 1.0, num_bins) # (num_bins,)
Expand Down
2 changes: 1 addition & 1 deletion monai/losses/multi_scale.py
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ def __init__(
scales: list of scalars or None, if None, do not apply any scaling.
kernel: gaussian or cauchy.
"""
super(MultiScaleLoss, self).__init__(reduction=LossReduction(reduction).value)
super().__init__(reduction=LossReduction(reduction).value)
if kernel not in kernel_fn_dict.keys():
raise ValueError(f"got unsupported kernel type: {kernel}", "only support gaussian and cauchy")
self.kernel_fn = kernel_fn_dict[kernel]
Expand Down
4 changes: 1 addition & 3 deletions monai/metrics/regression.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,9 +57,7 @@ def aggregate(self): # type: ignore

def _check_shape(self, y_pred: torch.Tensor, y: torch.Tensor) -> None:
if y_pred.shape != y.shape:
raise ValueError(
"y_pred and y shapes dont match, received y_pred: [{}] and y: [{}]".format(y_pred.shape, y.shape)
)
raise ValueError(f"y_pred and y shapes dont match, received y_pred: [{y_pred.shape}] and y: [{y.shape}]")

# also check if there is atleast one non-batch dimension i.e. num_dims >= 2
if len(y_pred.shape) < 2:
Expand Down
4 changes: 2 additions & 2 deletions monai/networks/blocks/activation.py
Original file line number Diff line number Diff line change
Expand Up @@ -122,7 +122,7 @@ class MemoryEfficientSwish(nn.Module):
"""

def __init__(self, inplace: bool = False):
super(MemoryEfficientSwish, self).__init__()
super().__init__()
# inplace only works when using torch.nn.functional.silu
self.inplace = inplace

Expand Down Expand Up @@ -156,7 +156,7 @@ class Mish(nn.Module):
"""

def __init__(self, inplace: bool = False):
super(Mish, self).__init__()
super().__init__()
# inplace only works when using torch.nn.functional.mish
self.inplace = inplace

Expand Down
2 changes: 1 addition & 1 deletion monai/networks/blocks/crf.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ def __init__(
compatibility_matrix: a matrix describing class compatibility,
should be NxN where N is the number of classes.
"""
super(CRF, self).__init__()
super().__init__()
self.iterations = iterations
self.bilateral_weight = bilateral_weight
self.gaussian_weight = gaussian_weight
Expand Down
8 changes: 4 additions & 4 deletions monai/networks/blocks/dynunet_block.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ def __init__(
norm_name: Union[Tuple, str],
dropout: Optional[Union[Tuple, str, float]] = None,
):
super(UnetResBlock, self).__init__()
super().__init__()
self.conv1 = get_conv_layer(
spatial_dims,
in_channels,
Expand Down Expand Up @@ -126,7 +126,7 @@ def __init__(
norm_name: Union[Tuple, str],
dropout: Optional[Union[Tuple, str, float]] = None,
):
super(UnetBasicBlock, self).__init__()
super().__init__()
self.conv1 = get_conv_layer(
spatial_dims,
in_channels,
Expand Down Expand Up @@ -188,7 +188,7 @@ def __init__(
norm_name: Union[Tuple, str],
dropout: Optional[Union[Tuple, str, float]] = None,
):
super(UnetUpBlock, self).__init__()
super().__init__()
upsample_stride = upsample_kernel_size
self.transp_conv = get_conv_layer(
spatial_dims,
Expand Down Expand Up @@ -222,7 +222,7 @@ class UnetOutBlock(nn.Module):
def __init__(
self, spatial_dims: int, in_channels: int, out_channels: int, dropout: Optional[Union[Tuple, str, float]] = None
):
super(UnetOutBlock, self).__init__()
super().__init__()
self.conv = get_conv_layer(
spatial_dims, in_channels, out_channels, kernel_size=1, stride=1, dropout=dropout, bias=True, conv_only=True
)
Expand Down
10 changes: 5 additions & 5 deletions monai/networks/blocks/fcn.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ def __init__(self, inplanes: int, planes: int, ks: int = 7):
planes: number of output channels.
ks: kernel size for one dimension. Defaults to 7.
"""
super(GCN, self).__init__()
super().__init__()

conv2d_type: Type[nn.Conv2d] = Conv[Conv.CONV, 2]
self.conv_l1 = conv2d_type(in_channels=inplanes, out_channels=planes, kernel_size=(ks, 1), padding=(ks // 2, 0))
Expand Down Expand Up @@ -67,7 +67,7 @@ def __init__(self, planes: int):
Args:
planes: number of input channels.
"""
super(Refine, self).__init__()
super().__init__()

relu_type: Type[nn.ReLU] = Act[Act.RELU]
conv2d_type: Type[nn.Conv2d] = Conv[Conv.CONV, 2]
Expand Down Expand Up @@ -116,7 +116,7 @@ class FCN(nn.Module):
def __init__(
self, out_channels: int = 1, upsample_mode: str = "bilinear", pretrained: bool = True, progress: bool = True
):
super(FCN, self).__init__()
super().__init__()

conv2d_type: Type[nn.Conv2d] = Conv[Conv.CONV, 2]

Expand Down Expand Up @@ -231,7 +231,7 @@ def __init__(
pretrained: bool = True,
progress: bool = True,
):
super(MCFCN, self).__init__(
super().__init__(
out_channels=out_channels, upsample_mode=upsample_mode, pretrained=pretrained, progress=progress
)

Expand All @@ -251,4 +251,4 @@ def forward(self, x: torch.Tensor):
x: in shape (batch, in_channels, spatial_1, spatial_2).
"""
x = self.init_proj(x)
return super(MCFCN, self).forward(x)
return super().forward(x)
10 changes: 5 additions & 5 deletions monai/networks/blocks/localnet_block.py
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,7 @@ def __init__(
out_channels: int,
kernel_size: Union[Sequence[int], int],
) -> None:
super(ResidualBlock, self).__init__()
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}"
Expand Down Expand Up @@ -119,7 +119,7 @@ def __init__(
in_channels: int,
out_channels: int,
) -> None:
super(LocalNetResidualBlock, self).__init__()
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}"
Expand Down Expand Up @@ -165,7 +165,7 @@ def __init__(
Raises:
NotImplementedError: when ``kernel_size`` is even
"""
super(LocalNetDownSampleBlock, self).__init__()
super().__init__()
self.conv_block = get_conv_block(
spatial_dims=spatial_dims, in_channels=in_channels, out_channels=out_channels, kernel_size=kernel_size
)
Expand Down Expand Up @@ -225,7 +225,7 @@ def __init__(
Raises:
ValueError: when ``in_channels != 2 * out_channels``
"""
super(LocalNetUpSampleBlock, self).__init__()
super().__init__()
self.deconv_block = get_deconv_block(
spatial_dims=spatial_dims,
in_channels=in_channels,
Expand Down Expand Up @@ -309,7 +309,7 @@ def __init__(
act: activation type and arguments. Defaults to ReLU.
kernel_initializer: kernel initializer. Defaults to None.
"""
super(LocalNetFeatureExtractorBlock, self).__init__()
super().__init__()
self.conv_block = get_conv_block(
spatial_dims=spatial_dims, in_channels=in_channels, out_channels=out_channels, act=act, norm=None
)
Expand Down
2 changes: 1 addition & 1 deletion monai/networks/blocks/patchembedding.py
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ def __init__(

"""

super(PatchEmbeddingBlock, self).__init__()
super().__init__()

if not (0 <= dropout_rate <= 1):
raise ValueError("dropout_rate should be between 0 and 1.")
Expand Down
6 changes: 3 additions & 3 deletions monai/networks/blocks/regunet_block.py
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,7 @@ def __init__(
num_layers: number of layers inside the block
kernel_size: kernel_size
"""
super(RegistrationResidualConvBlock, self).__init__()
super().__init__()
self.num_layers = num_layers
self.layers = nn.ModuleList(
[
Expand Down Expand Up @@ -158,7 +158,7 @@ def __init__(
channels: channels
pooling: use MaxPool if True, strided conv if False
"""
super(RegistrationDownSampleBlock, self).__init__()
super().__init__()
if pooling:
self.layer = Pool[Pool.MAX, spatial_dims](kernel_size=2)
else:
Expand Down Expand Up @@ -235,7 +235,7 @@ def __init__(
kernel_initializer: kernel initializer
activation: kernel activation function
"""
super(RegistrationExtractionBlock, self).__init__()
super().__init__()
self.extract_levels = extract_levels
self.max_level = max(extract_levels)
self.layers = nn.ModuleList(
Expand Down
2 changes: 1 addition & 1 deletion monai/networks/blocks/selfattention.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ def __init__(

"""

super(SABlock, self).__init__()
super().__init__()

if not (0 <= dropout_rate <= 1):
raise ValueError("dropout_rate should be between 0 and 1.")
Expand Down
Loading