diff --git a/source_code/SegMamba/monai/_extensions/gmm/gmm.cpp b/source_code/SegMamba/monai/_extensions/gmm/gmm.cpp new file mode 100644 index 0000000000000000000000000000000000000000..577e5b117ef13fb81f9aeaac8c70bd22fda963cb --- /dev/null +++ b/source_code/SegMamba/monai/_extensions/gmm/gmm.cpp @@ -0,0 +1,83 @@ +/* +Copyright (c) MONAI Consortium +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + http://www.apache.org/licenses/LICENSE-2.0 +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +#include + +#include "gmm.h" + +py::tuple init() { + torch::Tensor gmm_tensor = + torch::zeros({GMM_COUNT, GMM_COMPONENT_COUNT}, torch::dtype(torch::kFloat32).device(torch::kCUDA)); + torch::Tensor scratch_tensor = torch::empty({1}, torch::dtype(torch::kFloat32).device(torch::kCUDA)); + return py::make_tuple(gmm_tensor, scratch_tensor); +} + +void learn( + torch::Tensor gmm_tensor, + torch::Tensor scratch_tensor, + torch::Tensor input_tensor, + torch::Tensor label_tensor) { + c10::DeviceType device_type = input_tensor.device().type(); + + unsigned int batch_count = input_tensor.size(0); + unsigned int element_count = input_tensor.stride(1); + + unsigned int scratch_size = + batch_count * (element_count + GMM_COMPONENT_COUNT * GMM_COUNT * (element_count / (32 * 32))); + + if (scratch_tensor.size(0) < scratch_size) { + scratch_tensor.resize_({scratch_size}); + } + + float* gmm = gmm_tensor.data_ptr(); + float* scratch = scratch_tensor.data_ptr(); + float* input = input_tensor.data_ptr(); + int* labels = label_tensor.data_ptr(); + + if (device_type == torch::kCUDA) { + learn_cuda(input, labels, gmm, scratch, batch_count, element_count); + } else { + learn_cpu(input, labels, gmm, scratch, batch_count, element_count); + } +} + +torch::Tensor apply(torch::Tensor gmm_tensor, torch::Tensor input_tensor) { + c10::DeviceType device_type = input_tensor.device().type(); + + unsigned int dim = input_tensor.dim(); + unsigned int batch_count = input_tensor.size(0); + unsigned int element_count = input_tensor.stride(1); + + auto output_size = input_tensor.sizes().vec(); + output_size[1] = MIXTURE_COUNT; + torch::Tensor output_tensor = + torch::empty(c10::IntArrayRef(output_size), torch::dtype(torch::kFloat32).device(device_type)); + + const float* gmm = gmm_tensor.data_ptr(); + const float* input = input_tensor.data_ptr(); + float* output = output_tensor.data_ptr(); + + if (device_type == torch::kCUDA) { + apply_cuda(gmm, input, output, batch_count, element_count); + } else { + apply_cpu(gmm, input, output, batch_count, element_count); + } + + return output_tensor; +} + +PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) { + m.def("init", torch::wrap_pybind_function(init)); + m.def("learn", torch::wrap_pybind_function(learn)); + m.def("apply", torch::wrap_pybind_function(apply)); +} diff --git a/source_code/SegMamba/monai/_extensions/gmm/gmm.h b/source_code/SegMamba/monai/_extensions/gmm/gmm.h new file mode 100644 index 0000000000000000000000000000000000000000..09c0389ae66f0161e3ca4d997f0ce0a95e66e5df --- /dev/null +++ b/source_code/SegMamba/monai/_extensions/gmm/gmm.h @@ -0,0 +1,53 @@ +/* +Copyright (c) MONAI Consortium +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + http://www.apache.org/licenses/LICENSE-2.0 +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +#if !defined(CHANNEL_COUNT) || !defined(MIXTURE_COUNT) || !defined(MIXTURE_SIZE) +#error Definition of CHANNEL_COUNT, MIXTURE_COUNT, and MIXTURE_SIZE required +#endif + +#if CHANNEL_COUNT < 1 || MIXTURE_COUNT < 1 || MIXTURE_SIZE < 1 +#error CHANNEL_COUNT, MIXTURE_COUNT, and MIXTURE_SIZE must be positive +#endif + +#define MATRIX_COMPONENT_COUNT ((CHANNEL_COUNT + 1) * (CHANNEL_COUNT + 2) / 2) +#define SUB_MATRIX_COMPONENT_COUNT (CHANNEL_COUNT * (CHANNEL_COUNT + 1) / 2) +#define GMM_COMPONENT_COUNT (MATRIX_COMPONENT_COUNT + 1) +#define GMM_COUNT (MIXTURE_COUNT * MIXTURE_SIZE) + +void learn_cpu( + const float* input, + const int* labels, + float* gmm, + float* scratch_memory, + unsigned int batch_count, + unsigned int element_count); +void apply_cpu( + const float* gmm, + const float* input, + float* output, + unsigned int batch_count, + unsigned int element_count); + +void learn_cuda( + const float* input, + const int* labels, + float* gmm, + float* scratch_memory, + unsigned int batch_count, + unsigned int element_count); +void apply_cuda( + const float* gmm, + const float* input, + float* output, + unsigned int batch_count, + unsigned int element_count); diff --git a/source_code/SegMamba/monai/_extensions/gmm/gmm_cpu.cpp b/source_code/SegMamba/monai/_extensions/gmm/gmm_cpu.cpp new file mode 100644 index 0000000000000000000000000000000000000000..d7eedc07c8602b9c08e09d2be1c4431eb6045d7e --- /dev/null +++ b/source_code/SegMamba/monai/_extensions/gmm/gmm_cpu.cpp @@ -0,0 +1,35 @@ +/* +Copyright (c) MONAI Consortium +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + http://www.apache.org/licenses/LICENSE-2.0 +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +#include + +#include "gmm.h" + +void learn_cpu( + const float* input, + const int* labels, + float* gmm, + float* scratch_memory, + unsigned int batch_count, + unsigned int element_count) { + throw std::invalid_argument("GMM received a cpu tensor but is not yet implemented for the cpu"); +} + +void apply_cpu( + const float* gmm, + const float* input, + float* output, + unsigned int batch_count, + unsigned int element_count) { + throw std::invalid_argument("GMM received a cpu tensor but is not yet implemented for the cpu"); +} diff --git a/source_code/SegMamba/monai/apps/auto3dseg/__init__.py b/source_code/SegMamba/monai/apps/auto3dseg/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..7096fb7520a78a02cdeffaaef1e77e246d992d21 --- /dev/null +++ b/source_code/SegMamba/monai/apps/auto3dseg/__init__.py @@ -0,0 +1,25 @@ +# Copyright (c) MONAI Consortium +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from __future__ import annotations + +from .auto_runner import AutoRunner +from .bundle_gen import BundleAlgo, BundleGen +from .data_analyzer import DataAnalyzer +from .ensemble_builder import ( + AlgoEnsemble, + AlgoEnsembleBestByFold, + AlgoEnsembleBestN, + AlgoEnsembleBuilder, + EnsembleRunner, +) +from .hpo_gen import NNIGen, OptunaGen +from .utils import export_bundle_algo_history, get_name_from_algo_id, import_bundle_algo_history diff --git a/source_code/SegMamba/monai/apps/auto3dseg/__main__.py b/source_code/SegMamba/monai/apps/auto3dseg/__main__.py new file mode 100644 index 0000000000000000000000000000000000000000..dfc14c270b4f4edbabe5c394961d6c85ebb3271a --- /dev/null +++ b/source_code/SegMamba/monai/apps/auto3dseg/__main__.py @@ -0,0 +1,35 @@ +# Copyright (c) MONAI Consortium +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from __future__ import annotations + +from monai.apps.auto3dseg.auto_runner import AutoRunner +from monai.apps.auto3dseg.bundle_gen import BundleAlgo, BundleGen +from monai.apps.auto3dseg.data_analyzer import DataAnalyzer +from monai.apps.auto3dseg.ensemble_builder import AlgoEnsembleBuilder, EnsembleRunner +from monai.apps.auto3dseg.hpo_gen import NNIGen, OptunaGen + +if __name__ == "__main__": + from monai.utils import optional_import + + fire, _ = optional_import("fire") + fire.Fire( + { + "DataAnalyzer": DataAnalyzer, + "BundleGen": BundleGen, + "BundleAlgo": BundleAlgo, + "AlgoEnsembleBuilder": AlgoEnsembleBuilder, + "EnsembleRunner": EnsembleRunner, + "AutoRunner": AutoRunner, + "NNIGen": NNIGen, + "OptunaGen": OptunaGen, + } + ) diff --git a/source_code/SegMamba/monai/apps/auto3dseg/transforms.py b/source_code/SegMamba/monai/apps/auto3dseg/transforms.py new file mode 100644 index 0000000000000000000000000000000000000000..bb755aa78c13ff94f7022c7b6356ee61f4375bb6 --- /dev/null +++ b/source_code/SegMamba/monai/apps/auto3dseg/transforms.py @@ -0,0 +1,85 @@ +# Copyright (c) MONAI Consortium +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from __future__ import annotations + +import warnings +from collections.abc import Hashable, Mapping + +import numpy as np +import torch + +from monai.config import KeysCollection +from monai.networks.utils import pytorch_after +from monai.transforms import MapTransform +from monai.utils.misc import ImageMetaKey + + +class EnsureSameShaped(MapTransform): + """ + Checks if segmentation label images (in keys) have the same spatial shape as the main image (in source_key), + and raise an error if the shapes are significantly different. + If the shapes are only slightly different (within an allowed_shape_difference in each dim), then resize the label using + nearest interpolation. This transform is designed to correct datasets with slight label shape mismatches. + Generally image and segmentation label must have the same spatial shape, however some public datasets are having slight + shape mismatches, which will cause potential crashes when calculating loss or metric functions. + """ + + def __init__( + self, + keys: KeysCollection = "label", + allow_missing_keys: bool = False, + source_key: str = "image", + allowed_shape_difference: int = 5, + warn: bool = True, + ) -> None: + """ + Args: + keys: keys of the corresponding items to be compared to the source_key item shape. + allow_missing_keys: do not raise exception if key is missing. + source_key: key of the item with the reference shape. + allowed_shape_difference: raises error if shapes are different more than this value in any dimension, + otherwise corrects for the shape mismatch using nearest interpolation. + warn: if `True` prints a warning if the label image is resized + + + """ + super().__init__(keys=keys, allow_missing_keys=allow_missing_keys) + self.source_key = source_key + self.allowed_shape_difference = allowed_shape_difference + self.warn = warn + + def __call__(self, data: Mapping[Hashable, torch.Tensor]) -> dict[Hashable, torch.Tensor]: + d = dict(data) + image_shape = d[self.source_key].shape[1:] + for key in self.key_iterator(d): + label_shape = d[key].shape[1:] + if label_shape != image_shape: + filename = "" + if hasattr(d[key], "meta") and isinstance(d[key].meta, Mapping): # type: ignore[attr-defined] + filename = d[key].meta.get(ImageMetaKey.FILENAME_OR_OBJ) # type: ignore[attr-defined] + + if np.allclose(list(label_shape), list(image_shape), atol=self.allowed_shape_difference): + if self.warn: + warnings.warn( + f"The {key} with shape {label_shape} was resized to match the source shape {image_shape}" + f", the metadata was not updated {filename}." + ) + d[key] = torch.nn.functional.interpolate( + input=d[key].unsqueeze(0), + size=image_shape, + mode="nearest-exact" if pytorch_after(1, 11) else "nearest", + ).squeeze(0) + else: + raise ValueError( + f"The {key} shape {label_shape} is different from the source shape {image_shape} {filename}." + ) + return d diff --git a/source_code/SegMamba/monai/apps/auto3dseg/utils.py b/source_code/SegMamba/monai/apps/auto3dseg/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..64e1d2ea2a30c9bfdcedf286886011b48b5a03fb --- /dev/null +++ b/source_code/SegMamba/monai/apps/auto3dseg/utils.py @@ -0,0 +1,90 @@ +# Copyright (c) MONAI Consortium +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from __future__ import annotations + +import os + +from monai.apps.auto3dseg.bundle_gen import BundleAlgo +from monai.auto3dseg import algo_from_pickle, algo_to_pickle +from monai.utils.enums import AlgoKeys + +__all__ = ["import_bundle_algo_history", "export_bundle_algo_history", "get_name_from_algo_id"] + + +def import_bundle_algo_history( + output_folder: str = ".", template_path: str | None = None, only_trained: bool = True +) -> list: + """ + import the history of the bundleAlgo objects as a list of algo dicts. + each algo_dict has keys name (folder name), algo (bundleAlgo), is_trained (bool), + + Args: + output_folder: the root path of the algorithms templates. + template_path: the algorithm_template. It must contain algo.py in the follow path: + ``{algorithm_templates_dir}/{network}/scripts/algo.py``. + only_trained: only read the algo history if the algo is trained. + """ + + history = [] + + for name in sorted(os.listdir(output_folder)): + write_path = os.path.join(output_folder, name) + + if not os.path.isdir(write_path): + continue + + obj_filename = os.path.join(write_path, "algo_object.pkl") + if not os.path.isfile(obj_filename): # saved mode pkl + continue + + algo, algo_meta_data = algo_from_pickle(obj_filename, template_path=template_path) + + best_metric = algo_meta_data.get(AlgoKeys.SCORE, None) + if best_metric is None: + try: + best_metric = algo.get_score() + except BaseException: + pass + + is_trained = best_metric is not None + + if (only_trained and is_trained) or not only_trained: + history.append( + {AlgoKeys.ID: name, AlgoKeys.ALGO: algo, AlgoKeys.SCORE: best_metric, AlgoKeys.IS_TRAINED: is_trained} + ) + + return history + + +def export_bundle_algo_history(history: list[dict[str, BundleAlgo]]) -> None: + """ + Save all the BundleAlgo in the history to algo_object.pkl in each individual folder + + Args: + history: a List of Bundle. Typically, the history can be obtained from BundleGen get_history method + """ + for algo_dict in history: + algo = algo_dict[AlgoKeys.ALGO] + algo_to_pickle(algo, template_path=algo.template_path) + + +def get_name_from_algo_id(id: str) -> str: + """ + Get the name of Algo from the identifier of the Algo. + + Args: + id: identifier which follows a convention of "name_fold_other". + + Returns: + name of the Algo. + """ + return id.split("_")[0] diff --git a/source_code/SegMamba/monai/apps/detection/networks/retinanet_network.py b/source_code/SegMamba/monai/apps/detection/networks/retinanet_network.py new file mode 100644 index 0000000000000000000000000000000000000000..ec86c3b0e92147f24d1b2b2ae36986f0288a0ce5 --- /dev/null +++ b/source_code/SegMamba/monai/apps/detection/networks/retinanet_network.py @@ -0,0 +1,432 @@ +# Copyright (c) MONAI Consortium +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# ========================================================================= +# Adapted from https://github.com/pytorch/vision/blob/main/torchvision/models/detection/retinanet.py +# which has the following license... +# https://github.com/pytorch/vision/blob/main/LICENSE + +# BSD 3-Clause License + +# Copyright (c) Soumith Chintala 2016, +# All rights reserved. + +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are met: + +# * Redistributions of source code must retain the above copyright notice, this +# list of conditions and the following disclaimer. + +# * Redistributions in binary form must reproduce the above copyright notice, +# this list of conditions and the following disclaimer in the documentation +# and/or other materials provided with the distribution. + +# * Neither the name of the copyright holder nor the names of its +# contributors may be used to endorse or promote products derived from +# this software without specific prior written permission. +""" +Part of this script is adapted from +https://github.com/pytorch/vision/blob/main/torchvision/models/detection/retinanet.py +""" + +from __future__ import annotations + +import math +import warnings +from collections.abc import Callable, Sequence +from typing import Any, Dict + +import torch +from torch import Tensor, nn + +from monai.networks.blocks.backbone_fpn_utils import BackboneWithFPN, _resnet_fpn_extractor +from monai.networks.layers.factories import Conv +from monai.networks.nets import resnet +from monai.utils import ensure_tuple_rep, look_up_option, optional_import + +_validate_trainable_layers, _ = optional_import( + "torchvision.models.detection.backbone_utils", name="_validate_trainable_layers" +) + + +class RetinaNetClassificationHead(nn.Module): + """ + A classification head for use in RetinaNet. + + This head takes a list of feature maps as inputs, and outputs a list of classification maps. + Each output map has same spatial size with the corresponding input feature map, + and the number of output channel is num_anchors * num_classes. + + Args: + in_channels: number of channels of the input feature + num_anchors: number of anchors to be predicted + num_classes: number of classes to be predicted + spatial_dims: spatial dimension of the network, should be 2 or 3. + prior_probability: prior probability to initialize classification convolutional layers. + """ + + def __init__( + self, in_channels: int, num_anchors: int, num_classes: int, spatial_dims: int, prior_probability: float = 0.01 + ): + super().__init__() + + conv_type: Callable = Conv[Conv.CONV, spatial_dims] + conv = [] + for _ in range(4): + conv.append(conv_type(in_channels, in_channels, kernel_size=3, stride=1, padding=1)) + conv.append(nn.GroupNorm(num_groups=8, num_channels=in_channels)) + conv.append(nn.ReLU()) + self.conv = nn.Sequential(*conv) + + for layer in self.conv.children(): + if isinstance(layer, conv_type): # type: ignore + torch.nn.init.normal_(layer.weight, std=0.01) + torch.nn.init.constant_(layer.bias, 0) + + self.cls_logits = conv_type(in_channels, num_anchors * num_classes, kernel_size=3, stride=1, padding=1) + torch.nn.init.normal_(self.cls_logits.weight, std=0.01) + torch.nn.init.constant_(self.cls_logits.bias, -math.log((1 - prior_probability) / prior_probability)) + + self.num_classes = num_classes + self.num_anchors = num_anchors + + def forward(self, x: list[Tensor]) -> list[Tensor]: + """ + It takes a list of feature maps as inputs, and outputs a list of classification maps. + Each output classification map has same spatial size with the corresponding input feature map, + and the number of output channel is num_anchors * num_classes. + + Args: + x: list of feature map, x[i] is a (B, in_channels, H_i, W_i) or (B, in_channels, H_i, W_i, D_i) Tensor. + + Return: + cls_logits_maps, list of classification map. cls_logits_maps[i] is a + (B, num_anchors * num_classes, H_i, W_i) or (B, num_anchors * num_classes, H_i, W_i, D_i) Tensor. + + """ + cls_logits_maps = [] + + if isinstance(x, Tensor): + feature_maps = [x] + else: + feature_maps = x + + for features in feature_maps: + cls_logits = self.conv(features) + cls_logits = self.cls_logits(cls_logits) + + cls_logits_maps.append(cls_logits) + + if torch.isnan(cls_logits).any() or torch.isinf(cls_logits).any(): + if torch.is_grad_enabled(): + raise ValueError("cls_logits is NaN or Inf.") + else: + warnings.warn("cls_logits is NaN or Inf.") + + return cls_logits_maps + + +class RetinaNetRegressionHead(nn.Module): + """ + A regression head for use in RetinaNet. + + This head takes a list of feature maps as inputs, and outputs a list of box regression maps. + Each output box regression map has same spatial size with the corresponding input feature map, + and the number of output channel is num_anchors * 2 * spatial_dims. + + Args: + in_channels: number of channels of the input feature + num_anchors: number of anchors to be predicted + spatial_dims: spatial dimension of the network, should be 2 or 3. + """ + + def __init__(self, in_channels: int, num_anchors: int, spatial_dims: int): + super().__init__() + + conv_type: Callable = Conv[Conv.CONV, spatial_dims] + + conv = [] + for _ in range(4): + conv.append(conv_type(in_channels, in_channels, kernel_size=3, stride=1, padding=1)) + conv.append(nn.GroupNorm(num_groups=8, num_channels=in_channels)) + conv.append(nn.ReLU()) + + self.conv = nn.Sequential(*conv) + + self.bbox_reg = conv_type(in_channels, num_anchors * 2 * spatial_dims, kernel_size=3, stride=1, padding=1) + torch.nn.init.normal_(self.bbox_reg.weight, std=0.01) + torch.nn.init.zeros_(self.bbox_reg.bias) + + for layer in self.conv.children(): + if isinstance(layer, conv_type): # type: ignore + torch.nn.init.normal_(layer.weight, std=0.01) + torch.nn.init.zeros_(layer.bias) + + def forward(self, x: list[Tensor]) -> list[Tensor]: + """ + It takes a list of feature maps as inputs, and outputs a list of box regression maps. + Each output box regression map has same spatial size with the corresponding input feature map, + and the number of output channel is num_anchors * 2 * spatial_dims. + + Args: + x: list of feature map, x[i] is a (B, in_channels, H_i, W_i) or (B, in_channels, H_i, W_i, D_i) Tensor. + + Return: + box_regression_maps, list of box regression map. cls_logits_maps[i] is a + (B, num_anchors * 2 * spatial_dims, H_i, W_i) or (B, num_anchors * 2 * spatial_dims, H_i, W_i, D_i) Tensor. + + """ + box_regression_maps = [] + + if isinstance(x, Tensor): + feature_maps = [x] + else: + feature_maps = x + + for features in feature_maps: + box_regression = self.conv(features) + box_regression = self.bbox_reg(box_regression) + + box_regression_maps.append(box_regression) + + if torch.isnan(box_regression).any() or torch.isinf(box_regression).any(): + if torch.is_grad_enabled(): + raise ValueError("box_regression is NaN or Inf.") + else: + warnings.warn("box_regression is NaN or Inf.") + + return box_regression_maps + + +class RetinaNet(nn.Module): + """ + The network used in RetinaNet. + + It takes an image tensor as inputs, and outputs either 1) a dictionary ``head_outputs``. + ``head_outputs[self.cls_key]`` is the predicted classification maps, a list of Tensor. + ``head_outputs[self.box_reg_key]`` is the predicted box regression maps, a list of Tensor. + or 2) a list of 2N tensors ``head_outputs``, with first N tensors being the predicted + classification maps and second N tensors being the predicted box regression maps. + + Args: + spatial_dims: number of spatial dimensions of the images. We support both 2D and 3D images. + num_classes: number of output classes of the model (excluding the background). + num_anchors: number of anchors at each location. + feature_extractor: a network that outputs feature maps from the input images, + each feature map corresponds to a different resolution. + Its output can have a format of Tensor, Dict[Any, Tensor], or Sequence[Tensor]. + It can be the output of ``resnet_fpn_feature_extractor(*args, **kwargs)``. + size_divisible: the spatial size of the network input should be divisible by size_divisible, + decided by the feature_extractor. + use_list_output: default False. If False, the network outputs a dictionary ``head_outputs``, + ``head_outputs[self.cls_key]`` is the predicted classification maps, a list of Tensor. + ``head_outputs[self.box_reg_key]`` is the predicted box regression maps, a list of Tensor. + If True, the network outputs a list of 2N tensors ``head_outputs``, with first N tensors being + the predicted classification maps and second N tensors being the predicted box regression maps. + + Example: + + .. code-block:: python + + from monai.networks.nets import resnet + spatial_dims = 3 # 3D network + conv1_t_stride = (2,2,1) # stride of first convolutional layer in backbone + backbone = resnet.ResNet( + spatial_dims = spatial_dims, + block = resnet.ResNetBottleneck, + layers = [3, 4, 6, 3], + block_inplanes = resnet.get_inplanes(), + n_input_channels= 1, + conv1_t_stride = conv1_t_stride, + conv1_t_size = (7,7,7), + ) + # This feature_extractor outputs 4-level feature maps. + # number of output feature maps is len(returned_layers)+1 + returned_layers = [1,2,3] # returned layer from feature pyramid network + feature_extractor = resnet_fpn_feature_extractor( + backbone = backbone, + spatial_dims = spatial_dims, + pretrained_backbone = False, + trainable_backbone_layers = None, + returned_layers = returned_layers, + ) + # This feature_extractor requires input image spatial size + # to be divisible by (32, 32, 16). + size_divisible = tuple(2*s*2**max(returned_layers) for s in conv1_t_stride) + model = RetinaNet( + spatial_dims = spatial_dims, + num_classes = 5, + num_anchors = 6, + feature_extractor=feature_extractor, + size_divisible = size_divisible, + ).to(device) + result = model(torch.rand(2, 1, 128,128,128)) + cls_logits_maps = result["classification"] # a list of len(returned_layers)+1 Tensor + box_regression_maps = result["box_regression"] # a list of len(returned_layers)+1 Tensor + """ + + def __init__( + self, + spatial_dims: int, + num_classes: int, + num_anchors: int, + feature_extractor: nn.Module, + size_divisible: Sequence[int] | int = 1, + use_list_output: bool = False, + ): + super().__init__() + + self.spatial_dims = look_up_option(spatial_dims, supported=[1, 2, 3]) + self.num_classes = num_classes + self.size_divisible = ensure_tuple_rep(size_divisible, self.spatial_dims) + self.use_list_output = use_list_output + + if not hasattr(feature_extractor, "out_channels"): + raise ValueError( + "feature_extractor should contain an attribute out_channels " + "specifying the number of output channels (assumed to be the " + "same for all the levels)" + ) + self.feature_extractor = feature_extractor + + self.feature_map_channels: int = self.feature_extractor.out_channels + self.num_anchors = num_anchors + self.classification_head = RetinaNetClassificationHead( + self.feature_map_channels, self.num_anchors, self.num_classes, spatial_dims=self.spatial_dims + ) + self.regression_head = RetinaNetRegressionHead( + self.feature_map_channels, self.num_anchors, spatial_dims=self.spatial_dims + ) + + self.cls_key: str = "classification" + self.box_reg_key: str = "box_regression" + + def forward(self, images: Tensor) -> Any: + """ + It takes an image tensor as inputs, and outputs predicted classification maps + and predicted box regression maps in ``head_outputs``. + + Args: + images: input images, sized (B, img_channels, H, W) or (B, img_channels, H, W, D). + + Return: + 1) If self.use_list_output is False, output a dictionary ``head_outputs`` with + keys including self.cls_key and self.box_reg_key. + ``head_outputs[self.cls_key]`` is the predicted classification maps, a list of Tensor. + ``head_outputs[self.box_reg_key]`` is the predicted box regression maps, a list of Tensor. + 2) if self.use_list_output is True, outputs a list of 2N tensors ``head_outputs``, with first N tensors being + the predicted classification maps and second N tensors being the predicted box regression maps. + + """ + # compute features maps list from the input images. + features = self.feature_extractor(images) + if isinstance(features, Tensor): + feature_maps = [features] + elif torch.jit.isinstance(features, Dict[str, Tensor]): + feature_maps = list(features.values()) + else: + feature_maps = list(features) + + if not isinstance(feature_maps[0], Tensor): + raise ValueError("feature_extractor output format must be Tensor, Dict[str, Tensor], or Sequence[Tensor].") + + # compute classification and box regression maps from the feature maps + # expandable for mask prediction in the future + + if not self.use_list_output: + # output dict + head_outputs = {self.cls_key: self.classification_head(feature_maps)} + head_outputs[self.box_reg_key] = self.regression_head(feature_maps) + return head_outputs + else: + # output list of tensor, first half is classification, second half is box regression + head_outputs_sequence = self.classification_head(feature_maps) + self.regression_head(feature_maps) + return head_outputs_sequence + + +def resnet_fpn_feature_extractor( + backbone: resnet.ResNet, + spatial_dims: int, + pretrained_backbone: bool = False, + returned_layers: Sequence[int] = (1, 2, 3), + trainable_backbone_layers: int | None = None, +) -> BackboneWithFPN: + """ + Constructs a feature extractor network with a ResNet-FPN backbone, used as feature_extractor in RetinaNet. + + Reference: `"Focal Loss for Dense Object Detection" `_. + + The returned feature_extractor network takes an image tensor as inputs, + and outputs a dictionary that maps string to the extracted feature maps (Tensor). + + The input to the returned feature_extractor is expected to be a list of tensors, + each of shape ``[C, H, W]`` or ``[C, H, W, D]``, + one for each image. Different images can have different sizes. + + + Args: + backbone: a ResNet model, used as backbone. + spatial_dims: number of spatial dimensions of the images. We support both 2D and 3D images. + pretrained_backbone: whether the backbone has been pre-trained. + returned_layers: returned layers to extract feature maps. Each returned layer should be in the range [1,4]. + len(returned_layers)+1 will be the number of extracted feature maps. + There is an extra maxpooling layer LastLevelMaxPool() appended. + trainable_backbone_layers: number of trainable (not frozen) resnet layers starting from final block. + Valid values are between 0 and 5, with 5 meaning all backbone layers are trainable. + When pretrained_backbone is False, this value is set to be 5. + When pretrained_backbone is True, if ``None`` is passed (the default) this value is set to 3. + + Example: + + .. code-block:: python + + from monai.networks.nets import resnet + spatial_dims = 3 # 3D network + backbone = resnet.ResNet( + spatial_dims = spatial_dims, + block = resnet.ResNetBottleneck, + layers = [3, 4, 6, 3], + block_inplanes = resnet.get_inplanes(), + n_input_channels= 1, + conv1_t_stride = (2,2,1), + conv1_t_size = (7,7,7), + ) + # This feature_extractor outputs 4-level feature maps. + # number of output feature maps is len(returned_layers)+1 + feature_extractor = resnet_fpn_feature_extractor( + backbone = backbone, + spatial_dims = spatial_dims, + pretrained_backbone = False, + trainable_backbone_layers = None, + returned_layers = [1,2,3], + ) + model = RetinaNet( + spatial_dims = spatial_dims, + num_classes = 5, + num_anchors = 6, + feature_extractor=feature_extractor, + size_divisible = 32, + ).to(device) + """ + # If pretrained_backbone is False, valid_trainable_backbone_layers = 5. + # If pretrained_backbone is True, valid_trainable_backbone_layers = trainable_backbone_layers or 3 if None. + valid_trainable_backbone_layers: int = _validate_trainable_layers( + pretrained_backbone, trainable_backbone_layers, max_value=5, default_value=3 + ) + + feature_extractor = _resnet_fpn_extractor( + backbone, + spatial_dims, + valid_trainable_backbone_layers, + returned_layers=list(returned_layers), + extra_blocks=None, + ) + return feature_extractor diff --git a/source_code/SegMamba/monai/apps/mmars/model_desc.py b/source_code/SegMamba/monai/apps/mmars/model_desc.py new file mode 100644 index 0000000000000000000000000000000000000000..a3963689fb5e32f3c8e5c83a535cc6ea073257dc --- /dev/null +++ b/source_code/SegMamba/monai/apps/mmars/model_desc.py @@ -0,0 +1,229 @@ +# Copyright (c) MONAI Consortium +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +""" +Collection of the remote MMAR descriptors + +See Also: + - https://docs.nvidia.com/clara/clara-train-sdk/pt/mmar.html +""" + +from __future__ import annotations + +import os +from typing import Any + +__all__ = ["MODEL_DESC", "RemoteMMARKeys"] + + +class RemoteMMARKeys: + """ + Data keys used for loading MMAR. + ID must uniquely define an MMAR. + """ + + ID = "id" # unique MMAR + NAME = "name" # MMAR name for readability + URL = "url" # remote location of the MMAR, see also: `monai.apps.mmars.mmars._get_ngc_url` + DOC = "doc" # documentation page of the remote model, see also: `monai.apps.mmars.mmars._get_ngc_doc_url` + FILE_TYPE = "file_type" # type of the compressed MMAR + HASH_TYPE = "hash_type" # hashing method for the compressed MMAR + HASH_VAL = "hash_val" # hashing value for the compressed MMAR + MODEL_FILE = "model_file" # within an MMAR folder, the relative path to the model file + CONFIG_FILE = "config_file" # within an MMAR folder, the relative path to the config file (for model config) + VERSION = "version" # version of the MMAR + + +MODEL_DESC: tuple[dict[Any, Any], ...] = ( + { + RemoteMMARKeys.ID: "clara_pt_spleen_ct_segmentation_1", + RemoteMMARKeys.NAME: "clara_pt_spleen_ct_segmentation", + RemoteMMARKeys.FILE_TYPE: "zip", + RemoteMMARKeys.HASH_TYPE: "md5", + RemoteMMARKeys.HASH_VAL: None, + RemoteMMARKeys.MODEL_FILE: os.path.join("models", "model.pt"), + RemoteMMARKeys.CONFIG_FILE: os.path.join("config", "config_train.json"), + RemoteMMARKeys.VERSION: 1, + }, + { + RemoteMMARKeys.ID: "clara_pt_prostate_mri_segmentation_1", + RemoteMMARKeys.NAME: "clara_pt_prostate_mri_segmentation", + RemoteMMARKeys.FILE_TYPE: "zip", + RemoteMMARKeys.HASH_TYPE: "md5", + RemoteMMARKeys.HASH_VAL: None, + RemoteMMARKeys.MODEL_FILE: os.path.join("models", "model.pt"), + RemoteMMARKeys.CONFIG_FILE: os.path.join("config", "config_train.json"), + RemoteMMARKeys.VERSION: 1, + }, + { + RemoteMMARKeys.ID: "clara_pt_covid19_ct_lesion_segmentation_1", + RemoteMMARKeys.NAME: "clara_pt_covid19_ct_lesion_segmentation", + RemoteMMARKeys.FILE_TYPE: "zip", + RemoteMMARKeys.HASH_TYPE: "md5", + RemoteMMARKeys.HASH_VAL: None, + RemoteMMARKeys.MODEL_FILE: os.path.join("models", "model.pt"), + RemoteMMARKeys.VERSION: 1, + }, + { + RemoteMMARKeys.ID: "clara_pt_covid19_3d_ct_classification_1", + RemoteMMARKeys.NAME: "clara_pt_covid19_3d_ct_classification", + RemoteMMARKeys.FILE_TYPE: "zip", + RemoteMMARKeys.HASH_TYPE: "md5", + RemoteMMARKeys.HASH_VAL: None, + RemoteMMARKeys.MODEL_FILE: os.path.join("models", "model.pt"), + RemoteMMARKeys.CONFIG_FILE: os.path.join("config", "config_train.json"), + RemoteMMARKeys.VERSION: 1, + }, + { + RemoteMMARKeys.ID: "clara_pt_covid19_ct_lung_annotation_1", + RemoteMMARKeys.NAME: "clara_pt_covid19_ct_lung_annotation", + RemoteMMARKeys.FILE_TYPE: "zip", + RemoteMMARKeys.HASH_TYPE: "md5", + RemoteMMARKeys.HASH_VAL: None, + RemoteMMARKeys.MODEL_FILE: os.path.join("models", "model.pt"), + RemoteMMARKeys.VERSION: 1, + }, + { + RemoteMMARKeys.ID: "clara_pt_fed_learning_brain_tumor_mri_segmentation_1", + RemoteMMARKeys.NAME: "clara_pt_fed_learning_brain_tumor_mri_segmentation", + RemoteMMARKeys.FILE_TYPE: "zip", + RemoteMMARKeys.HASH_TYPE: "md5", + RemoteMMARKeys.HASH_VAL: None, + RemoteMMARKeys.MODEL_FILE: os.path.join("models", "server", "best_FL_global_model.pt"), + RemoteMMARKeys.VERSION: 1, + }, + { + RemoteMMARKeys.ID: "clara_pt_pathology_metastasis_detection_1", + RemoteMMARKeys.NAME: "clara_pt_pathology_metastasis_detection", + RemoteMMARKeys.FILE_TYPE: "zip", + RemoteMMARKeys.HASH_TYPE: "md5", + RemoteMMARKeys.HASH_VAL: None, + RemoteMMARKeys.MODEL_FILE: os.path.join("models", "model.pt"), + RemoteMMARKeys.CONFIG_FILE: os.path.join("config", "config_train.json"), + RemoteMMARKeys.VERSION: 1, + }, + { + RemoteMMARKeys.ID: "clara_pt_brain_mri_segmentation_1", + RemoteMMARKeys.NAME: "clara_pt_brain_mri_segmentation", + RemoteMMARKeys.FILE_TYPE: "zip", + RemoteMMARKeys.HASH_TYPE: "md5", + RemoteMMARKeys.HASH_VAL: None, + RemoteMMARKeys.MODEL_FILE: os.path.join("models", "model.pt"), + RemoteMMARKeys.VERSION: 1, + }, + { + RemoteMMARKeys.ID: "clara_pt_brain_mri_segmentation_t1c_1", + RemoteMMARKeys.NAME: "clara_pt_brain_mri_segmentation_t1c", + RemoteMMARKeys.FILE_TYPE: "zip", + RemoteMMARKeys.HASH_TYPE: "md5", + RemoteMMARKeys.HASH_VAL: None, + RemoteMMARKeys.MODEL_FILE: os.path.join("models", "model.pt"), + RemoteMMARKeys.VERSION: 1, + }, + { + RemoteMMARKeys.ID: "clara_pt_liver_and_tumor_ct_segmentation_1", + RemoteMMARKeys.NAME: "clara_pt_liver_and_tumor_ct_segmentation", + RemoteMMARKeys.FILE_TYPE: "zip", + RemoteMMARKeys.HASH_TYPE: "md5", + RemoteMMARKeys.HASH_VAL: None, + RemoteMMARKeys.MODEL_FILE: os.path.join("models", "model.pt"), + RemoteMMARKeys.CONFIG_FILE: os.path.join("config", "config_train.json"), + RemoteMMARKeys.VERSION: 1, + }, + { + RemoteMMARKeys.ID: "clara_pt_pancreas_and_tumor_ct_segmentation_1", + RemoteMMARKeys.NAME: "clara_pt_pancreas_and_tumor_ct_segmentation", + RemoteMMARKeys.FILE_TYPE: "zip", + RemoteMMARKeys.HASH_TYPE: "md5", + RemoteMMARKeys.HASH_VAL: None, + RemoteMMARKeys.MODEL_FILE: os.path.join("models", "model.pt"), + RemoteMMARKeys.CONFIG_FILE: os.path.join("config", "config_train.json"), + RemoteMMARKeys.VERSION: 1, + }, + { + RemoteMMARKeys.ID: "clara_pt_brain_mri_annotation_t1c_1", + RemoteMMARKeys.NAME: "clara_pt_brain_mri_annotation_t1c", + RemoteMMARKeys.FILE_TYPE: "zip", + RemoteMMARKeys.HASH_TYPE: "md5", + RemoteMMARKeys.HASH_VAL: None, + RemoteMMARKeys.MODEL_FILE: os.path.join("models", "model.pt"), + RemoteMMARKeys.VERSION: 1, + }, + { + RemoteMMARKeys.ID: "clara_pt_spleen_ct_annotation_1", + RemoteMMARKeys.NAME: "clara_pt_spleen_ct_annotation", + RemoteMMARKeys.FILE_TYPE: "zip", + RemoteMMARKeys.HASH_TYPE: "md5", + RemoteMMARKeys.HASH_VAL: None, + RemoteMMARKeys.MODEL_FILE: os.path.join("models", "model.pt"), + RemoteMMARKeys.CONFIG_FILE: os.path.join("config", "config_train.json"), + RemoteMMARKeys.VERSION: 1, + }, + { + RemoteMMARKeys.ID: "clara_pt_deepgrow_3d_annotation_1", + RemoteMMARKeys.NAME: "clara_pt_deepgrow_3d_annotation", + RemoteMMARKeys.FILE_TYPE: "zip", + RemoteMMARKeys.HASH_TYPE: "md5", + RemoteMMARKeys.HASH_VAL: None, + RemoteMMARKeys.MODEL_FILE: os.path.join("models", "model.pt"), + RemoteMMARKeys.CONFIG_FILE: os.path.join("config", "config_train.json"), + RemoteMMARKeys.VERSION: 1, + }, + { + RemoteMMARKeys.ID: "clara_pt_deepgrow_2d_annotation_1", + RemoteMMARKeys.NAME: "clara_pt_deepgrow_2d_annotation", + RemoteMMARKeys.FILE_TYPE: "zip", + RemoteMMARKeys.HASH_TYPE: "md5", + RemoteMMARKeys.HASH_VAL: None, + RemoteMMARKeys.MODEL_FILE: os.path.join("models", "model.pt"), + RemoteMMARKeys.CONFIG_FILE: os.path.join("config", "config_train.json"), + RemoteMMARKeys.VERSION: 1, + }, + { + RemoteMMARKeys.ID: "clara_pt_covid19_ct_lung_segmentation_1", + RemoteMMARKeys.NAME: "clara_pt_covid19_ct_lung_segmentation", + RemoteMMARKeys.FILE_TYPE: "zip", + RemoteMMARKeys.HASH_TYPE: "md5", + RemoteMMARKeys.HASH_VAL: None, + RemoteMMARKeys.MODEL_FILE: os.path.join("models", "model.pt"), + RemoteMMARKeys.CONFIG_FILE: os.path.join("config", "config_train.json"), + RemoteMMARKeys.VERSION: 1, + }, + { + RemoteMMARKeys.ID: "clara_pt_unetr_ct_btcv_segmentation", + RemoteMMARKeys.NAME: "clara_pt_unetr_ct_btcv_segmentation", + RemoteMMARKeys.FILE_TYPE: "zip", + RemoteMMARKeys.HASH_TYPE: "md5", + RemoteMMARKeys.HASH_VAL: None, + RemoteMMARKeys.MODEL_FILE: os.path.join("models", "model.pt"), + RemoteMMARKeys.CONFIG_FILE: os.path.join("config", "config_train.json"), + RemoteMMARKeys.VERSION: 4.1, + }, + { + RemoteMMARKeys.ID: "clara_pt_chest_xray_classification", + RemoteMMARKeys.NAME: "clara_pt_chest_xray_classification", + RemoteMMARKeys.FILE_TYPE: "zip", + RemoteMMARKeys.HASH_TYPE: "md5", + RemoteMMARKeys.HASH_VAL: None, + RemoteMMARKeys.MODEL_FILE: os.path.join("models", "model.pt"), + RemoteMMARKeys.CONFIG_FILE: os.path.join("config", "config_train.json"), + RemoteMMARKeys.VERSION: 4.1, + }, + { + RemoteMMARKeys.ID: "clara_pt_self_supervised_learning_segmentation", + RemoteMMARKeys.NAME: "clara_pt_self_supervised_learning_segmentation", + RemoteMMARKeys.FILE_TYPE: "zip", + RemoteMMARKeys.HASH_TYPE: "md5", + RemoteMMARKeys.HASH_VAL: None, + RemoteMMARKeys.MODEL_FILE: os.path.join("models_2gpu", "best_metric_model.pt"), + RemoteMMARKeys.CONFIG_FILE: os.path.join("config", "config_train.json"), + RemoteMMARKeys.VERSION: 4.1, + }, +) diff --git a/source_code/SegMamba/monai/apps/pathology/inferers/__init__.py b/source_code/SegMamba/monai/apps/pathology/inferers/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..3549b8ec29fa67d0a0ba34f37fa6d54f032cdf50 --- /dev/null +++ b/source_code/SegMamba/monai/apps/pathology/inferers/__init__.py @@ -0,0 +1,14 @@ +# Copyright (c) MONAI Consortium +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from __future__ import annotations + +from .inferer import SlidingWindowHoVerNetInferer diff --git a/source_code/SegMamba/monai/apps/pathology/inferers/inferer.py b/source_code/SegMamba/monai/apps/pathology/inferers/inferer.py new file mode 100644 index 0000000000000000000000000000000000000000..71259ca7dfd6f5f4f9c627a634b283b2790ef8d6 --- /dev/null +++ b/source_code/SegMamba/monai/apps/pathology/inferers/inferer.py @@ -0,0 +1,210 @@ +# Copyright (c) MONAI Consortium +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from __future__ import annotations + +from typing import Any, Callable, Sequence + +import numpy as np +import torch +import torch.nn.functional as F + +from monai.inferers import SlidingWindowInferer +from monai.inferers.utils import sliding_window_inference +from monai.utils import BlendMode, PytorchPadMode, look_up_option + +__all__ = ["SlidingWindowHoVerNetInferer"] + + +class SlidingWindowHoVerNetInferer(SlidingWindowInferer): + """ + Sliding window method for HoVerNet model inference, + with `sw_batch_size` windows for every model.forward(). + Usage example can be found in the :py:class:`monai.inferers.Inferer` base class. + + Args: + roi_size: the window size to execute SlidingWindow evaluation. + If it has non-positive components, the corresponding `inputs` size will be used. + if the components of the `roi_size` are non-positive values, the transform will use the + corresponding components of img size. For example, `roi_size=(32, -1)` will be adapted + to `(32, 64)` if the second spatial dimension size of img is `64`. + sw_batch_size: the batch size to run window slices. + overlap: Amount of overlap between scans. + mode: {``"constant"``, ``"gaussian"``} + How to blend output of overlapping windows. Defaults to ``"constant"``. + + - ``"constant``": gives equal weight to all predictions. + - ``"gaussian``": gives less weight to predictions on edges of windows. + + sigma_scale: the standard deviation coefficient of the Gaussian window when `mode` is ``"gaussian"``. + Default: 0.125. Actual window sigma is ``sigma_scale`` * ``dim_size``. + When sigma_scale is a sequence of floats, the values denote sigma_scale at the corresponding + spatial dimensions. + padding_mode: {``"constant"``, ``"reflect"``, ``"replicate"``, ``"circular"``} + Padding mode when ``roi_size`` is larger than inputs. Defaults to ``"constant"`` + See also: https://pytorch.org/docs/stable/generated/torch.nn.functional.pad.html + cval: fill value for 'constant' padding mode. Default: 0 + sw_device: device for the window data. + By default the device (and accordingly the memory) of the `inputs` is used. + Normally `sw_device` should be consistent with the device where `predictor` is defined. + device: device for the stitched output prediction. + By default the device (and accordingly the memory) of the `inputs` is used. If for example + set to device=torch.device('cpu') the gpu memory consumption is less and independent of the + `inputs` and `roi_size`. Output is on the `device`. + progress: whether to print a tqdm progress bar. + cache_roi_weight_map: whether to pre-compute the ROI weight map. + cpu_thresh: when provided, dynamically switch to stitching on cpu (to save gpu memory) + when input image volume is larger than this threshold (in pixels/voxels). + Otherwise use ``"device"``. Thus, the output may end-up on either cpu or gpu. + extra_input_padding: the amount of padding for the input image, which is a tuple of even number of pads. + Refer to to the `pad` argument of `torch.nn.functional.pad` for more details. + + Note: + ``sw_batch_size`` denotes the max number of windows per network inference iteration, + not the batch size of inputs. + + """ + + def __init__( + self, + roi_size: Sequence[int] | int, + sw_batch_size: int = 1, + overlap: float = 0.25, + mode: BlendMode | str = BlendMode.CONSTANT, + sigma_scale: Sequence[float] | float = 0.125, + padding_mode: PytorchPadMode | str = PytorchPadMode.CONSTANT, + cval: float = 0.0, + sw_device: torch.device | str | None = None, + device: torch.device | str | None = None, + progress: bool = False, + cache_roi_weight_map: bool = False, + cpu_thresh: int | None = None, + extra_input_padding: tuple[int] | None = None, + ) -> None: + super().__init__( + roi_size=roi_size, + sw_batch_size=sw_batch_size, + overlap=overlap, + mode=mode, + sigma_scale=sigma_scale, + padding_mode=padding_mode, + cval=cval, + sw_device=sw_device, + device=device, + progress=progress, + cache_roi_weight_map=cache_roi_weight_map, + cpu_thresh=cpu_thresh, + ) + self.extra_input_padding = extra_input_padding + + def process_output(self, seg_prob_tuple, window_data, importance_map_): + window_shape = window_data.shape[2:] + seg_shape = seg_prob_tuple[0].shape[2:] + + window_pad_size = [] + window_pad_slices = [] + for window_s, output_s in zip(window_shape, seg_shape): + pad_width = max(window_s - output_s, 0) + pad_half_1 = pad_width // 2 + pad_half_2 = pad_width - pad_half_1 + window_pad_size.extend([pad_half_1, pad_half_2]) + window_pad_slices.append(slice(pad_half_1, window_s - pad_half_2)) + + # Make the padding area of the importance map zero + importance_map = torch.zeros(window_shape, dtype=importance_map_.dtype, device=importance_map_.device) + importance_map[window_pad_slices] = importance_map_[window_pad_slices] + + seg_prob_tuple = tuple( + F.pad(seg_prob, pad=tuple(window_pad_size), mode=self.padding_mode, value=self.cval) + for seg_prob in seg_prob_tuple + ) + + return seg_prob_tuple, importance_map + + def __call__( + self, + inputs: torch.Tensor, + network: Callable[..., torch.Tensor | Sequence[torch.Tensor] | dict[Any, torch.Tensor]], + *args: Any, + **kwargs: Any, + ) -> torch.Tensor | tuple[torch.Tensor, ...] | dict[Any, torch.Tensor]: + """ + + Args: + inputs: model input data for inference. + network: target model to execute inference. + supports callables such as ``lambda x: my_torch_model(x, additional_config)`` + args: optional args to be passed to ``network``. + kwargs: optional keyword args to be passed to ``network``. + + """ + + device = self.device + if device is None and self.cpu_thresh is not None and inputs.shape[2:].numel() > self.cpu_thresh: + device = "cpu" # stitch in cpu memory if image is too large + + if self.extra_input_padding: + image_size_original = inputs.shape[2:] + num_spatial_dims = len(image_size_original) + inputs = F.pad( + inputs, + pad=tuple(self.extra_input_padding), + mode=look_up_option(self.padding_mode, PytorchPadMode), + value=self.cval, + ) + + results = sliding_window_inference( + inputs, + self.roi_size, + self.sw_batch_size, + network, + self.overlap, + self.mode, + self.sigma_scale, + self.padding_mode, + self.cval, + self.sw_device, + device, + self.progress, + self.roi_weight_map, + self.process_output, + self.buffer_steps, + self.buffer_dim, + False, + *args, + **kwargs, + ) + + if self.extra_input_padding: + extra_slicing: list[slice] = [] + num_padded_dims = len(self.extra_input_padding) // 2 + for sp in range(num_padded_dims): + slice_dim = slice( + self.extra_input_padding[sp * 2], + image_size_original[num_spatial_dims - sp - 1] + self.extra_input_padding[sp * 2], + ) + extra_slicing.insert(0, slice_dim) + for _ in range(len(inputs.shape) - num_padded_dims): + extra_slicing.insert(0, slice(None)) + + if isinstance(results, dict): + for k, v in results.items(): + results[k] = v[extra_slicing] + elif isinstance(results, (list, tuple)): + results = type(results)([res[extra_slicing] for res in results]) + elif isinstance(results, (torch.Tensor, np.ndarray)): + results = results[extra_slicing] + else: + raise ValueError( + f"The output [{type(results)}] should be either dict, list, tuple, torch.Tensor, or numpy array." + ) + + return results diff --git a/source_code/SegMamba/monai/apps/pathology/transforms/post/array.py b/source_code/SegMamba/monai/apps/pathology/transforms/post/array.py new file mode 100644 index 0000000000000000000000000000000000000000..99e94f89c088ff3a216427c22649e304bc4da78b --- /dev/null +++ b/source_code/SegMamba/monai/apps/pathology/transforms/post/array.py @@ -0,0 +1,837 @@ +# Copyright (c) MONAI Consortium +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from __future__ import annotations + +import warnings +from typing import Callable, Sequence + +import numpy as np +import torch + +from monai.config.type_definitions import DtypeLike, NdarrayOrTensor +from monai.transforms import ( + Activations, + AsDiscrete, + BoundingRect, + FillHoles, + GaussianSmooth, + RemoveSmallObjects, + SobelGradients, +) +from monai.transforms.transform import Transform +from monai.transforms.utils_pytorch_numpy_unification import max, maximum, min, sum, unique +from monai.utils import TransformBackends, convert_to_numpy, optional_import +from monai.utils.misc import ensure_tuple_rep +from monai.utils.type_conversion import convert_to_dst_type, convert_to_tensor + +label, _ = optional_import("scipy.ndimage.measurements", name="label") +disk, _ = optional_import("skimage.morphology", name="disk") +opening, _ = optional_import("skimage.morphology", name="opening") +watershed, _ = optional_import("skimage.segmentation", name="watershed") +find_contours, _ = optional_import("skimage.measure", name="find_contours") +centroid, _ = optional_import("skimage.measure", name="centroid") + +__all__ = [ + "Watershed", + "GenerateWatershedMask", + "GenerateInstanceBorder", + "GenerateDistanceMap", + "GenerateWatershedMarkers", + "GenerateSuccinctContour", + "GenerateInstanceContour", + "GenerateInstanceCentroid", + "GenerateInstanceType", + "HoVerNetInstanceMapPostProcessing", + "HoVerNetNuclearTypePostProcessing", +] + + +class Watershed(Transform): + """ + Use `skimage.segmentation.watershed` to get instance segmentation results from images. + See: https://scikit-image.org/docs/stable/api/skimage.segmentation.html#skimage.segmentation.watershed. + + Args: + connectivity: an array with the same number of dimensions as image whose non-zero elements indicate + neighbors for connection. Following the scipy convention, default is a one-connected array of + the dimension of the image. + dtype: target data content type to convert, default is np.int64. + + """ + + backend = [TransformBackends.NUMPY] + + def __init__(self, connectivity: int | None = 1, dtype: DtypeLike = np.int64) -> None: + self.connectivity = connectivity + self.dtype = dtype + + def __call__( + self, image: NdarrayOrTensor, mask: NdarrayOrTensor | None = None, markers: NdarrayOrTensor | None = None + ) -> NdarrayOrTensor: + """ + Args: + image: image where the lowest value points are labeled first. Shape must be [1, H, W, [D]]. + mask: optional, the same shape as image. Only points at which mask == True will be labeled. + If None (no mask given), it is a volume of all 1s. + markers: optional, the same shape as image. The desired number of markers, or an array marking + the basins with the values to be assigned in the label matrix. Zero means not a marker. + If None (no markers given), the local minima of the image are used as markers. + """ + + image = convert_to_numpy(image) + markers = convert_to_numpy(markers) + mask = convert_to_numpy(mask) + + instance_seg = watershed(image, markers=markers, mask=mask, connectivity=self.connectivity) + + return convert_to_dst_type(instance_seg, image, dtype=self.dtype)[0] + + +class GenerateWatershedMask(Transform): + """ + generate mask used in `watershed`. Only points at which mask == True will be labeled. + + Args: + activation: the activation layer to be applied on the input probability map. + It can be "softmax" or "sigmoid" string, or any callable. Defaults to "softmax". + threshold: an optional float value to threshold to binarize probability map. + If not provided, defaults to 0.5 when activation is not "softmax", otherwise None. + min_object_size: objects smaller than this size (in pixel) are removed. Defaults to 10. + dtype: target data content type to convert, default is np.uint8. + + """ + + backend = [TransformBackends.NUMPY] + + def __init__( + self, + activation: str | Callable = "softmax", + threshold: float | None = None, + min_object_size: int = 10, + dtype: DtypeLike = np.uint8, + ) -> None: + self.dtype = dtype + + # set activation layer + use_softmax = False + use_sigmoid = False + activation_fn = None + if isinstance(activation, str): + if activation.lower() == "softmax": + use_softmax = True + elif activation.lower() == "sigmoid": + use_sigmoid = True + else: + raise ValueError( + f"The activation should be 'softmax' or 'sigmoid' string, or any callable. '{activation}' was given." + ) + elif callable(activation): + activation_fn = activation + else: + raise ValueError(f"The activation type should be either str or callable. '{type(activation)}' was given.") + self.activation = Activations(softmax=use_softmax, sigmoid=use_sigmoid, other=activation_fn) + + # set discretization transform + if not use_softmax and threshold is None: + threshold = 0.5 + self.as_discrete = AsDiscrete(threshold=threshold, argmax=use_softmax) + + # set small object removal transform + self.remove_small_objects = RemoveSmallObjects(min_size=min_object_size) if min_object_size > 0 else None + + def __call__(self, prob_map: NdarrayOrTensor) -> NdarrayOrTensor: + """ + Args: + prob_map: probability map of segmentation, shape must be [C, H, W, [D]] + """ + + pred = self.activation(prob_map) + pred = self.as_discrete(pred) + + pred = convert_to_numpy(pred) + + pred = label(pred)[0] + if self.remove_small_objects is not None: + pred = self.remove_small_objects(pred) + pred[pred > 0] = 1 + + return convert_to_dst_type(pred, prob_map, dtype=self.dtype)[0] + + +class GenerateInstanceBorder(Transform): + """ + Generate instance border by hover map. The more parts of the image that cannot be identified as foreground areas, + the larger the grey scale value. The grey value of the instance's border will be larger. + + Args: + kernel_size: the size of the Sobel kernel. Defaults to 5. + dtype: target data type to convert to. Defaults to np.float32. + + + Raises: + ValueError: when the `mask` shape is not [1, H, W]. + ValueError: when the `hover_map` shape is not [2, H, W]. + + """ + + backend = [TransformBackends.NUMPY] + + def __init__(self, kernel_size: int = 5, dtype: DtypeLike = np.float32) -> None: + self.dtype = dtype + self.sobel_gradient = SobelGradients(kernel_size=kernel_size) + + def __call__(self, mask: NdarrayOrTensor, hover_map: NdarrayOrTensor) -> NdarrayOrTensor: # type: ignore + """ + Args: + mask: binary segmentation map, the output of :py:class:`GenerateWatershedMask`. + Shape must be [1, H, W] or [H, W]. + hover_map: horizontal and vertical distances of nuclear pixels to their centres of mass. Shape must be [2, H, W]. + The first and second channel represent the horizontal and vertical maps respectively. For more details refer + to papers: https://arxiv.org/abs/1812.06499. + """ + if len(hover_map.shape) != 3: + raise ValueError(f"The hover map should have the shape of [C, H, W], but got {hover_map.shape}.") + if len(mask.shape) == 3: + if mask.shape[0] != 1: + raise ValueError(f"The mask should have only one channel, but got {mask.shape[0]}.") + elif len(mask.shape) == 2: + mask = mask[None] + else: + raise ValueError(f"The mask should have the shape of [1, H, W] or [H, W], but got {mask.shape}.") + if hover_map.shape[0] != 2: + raise ValueError(f"Suppose the hover map only has two channels, but got {hover_map.shape[0]}") + + hover_h = hover_map[0:1, ...] + hover_v = hover_map[1:2, ...] + + hover_h_min, hover_h_max = min(hover_h), max(hover_h) + hover_v_min, hover_v_max = min(hover_v), max(hover_v) + if (hover_h_max - hover_h_min) == 0 or (hover_v_max - hover_v_min) == 0: + raise ValueError("Not a valid hover map, please check your input") + hover_h = (hover_h - hover_h_min) / (hover_h_max - hover_h_min) + hover_v = (hover_v - hover_v_min) / (hover_v_max - hover_v_min) + sobelh = self.sobel_gradient(hover_h)[1, ...] + sobelv = self.sobel_gradient(hover_v)[0, ...] + sobelh_min, sobelh_max = min(sobelh), max(sobelh) + sobelv_min, sobelv_max = min(sobelv), max(sobelv) + if (sobelh_max - sobelh_min) == 0 or (sobelv_max - sobelv_min) == 0: + raise ValueError("Not a valid sobel gradient map") + sobelh = 1 - (sobelh - sobelh_min) / (sobelh_max - sobelh_min) + sobelv = 1 - (sobelv - sobelv_min) / (sobelv_max - sobelv_min) + + # combine the h & v values using max + overall = maximum(sobelh, sobelv) + overall = overall - (1 - mask) + overall[overall < 0] = 0 + + return convert_to_dst_type(overall, mask, dtype=self.dtype)[0] + + +class GenerateDistanceMap(Transform): + """ + Generate distance map. + In general, the instance map is calculated from the distance to the background. + Here, we use 1 - "instance border map" to generate the distance map. + Nuclei values form mountains so invert them to get basins. + + Args: + smooth_fn: smoothing function for distance map, which can be any callable object. + If not provided :py:class:`monai.transforms.GaussianSmooth()` is used. + dtype: target data type to convert to. Defaults to np.float32. + """ + + backend = [TransformBackends.NUMPY] + + def __init__(self, smooth_fn: Callable | None = None, dtype: DtypeLike = np.float32) -> None: + self.smooth_fn = smooth_fn if smooth_fn is not None else GaussianSmooth() + self.dtype = dtype + + def __call__(self, mask: NdarrayOrTensor, instance_border: NdarrayOrTensor) -> NdarrayOrTensor: # type: ignore + """ + Args: + mask: binary segmentation map, the output of :py:class:`GenerateWatershedMask`. + Shape must be [1, H, W] or [H, W]. + instance_border: instance border map, the output of :py:class:`GenerateInstanceBorder`. + Shape must be [1, H, W]. + """ + if len(mask.shape) == 3: + if mask.shape[0] != 1: + raise ValueError(f"The mask should have only one channel, but got {mask.shape[0]}.") + elif len(mask.shape) == 2: + mask = mask[None] + else: + raise ValueError(f"The mask should have the shape of [1, H, W] or [H, W], but got {mask.shape}.") + if instance_border.shape[0] != 1 or instance_border.ndim != 3: + raise ValueError(f"Input instance_border should be with size of [1, H, W], but got {instance_border.shape}") + + distance_map = (1.0 - instance_border) * mask + distance_map = self.smooth_fn(distance_map) # type: ignore + + return convert_to_dst_type(-distance_map, mask, dtype=self.dtype)[0] + + +class GenerateWatershedMarkers(Transform): + """ + Generate markers to be used in `watershed`. The watershed algorithm treats pixels values as a local topography + (elevation). The algorithm floods basins from the markers until basins attributed to different markers meet on + watershed lines. Generally, markers are chosen as local minima of the image, from which basins are flooded. + Here is the implementation from HoVerNet paper. + For more details refer to papers: https://arxiv.org/abs/1812.06499. + + Args: + threshold: a float value to threshold to binarize instance border map. + It turns uncertain area to 1 and other area to 0. Defaults to 0.4. + radius: the radius of the disk-shaped footprint used in `opening`. Defaults to 2. + min_object_size: objects smaller than this size (in pixel) are removed. Defaults to 10. + postprocess_fn: additional post-process function on the markers. + If not provided, :py:class:`monai.transforms.post.FillHoles()` will be used. + dtype: target data type to convert to. Defaults to np.int64. + + """ + + backend = [TransformBackends.NUMPY] + + def __init__( + self, + threshold: float = 0.4, + radius: int = 2, + min_object_size: int = 10, + postprocess_fn: Callable | None = None, + dtype: DtypeLike = np.int64, + ) -> None: + self.threshold = threshold + self.radius = radius + self.dtype = dtype + if postprocess_fn is None: + postprocess_fn = FillHoles() + + self.postprocess_fn = postprocess_fn + self.remove_small_objects = RemoveSmallObjects(min_size=min_object_size) if min_object_size > 0 else None + + def __call__(self, mask: NdarrayOrTensor, instance_border: NdarrayOrTensor) -> NdarrayOrTensor: # type: ignore + """ + Args: + mask: binary segmentation map, the output of :py:class:`GenerateWatershedMask`. + Shape must be [1, H, W] or [H, W]. + instance_border: instance border map, the output of :py:class:`GenerateInstanceBorder`. + Shape must be [1, H, W]. + """ + if len(mask.shape) == 3: + if mask.shape[0] != 1: + raise ValueError(f"The mask should have only one channel, but got {mask.shape[0]}.") + elif len(mask.shape) == 2: + mask = mask[None] + else: + raise ValueError(f"The mask should have the shape of [1, H, W] or [H, W], but got {mask.shape}.") + if instance_border.shape[0] != 1 or instance_border.ndim != 3: + raise ValueError(f"Input instance_border should be with size of [1, H, W], but got {instance_border.shape}") + + instance_border = instance_border >= self.threshold # uncertain area + + marker = mask - convert_to_dst_type(instance_border, mask)[0] # certain foreground + marker[marker < 0] = 0 + marker = self.postprocess_fn(marker) + marker = convert_to_numpy(marker) + + marker = opening(marker.squeeze(), disk(self.radius)) + marker = label(marker)[0][None] + if self.remove_small_objects is not None: + marker = self.remove_small_objects(marker) + + return convert_to_dst_type(marker, mask, dtype=self.dtype)[0] + + +class GenerateSuccinctContour(Transform): + """ + Converts SciPy-style contours (generated by skimage.measure.find_contours) to a more succinct version which only includes + the pixels to which lines need to be drawn (i.e. not the intervening pixels along each line). + + Args: + height: height of bounding box, used to detect direction of line segment. + width: width of bounding box, used to detect direction of line segment. + + Returns: + the pixels that need to be joined by straight lines to describe the outmost pixels of the foreground similar to + OpenCV's cv.CHAIN_APPROX_SIMPLE (counterclockwise) + """ + + def __init__(self, height: int, width: int) -> None: + self.height = height + self.width = width + + def _generate_contour_coord(self, current: np.ndarray, previous: np.ndarray) -> tuple[int, int]: + """ + Generate contour coordinates. Given the previous and current coordinates of border positions, + returns the int pixel that marks the extremity of the segmented pixels. + + Args: + current: coordinates of the current border position. + previous: coordinates of the previous border position. + """ + + p_delta = (current[0] - previous[0], current[1] - previous[1]) + + if p_delta in ((0.0, 1.0), (0.5, 0.5), (1.0, 0.0)): + row = int(current[0] + 0.5) + col = int(current[1]) + elif p_delta in ((0.0, -1.0), (0.5, -0.5)): + row = int(current[0]) + col = int(current[1]) + elif p_delta in ((-1, 0.0), (-0.5, -0.5)): + row = int(current[0]) + col = int(current[1] + 0.5) + elif p_delta == (-0.5, 0.5): + row = int(current[0] + 0.5) + col = int(current[1] + 0.5) + + return row, col + + def _calculate_distance_from_top_left(self, sequence: Sequence[tuple[int, int]]) -> int: + """ + Each sequence of coordinates describes a boundary between foreground and background starting and ending at two sides + of the bounding box. To order the sequences correctly, we compute the distance from the top-left of the bounding box + around the perimeter in a clockwise direction. + + Args: + sequence: list of border points coordinates. + + Returns: + the distance round the perimeter of the bounding box from the top-left origin + """ + distance: int + first_coord = sequence[0] + if first_coord[0] == 0: + distance = first_coord[1] + elif first_coord[1] == self.width - 1: + distance = self.width + first_coord[0] + elif first_coord[0] == self.height - 1: + distance = 2 * self.width + self.height - first_coord[1] + else: + distance = 2 * (self.width + self.height) - first_coord[0] + + return distance + + def __call__(self, contours: list[np.ndarray]) -> np.ndarray: + """ + Args: + contours: list of (n, 2)-ndarrays, scipy-style clockwise line segments, with lines separating foreground/background. + Each contour is an ndarray of shape (n, 2), consisting of n (row, column) coordinates along the contour. + """ + pixels: list[tuple[int, int]] = [] + sequences = [] + corners = [False, False, False, False] + + for group in contours: + sequence: list[tuple[int, int]] = [] + last_added = None + prev = None + corner = -1 + + for i, coord in enumerate(group): + if i == 0: + # originating from the top, so must be heading south east + if coord[0] == 0.0: + corner = 1 + pixel = (0, int(coord[1] - 0.5)) + if pixel[1] == self.width - 1: + corners[1] = True + elif pixel[1] == 0.0: + corners[0] = True + # originating from the left, so must be heading north east + elif coord[1] == 0.0: + corner = 0 + pixel = (int(coord[0] + 0.5), 0) + # originating from the bottom, so must be heading north west + elif coord[0] == self.height - 1: + corner = 3 + pixel = (int(coord[0]), int(coord[1] + 0.5)) + if pixel[1] == self.width - 1: + corners[2] = True + # originating from the right, so must be heading south west + elif coord[1] == self.width - 1: + corner = 2 + pixel = (int(coord[0] - 0.5), int(coord[1])) + else: + warnings.warn(f"Invalid contour coord {coord} is generated, skip this instance.") + return None # type: ignore + sequence.append(pixel) + last_added = pixel + elif i == len(group) - 1: + # add this point + pixel = self._generate_contour_coord(coord, prev) # type: ignore + if pixel != last_added: + sequence.append(pixel) + last_added = pixel + elif np.any(coord - prev != group[i + 1] - coord): + pixel = self._generate_contour_coord(coord, prev) # type: ignore + if pixel != last_added: + sequence.append(pixel) + last_added = pixel + + # flag whether each corner has been crossed + if i == len(group) - 1: + if corner == 0: + if coord[0] == 0: + corners[corner] = True + elif corner == 1: + if coord[1] == self.width - 1: + corners[corner] = True + elif corner == 2: + if coord[0] == self.height - 1: + corners[corner] = True + elif corner == 3: + if coord[1] == 0.0: + corners[corner] = True + + prev = coord + dist = self._calculate_distance_from_top_left(sequence) + + sequences.append({"distance": dist, "sequence": sequence}) + + # check whether we need to insert any missing corners + if corners[0] is False: + sequences.append({"distance": 0, "sequence": [(0, 0)]}) + if corners[1] is False: + sequences.append({"distance": self.width, "sequence": [(0, self.width - 1)]}) + if corners[2] is False: + sequences.append({"distance": self.width + self.height, "sequence": [(self.height - 1, self.width - 1)]}) + if corners[3] is False: + sequences.append({"distance": 2 * self.width + self.height, "sequence": [(self.height - 1, 0)]}) + + # join the sequences into a single contour + # starting at top left and rotating clockwise + sequences.sort(key=lambda x: x.get("distance")) # type: ignore + + last = (-1, -1) + for _sequence in sequences: + if _sequence["sequence"][0] == last: # type: ignore + pixels.pop() + if pixels: + pixels = [*pixels, *_sequence["sequence"]] # type: ignore + else: + pixels = _sequence["sequence"] # type: ignore + last = pixels[-1] + + if pixels[0] == last: + pixels.pop(0) + + if pixels[0] == (0, 0): + pixels.append(pixels.pop(0)) + + return np.flip(convert_to_numpy(pixels, dtype=np.int32)) # type: ignore + + +class GenerateInstanceContour(Transform): + """ + Generate contour for each instance in a 2D array. Use `GenerateSuccinctContour` to only include + the pixels to which lines need to be drawn + + Args: + min_num_points: assumed that the created contour does not form a contour if it does not contain more points + than the specified value. Defaults to 3. + contour_level: an optional value for `skimage.measure.find_contours` to find contours in the array. + If not provided, the level is set to `(max(image) + min(image)) / 2`. + + """ + + backend = [TransformBackends.NUMPY] + + def __init__(self, min_num_points: int = 3, contour_level: float | None = None) -> None: + self.contour_level = contour_level + self.min_num_points = min_num_points + + def __call__(self, inst_mask: NdarrayOrTensor, offset: Sequence[int] | None = (0, 0)) -> np.ndarray | None: + """ + Args: + inst_mask: segmentation mask for a single instance. Shape should be [1, H, W, [D]] + offset: optional offset of starting position of the instance mask in the original array. Default to 0 for each dim. + """ + inst_mask = inst_mask.squeeze() # squeeze channel dim + inst_mask = convert_to_numpy(inst_mask) + inst_contour_cv = find_contours(inst_mask, level=self.contour_level) + generate_contour = GenerateSuccinctContour(inst_mask.shape[0], inst_mask.shape[1]) + inst_contour = generate_contour(inst_contour_cv) + if inst_contour is None: + return None + # less than `self.min_num_points` points don't make a contour, so skip. + # They are likely to be artifacts as the contours obtained via approximation. + if inst_contour.shape[0] < self.min_num_points: + print(f"< {self.min_num_points} points don't make a contour, so skipped!") + return None + # check for tricky shape + elif len(inst_contour.shape) != 2: + print(f"{len(inst_contour.shape)} != 2, check for tricky shapes!") + return None + else: + inst_contour[:, 0] += offset[0] # type: ignore + inst_contour[:, 1] += offset[1] # type: ignore + return inst_contour + + +class GenerateInstanceCentroid(Transform): + """ + Generate instance centroid using `skimage.measure.centroid`. + + Args: + dtype: the data type of output centroid. + + """ + + backend = [TransformBackends.NUMPY] + + def __init__(self, dtype: DtypeLike | None = int) -> None: + self.dtype = dtype + + def __call__(self, inst_mask: NdarrayOrTensor, offset: Sequence[int] | int = 0) -> NdarrayOrTensor: + """ + Args: + inst_mask: segmentation mask for a single instance. Shape should be [1, H, W, [D]] + offset: optional offset of starting position of the instance mask in the original array. Default to 0 for each dim. + + """ + inst_mask = convert_to_numpy(inst_mask) + inst_mask = inst_mask.squeeze(0) # squeeze channel dim + ndim = len(inst_mask.shape) + offset = ensure_tuple_rep(offset, ndim) + + inst_centroid = centroid(inst_mask) + for i in range(ndim): + inst_centroid[i] += offset[i] + + return convert_to_dst_type(inst_centroid, inst_mask, dtype=self.dtype)[0] + + +class GenerateInstanceType(Transform): + """ + Generate instance type and probability for each instance. + """ + + backend = [TransformBackends.NUMPY] + + def __call__( # type: ignore + self, type_pred: NdarrayOrTensor, seg_pred: NdarrayOrTensor, bbox: np.ndarray, instance_id: int + ) -> tuple[int, float]: + """ + Args: + type_pred: pixel-level type prediction map after activation function. + seg_pred: pixel-level segmentation prediction map after activation function. + bbox: bounding box coordinates of the instance, shape is [channel, 2 * spatial dims]. + instance_id: get instance type from specified instance id. + """ + + rmin, rmax, cmin, cmax = bbox.flatten() + seg_map_crop = seg_pred[0, rmin:rmax, cmin:cmax] + type_map_crop = type_pred[0, rmin:rmax, cmin:cmax] + + seg_map_crop = convert_to_dst_type(seg_map_crop == instance_id, type_map_crop, dtype=bool)[0] + + inst_type = type_map_crop[seg_map_crop] + type_list, type_pixels = unique(inst_type, return_counts=True) + type_list = list(zip(type_list, type_pixels)) + type_list = sorted(type_list, key=lambda x: x[1], reverse=True) + inst_type = type_list[0][0] + if inst_type == 0: # ! pick the 2nd most dominant if exist + if len(type_list) > 1: + inst_type = type_list[1][0] + type_dict = {v[0]: v[1] for v in type_list} + type_prob = type_dict[inst_type] / (sum(seg_map_crop) + 1.0e-6) + + return (int(inst_type), float(type_prob)) + + +class HoVerNetInstanceMapPostProcessing(Transform): + """ + The post-processing transform for HoVerNet model to generate instance segmentation map. + It generates an instance segmentation map as well as a dictionary containing centroids, bounding boxes, and contours + for each instance. + + Args: + activation: the activation layer to be applied on the input probability map. + It can be "softmax" or "sigmoid" string, or any callable. Defaults to "softmax". + mask_threshold: a float value to threshold to binarize probability map to generate mask. + min_object_size: objects smaller than this size (in pixel) are removed. Defaults to 10. + sobel_kernel_size: the size of the Sobel kernel used in :py:class:`GenerateInstanceBorder`. Defaults to 5. + distance_smooth_fn: smoothing function for distance map. + If not provided, :py:class:`monai.transforms.intensity.GaussianSmooth()` will be used. + marker_threshold: a float value to threshold to binarize instance border map for markers. + It turns uncertain area to 1 and other area to 0. Defaults to 0.4. + marker_radius: the radius of the disk-shaped footprint used in `opening` of markers. Defaults to 2. + marker_postprocess_fn: post-process function for watershed markers. + If not provided, :py:class:`monai.transforms.post.FillHoles()` will be used. + watershed_connectivity: `connectivity` argument of `skimage.segmentation.watershed`. + min_num_points: minimum number of points to be considered as a contour. Defaults to 3. + contour_level: an optional value for `skimage.measure.find_contours` to find contours in the array. + If not provided, the level is set to `(max(image) + min(image)) / 2`. + device: target device to put the output Tensor data. + """ + + def __init__( + self, + activation: str | Callable = "softmax", + mask_threshold: float | None = None, + min_object_size: int = 10, + sobel_kernel_size: int = 5, + distance_smooth_fn: Callable | None = None, + marker_threshold: float = 0.4, + marker_radius: int = 2, + marker_postprocess_fn: Callable | None = None, + watershed_connectivity: int | None = 1, + min_num_points: int = 3, + contour_level: float | None = None, + device: str | torch.device | None = None, + ) -> None: + super().__init__() + self.device = device + self.generate_watershed_mask = GenerateWatershedMask( + activation=activation, threshold=mask_threshold, min_object_size=min_object_size + ) + self.generate_instance_border = GenerateInstanceBorder(kernel_size=sobel_kernel_size) + self.generate_distance_map = GenerateDistanceMap(smooth_fn=distance_smooth_fn) + self.generate_watershed_markers = GenerateWatershedMarkers( + threshold=marker_threshold, + radius=marker_radius, + postprocess_fn=marker_postprocess_fn, + min_object_size=min_object_size, + ) + self.watershed = Watershed(connectivity=watershed_connectivity) + self.generate_instance_contour = GenerateInstanceContour( + min_num_points=min_num_points, contour_level=contour_level + ) + self.generate_instance_centroid = GenerateInstanceCentroid() + + def __call__( # type: ignore + self, nuclear_prediction: NdarrayOrTensor, hover_map: NdarrayOrTensor + ) -> tuple[dict, NdarrayOrTensor]: + """post-process instance segmentation branches (NP and HV) to generate instance segmentation map. + + Args: + nuclear_prediction: the output of NP (nuclear prediction) branch of HoVerNet model + hover_map: the output of HV (hover map) branch of HoVerNet model + """ + + # Process NP and HV branch using watershed algorithm + watershed_mask = self.generate_watershed_mask(nuclear_prediction) + instance_borders = self.generate_instance_border(watershed_mask, hover_map) + distance_map = self.generate_distance_map(watershed_mask, instance_borders) + watershed_markers = self.generate_watershed_markers(watershed_mask, instance_borders) + instance_map = self.watershed(distance_map, watershed_mask, watershed_markers) + + # Create bounding boxes, contours and centroids + instance_ids = set(np.unique(instance_map)) - {0} # exclude background + instance_info = {} + for inst_id in instance_ids: + instance_mask = instance_map == inst_id + instance_bbox = BoundingRect()(instance_mask) + + instance_mask = instance_mask[ + :, instance_bbox[0][0] : instance_bbox[0][1], instance_bbox[0][2] : instance_bbox[0][3] + ] + offset = [instance_bbox[0][2], instance_bbox[0][0]] + instance_contour = self.generate_instance_contour(FillHoles()(instance_mask), offset) + if instance_contour is not None: + instance_centroid = self.generate_instance_centroid(instance_mask, offset) + instance_info[inst_id] = { + "bounding_box": instance_bbox, + "centroid": instance_centroid, + "contour": instance_contour, + } + instance_map = convert_to_tensor(instance_map, device=self.device) + return instance_info, instance_map + + +class HoVerNetNuclearTypePostProcessing(Transform): + """ + The post-processing transform for HoVerNet model to generate nuclear type information. + It updates the input instance info dictionary with information about types of the nuclei (value and probability). + Also if requested (`return_type_map=True`), it generates a pixel-level type map. + + Args: + activation: the activation layer to be applied on nuclear type branch. It can be "softmax" or "sigmoid" string, + or any callable. Defaults to "softmax". + threshold: an optional float value to threshold to binarize probability map. + If not provided, defaults to 0.5 when activation is not "softmax", otherwise None. + return_type_map: whether to calculate and return pixel-level type map. + device: target device to put the output Tensor data. + + """ + + def __init__( + self, + activation: str | Callable = "softmax", + threshold: float | None = None, + return_type_map: bool = True, + device: str | torch.device | None = None, + ) -> None: + super().__init__() + self.device = device + self.return_type_map = return_type_map + self.generate_instance_type = GenerateInstanceType() + + # set activation layer + use_softmax = False + use_sigmoid = False + activation_fn = None + if isinstance(activation, str): + if activation.lower() == "softmax": + use_softmax = True + elif activation.lower() == "sigmoid": + use_sigmoid = True + else: + raise ValueError( + f"The activation should be 'softmax' or 'sigmoid' string, or any callable. '{activation}' was given." + ) + elif callable(activation): + activation_fn = activation + else: + raise ValueError(f"The activation type should be either str or callable. '{type(activation)}' was given.") + self.activation = Activations(softmax=use_softmax, sigmoid=use_sigmoid, other=activation_fn) + + # set discretization transform + if not use_softmax and threshold is None: + threshold = 0.5 + self.as_discrete = AsDiscrete(threshold=threshold, argmax=use_softmax) + + def __call__( # type: ignore + self, type_prediction: NdarrayOrTensor, instance_info: dict[int, dict], instance_map: NdarrayOrTensor + ) -> tuple[dict, NdarrayOrTensor | None]: + """Process NC (type prediction) branch and combine it with instance segmentation + It updates the instance_info with instance type and associated probability, and generate instance type map. + + Args: + instance_info: instance information dictionary, the output of :py:class:`HoVerNetInstanceMapPostProcessing` + instance_map: instance segmentation map, the output of :py:class:`HoVerNetInstanceMapPostProcessing` + type_prediction: the output of NC (type prediction) branch of HoVerNet model + """ + type_prediction = self.activation(type_prediction) + type_prediction = self.as_discrete(type_prediction) + + type_map = None + if self.return_type_map: + type_map = convert_to_dst_type(torch.zeros(instance_map.shape), instance_map)[0] + + for inst_id in instance_info: + instance_type, instance_type_prob = self.generate_instance_type( + type_pred=type_prediction, + seg_pred=instance_map, + bbox=instance_info[inst_id]["bounding_box"], + instance_id=inst_id, + ) + # update instance info dict with type data + instance_info[inst_id]["type_prob"] = instance_type_prob + instance_info[inst_id]["type"] = instance_type + + # update instance type map + if type_map is not None: + type_map[instance_map == inst_id] = instance_type + type_map = convert_to_tensor(type_map, device=self.device) + + return instance_info, type_map diff --git a/source_code/SegMamba/monai/apps/reconstruction/__init__.py b/source_code/SegMamba/monai/apps/reconstruction/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..1e97f8940782e96a77c1c08483fc41da9a48ae22 --- /dev/null +++ b/source_code/SegMamba/monai/apps/reconstruction/__init__.py @@ -0,0 +1,10 @@ +# Copyright (c) MONAI Consortium +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. diff --git a/source_code/SegMamba/monai/apps/reconstruction/networks/blocks/varnetblock.py b/source_code/SegMamba/monai/apps/reconstruction/networks/blocks/varnetblock.py new file mode 100644 index 0000000000000000000000000000000000000000..75dc7e15ce97124e05f1c44b8251769b60e080c5 --- /dev/null +++ b/source_code/SegMamba/monai/apps/reconstruction/networks/blocks/varnetblock.py @@ -0,0 +1,81 @@ +# Copyright (c) MONAI Consortium +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from __future__ import annotations + +import torch +import torch.nn as nn +from torch import Tensor + +from monai.apps.reconstruction.networks.nets.utils import sensitivity_map_expand, sensitivity_map_reduce + + +class VarNetBlock(nn.Module): + """ + A variational block based on Sriram et. al., "End-to-end variational networks for accelerated MRI reconstruction". + It applies data consistency and refinement to the intermediate kspace and combines those results. + + Modified and adopted from: https://github.com/facebookresearch/fastMRI + + Args: + refinement_model: the model used for refinement (typically a U-Net but can be any deep learning model + that performs well when the input and output are in image domain (e.g., a convolutional network). + spatial_dims: is 2 for 2D data and is 3 for 3D data + """ + + def __init__(self, refinement_model: nn.Module, spatial_dims: int = 2): + super().__init__() + self.model = refinement_model + self.spatial_dims = spatial_dims + self.dc_weight = nn.Parameter(torch.ones(1)) # learned scalar as the multiplier of the DC block + + buffer_shape = [1 for _ in range(spatial_dims + 3)] # 3 denotes the batch, channel, and real/complex dimensions + self.register_buffer("zeros", torch.zeros(buffer_shape)) + + def soft_dc(self, x: Tensor, ref_kspace: Tensor, mask: Tensor) -> Tensor: + """ + Applies data consistency to input x. Suppose x is an intermediate estimate of the kspace and ref_kspace + is the reference under-sampled measurement. This function returns mask * (x - ref_kspace). View this as the + residual between the original under-sampled kspace and the estimate given by the network. + + Args: + x: 2D kspace (B,C,H,W,2) with the last dimension being 2 (for real/imaginary parts) and C denoting the + coil dimension. 3D data will have the shape (B,C,H,W,D,2). + ref_kspace: original under-sampled kspace with the same shape as x. + mask: the under-sampling mask with shape (1,1,1,W,1) for 2D data or (1,1,1,1,D,1) for 3D data. + + Returns: + Output of DC block with the same shape as x + """ + return torch.where(mask, x - ref_kspace, self.zeros) * self.dc_weight + + def forward(self, current_kspace: Tensor, ref_kspace: Tensor, mask: Tensor, sens_maps: Tensor) -> Tensor: + """ + Args: + current_kspace: Predicted kspace from the previous block. It's a 2D kspace (B,C,H,W,2) + with the last dimension being 2 (for real/imaginary parts) and C denoting the + coil dimension. 3D data will have the shape (B,C,H,W,D,2). + ref_kspace: reference kspace for applying data consistency (is the under-sampled kspace in MRI reconstruction). + Its shape is the same as current_kspace. + mask: the under-sampling mask with shape (1,1,1,W,1) for 2D data or (1,1,1,1,D,1) for 3D data. + sens_maps: coil sensitivity maps with the same shape as current_kspace + + Returns: + Output of VarNetBlock with the same shape as current_kspace + """ + dc_out = self.soft_dc(current_kspace, ref_kspace, mask) # output of DC block + refinement_out = sensitivity_map_expand( + self.model(sensitivity_map_reduce(current_kspace, sens_maps, spatial_dims=self.spatial_dims)), + sens_maps, + spatial_dims=self.spatial_dims, + ) # output of refinement model + output = current_kspace - dc_out - refinement_out + return output diff --git a/source_code/SegMamba/monai/apps/reconstruction/networks/nets/__init__.py b/source_code/SegMamba/monai/apps/reconstruction/networks/nets/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..1e97f8940782e96a77c1c08483fc41da9a48ae22 --- /dev/null +++ b/source_code/SegMamba/monai/apps/reconstruction/networks/nets/__init__.py @@ -0,0 +1,10 @@ +# Copyright (c) MONAI Consortium +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. diff --git a/source_code/SegMamba/monai/apps/reconstruction/networks/nets/coil_sensitivity_model.py b/source_code/SegMamba/monai/apps/reconstruction/networks/nets/coil_sensitivity_model.py new file mode 100644 index 0000000000000000000000000000000000000000..91a9f3d8d3e30b7f82ac78acc545c1349f0b53a5 --- /dev/null +++ b/source_code/SegMamba/monai/apps/reconstruction/networks/nets/coil_sensitivity_model.py @@ -0,0 +1,142 @@ +# Copyright (c) MONAI Consortium +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from __future__ import annotations + +from collections.abc import Sequence + +import torch +import torch.nn as nn +from torch import Tensor + +from monai.apps.reconstruction.mri_utils import root_sum_of_squares_t +from monai.apps.reconstruction.networks.nets.complex_unet import ComplexUnet +from monai.apps.reconstruction.networks.nets.utils import ( + reshape_batch_channel_to_channel_dim, + reshape_channel_to_batch_dim, +) +from monai.networks.blocks.fft_utils_t import ifftn_centered_t + + +class CoilSensitivityModel(nn.Module): + """ + This class uses a convolutional model to learn coil sensitivity maps for multi-coil MRI reconstruction. + The convolutional model is :py:class:`monai.apps.reconstruction.networks.nets.complex_unet` by default + but can be specified by the user as well. Learning is done on the center of the under-sampled + kspace (that region is fully sampled). + + The data being a (complex) 2-channel tensor is a requirement for using this model. + + Modified and adopted from: https://github.com/facebookresearch/fastMRI + + Args: + spatial_dims: number of spatial dimensions. + features: six integers as numbers of features. denotes number of channels in each layer. + act: activation type and arguments. Defaults to LeakyReLU. + norm: feature normalization type and arguments. Defaults to instance norm. + bias: whether to have a bias term in convolution blocks. Defaults to True. + dropout: dropout ratio. Defaults to 0.0. + upsample: upsampling mode, available options are + ``"deconv"``, ``"pixelshuffle"``, ``"nontrainable"``. + coil_dim: coil dimension in the data + conv_net: the learning model used to estimate the coil sensitivity maps. default + is :py:class:`monai.apps.reconstruction.networks.nets.complex_unet`. The only + requirement on the model is to have 2 as input and output number of channels. + """ + + def __init__( + self, + spatial_dims: int = 2, + features: Sequence[int] = (32, 32, 64, 128, 256, 32), + act: str | tuple = ("LeakyReLU", {"negative_slope": 0.1, "inplace": True}), + norm: str | tuple = ("instance", {"affine": True}), + bias: bool = True, + dropout: float | tuple = 0.0, + upsample: str = "deconv", + coil_dim: int = 1, + conv_net: nn.Module | None = None, + ): + super().__init__() + if conv_net is None: + self.conv_net = ComplexUnet( + spatial_dims=spatial_dims, + features=features, + act=act, + norm=norm, + bias=bias, + dropout=dropout, + upsample=upsample, + ) + else: + # assume the first layer is convolutional and + # check whether in_channels == 2 + params = [p.shape for p in conv_net.parameters()] + if params[0][1] != 2: + raise ValueError(f"in_channels should be 2 but it's {params[0][1]}.") + self.conv_net = conv_net # type: ignore + self.spatial_dims = spatial_dims + self.coil_dim = coil_dim + + def get_fully_sampled_region(self, mask: Tensor) -> tuple[int, int]: + """ + Extracts the size of the fully-sampled part of the kspace. Note that when a kspace + is under-sampled, a part of its center is fully sampled. This part is called the Auto + Calibration Region (ACR). ACR is used for sensitivity map computation. + + Args: + mask: the under-sampling mask of shape (..., S, 1) where S denotes the sampling dimension + + Returns: + A tuple containing + (1) left index of the region + (2) right index of the region + + Note: + Suppose the mask is of shape (1,1,20,1). If this function returns 8,12 as left and right + indices, then it means that the fully-sampled center region has size 4 starting from 8 to 12. + """ + left = right = mask.shape[-2] // 2 + while mask[..., right, :]: + right += 1 + + while mask[..., left, :]: + left -= 1 + + return left + 1, right + + def forward(self, masked_kspace: Tensor, mask: Tensor) -> Tensor: + """ + Args: + masked_kspace: the under-sampled kspace (which is the input measurement). Its shape + is (B,C,H,W,2) for 2D data or (B,C,H,W,D,2) for 3D data. + mask: the under-sampling mask with shape (1,1,1,W,1) for 2D data or (1,1,1,1,D,1) for 3D data. + + Returns: + predicted coil sensitivity maps with shape (B,C,H,W,2) for 2D data or (B,C,H,W,D,2) for 3D data. + """ + left, right = self.get_fully_sampled_region(mask) + num_low_freqs = right - left # size of the fully-sampled center + + # take out the fully-sampled region and set the rest of the data to zero + x = torch.zeros_like(masked_kspace) + start = (mask.shape[-2] - num_low_freqs + 1) // 2 # this marks the start of center extraction + x[..., start : start + num_low_freqs, :] = masked_kspace[..., start : start + num_low_freqs, :] + + # apply inverse fourier to the extracted fully-sampled data + x = ifftn_centered_t(x, spatial_dims=self.spatial_dims, is_complex=True) + + x, b = reshape_channel_to_batch_dim(x) # shape of x will be (B*C,1,...) + x = self.conv_net(x) + x = reshape_batch_channel_to_channel_dim(x, b) # shape will be (B,C,...) + # normalize the maps + x = x / root_sum_of_squares_t(x, spatial_dim=self.coil_dim).unsqueeze(self.coil_dim) + + return x diff --git a/source_code/SegMamba/monai/csrc/filtering/bilateral/bilateral.cpp b/source_code/SegMamba/monai/csrc/filtering/bilateral/bilateral.cpp new file mode 100644 index 0000000000000000000000000000000000000000..183e13bb239f345dd54017061f3aca067469ae3c --- /dev/null +++ b/source_code/SegMamba/monai/csrc/filtering/bilateral/bilateral.cpp @@ -0,0 +1,49 @@ +/* +Copyright (c) MONAI Consortium +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + http://www.apache.org/licenses/LICENSE-2.0 +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +#include +#include +#include + +#include "bilateral.h" +#include "utils/common_utils.h" + +torch::Tensor BilateralFilter(torch::Tensor input, float spatial_sigma, float color_sigma, bool usePHL) { + torch::Tensor (*filterFunction)(torch::Tensor, float, float); + +#ifdef WITH_CUDA + + if (torch::cuda::is_available() && input.is_cuda()) { + CHECK_CONTIGUOUS_CUDA(input); + + if (input.size(1) > BF_CUDA_MAX_CHANNELS) { + throw std::runtime_error( + "Bilateral filtering not implemented for channel count > " + std::to_string(BF_CUDA_MAX_CHANNELS)); + } + + if (input.dim() - 2 > BF_CUDA_MAX_SPATIAL_DIMENSION) { + throw std::runtime_error( + "Bilateral filtering not implemented for spatial dimension > " + + std::to_string(BF_CUDA_MAX_SPATIAL_DIMENSION)); + } + + filterFunction = usePHL ? &BilateralFilterPHLCuda : &BilateralFilterCuda; + } else { + filterFunction = usePHL ? &BilateralFilterPHLCpu : &BilateralFilterCpu; + } +#else + filterFunction = usePHL ? &BilateralFilterPHLCpu : &BilateralFilterCpu; +#endif + + return filterFunction(input, spatial_sigma, color_sigma); +} diff --git a/source_code/SegMamba/monai/csrc/filtering/bilateral/bilateralfilter_cpu.cpp b/source_code/SegMamba/monai/csrc/filtering/bilateral/bilateralfilter_cpu.cpp new file mode 100644 index 0000000000000000000000000000000000000000..39f6d99a8c0e09ca0d60452a40dc2f88118c0429 --- /dev/null +++ b/source_code/SegMamba/monai/csrc/filtering/bilateral/bilateralfilter_cpu.cpp @@ -0,0 +1,136 @@ +/* +Copyright (c) MONAI Consortium +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + http://www.apache.org/licenses/LICENSE-2.0 +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +#include +#include + +#include "utils/tensor_description.h" +#include "utils/tensor_indexing.h" + +template +void BilateralFilterCpu(torch::Tensor inputTensor, torch::Tensor outputTensor, float spatialSigma, float colorSigma) { + // Getting tensor description. + TensorDescription desc = TensorDescription(inputTensor); + + // Raw tensor data pointers. + scalar_t* inputTensorData = inputTensor.data_ptr(); + scalar_t* outputTensorData = outputTensor.data_ptr(); + + // Pre-calculate common values + int windowSize = (int)ceil(5.0f * spatialSigma) | 1; // ORing last bit to ensure odd window size + int halfWindowSize = floor(0.5f * windowSize); + scalar_t spatialExpConstant = -1.0f / (2 * spatialSigma * spatialSigma); + scalar_t colorExpConstant = -1.0f / (2 * colorSigma * colorSigma); + + // Kernel sizes. + int* kernelSizes = new int[desc.dimensions]; + + for (int i = 0; i < desc.dimensions; i++) { + kernelSizes[i] = windowSize; + } + + // Pre-calculate gaussian kernel in 1D. + scalar_t* gaussianKernel = new scalar_t[windowSize]; + + for (int i = 0; i < windowSize; i++) { + int distance = i - halfWindowSize; + gaussianKernel[i] = exp(distance * distance * spatialExpConstant); + } + + // Kernel aggregates used to calculate + // the output value. + scalar_t* valueSum = new scalar_t[desc.channelCount]; + scalar_t weightSum = 0; + + // Looping over the batches + for (int b = 0; b < desc.batchCount; b++) { + int batchOffset = b * desc.batchStride; + + // Looping over all dimensions for the home element + Indexer homeIndex = Indexer(desc.dimensions, desc.sizes); + do // while(homeIndex++) + { + // Calculating indexing offset for the home element + int homeOffset = batchOffset; + + for (int i = 0; i < desc.dimensions; i++) { + homeOffset += homeIndex[i] * desc.strides[i]; + } + + // Zero kernel aggregates. + for (int i = 0; i < desc.channelCount; i++) { + valueSum[i] = 0; + } + + weightSum = 0.0f; + + // Looping over all dimensions for the neighbour element + Indexer kernelIndex = Indexer(desc.dimensions, kernelSizes); + do // while(kernelIndex++) + { + // Calculating buffer offset for the neighbour element + // Index is clamped to the border in each dimension. + int neighbourOffset = batchOffset; + + for (int i = 0; i < desc.dimensions; i++) { + int neighbourIndex = homeIndex[i] + kernelIndex[i] - halfWindowSize; + int neighbourIndexClamped = std::min(desc.sizes[i] - 1, std::max(0, neighbourIndex)); + neighbourOffset += neighbourIndexClamped * desc.strides[i]; + } + + // Euclidean color distance. + scalar_t colorDistanceSquared = 0; + + for (int i = 0; i < desc.channelCount; i++) { + scalar_t diff = inputTensorData[homeOffset + i * desc.channelStride] - + inputTensorData[neighbourOffset + i * desc.channelStride]; + colorDistanceSquared += diff * diff; + } + + // Calculating and combining the spatial + // and color weights. + scalar_t spatialWeight = 1; + + for (int i = 0; i < desc.dimensions; i++) { + spatialWeight *= gaussianKernel[kernelIndex[i]]; + } + + scalar_t colorWeight = exp(colorDistanceSquared * colorExpConstant); + scalar_t totalWeight = spatialWeight * colorWeight; + + // Aggregating values. + for (int i = 0; i < desc.channelCount; i++) { + valueSum[i] += inputTensorData[neighbourOffset + i * desc.channelStride] * totalWeight; + } + + weightSum += totalWeight; + } while (kernelIndex++); + + for (int i = 0; i < desc.channelCount; i++) { + outputTensorData[homeOffset + i * desc.channelStride] = valueSum[i] / weightSum; + } + } while (homeIndex++); + } +} + +torch::Tensor BilateralFilterCpu(torch::Tensor inputTensor, float spatialSigma, float colorSigma) { + // Preparing output tensor. + torch::Tensor outputTensor = torch::zeros_like(inputTensor); + + AT_DISPATCH_FLOATING_TYPES_AND_HALF(inputTensor.scalar_type(), "BilateralFilterCpu", ([&] { + BilateralFilterCpu( + inputTensor, outputTensor, spatialSigma, colorSigma); + })); + + return outputTensor; +} diff --git a/source_code/SegMamba/monai/csrc/filtering/bilateral/bilateralfilter_cpu_phl.cpp b/source_code/SegMamba/monai/csrc/filtering/bilateral/bilateralfilter_cpu_phl.cpp new file mode 100644 index 0000000000000000000000000000000000000000..ec28c05520cc4cfca338d65a8264da283b605dfd --- /dev/null +++ b/source_code/SegMamba/monai/csrc/filtering/bilateral/bilateralfilter_cpu_phl.cpp @@ -0,0 +1,88 @@ +/* +Copyright (c) MONAI Consortium +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + http://www.apache.org/licenses/LICENSE-2.0 +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +#include + +#include "filtering/permutohedral/permutohedral.h" +#include "utils/tensor_description.h" + +template +void BilateralFilterPHLCpu( + torch::Tensor inputTensor, + torch::Tensor outputTensor, + float spatialSigma, + float colorSigma) { + // Getting tensor description. + TensorDescription desc = TensorDescription(inputTensor); + + int featureChannels = desc.channelCount + desc.dimensions; + + // Preparing memory + scalar_t* inputTensorData = inputTensor.data_ptr(); + scalar_t* outputTensorData = outputTensor.data_ptr(); + scalar_t* data = new scalar_t[desc.channelStride * desc.channelCount]; + scalar_t* features = new scalar_t[desc.channelStride * featureChannels]; + + // Precalculating inverse sigmas + float invSpatialSigma = 1.0f / spatialSigma; + float invColorSigma = 1.0f / colorSigma; + + // Looping over batches + for (int b = 0; b < desc.batchCount; b++) { + int batchOffset = b * desc.batchStride; + + // Creating features (also permuting input data to be channel last. Permutohedral + // implementation should be changed to channel first to avoid this) + for (int i = 0; i < desc.channelStride; i++) { + // Color features (and permutation) + for (int c = 0; c < desc.channelCount; c++) { + features[i * featureChannels + c] = invColorSigma * inputTensorData[batchOffset + i + c * desc.channelStride]; + data[i * desc.channelCount + c] = inputTensorData[batchOffset + i + c * desc.channelStride]; + } + + // Spatial features + int offsetRemainder = i; + + for (int d = 0; d < desc.dimensions; d++) { + int coord = offsetRemainder / desc.strides[d]; + offsetRemainder -= coord * desc.strides[d]; + + features[i * featureChannels + desc.channelCount + d] = (scalar_t)invSpatialSigma * coord; + } + } + + // Filtering data with respect to the features. + PermutohedralCPU(data, features, desc.channelCount, featureChannels, desc.channelStride); + + // Writing output tensor. + for (int i = 0; i < desc.channelStride; i++) { + for (int c = 0; c < desc.channelCount; c++) { + outputTensorData[batchOffset + i + c * desc.channelStride] = data[i * desc.channelCount + c]; + } + } + } + + delete[] data; + delete[] features; +} + +// Function to choose template implementation based on dynamic, channels and dimensions +torch::Tensor BilateralFilterPHLCpu(torch::Tensor inputTensor, float spatialSigma, float colorSigma) { + torch::Tensor outputTensor = torch::zeros_like(inputTensor); + + AT_DISPATCH_FLOATING_TYPES(inputTensor.scalar_type(), "BilateralFilterPhlCpu", ([&] { + BilateralFilterPHLCpu(inputTensor, outputTensor, spatialSigma, colorSigma); + })); + + return outputTensor; +} diff --git a/source_code/SegMamba/monai/csrc/filtering/bilateral/bilateralfilter_cuda.cu b/source_code/SegMamba/monai/csrc/filtering/bilateral/bilateralfilter_cuda.cu new file mode 100644 index 0000000000000000000000000000000000000000..a24e6ed092f5e0e3694dd68d24d3a8fa99e9aa3a --- /dev/null +++ b/source_code/SegMamba/monai/csrc/filtering/bilateral/bilateralfilter_cuda.cu @@ -0,0 +1,260 @@ +/* +Copyright (c) MONAI Consortium +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + http://www.apache.org/licenses/LICENSE-2.0 +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +#include +#include +#include + +#include "bilateral.h" +#include "utils/meta_macros.h" +#include "utils/tensor_description.h" + +__constant__ int cBatchStride; +__constant__ int cColorStride; + +__constant__ int cSizes[3]; +__constant__ int cStrides[3]; + +__constant__ int cKernelSize; +__constant__ float cKernel[256]; + +__constant__ float cColorExponentFactor; + +template +__global__ void BilateralFilterCudaKernel1D(scalar_t* input, scalar_t* output) { + int kernelHalfSize = cKernelSize / 2; + + int homeOffset = blockIdx.x * blockDim.x + threadIdx.x; + int batchOffset = blockIdx.y * cBatchStride; + + if (homeOffset >= cColorStride) + return; + + scalar_t weightSum = 0; + + for (int kernelOffset = 0; kernelOffset < cKernelSize; kernelOffset++) { + int neighbourOffset = max(0, min(homeOffset + (kernelOffset - kernelHalfSize), cSizes[0] - 1)); + scalar_t gaussian = cKernel[kernelOffset]; + + scalar_t distanceSquared = 0; + +#pragma unroll + for (int c = 0; c < C; c++) { + scalar_t a = input[batchOffset + homeOffset + c * cColorStride]; + scalar_t b = input[batchOffset + neighbourOffset + c * cColorStride]; + scalar_t diff = a - b; + distanceSquared += diff * diff; + } + + scalar_t spatialWeight = gaussian; + scalar_t colorWeight = exp(cColorExponentFactor * distanceSquared); + scalar_t totalWeight = spatialWeight * colorWeight; + +#pragma unroll + for (int c = 0; c < C; c++) { + scalar_t a = input[batchOffset + neighbourOffset + c * cColorStride]; + + output[batchOffset + homeOffset + c * cColorStride] += a * totalWeight; + } + + weightSum += totalWeight; + } + +#pragma unroll + for (int c = 0; c < C; c++) { + output[batchOffset + homeOffset + c * cColorStride] /= weightSum; + } +} + +template +__global__ void BilateralFilterCudaKernel2D(scalar_t* input, scalar_t* output) { + int kernelHalfSize = cKernelSize / 2; + + int homeOffset = blockIdx.x * blockDim.x + threadIdx.x; + int batchOffset = blockIdx.y * cBatchStride; + + if (homeOffset >= cColorStride) + return; + + int homeX = homeOffset / cStrides[0]; + int homeY = (homeOffset - homeX * cStrides[0]) / cStrides[1]; + + scalar_t weightSum = 0; + + for (int kernelX = 0; kernelX < cKernelSize; kernelX++) { + int neighbourX = max(0, min(homeX + (kernelX - kernelHalfSize), cSizes[0] - 1)); + scalar_t gaussianX = cKernel[kernelX]; + + for (int kernelY = 0; kernelY < cKernelSize; kernelY++) { + int neighbourY = max(0, min(homeY + (kernelY - kernelHalfSize), cSizes[1] - 1)); + scalar_t gaussianY = cKernel[kernelY]; + + int neighbourOffset = neighbourX * cStrides[0] + neighbourY; + + scalar_t distanceSquared = 0; + +#pragma unroll + for (int c = 0; c < C; c++) { + scalar_t a = input[batchOffset + homeOffset + c * cColorStride]; + scalar_t b = input[batchOffset + neighbourOffset + c * cColorStride]; + scalar_t diff = a - b; + distanceSquared += diff * diff; + } + + scalar_t spatialWeight = gaussianX * gaussianY; + scalar_t colorWeight = exp(cColorExponentFactor * distanceSquared); + scalar_t totalWeight = spatialWeight * colorWeight; + +#pragma unroll + for (int c = 0; c < C; c++) { + scalar_t a = input[batchOffset + neighbourOffset + c * cColorStride]; + + output[batchOffset + homeOffset + c * cColorStride] += a * totalWeight; + } + + weightSum += totalWeight; + } + } + +#pragma unroll + for (int c = 0; c < C; c++) { + output[batchOffset + homeOffset + c * cColorStride] /= weightSum; + } +} + +template +__global__ void BilateralFilterCudaKernel3D(scalar_t* input, scalar_t* output) { + int kernelHalfSize = cKernelSize / 2; + + int homeOffset = blockIdx.x * blockDim.x + threadIdx.x; + int batchOffset = blockIdx.y * cBatchStride; + + if (homeOffset >= cColorStride) + return; + + int homeX = homeOffset / cStrides[0]; + int homeY = (homeOffset - homeX * cStrides[0]) / cStrides[1]; + int homeZ = (homeOffset - homeX * cStrides[0] - homeY * cStrides[1]) / cStrides[2]; + + scalar_t weightSum = 0; + + for (int kernelX = 0; kernelX < cKernelSize; kernelX++) { + int neighbourX = max(0, min(homeX + (kernelX - kernelHalfSize), cSizes[0] - 1)); + scalar_t gaussianX = cKernel[kernelX]; + + for (int kernelY = 0; kernelY < cKernelSize; kernelY++) { + int neighbourY = max(0, min(homeY + (kernelY - kernelHalfSize), cSizes[1] - 1)); + scalar_t gaussianY = cKernel[kernelY]; + + for (int kernelZ = 0; kernelZ < cKernelSize; kernelZ++) { + int neighbourZ = max(0, min(homeZ + (kernelZ - kernelHalfSize), cSizes[2] - 1)); + scalar_t gaussianZ = cKernel[kernelZ]; + + int neighbourOffset = neighbourX * cStrides[0] + neighbourY * cStrides[1] + neighbourZ; + + scalar_t distanceSquared = 0; + +#pragma unroll + for (int c = 0; c < C; c++) { + scalar_t a = input[batchOffset + homeOffset + c * cColorStride]; + scalar_t b = input[batchOffset + neighbourOffset + c * cColorStride]; + scalar_t diff = a - b; + distanceSquared += diff * diff; + } + + scalar_t spatialWeight = gaussianX * gaussianY * gaussianZ; + scalar_t colorWeight = exp(cColorExponentFactor * distanceSquared); + scalar_t totalWeight = spatialWeight * colorWeight; + +#pragma unroll + for (int c = 0; c < C; c++) { + scalar_t a = input[batchOffset + neighbourOffset + c * cColorStride]; + output[batchOffset + homeOffset + c * cColorStride] += a * totalWeight; + } + + weightSum += totalWeight; + } + } + } + +#pragma unroll + for (int c = 0; c < C; c++) { + output[batchOffset + homeOffset + c * cColorStride] /= weightSum; + } +} + +template +void BilateralFilterCuda(torch::Tensor inputTensor, torch::Tensor outputTensor, float spatialSigma, float colorSigma) { + // Getting tensor description. + TensorDescription desc = TensorDescription(inputTensor); + + // Pre-calculating exponent factors. + float spatialExponentFactor = -1.0f / (2 * spatialSigma * spatialSigma); + float colorExponentFactor = -1.0f / (2 * colorSigma * colorSigma); + + // Pre-calculating gaussian kernel. + int kernelSize = (int)ceil(5.0f * spatialSigma) | 1; // ORing last bit to ensure odd window size + int kernelHalfSize = floor(0.5f * kernelSize); + float* kernel = new float[kernelSize]; + + for (int i = 0; i < kernelSize; i++) { + int distance = i - kernelHalfSize; + kernel[i] = exp(distance * distance * spatialExponentFactor); + } + + // Writing constant memory. + cudaMemcpyToSymbol(cBatchStride, &desc.batchStride, sizeof(int)); + cudaMemcpyToSymbol(cColorStride, &desc.channelStride, sizeof(int)); + cudaMemcpyToSymbol(cSizes, desc.sizes, sizeof(int) * D); + cudaMemcpyToSymbol(cStrides, desc.strides, sizeof(int) * D); + cudaMemcpyToSymbol(cKernelSize, &kernelSize, sizeof(int)); + cudaMemcpyToSymbol(cKernel, kernel, sizeof(float) * kernelSize); + cudaMemcpyToSymbol(cColorExponentFactor, &colorExponentFactor, sizeof(float)); + +#define BLOCK_SIZE 32 + + AT_DISPATCH_FLOATING_TYPES_AND_HALF( + inputTensor.scalar_type(), "BilateralFilterCudaKernel", ([&] { + // Dispatch kernel. (Partial template function specialisation not supported at present so using this switch + // instead) + switch (D) { + case (1): + BilateralFilterCudaKernel1D + <<>>( + inputTensor.data_ptr(), outputTensor.data_ptr()); + break; + case (2): + BilateralFilterCudaKernel2D + <<>>( + inputTensor.data_ptr(), outputTensor.data_ptr()); + break; + case (3): + BilateralFilterCudaKernel3D + <<>>( + inputTensor.data_ptr(), outputTensor.data_ptr()); + break; + } + })); + + delete[] kernel; +} + +// Function to choose template implementation based on dynamic, channels and dimensions +torch::Tensor BilateralFilterCuda(torch::Tensor inputTensor, float spatialSigma, float colorSigma) { + torch::Tensor outputTensor = torch::zeros_like(inputTensor); + +#define CASE(c, d) BilateralFilterCuda(inputTensor, outputTensor, spatialSigma, colorSigma); + SWITCH_AB(CASE, BF_CUDA_MAX_CHANNELS, BF_CUDA_MAX_SPATIAL_DIMENSION, inputTensor.size(1), inputTensor.dim() - 2); + + return outputTensor; +} diff --git a/source_code/SegMamba/monai/csrc/filtering/bilateral/bilateralfilter_cuda_phl.cu b/source_code/SegMamba/monai/csrc/filtering/bilateral/bilateralfilter_cuda_phl.cu new file mode 100644 index 0000000000000000000000000000000000000000..20df9419faf1a7c3d87e79ad8a723ed4584a8788 --- /dev/null +++ b/source_code/SegMamba/monai/csrc/filtering/bilateral/bilateralfilter_cuda_phl.cu @@ -0,0 +1,142 @@ +/* +Copyright (c) MONAI Consortium +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + http://www.apache.org/licenses/LICENSE-2.0 +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +#include +#include +#include + +#include "bilateral.h" +#include "filtering/permutohedral/permutohedral.h" +#include "utils/meta_macros.h" +#include "utils/tensor_description.h" + +__constant__ int cBatchStride; +__constant__ int cChannelStride; +__constant__ int cSpatialStrides[3]; +__constant__ float cInvSpatialSigma; +__constant__ float cInvColorSigma; + +template +__global__ void FeatureCreation(const scalar_t* inputTensor, scalar_t* outputData, scalar_t* outputFeatures) { + int elementIndex = blockIdx.x * blockDim.x + threadIdx.x; + int batchIndex = blockIdx.y; + + if (elementIndex >= cChannelStride) + return; + + int dataBatchOffset = batchIndex * cBatchStride; + int featureBatchOffset = batchIndex * (D + C) * cChannelStride; + +#pragma unroll + for (int i = 0; i < C; i++) { + outputData[dataBatchOffset + elementIndex * C + i] = + inputTensor[dataBatchOffset + elementIndex + i * cChannelStride]; + outputFeatures[featureBatchOffset + elementIndex * (C + D) + i] = + inputTensor[dataBatchOffset + elementIndex + i * cChannelStride] * cInvColorSigma; + } + + int remainder = elementIndex; + +#pragma unroll + for (int i = 0; i < D; i++) { + int coord = remainder / cSpatialStrides[i]; + remainder -= coord * cSpatialStrides[i]; + + outputFeatures[featureBatchOffset + elementIndex * (C + D) + C + i] = coord * cInvSpatialSigma; + } +} + +template +__global__ void WriteOutput(const scalar_t* data, scalar_t* outputTensor) { + int elementIndex = blockIdx.x * blockDim.x + threadIdx.x; + int batchIndex = blockIdx.y; + + if (elementIndex >= cChannelStride) + return; + + int batchOffset = batchIndex * cBatchStride; + +#pragma unroll + for (int i = 0; i < C; i++) { + outputTensor[batchOffset + elementIndex + i * cChannelStride] = data[batchOffset + elementIndex * C + i]; + } +} + +template +void BilateralFilterPHLCuda( + torch::Tensor inputTensor, + torch::Tensor outputTensor, + float spatialSigma, + float colorSigma) { + // Getting tensor description. + TensorDescription desc = TensorDescription(inputTensor); + + int featureChannelCount = desc.channelCount + desc.dimensions; + + // Pre calculating inverse sigmas. + float invSpatialSigma = 1.0f / spatialSigma; + float invColorSigma = 1.0f / colorSigma; + + // Preparing global memory + scalar_t* inputTensorData = inputTensor.data_ptr(); + scalar_t* outputTensorData = outputTensor.data_ptr(); + + scalar_t* data; + scalar_t* features; + cudaMalloc(&data, desc.batchCount * desc.channelStride * desc.channelCount * sizeof(scalar_t)); + cudaMalloc(&features, desc.batchCount * desc.channelStride * featureChannelCount * sizeof(scalar_t)); + + // Preparing constant memory + cudaMemcpyToSymbol(cBatchStride, &desc.batchStride, sizeof(int)); + cudaMemcpyToSymbol(cChannelStride, &desc.channelStride, sizeof(int)); + cudaMemcpyToSymbol(cSpatialStrides, desc.strides, sizeof(int) * desc.dimensions); + cudaMemcpyToSymbol(cInvSpatialSigma, &invSpatialSigma, sizeof(float)); + cudaMemcpyToSymbol(cInvColorSigma, &invColorSigma, sizeof(float)); + +#define BLOCK_SIZE 32 + + // Creating features + FeatureCreation + <<>>( + inputTensorData, data, features); + + // Filtering data with respect to the features for each sample in batch + for (int batchIndex = 0; batchIndex < desc.batchCount; batchIndex++) { + scalar_t* offsetData = data + batchIndex * desc.batchStride; + scalar_t* offsetFeatures = features + batchIndex * featureChannelCount * desc.channelStride; + + PermutohedralCuda(offsetData, offsetFeatures, desc.channelStride, true); + } + + // Writing output + WriteOutput<<>>( + data, outputTensorData); + + cudaFree(data); + cudaFree(features); +} + +// Function to choose template implementation based on dynamic, channels and dimensions +torch::Tensor BilateralFilterPHLCuda(torch::Tensor inputTensor, float spatialSigma, float colorSigma) { + torch::Tensor outputTensor = torch::zeros_like(inputTensor); + +#define CASE(c, d) \ + AT_DISPATCH_FLOATING_TYPES(inputTensor.scalar_type(), "BilateralFilterCudaPHL", ([&] { \ + BilateralFilterPHLCuda( \ + inputTensor, outputTensor, spatialSigma, colorSigma); \ + })); + + SWITCH_AB(CASE, BF_CUDA_MAX_CHANNELS, BF_CUDA_MAX_SPATIAL_DIMENSION, inputTensor.size(1), inputTensor.dim() - 2); + + return outputTensor; +} diff --git a/source_code/SegMamba/monai/csrc/filtering/filtering.h b/source_code/SegMamba/monai/csrc/filtering/filtering.h new file mode 100644 index 0000000000000000000000000000000000000000..1ff799cf5e615dd25c561ed737d2df939e745521 --- /dev/null +++ b/source_code/SegMamba/monai/csrc/filtering/filtering.h @@ -0,0 +1,19 @@ +/* +Copyright (c) MONAI Consortium +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + http://www.apache.org/licenses/LICENSE-2.0 +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +#pragma once + +#include "bilateral/bilateral.h" +#include "permutohedral/permutohedral.h" +#include "trainable_bilateral/trainable_bilateral.h" +#include "trainable_joint_bilateral/trainable_joint_bilateral.h" diff --git a/source_code/SegMamba/monai/csrc/filtering/permutohedral/hash_table.cuh b/source_code/SegMamba/monai/csrc/filtering/permutohedral/hash_table.cuh new file mode 100644 index 0000000000000000000000000000000000000000..5507034dea2082adc2cbc338f5c9c1db63b2a483 --- /dev/null +++ b/source_code/SegMamba/monai/csrc/filtering/permutohedral/hash_table.cuh @@ -0,0 +1,260 @@ +/* +Copyright (c) MONAI Consortium +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + http://www.apache.org/licenses/LICENSE-2.0 +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +#include + +//#define USE_ADDITIVE_HASH + +// turn this on if you want to get slightly less memory consumption and slightly longer run times. +//#define LINEAR_D_MEMORY + +#define USE_CUSTOM_MODULO + +__device__ __constant__ signed short* table_keys; +__device__ __constant__ int* table_entries; +__device__ __constant__ unsigned int table_capacity; +__device__ __constant__ signed short* table_zeros; +__device__ __constant__ char* table_rank; + +/*************************************************************/ +/* Fast computation of modulo operator with constant divisor */ +/*************************************************************/ +__device__ __constant__ unsigned int __div_m; +__device__ __constant__ unsigned int __div_l; +__device__ __constant__ unsigned int __div_c; + +#ifdef USE_CUSTOM_MODULO +__device__ inline unsigned int modHash(unsigned int n) { + unsigned int t1 = __umulhi(__div_m, n); + return n - ((t1 + ((n - t1) >> 1)) >> (__div_l - 1)) * __div_c; +} + +#else +#define modHash(n) ((n) % (2 * table_capacity)); +#endif + +/*************************************************************/ +/* End modulo */ +/*************************************************************/ + +__device__ __constant__ static unsigned int hOffset[64]; + +template +static scalar_t* createHashTable(int capacity) { + scalar_t* values; + cudaMalloc(&values, capacity * vd * sizeof(scalar_t)); + cudaMemset(values, 0, capacity * vd * sizeof(scalar_t)); + + int* entries; + cudaMalloc(&entries, capacity * 2 * sizeof(int)); + cudaMemset(entries, -1, capacity * 2 * sizeof(int)); + + cudaMemcpyToSymbol(table_capacity, &capacity, sizeof(int)); + + cudaMemcpyToSymbol(table_entries, &entries, sizeof(int*)); + +#ifdef LINEAR_D_MEMORY + + char* ranks; + cudaMalloc(&ranks, capacity * sizeof(char)); + + signed short* zeros; + cudaMalloc(&zeros, capacity * sizeof(signed short)); + + cudaMemcpyToSymbol(table_rank, &ranks, sizeof(char*)); + cudaMemcpyToSymbol(table_zeros, &zeros, sizeof(char*)); + +#else + + signed short* keys; + cudaMalloc(&keys, capacity * kd * sizeof(signed short)); + cudaMemset(keys, 0, capacity * kd * sizeof(signed short)); + + cudaMemcpyToSymbol(table_keys, &keys, sizeof(unsigned int*)); + +#endif + + return values; +} + +template +static void destroyHashTable() { +#ifndef LINEAR_D_MEMORY + signed short* keys; + cudaMemcpyFromSymbol(&keys, table_keys, sizeof(unsigned int*)); + cudaFree(keys); +#endif + + int* entries; + cudaMemcpyFromSymbol(&entries, table_entries, sizeof(int*)); + cudaFree(entries); +} + +template +__device__ __host__ static unsigned int hash(signed short* key) { + unsigned int k = 0; + for (int i = 0; i < kd; i++) { + k += key[i]; + k = k * 2531011; + } + return k; +} + +template +__device__ __host__ static unsigned int hash(int* key) { + unsigned int k = 0; + for (int i = 0; i < kd; i++) { + k += key[i]; + k = k * 2531011; + } + return k; +} + +template +__device__ static bool matchKey(int idx, signed short* key) { + bool match = true; + int slot = idx / (d + 1), color = idx - slot * (d + 1); + char* rank = table_rank + slot * (d + 1); + signed short* zero = table_zeros + slot * (d + 1); + + for (int i = 0; i < d && match; i++) { + match = (key[i] == zero[i] + color - (rank[i] > d - color ? (d + 1) : 0)); + } + + return match; +} + +template +__device__ static void generateKey(int idx, signed short* key) { + int slot = idx / (d + 1), color = idx - slot * (d + 1); + char* rank = table_rank + slot * (d + 1); + signed short* zero = table_zeros + slot * (d + 1); + + for (int i = 0; i < d; i++) { + key[i] = zero[i] + color - (rank[i] > d - color ? (d + 1) : 0); + } +} + +template +__device__ static int hashTableInsert(unsigned int fh, signed short* key, unsigned int slot) { + int h = modHash(fh); + while (1) { + int* e = &table_entries[h]; + + // If the cell is empty (-1), lock it (-2) + int contents = atomicCAS(e, -1, -2); + + if (contents == -2) { + // If it was locked already, move on to the next cell + } else if (contents == -1) { + // If it was empty, we successfully locked it. Write our key. + +#ifndef LINEAR_D_MEMORY + for (int i = 0; i < kd; i++) { + table_keys[slot * kd + i] = key[i]; + } +#endif + + // Unlock + atomicExch(e, slot); + + return h; + } else { +// The cell is unlocked and has a key in it, check if it matches +#ifdef LINEAR_D_MEMORY + if (matchKey(contents, key)) + return h; +#else + bool match = true; + + for (int i = 0; i < kd && match; i++) { + match = (table_keys[contents * kd + i] == key[i]); + } + + if (match) + return h; +#endif + } + // increment the bucket with wraparound + h++; + + if (h == table_capacity * 2) + h = 0; + } +} + +template +__device__ static int hashTableInsert(signed short* key, unsigned int slot) { + unsigned int myHash = hash(key); + return hashTableInsert(myHash, key, slot); +} + +template +__device__ static int hashTableRetrieveWithHash(unsigned int fh, signed short* key) { + int h = modHash(fh); + while (1) { + int* e = table_entries + h; + + if (*e == -1) + return -1; + +#ifdef LINEAR_D_MEMORY + if (matchKey((*e), key)) + return *e; +#else + bool match = true; + + for (int i = 0; i < kd && match; i++) { + match = (table_keys[(*e) * kd + i] == key[i]); + } + + if (match) + return *e; +#endif + + h++; + + if (h == table_capacity * 2) + h = 0; + } +} + +template +__device__ static int hashTableRetrieve(signed short* key) { + int h = modHash(hash(key)); + while (1) { + int* e = table_entries + h; + + if (*e == -1) + return -1; + +#ifdef LINEAR_D_MEMORY + if (matchKey((*e), key)) + return *e; +#else + bool match = true; + + for (int i = 0; i < kd && match; i++) { + match = (table_keys[(*e) * kd + i] == key[i]); + } + + if (match) + return *e; +#endif + + h++; + + if (h == table_capacity * 2) + h = 0; + } +} diff --git a/source_code/SegMamba/monai/csrc/filtering/permutohedral/permutohedral.cpp b/source_code/SegMamba/monai/csrc/filtering/permutohedral/permutohedral.cpp new file mode 100644 index 0000000000000000000000000000000000000000..6ffe966f2c8c1dc15b9153ed2c01bec2a0bd8c0b --- /dev/null +++ b/source_code/SegMamba/monai/csrc/filtering/permutohedral/permutohedral.cpp @@ -0,0 +1,97 @@ +/* +Copyright (c) MONAI Consortium +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + http://www.apache.org/licenses/LICENSE-2.0 +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +#include +#include + +#include "utils/common_utils.h" +#include "utils/meta_macros.h" + +#include "permutohedral.h" + +torch::Tensor PermutohedralFilter(torch::Tensor input, torch::Tensor features) { + input = input.contiguous(); + + int batchCount = input.size(0); + int batchStride = input.stride(0); + int elementCount = input.stride(1); + int channelCount = input.size(1); + int featureCount = features.size(1); + +// movedim not support in torch < 1.7.1 +#if MONAI_TORCH_VERSION >= 10701 + torch::Tensor data = input.clone().movedim(1, -1).contiguous(); + features = features.movedim(1, -1).contiguous(); +#else + torch::Tensor data = input.clone(); + features = features; + + for (int i = 1; i < input.dim() - 1; i++) { + data = data.transpose(i, i + 1); + features = features.transpose(i, i + 1); + } + + data = data.contiguous(); + features = features.contiguous(); +#endif + +#ifdef WITH_CUDA + if (torch::cuda::is_available() && data.is_cuda()) { + CHECK_CONTIGUOUS_CUDA(data); + + if (channelCount > PHL_CUDA_MAX_CHANNELS) { + throw std::runtime_error( + "PHL filtering not implemented for channel count > " + std::to_string(PHL_CUDA_MAX_CHANNELS)); + } + + if (featureCount > PHL_CUDA_MAX_FEATURES) { + throw std::runtime_error( + "PHL filtering not implemented for feature count > " + std::to_string(PHL_CUDA_MAX_FEATURES)); + } + +#define CASE(dc, fc) \ + AT_DISPATCH_FLOATING_TYPES(data.scalar_type(), "PermutohedralCuda", ([&] { \ + for (int batchIndex = 0; batchIndex < batchCount; batchIndex++) { \ + scalar_t* offsetData = data.data_ptr() + batchIndex * batchStride; \ + scalar_t* offsetFeatures = \ + features.data_ptr() + batchIndex * fc * elementCount; \ + PermutohedralCuda(offsetData, offsetFeatures, elementCount, true); \ + } \ + })); + SWITCH_AB(CASE, PHL_CUDA_MAX_CHANNELS, PHL_CUDA_MAX_FEATURES, channelCount, featureCount); + + } else { +#endif + AT_DISPATCH_FLOATING_TYPES( + data.scalar_type(), "PermutohedralCPU", ([&] { + for (int batchIndex = 0; batchIndex < batchCount; batchIndex++) { + scalar_t* offsetData = data.data_ptr() + batchIndex * batchStride; + scalar_t* offsetFeatures = features.data_ptr() + batchIndex * featureCount * elementCount; + PermutohedralCPU(offsetData, offsetFeatures, channelCount, featureCount, elementCount); + } + })); +#ifdef WITH_CUDA + } +#endif + +// movedim not support in torch < 1.7.1 +#if MONAI_TORCH_VERSION >= 10701 + data = data.movedim(-1, 1); +#else + for (int i = input.dim() - 1; i > 1; i--) { + data = data.transpose(i - 1, i); + } +#endif + + return data; +} diff --git a/source_code/SegMamba/monai/csrc/filtering/permutohedral/permutohedral.h b/source_code/SegMamba/monai/csrc/filtering/permutohedral/permutohedral.h new file mode 100644 index 0000000000000000000000000000000000000000..cdc0f693d0185296c6c5b9ab7a2425887b018df4 --- /dev/null +++ b/source_code/SegMamba/monai/csrc/filtering/permutohedral/permutohedral.h @@ -0,0 +1,28 @@ +/* +Copyright (c) MONAI Consortium +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + http://www.apache.org/licenses/LICENSE-2.0 +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +#pragma once + +#include + +#define PHL_CUDA_MAX_CHANNELS 16 +#define PHL_CUDA_MAX_FEATURES 19 + +template +void PermutohedralCPU(scalar_t* data, scalar_t* features, int dataChannels, int featureChannels, int elementCount); +#ifdef WITH_CUDA +template +void PermutohedralCuda(scalar_t* data, scalar_t* features, int elementCount, bool accurate); +#endif + +torch::Tensor PermutohedralFilter(torch::Tensor input, torch::Tensor features); diff --git a/source_code/SegMamba/monai/csrc/filtering/permutohedral/permutohedral_cpu.cpp b/source_code/SegMamba/monai/csrc/filtering/permutohedral/permutohedral_cpu.cpp new file mode 100644 index 0000000000000000000000000000000000000000..7561320d2f70a48dac20c3a7b93e3ea1844956fd --- /dev/null +++ b/source_code/SegMamba/monai/csrc/filtering/permutohedral/permutohedral_cpu.cpp @@ -0,0 +1,502 @@ +/* +Copyright (c) MONAI Consortium +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + http://www.apache.org/licenses/LICENSE-2.0 +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +/* +Adapted from https://github.com/abadams/permutohedral +which has the following license... + +MIT License + +Copyright (c) 2020 Andrew Adams + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. +*/ + +#include +#include + +#include + +using namespace std; + +/***************************************************************/ +/* Hash table implementation for permutohedral lattice + * + * The lattice points are stored sparsely using a hash table. + * The key for each point is its spatial location in the (d+1)- + * dimensional space. + */ +/***************************************************************/ +template +class HashTablePermutohedral { + public: + /* Constructor + * kd_: the dimensionality of the position vectors on the hyperplane. + * vd_: the dimensionality of the value vectors + */ + HashTablePermutohedral(int kd_, int vd_) : kd(kd_), vd(vd_) { + capacity = 1 << 15; + filled = 0; + entries = new Entry[capacity]; + keys = new short[kd * capacity / 2]; + values = new scalar_t[vd * capacity / 2]; + memset(values, 0, sizeof(scalar_t) * vd * capacity / 2); + } + + // Returns the number of vectors stored. + int size() { + return filled; + } + + // Returns a pointer to the keys array. + short* getKeys() { + return keys; + } + + // Returns a pointer to the values array. + scalar_t* getValues() { + return values; + } + + /* Returns the index into the hash table for a given key. + * key: a pointer to the position vector. + * h: hash of the position vector. + * create: a flag specifying whether an entry should be created, + * should an entry with the given key not found. + */ + int lookupOffset(short* key, size_t h, bool create = true) { + // Double hash table size if necessary + if (filled >= (capacity / 2) - 1) { + grow(); + } + + // Find the entry with the given key + while (1) { + Entry e = entries[h]; + // check if the cell is empty + if (e.keyIdx == -1) { + if (!create) + return -1; // Return not found. + // need to create an entry. Store the given key. + for (int i = 0; i < kd; i++) + keys[filled * kd + i] = key[i]; + e.keyIdx = filled * kd; + e.valueIdx = filled * vd; + entries[h] = e; + filled++; + return e.valueIdx; + } + + // check if the cell has a matching key + bool match = true; + for (int i = 0; i < kd && match; i++) + match = keys[e.keyIdx + i] == key[i]; + if (match) + return e.valueIdx; + + // increment the bucket with wraparound + h++; + if (h == capacity) + h = 0; + } + } + + /* Looks up the value vector associated with a given key vector. + * k : pointer to the key vector to be looked up. + * create : true if a non-existing key should be created. + */ + scalar_t* lookup(short* k, bool create = true) { + size_t h = hash(k) % capacity; + int offset = lookupOffset(k, h, create); + if (offset < 0) + return NULL; + else + return values + offset; + }; + + /* Hash function used in this implementation. A simple base conversion. */ + size_t hash(const short* key) { + size_t k = 0; + for (int i = 0; i < kd; i++) { + k += key[i]; + k *= 2531011; + } + return k; + } + + private: + /* Grows the size of the hash table */ + void grow() { + size_t oldCapacity = capacity; + capacity *= 2; + + // Migrate the value vectors. + scalar_t* newValues = new scalar_t[vd * capacity / 2]; + memset(newValues, 0, sizeof(scalar_t) * vd * capacity / 2); + memcpy(newValues, values, sizeof(scalar_t) * vd * filled); + delete[] values; + values = newValues; + + // Migrate the key vectors. + short* newKeys = new short[kd * capacity / 2]; + memcpy(newKeys, keys, sizeof(short) * kd * filled); + delete[] keys; + keys = newKeys; + + Entry* newEntries = new Entry[capacity]; + + // Migrate the table of indices. + for (size_t i = 0; i < oldCapacity; i++) { + if (entries[i].keyIdx == -1) + continue; + size_t h = hash(keys + entries[i].keyIdx) % capacity; + while (newEntries[h].keyIdx != -1) { + h++; + if (h == capacity) + h = 0; + } + newEntries[h] = entries[i]; + } + delete[] entries; + entries = newEntries; + } + + // Private struct for the hash table entries. + struct Entry { + Entry() : keyIdx(-1), valueIdx(-1) {} + int keyIdx; + int valueIdx; + }; + + short* keys; + scalar_t* values; + Entry* entries; + size_t capacity, filled; + int kd, vd; +}; + +/***************************************************************/ +/* The algorithm class that performs the filter + * + * PermutohedralLattice::filter(...) does all the work. + * + */ +/***************************************************************/ +template +class PermutohedralLattice { + public: + /* Filters given image against a reference image. + * im : image to be bilateral-filtered. + * ref : reference image whose edges are to be respected. + */ + static void filter(scalar_t* data, scalar_t* features, int dataChannels, int featureChannels, int elementCount) { + // Create lattice + PermutohedralLattice lattice(featureChannels, dataChannels + 1, elementCount); + + // Splat into the lattice + scalar_t* col = new scalar_t[dataChannels + 1]; + col[dataChannels] = 1; // homogeneous coordinate + + for (int i = 0, e = 0; e < elementCount; e++) { + for (int c = 0; c < dataChannels; c++, i++) { + col[c] = data[i]; + } + + scalar_t* featureVec = features + e * featureChannels; + lattice.splat(featureVec, col); + } + + // Blur the lattice + lattice.blur(); + + // Slice from the lattice + lattice.beginSlice(); + + for (int i = 0, e = 0; e < elementCount; e++) { + lattice.slice(col); + + scalar_t scale = 1.0f / col[dataChannels]; + for (int c = 0; c < dataChannels; c++, i++) { + data[i] = col[c] * scale; + } + } + } + + /* Constructor + * d_ : dimensionality of key vectors + * vd_ : dimensionality of value vectors + * nData_ : number of points in the input + */ + PermutohedralLattice(int d_, int vd_, int nData_) : d(d_), vd(vd_), nData(nData_), hashTable(d_, vd_) { + // Allocate storage for various arrays + elevated = new scalar_t[d + 1]; + scaleFactor = new scalar_t[d]; + + greedy = new short[d + 1]; + rank = new char[d + 1]; + barycentric = new scalar_t[d + 2]; + replay = new ReplayEntry[nData * (d + 1)]; + nReplay = 0; + canonical = new short[(d + 1) * (d + 1)]; + key = new short[d + 1]; + + // compute the coordinates of the canonical simplex, in which + // the difference between a contained point and the zero + // remainder vertex is always in ascending order. (See pg.4 of paper.) + for (int i = 0; i <= d; i++) { + for (int j = 0; j <= d - i; j++) + canonical[i * (d + 1) + j] = i; + for (int j = d - i + 1; j <= d; j++) + canonical[i * (d + 1) + j] = i - (d + 1); + } + + // Compute parts of the rotation matrix E. (See pg.4-5 of paper.) + for (int i = 0; i < d; i++) { + // the diagonal entries for normalization + scaleFactor[i] = 1.0f / (sqrtf((scalar_t)(i + 1) * (i + 2))); + + /* We presume that the user would like to do a Gaussian blur of standard deviation + * 1 in each dimension (or a total variance of d, summed over dimensions.) + * Because the total variance of the blur performed by this algorithm is not d, + * we must scale the space to offset this. + * + * The total variance of the algorithm is (See pg.6 and 10 of paper): + * [variance of splatting] + [variance of blurring] + [variance of splatting] + * = d(d+1)(d+1)/12 + d(d+1)(d+1)/2 + d(d+1)(d+1)/12 + * = 2d(d+1)(d+1)/3. + * + * So we need to scale the space by (d+1)sqrt(2/3). + */ + scaleFactor[i] *= (d + 1) * sqrtf(2.0 / 3); + } + } + + /* Performs splatting with given position and value vectors */ + void splat(scalar_t* position, scalar_t* value) { + // first rotate position into the (d+1)-dimensional hyperplane + elevated[d] = -d * position[d - 1] * scaleFactor[d - 1]; + for (int i = d - 1; i > 0; i--) + elevated[i] = + (elevated[i + 1] - i * position[i - 1] * scaleFactor[i - 1] + (i + 2) * position[i] * scaleFactor[i]); + elevated[0] = elevated[1] + 2 * position[0] * scaleFactor[0]; + + // prepare to find the closest lattice points + scalar_t scale = 1.0f / (d + 1); + char* myrank = rank; + short* mygreedy = greedy; + + // greedily search for the closest zero-colored lattice point + int sum = 0; + for (int i = 0; i <= d; i++) { + scalar_t v = elevated[i] * scale; + scalar_t up = ceilf(v) * (d + 1); + scalar_t down = floorf(v) * (d + 1); + + if (up - elevated[i] < elevated[i] - down) + mygreedy[i] = (short)up; + else + mygreedy[i] = (short)down; + + sum += mygreedy[i]; + } + sum /= d + 1; + + // rank differential to find the permutation between this simplex and the canonical one. + // (See pg. 3-4 in paper.) + memset(myrank, 0, sizeof(char) * (d + 1)); + for (int i = 0; i < d; i++) + for (int j = i + 1; j <= d; j++) + if (elevated[i] - mygreedy[i] < elevated[j] - mygreedy[j]) + myrank[i]++; + else + myrank[j]++; + + if (sum > 0) { + // sum too large - the point is off the hyperplane. + // need to bring down the ones with the smallest differential + for (int i = 0; i <= d; i++) { + if (myrank[i] >= d + 1 - sum) { + mygreedy[i] -= d + 1; + myrank[i] += sum - (d + 1); + } else + myrank[i] += sum; + } + } else if (sum < 0) { + // sum too small - the point is off the hyperplane + // need to bring up the ones with largest differential + for (int i = 0; i <= d; i++) { + if (myrank[i] < -sum) { + mygreedy[i] += d + 1; + myrank[i] += (d + 1) + sum; + } else + myrank[i] += sum; + } + } + + // Compute barycentric coordinates (See pg.10 of paper.) + memset(barycentric, 0, sizeof(scalar_t) * (d + 2)); + for (int i = 0; i <= d; i++) { + barycentric[d - myrank[i]] += (elevated[i] - mygreedy[i]) * scale; + barycentric[d + 1 - myrank[i]] -= (elevated[i] - mygreedy[i]) * scale; + } + barycentric[0] += 1.0f + barycentric[d + 1]; + + // Splat the value into each vertex of the simplex, with barycentric weights. + for (int remainder = 0; remainder <= d; remainder++) { + // Compute the location of the lattice point explicitly (all but the last coordinate - it's redundant because they + // sum to zero) + for (int i = 0; i < d; i++) + key[i] = mygreedy[i] + canonical[remainder * (d + 1) + myrank[i]]; + + // Retrieve pointer to the value at this vertex. + scalar_t* val = hashTable.lookup(key, true); + + // Accumulate values with barycentric weight. + for (int i = 0; i < vd; i++) + val[i] += barycentric[remainder] * value[i]; + + // Record this interaction to use later when slicing + replay[nReplay].offset = val - hashTable.getValues(); + replay[nReplay].weight = barycentric[remainder]; + nReplay++; + } + } + + // Prepare for slicing + void beginSlice() { + nReplay = 0; + } + + /* Performs slicing out of position vectors. Note that the barycentric weights and the simplex + * containing each position vector were calculated and stored in the splatting step. + * We may reuse this to accelerate the algorithm. (See pg. 6 in paper.) + */ + void slice(scalar_t* col) { + scalar_t* base = hashTable.getValues(); + for (int j = 0; j < vd; j++) + col[j] = 0; + for (int i = 0; i <= d; i++) { + ReplayEntry r = replay[nReplay++]; + for (int j = 0; j < vd; j++) { + col[j] += r.weight * base[r.offset + j]; + } + } + } + + /* Performs a Gaussian blur along each projected axis in the hyperplane. */ + void blur() { + // Prepare arrays + short* neighbor1 = new short[d + 1]; + short* neighbor2 = new short[d + 1]; + scalar_t* newValue = new scalar_t[vd * hashTable.size()]; + scalar_t* oldValue = hashTable.getValues(); + scalar_t* hashTableBase = oldValue; + + scalar_t* zero = new scalar_t[vd]; + for (int k = 0; k < vd; k++) + zero[k] = 0; + + // For each of d+1 axes, + for (int j = 0; j <= d; j++) { + // For each vertex in the lattice, + for (int i = 0; i < hashTable.size(); i++) { // blur point i in dimension j + short* key = hashTable.getKeys() + i * (d); // keys to current vertex + for (int k = 0; k < d; k++) { + neighbor1[k] = key[k] + 1; + neighbor2[k] = key[k] - 1; + } + neighbor1[j] = key[j] - d; + neighbor2[j] = key[j] + d; // keys to the neighbors along the given axis. + + scalar_t* oldVal = oldValue + i * vd; + scalar_t* newVal = newValue + i * vd; + + scalar_t *vm1, *vp1; + + vm1 = hashTable.lookup(neighbor1, false); // look up first neighbor + if (vm1) + vm1 = vm1 - hashTableBase + oldValue; + else + vm1 = zero; + + vp1 = hashTable.lookup(neighbor2, false); // look up second neighbor + if (vp1) + vp1 = vp1 - hashTableBase + oldValue; + else + vp1 = zero; + + // Mix values of the three vertices + for (int k = 0; k < vd; k++) + newVal[k] = (0.25f * vm1[k] + 0.5f * oldVal[k] + 0.25f * vp1[k]); + } + scalar_t* tmp = newValue; + newValue = oldValue; + oldValue = tmp; + // the freshest data is now in oldValue, and newValue is ready to be written over + } + + // depending where we ended up, we may have to copy data + if (oldValue != hashTableBase) { + memcpy(hashTableBase, oldValue, hashTable.size() * vd * sizeof(scalar_t)); + delete[] oldValue; + } else { + delete[] newValue; + } + + delete[] zero; + delete[] neighbor1; + delete[] neighbor2; + } + + private: + int d, vd, nData; + scalar_t *elevated, *scaleFactor, *barycentric; + short* canonical; + short* key; + + // slicing is done by replaying splatting (ie storing the sparse matrix) + struct ReplayEntry { + int offset; + scalar_t weight; + } * replay; + int nReplay, nReplaySub; + + public: + char* rank; + short* greedy; + HashTablePermutohedral hashTable; +}; + +template +void PermutohedralCPU(scalar_t* data, scalar_t* features, int dataChannels, int featureChannels, int elementCount) { + PermutohedralLattice::filter(data, features, dataChannels, featureChannels, elementCount); +} + +template void PermutohedralCPU(float* data, float* features, int dataChannels, int featureChannels, int elementCount); +template void PermutohedralCPU(double* data, double* features, int dataChannels, int featureChannels, int elementCount); diff --git a/source_code/SegMamba/monai/csrc/filtering/permutohedral/permutohedral_cuda.cu b/source_code/SegMamba/monai/csrc/filtering/permutohedral/permutohedral_cuda.cu new file mode 100644 index 0000000000000000000000000000000000000000..fa06590fa921aa2e2e79bfcdc0c84883fa2135cc --- /dev/null +++ b/source_code/SegMamba/monai/csrc/filtering/permutohedral/permutohedral_cuda.cu @@ -0,0 +1,540 @@ +/* +Copyright (c) MONAI Consortium +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + http://www.apache.org/licenses/LICENSE-2.0 +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +/* +Adapted from https://github.com/abadams/permutohedral +which has the following license... + +MIT License + +Copyright (c) 2020 Andrew Adams + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. +*/ + +#define BLOCK_SIZE 32 + +#include +#include +#include +#include +#include + +#include "hash_table.cuh" +#include "permutohedral.h" +#include "utils/meta_macros.h" + +template +struct MatrixEntry { + int index; + scalar_t weight; +}; + +template +__global__ static void createMatrix( + const int elementCount, + const scalar_t* positions, + const scalar_t* values, + const scalar_t* scaleFactor, + MatrixEntry* matrix) { + const int threadId = threadIdx.x; + const int idx = threadIdx.x + blockIdx.x * BLOCK_SIZE; + const bool outOfBounds = idx >= elementCount; + + scalar_t myElevated[pd + 1]; + const scalar_t* myPosition = positions + idx * pd; + + int myGreedy[pd + 1]; + int myRank[pd + 1]; + + scalar_t myBarycentric[pd + 2]; + __shared__ short keys[pd * BLOCK_SIZE]; + short* myKey = keys + threadId * pd; + + if (!outOfBounds) { + myElevated[pd] = -pd * myPosition[pd - 1] * scaleFactor[pd - 1]; + + for (int i = pd - 1; i > 0; i--) { + myElevated[i] = + myElevated[i + 1] - i * (myPosition[i - 1]) * scaleFactor[i - 1] + (i + 2) * myPosition[i] * scaleFactor[i]; + } + + myElevated[0] = myElevated[1] + 2 * myPosition[0] * scaleFactor[0]; + + // find the closest zero-colored lattice point + + // greedily search for the closest zero-colored lattice point + signed short sum = 0; + + for (int i = 0; i <= pd; i++) { + scalar_t v = myElevated[i] * (1.0f / (pd + 1)); + scalar_t up = ceilf(v) * (pd + 1); + scalar_t down = floorf(v) * (pd + 1); + + myGreedy[i] = (signed short)(up - myElevated[i] < myElevated[i] - down ? up : down); + sum += myGreedy[i]; + } + + sum /= pd + 1; + + // sort differential to find the permutation between this simplex and the canonical one + for (int i = 0; i <= pd; i++) { + myRank[i] = 0; + + for (int j = 0; j <= pd; j++) { + scalar_t iDiff = myElevated[i] - myGreedy[i]; + scalar_t jDiff = myElevated[j] - myGreedy[j]; + + if (iDiff < jDiff || (iDiff == jDiff && i > j)) { + myRank[i]++; + } + } + } + + if (sum > 0) // sum too large, need to bring down the ones with the smallest differential + { + for (int i = 0; i <= pd; i++) { + if (myRank[i] >= pd + 1 - sum) { + myGreedy[i] -= (pd + 1); + myRank[i] += sum - (pd + 1); + } else { + myRank[i] += sum; + } + } + } else if (sum < 0) // sum too small, need to bring up the ones with largest differential + { + for (int i = 0; i <= pd; i++) { + if (myRank[i] < -sum) { + myGreedy[i] += (pd + 1); + myRank[i] += sum + (pd + 1); + } else { + myRank[i] += sum; + } + } + } + +#ifdef LINEAR_D_MEMORY + for (int i = 0; i <= pd; i++) { + table_zeros[idx * (pd + 1) + i] = myGreedy[i]; + table_rank[idx * (pd + 1) + i] = myRank[i]; + } +#endif + + // turn delta into barycentric coords + for (int i = 0; i <= pd + 1; i++) { + myBarycentric[i] = 0; + } + + for (int i = 0; i <= pd; i++) { + scalar_t delta = (myElevated[i] - myGreedy[i]) * (1.0f / (pd + 1)); + myBarycentric[pd - myRank[i]] += delta; + myBarycentric[pd + 1 - myRank[i]] -= delta; + } + + myBarycentric[0] += 1.0f + myBarycentric[pd + 1]; + } + +#ifdef USE_ADDITIVE_HASH + unsigned int cumulative_hash = hash(myGreedy); +#endif + + for (int color = 0; color <= pd; color++) { + // Compute the location of the lattice point explicitly (all but + // the last coordinate - it's redundant because they sum to zero) + if (!outOfBounds) { + for (int i = 0; i < pd; i++) { + myKey[i] = myGreedy[i] + color; + + if (myRank[i] > pd - color) { + myKey[i] -= (pd + 1); + } + } + } + +#ifdef USE_ADDITIVE_HASH + for (int i = 0; i < pd; i++) { + if (myRank[i] == pd - color) { + cumulative_hash += hOffset[i]; + } + } +#endif + + if (!outOfBounds) { + MatrixEntry r; + +#ifdef USE_ADDITIVE_HASH + r.index = hashTableInsert(cumulative_hash, myKey, idx * (pd + 1) + color); +#else + r.index = hashTableInsert(myKey, idx * (pd + 1) + color); +#endif + + r.weight = myBarycentric[color]; + matrix[idx * (pd + 1) + color] = r; + } + } +} + +template +__global__ static void cleanHashTable(const int elementCount, MatrixEntry* matrix) { + const int idx = threadIdx.x + blockIdx.x * blockDim.x; + + if (idx >= elementCount) + return; + + // find my hash table entry + int* e = table_entries + idx; + + // Check if I created my own key in the previous phase + if (*e >= 0) { + // Rehash my key and reset the pointer in order to merge with + // any other pixel that created a different entry under the + // same key. If the computation was serial this would never + // happen, but sometimes race conditions can make the same key + // be inserted twice. hashTableRetrieve always returns the + // earlier, so it's no problem as long as we rehash now. + +#ifdef LINEAR_D_MEMORY + // Get my key + short myKey[kd]; + generateKey(*e, myKey); + *e = hashTableRetrieve(myKey); +#else + *e = hashTableRetrieve(table_keys + *e * kd); +#endif + } +} + +template +__global__ static void splat( + const int elementCount, + scalar_t* values, + MatrixEntry* matrix, + scalar_t* table_values) { + const int color = threadIdx.y; + const int idx = threadIdx.x + blockIdx.x * blockDim.x; + + const bool outOfBounds = idx >= elementCount; + + if (outOfBounds) { + return; + } + + scalar_t* myValue = values + idx * vd; + + MatrixEntry r = matrix[idx * (pd + 1) + color]; + + matrix[idx * (pd + 1) + color].index = r.index = table_entries[r.index]; + scalar_t* val = table_values + r.index * (vd + 1); + + for (int j = 0; j < vd; j++) { + gpuAtomicAdd(val + j, myValue[j] * r.weight); + } + + gpuAtomicAdd(val + vd, r.weight); +} + +// splat splits by color, so extend the y coordinate to our blocks to represent that +// dim3 oldblocks((w-1)/8+1, (h-1)/8+1, 1); +// dim3 oldblockSize(8, 8, 1); +// oldblocks.y *= pd+1; +// splatCache<<>>(w, h, values, matrix); + +// int blockCount = (elementCount + 1) / BLOCK_SIZE + 1; +// int blockSize = BLOCK_SIZE; + +// splatCache<<>>(elementCount, values, matrix); + +template +__global__ static void splatCache( + const int elementCount, + scalar_t* values, + MatrixEntry* matrix, + scalar_t* table_values) { + // const int x = threadIdx.x + blockIdx.x * blockDim.x; + // const int y = threadIdx.y + (blockIdx.y/(pd+1)) * blockDim.y; + + // const int threadId = threadIdx.y*blockDim.x + threadIdx.x; + // const int color = blockIdx.y % (pd+1); + // const int idx = y*w + x; + + const int threadId = threadIdx.x; + const int color = threadIdx.y; + const int idx = threadIdx.x + blockIdx.x * BLOCK_SIZE; + + const bool outOfBounds = idx >= elementCount; + + __shared__ int sharedOffsets[BLOCK_SIZE]; + __shared__ scalar_t sharedValues[BLOCK_SIZE * (vd + 1)]; + + int myOffset = -1; + scalar_t* myValue = sharedValues + threadId * (vd + 1); + + if (!outOfBounds) { + scalar_t* value = values + idx * vd; + + MatrixEntry r = matrix[idx * (pd + 1) + color]; + + // convert the matrix entry from a pointer into the entries array to a pointer into the keys/values array + matrix[idx * (pd + 1) + color].index = r.index = table_entries[r.index]; + // record the offset into the keys/values array in shared space + myOffset = sharedOffsets[threadId] = r.index * (vd + 1); + + for (int j = 0; j < vd; j++) { + myValue[j] = value[j] * r.weight; + } + myValue[vd] = r.weight; + + } else { + sharedOffsets[threadId] = -1; + } + + __syncthreads(); + + // am I the first thread in this block to care about this key? + + if (outOfBounds) + return; + + for (int i = 0; i < BLOCK_SIZE; i++) { + if (i < threadId) { + if (myOffset == sharedOffsets[i]) { + // somebody else with higher priority cares about this key + return; + } + } else if (i > threadId) { + if (myOffset == sharedOffsets[i]) { + // someone else with lower priority cares about this key, accumulate it into mine + for (int j = 0; j <= vd; j++) { + sharedValues[threadId * (vd + 1) + j] += sharedValues[i * (vd + 1) + j]; + } + } + } + } + + // only the threads with something to write to main memory are still going + scalar_t* val = table_values + myOffset; + for (int j = 0; j <= vd; j++) { + gpuAtomicAdd(val + j, myValue[j]); + } +} + +template +__global__ static void blur( + int n, + scalar_t* newValues, + MatrixEntry* matrix, + int color, + scalar_t* table_values) { + const int idx = (blockIdx.y * gridDim.x + blockIdx.x) * blockDim.x * blockDim.y + threadIdx.x; + + if (idx >= n) + return; + + // Check if I'm valid + if (matrix[idx].index != idx) + return; + + // find my key and the keys of my neighbours + short myKey[pd + 1]; + short np[pd + 1]; + short nm[pd + 1]; + +#ifdef LINEAR_D_MEMORY + generateKey(idx, myKey); + for (int i = 0; i < pd; i++) { + np[i] = myKey[i] + 1; + nm[i] = myKey[i] - 1; + } +#else + for (int i = 0; i < pd; i++) { + myKey[i] = table_keys[idx * pd + i]; + np[i] = myKey[i] + 1; + nm[i] = myKey[i] - 1; + } +#endif + + np[color] -= pd + 1; + nm[color] += pd + 1; + +#ifdef USE_ADDITIVE_HASH + unsigned int hCurrent = hash(myKey); + int offNp = hashTableRetrieveWithHash(hCurrent + hOffset[color], np); + int offNm = hashTableRetrieveWithHash(hCurrent - hOffset[color], nm); +#else + int offNp = hashTableRetrieve(np); + int offNm = hashTableRetrieve(nm); +#endif + + scalar_t* valMe = table_values + (vd + 1) * idx; + scalar_t* valNp = table_values + (vd + 1) * offNp; + scalar_t* valNm = table_values + (vd + 1) * offNm; + scalar_t* valOut = newValues + (vd + 1) * idx; + + if (offNp >= 0 && offNm >= 0) { + for (int i = 0; i <= vd; i++) { + valOut[i] = (valNp[i] + (valMe[i] * 2) + valNm[i]) / 4; + } + } else if (offNp >= 0) { + for (int i = 0; i <= vd; i++) { + valOut[i] = (valNp[i] + (valMe[i] * 2)) / 4; + } + } else if (offNm >= 0) { + for (int i = 0; i <= vd; i++) { + valOut[i] = (valNm[i] + (valMe[i] * 2)) / 4; + } + } else { + for (int i = 0; i <= vd; i++) { + valOut[i] = valMe[i] * 2; + } + } +} + +template +__global__ static void slice( + const int elementCount, + scalar_t* values, + MatrixEntry* matrix, + scalar_t* table_values) { + const int threadId = threadIdx.x; + const int idx = threadIdx.x + blockIdx.x * BLOCK_SIZE; + const bool outOfBounds = idx >= elementCount; + + if (outOfBounds) + return; + + __shared__ scalar_t localValue[BLOCK_SIZE * vd]; + + scalar_t* myValue = localValue + threadId * vd; + scalar_t myWeight = 0; + + for (int i = 0; i < vd; i++) { + myValue[i] = 0; + } + + for (int i = 0; i <= pd; i++) { + MatrixEntry r = matrix[idx * (pd + 1) + i]; + scalar_t* val = table_values + r.index * (vd + 1); + + for (int j = 0; j < vd; j++) { + myValue[j] += r.weight * val[j]; + } + + myWeight += r.weight * val[vd]; + } + + myWeight = 1.0f / myWeight; + + for (int j = 0; j < vd; j++) { + values[idx * vd + j] = myValue[j] * myWeight; + } +} + +template +void PermutohedralCuda(scalar_t* values, scalar_t* positions, int elementCount, bool accurate) { + scalar_t blurVariance = accurate ? 0.5 : 0; + + scalar_t* scaleFactor; + cudaMalloc(&scaleFactor, pd * sizeof(scalar_t)); + + scalar_t scaleFactorHost[pd]; + for (int i = 0; i < pd; i++) { + scaleFactorHost[i] = (pd + 1) * sqrtf((1.0 / 6 + blurVariance) / ((i + 1) * (i + 2))); + } + + cudaMemcpy(scaleFactor, scaleFactorHost, pd * sizeof(scalar_t), cudaMemcpyHostToDevice); + + MatrixEntry* matrix; + cudaMalloc(&matrix, elementCount * (pd + 1) * sizeof(MatrixEntry)); + + scalar_t* table_values = createHashTable(elementCount * (pd + 1)); + + // Populate constant memory for hash helpers + unsigned long long int __host_two32 = ((unsigned long long int)1) << 32; + unsigned int __host_div_c = 2 * (elementCount * (pd + 1)); + unsigned int __host_div_l = ceilf(logf((float)__host_div_c) / logf(2.0f)); + unsigned int __host_div_m = (__host_two32 << __host_div_l) / __host_div_c - __host_two32 + 1; + cudaMemcpyToSymbol(__div_c, &__host_div_c, sizeof(unsigned int)); + cudaMemcpyToSymbol(__div_l, &__host_div_l, sizeof(unsigned int)); + cudaMemcpyToSymbol(__div_m, &__host_div_m, sizeof(unsigned int)); + + // Populate constant memory with hash of offset vectors + unsigned int hOffset_host[pd + 1]; + signed short offset[pd + 1]; + for (int i = 0; i < pd; offset[i] = 1, i++) + ; + for (int i = 0; i <= pd; i++) { + offset[i] -= pd + 1; + hOffset_host[i] = hash(offset); + offset[i] += pd + 1; + } + cudaMemcpyToSymbol(hOffset, &hOffset_host, sizeof(unsigned int) * (pd + 1)); + + int blockCount = (elementCount + 1) / BLOCK_SIZE + 1; + int blockSize = BLOCK_SIZE; + + createMatrix<<>>(elementCount, positions, values, scaleFactor, matrix); + + // fix duplicate hash table entries + int tableSize = elementCount * 2 * (pd + 1); + int cleanBlockSize = 32; + int cleanBlocks = (tableSize - 1) / cleanBlockSize + 1; + + cleanHashTable<<>>(tableSize, matrix); + + splat<<>>(elementCount, values, matrix, table_values); + + if (accurate) { + scalar_t* newValues; + cudaMalloc(&newValues, elementCount * (pd + 1) * (vd + 1) * sizeof(scalar_t)); + cudaMemset(newValues, 0, elementCount * (pd + 1) * (vd + 1) * sizeof(scalar_t)); + + for (int color = 0; color <= pd; color++) { + blur + <<>>(elementCount * (pd + 1), newValues, matrix, color, table_values); + + scalar_t* swap = newValues; + newValues = table_values; + table_values = swap; + } + + cudaFree(newValues); + } + + slice<<>>(elementCount, values, matrix, table_values); + + destroyHashTable(); + cudaFree(table_values); + cudaFree(scaleFactor); + cudaFree(matrix); +} + +#define DECLARATION(dc, fc) \ + template void PermutohedralCuda(float* values, float* positions, int elementCount, bool accurate); \ + template void PermutohedralCuda(double* values, double* positions, int elementCount, bool accurate); +DO_FOR_AB(DECLARATION, 16, 19) diff --git a/source_code/SegMamba/monai/csrc/filtering/trainable_bilateral/bf_layer_cpu_backward.cpp b/source_code/SegMamba/monai/csrc/filtering/trainable_bilateral/bf_layer_cpu_backward.cpp new file mode 100644 index 0000000000000000000000000000000000000000..01840dc2e3e59a0c37cf19379ca1b775468fd6c3 --- /dev/null +++ b/source_code/SegMamba/monai/csrc/filtering/trainable_bilateral/bf_layer_cpu_backward.cpp @@ -0,0 +1,232 @@ +/* +Copyright (c) MONAI Consortium +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + http://www.apache.org/licenses/LICENSE-2.0 +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + +========================================================================= +Adapted from https://github.com/faebstn96/trainable-bilateral-filter-source +which has the following license... +https://github.com/faebstn96/trainable-bilateral-filter-source/blob/main/LICENSE.md + +Copyright 2022 Fabian Wagner, Pattern Recognition Lab, FAU Erlangen-Nuernberg, Erlangen, Germany +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + http://www.apache.org/licenses/LICENSE-2.0 +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +#include "trainable_bilateral.h" +#include "utils/tensor_description.h" +#include "utils/tensor_indexing.h" + +template +void BilateralFilterCpuBackward_3d( + torch::Tensor gradientInputTensor, + torch::Tensor gradientOutputTensor, + torch::Tensor inputTensor, + torch::Tensor outputTensor, + torch::Tensor outputWeightsTensor, + torch::Tensor dO_dx_ki, + float sigma_x, + float sigma_y, + float sigma_z, + float colorSigma) { + // Getting tensor description. + TensorDescription desc = TensorDescription(gradientInputTensor); + + // Raw tensor data pointers. + scalar_t* gradientInputTensorData = gradientInputTensor.data_ptr(); + scalar_t* gradientOutputTensorData = gradientOutputTensor.data_ptr(); + scalar_t* inputTensorData = inputTensor.data_ptr(); + scalar_t* outputTensorData = outputTensor.data_ptr(); + scalar_t* outputWeightsTensorData = outputWeightsTensor.data_ptr(); + scalar_t* dO_dx_kiData = dO_dx_ki.data_ptr(); + + // Pre-calculate common values + int windowSize_x = std::max(((int)ceil(5.0f * sigma_x) | 1), 5); // ORing last bit to ensure odd window size + int windowSize_y = std::max(((int)ceil(5.0f * sigma_y) | 1), 5); // ORing last bit to ensure odd window size + int windowSize_z = std::max(((int)ceil(5.0f * sigma_z) | 1), 5); // ORing last bit to ensure odd window size + int halfWindowSize_x = floor(0.5f * windowSize_x); + int halfWindowSize_y = floor(0.5f * windowSize_y); + int halfWindowSize_z = floor(0.5f * windowSize_z); + int halfWindowSize_arr[] = {halfWindowSize_x, halfWindowSize_y, halfWindowSize_z}; + scalar_t spatialExpConstant_x = -1.0f / (2 * sigma_x * sigma_x); + scalar_t spatialExpConstant_y = -1.0f / (2 * sigma_y * sigma_y); + scalar_t spatialExpConstant_z = -1.0f / (2 * sigma_z * sigma_z); + scalar_t colorExpConstant = -1.0f / (2 * colorSigma * colorSigma); + + // Set kernel sizes with respect to the defined spatial sigmas. + int* kernelSizes = new int[desc.dimensions]; + + kernelSizes[0] = windowSize_x; + kernelSizes[1] = windowSize_y; + kernelSizes[2] = windowSize_z; + + // Pre-calculate gaussian kernel and distance map in 1D. + scalar_t* gaussianKernel_x = new scalar_t[windowSize_x]; + scalar_t* gaussianKernel_y = new scalar_t[windowSize_y]; + scalar_t* gaussianKernel_z = new scalar_t[windowSize_z]; + scalar_t* xDistanceSquared = new scalar_t[windowSize_x]; + scalar_t* yDistanceSquared = new scalar_t[windowSize_y]; + scalar_t* zDistanceSquared = new scalar_t[windowSize_z]; + + for (int i = 0; i < windowSize_x; i++) { + int distance = i - halfWindowSize_x; + gaussianKernel_x[i] = exp(distance * distance * spatialExpConstant_x); + xDistanceSquared[i] = distance * distance; + } + for (int i = 0; i < windowSize_y; i++) { + int distance = i - halfWindowSize_y; + gaussianKernel_y[i] = exp(distance * distance * spatialExpConstant_y); + yDistanceSquared[i] = distance * distance; + } + for (int i = 0; i < windowSize_z; i++) { + int distance = i - halfWindowSize_z; + gaussianKernel_z[i] = exp(distance * distance * spatialExpConstant_z); + zDistanceSquared[i] = distance * distance; + } + + // Looping over the batches + for (int b = 0; b < desc.batchCount; b++) { + int batchOffset = b * desc.batchStride; + + // Looping over all dimensions for the home element + for (int z = 0; z < desc.sizes[2]; z++) +#pragma omp parallel for + for (int y = 0; y < desc.sizes[1]; y++) { + for (int x = 0; x < desc.sizes[0]; x++) { + // Calculating indexing offset for the home element + int homeOffset = batchOffset; + + int homeIndex[] = {x, y, z}; + homeOffset += x * desc.strides[0]; + homeOffset += y * desc.strides[1]; + homeOffset += z * desc.strides[2]; + + // Zero kernel aggregates. + scalar_t filter_kernel = 0; + scalar_t valueSum = 0; + + // Looping over all dimensions for the neighbour element + Indexer kernelIndex = Indexer(desc.dimensions, kernelSizes); + do // while(kernelIndex++) + { + // Calculating buffer offset for the neighbour element + // Index is clamped to the border in each dimension. + int neighbourOffset = batchOffset; + bool flagNotClamped = true; + + for (int i = 0; i < desc.dimensions; i++) { + int neighbourIndex = homeIndex[i] + kernelIndex[i] - halfWindowSize_arr[i]; + int neighbourIndexClamped = std::min(desc.sizes[i] - 1, std::max(0, neighbourIndex)); + neighbourOffset += neighbourIndexClamped * desc.strides[i]; + if (neighbourIndex != neighbourIndexClamped) { + flagNotClamped = false; + } + } + + // Euclidean color distance. + scalar_t colorDistance = 0; + scalar_t colorDistanceSquared = 0; + + for (int i = 0; i < desc.channelCount; i++) { + scalar_t diff = inputTensorData[neighbourOffset + i * desc.channelStride] - + inputTensorData[homeOffset + + i * desc.channelStride]; // Be careful: Here it is (X_k - X_i) and not (X_i - X_q) + colorDistance += diff; // Do not take the absolute value here. Be careful with the signs. + colorDistanceSquared += diff * diff; + } + + // Calculating and combining the spatial + // and color weights. + scalar_t spatialWeight = 1; + + spatialWeight = + gaussianKernel_x[kernelIndex[0]] * gaussianKernel_y[kernelIndex[1]] * gaussianKernel_z[kernelIndex[2]]; + + scalar_t colorWeight = exp(colorDistanceSquared * colorExpConstant); + scalar_t totalWeight = spatialWeight * colorWeight; + + // Aggregating values. Only do this if flagNotClamped: Pixels outside the image are disregarded. + if (flagNotClamped) { + for (int i = 0; i < desc.channelCount; i++) { + // Distinguish cases for k!=i (calculation is done here) + // and k==i (partial derivatives are precalculated). + // If statement replaces center element of neighborhood/kernel. + if (kernelIndex[0] != halfWindowSize_x || kernelIndex[1] != halfWindowSize_y || + kernelIndex[2] != halfWindowSize_z) { + filter_kernel = -(1 / outputWeightsTensorData[neighbourOffset + i * desc.channelStride]) * + outputTensorData[neighbourOffset + i * desc.channelStride] * totalWeight * colorDistance / + (colorSigma * colorSigma) + + (1 / outputWeightsTensorData[neighbourOffset + i * desc.channelStride]) * totalWeight * + (1 + + inputTensorData[homeOffset + i * desc.channelStride] * colorDistance / + (colorSigma * colorSigma)); // inputTensorData[homeOffset] !! + } else { + filter_kernel = dO_dx_kiData[homeOffset + i * desc.channelStride]; + } + + valueSum += gradientInputTensorData[neighbourOffset + i * desc.channelStride] * filter_kernel; + } + } + } while (kernelIndex++); + + // Do the filtering and calculate the values for the backward pass. + for (int i = 0; i < desc.channelCount; i++) { + // Filtering: + gradientOutputTensorData[homeOffset + i * desc.channelStride] = valueSum; + } + } + } + } + + delete[] kernelSizes; + delete[] gaussianKernel_x; + delete[] gaussianKernel_y; + delete[] gaussianKernel_z; + delete[] xDistanceSquared; + delete[] yDistanceSquared; + delete[] zDistanceSquared; +} + +torch::Tensor BilateralFilterCpuBackward( + torch::Tensor gradientInputTensor, + torch::Tensor inputTensor, + torch::Tensor outputTensor, + torch::Tensor outputWeightsTensor, + torch::Tensor dO_dx_ki, + float sigma_x, + float sigma_y, + float sigma_z, + float colorSigma) { + // Preparing output tensor. + torch::Tensor gradientOutputTensor = torch::zeros_like(gradientInputTensor); + + AT_DISPATCH_FLOATING_TYPES_AND_HALF(gradientInputTensor.scalar_type(), "BilateralFilterCpuBackward_3d", ([&] { + BilateralFilterCpuBackward_3d( + gradientInputTensor, + gradientOutputTensor, + inputTensor, + outputTensor, + outputWeightsTensor, + dO_dx_ki, + sigma_x, + sigma_y, + sigma_z, + colorSigma); + })); + + return gradientOutputTensor; +} diff --git a/source_code/SegMamba/monai/csrc/filtering/trainable_bilateral/bf_layer_gpu_backward.cu b/source_code/SegMamba/monai/csrc/filtering/trainable_bilateral/bf_layer_gpu_backward.cu new file mode 100644 index 0000000000000000000000000000000000000000..973f3e163991ee1e635201cd354e204ffa74b832 --- /dev/null +++ b/source_code/SegMamba/monai/csrc/filtering/trainable_bilateral/bf_layer_gpu_backward.cu @@ -0,0 +1,296 @@ +/* +Copyright (c) MONAI Consortium +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + http://www.apache.org/licenses/LICENSE-2.0 +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + +========================================================================= +Adapted from https://github.com/faebstn96/trainable-bilateral-filter-source +which has the following license... +https://github.com/faebstn96/trainable-bilateral-filter-source/blob/main/LICENSE.md + +Copyright 2022 Fabian Wagner, Pattern Recognition Lab, FAU Erlangen-Nuernberg, Erlangen, Germany +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + http://www.apache.org/licenses/LICENSE-2.0 +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +#include +#include + +#include "trainable_bilateral.h" +//#include "../utils/cuda_error_check.h" +#include "utils/meta_macros.h" +#include "utils/tensor_description.h" + +__constant__ int cBatchStrideBack; +__constant__ int cColorStrideBack; + +__constant__ int cSizesBack[3]; +__constant__ int cStridesBack[3]; + +__constant__ int cKernelSizesBack[3]; +__constant__ int cHalfWindowSize_arrBack[3]; +__constant__ float cGaussianKernel_xBack[256]; +__constant__ float cGaussianKernel_yBack[256]; +__constant__ float cGaussianKernel_zBack[256]; +__constant__ float cXDistanceSquaredBack[256]; +__constant__ float cYDistanceSquaredBack[256]; +__constant__ float cZDistanceSquaredBack[256]; +__constant__ float cColorExponentConstantBack; +__constant__ float cSigma_xBack; +__constant__ float cSigma_yBack; +__constant__ float cSigma_zBack; +__constant__ float cColorSigmaBack; + +template +__global__ void BilateralFilterCudaKernel3DBackward( + scalar_t* gradientInputTensor, + scalar_t* gradientOutputTensor, + scalar_t* inputTensor, + scalar_t* outputTensor, + scalar_t* outputWeightsTensor, + scalar_t* dO_dx_ki) { + int homeOffset = blockIdx.x * blockDim.x + threadIdx.x; + int batchOffset = blockIdx.y * cBatchStrideBack; + + if (homeOffset >= cColorStrideBack) + return; + + int homeX = homeOffset / cStridesBack[0]; + int homeY = (homeOffset - homeX * cStridesBack[0]) / cStridesBack[1]; + int homeZ = (homeOffset - homeX * cStridesBack[0] - homeY * cStridesBack[1]) / cStridesBack[2]; + int homeIndex[] = {homeX, homeY, homeZ}; + + // Zero kernel aggregates. + scalar_t valueSum = 0; + + for (int kernelX = 0; kernelX < cKernelSizesBack[0]; kernelX++) { + int neighbourX = max(0, min(homeX + (kernelX - cHalfWindowSize_arrBack[0]), cSizesBack[0] - 1)); + scalar_t gaussianX = cGaussianKernel_xBack[kernelX]; + + for (int kernelY = 0; kernelY < cKernelSizesBack[1]; kernelY++) { + int neighbourY = max(0, min(homeY + (kernelY - cHalfWindowSize_arrBack[1]), cSizesBack[1] - 1)); + scalar_t gaussianY = cGaussianKernel_yBack[kernelY]; + + for (int kernelZ = 0; kernelZ < cKernelSizesBack[2]; kernelZ++) { + int neighbourZ = max(0, min(homeZ + (kernelZ - cHalfWindowSize_arrBack[2]), cSizesBack[2] - 1)); + scalar_t gaussianZ = cGaussianKernel_zBack[kernelZ]; + + int neighbourOffset = neighbourX * cStridesBack[0] + neighbourY * cStridesBack[1] + neighbourZ; + + bool flagNotClamped = true; + int kernelIndex[] = {kernelX, kernelY, kernelZ}; + int dimensions = 3; // Must equal the number of spatial dimensions. + + for (int i = 0; i < dimensions; i++) { + int HalfWindowSizeBack = cHalfWindowSize_arrBack[i]; // Define constant memory as new variable here (!!), + // otherwise: cudaErrorMisalignedAddress + int neighbourIndex = homeIndex[i] + kernelIndex[i] - HalfWindowSizeBack; + int neighbourIndexClamped = min(cSizesBack[i] - 1, max(0, neighbourIndex)); + if (neighbourIndex != neighbourIndexClamped) { + flagNotClamped = false; + } + } + + scalar_t colorDistance = 0; + scalar_t colorDistanceSquared = 0; + +#pragma unroll + for (int c = 0; c < C; c++) { + scalar_t a = inputTensor[batchOffset + neighbourOffset + c * cColorStrideBack]; + scalar_t b = inputTensor[batchOffset + homeOffset + c * cColorStrideBack]; // Be careful: Here it is (X_k - + // X_i) and not (X_i - X_q) + scalar_t diff = a - b; + colorDistance += diff; // Do not take the absolute value here. Be careful with the signs. + colorDistanceSquared += diff * diff; + } + + scalar_t spatialWeight = gaussianX * gaussianY * gaussianZ; + scalar_t colorWeight = exp(cColorExponentConstantBack * colorDistanceSquared); + scalar_t totalWeight = spatialWeight * colorWeight; + + // Aggregating values. Only do this if flagNotClamped: Pixels outside the image are disregarded. + if (flagNotClamped) { + scalar_t filter_kernel_back; + +#pragma unroll + for (int c = 0; c < C; c++) { + // Distinguish cases for k!=i (calculation is done here) + // and k==i (partial derivatives are precalculated). + // If statement replaces center element of neighborhood/kernel. + if (kernelX != cHalfWindowSize_arrBack[0] || kernelY != cHalfWindowSize_arrBack[1] || + kernelZ != cHalfWindowSize_arrBack[2]) { + filter_kernel_back = -(1 / outputWeightsTensor[batchOffset + neighbourOffset + c * cColorStrideBack]) * + outputTensor[batchOffset + neighbourOffset + c * cColorStrideBack] * totalWeight * colorDistance / + (cColorSigmaBack * cColorSigmaBack) + + (1 / outputWeightsTensor[batchOffset + neighbourOffset + c * cColorStrideBack]) * totalWeight * + (1 + + inputTensor[batchOffset + homeOffset + c * cColorStrideBack] * colorDistance / + (cColorSigmaBack * cColorSigmaBack)); // inputTensorData[homeOffset] !! + } else { + filter_kernel_back = dO_dx_ki[batchOffset + homeOffset + c * cColorStrideBack]; + } + + valueSum += gradientInputTensor[batchOffset + neighbourOffset + c * cColorStrideBack] * filter_kernel_back; + } + } + } + } + } + +#pragma unroll + for (int c = 0; c < C; c++) { + gradientOutputTensor[batchOffset + homeOffset + c * cColorStrideBack] = valueSum; + } +} + +template +void BilateralFilterCudaBackwardFunction( + torch::Tensor gradientInputTensor, + torch::Tensor gradientOutputTensor, + torch::Tensor inputTensor, + torch::Tensor outputTensor, + torch::Tensor outputWeightsTensor, + torch::Tensor dO_dx_ki, + float sigma_x, + float sigma_y, + float sigma_z, + float colorSigma) { + // Getting tensor description. + TensorDescription desc = TensorDescription(inputTensor); + + // Pre-calculating gaussian kernel. + int windowSize_x = std::max(((int)ceil(5.0f * sigma_x) | 1), 5); // ORing last bit to ensure odd window size + int windowSize_y = std::max(((int)ceil(5.0f * sigma_y) | 1), 5); // ORing last bit to ensure odd window size + int windowSize_z = std::max(((int)ceil(5.0f * sigma_z) | 1), 5); // ORing last bit to ensure odd window size + int halfWindowSize_x = floor(0.5f * windowSize_x); + int halfWindowSize_y = floor(0.5f * windowSize_y); + int halfWindowSize_z = floor(0.5f * windowSize_z); + int halfWindowSize_arr[] = {halfWindowSize_x, halfWindowSize_y, halfWindowSize_z}; + float spatialExpConstant_x = -1.0f / (2 * sigma_x * sigma_x); + float spatialExpConstant_y = -1.0f / (2 * sigma_y * sigma_y); + float spatialExpConstant_z = -1.0f / (2 * sigma_z * sigma_z); + float colorExpConstant = -1.0f / (2 * colorSigma * colorSigma); + + int* kernelSizes = new int[desc.dimensions]; + kernelSizes[0] = windowSize_x; + kernelSizes[1] = windowSize_y; + kernelSizes[2] = windowSize_z; + + auto* gaussianKernel_x = new float[windowSize_x]; + auto* gaussianKernel_y = new float[windowSize_y]; + auto* gaussianKernel_z = new float[windowSize_z]; + auto* xDistanceSquared = new float[windowSize_x]; + auto* yDistanceSquared = new float[windowSize_y]; + auto* zDistanceSquared = new float[windowSize_z]; + + for (int i = 0; i < windowSize_x; i++) { + int distance = i - halfWindowSize_x; + gaussianKernel_x[i] = exp(distance * distance * spatialExpConstant_x); + xDistanceSquared[i] = distance * distance; + } + for (int i = 0; i < windowSize_y; i++) { + int distance = i - halfWindowSize_y; + gaussianKernel_y[i] = exp(distance * distance * spatialExpConstant_y); + yDistanceSquared[i] = distance * distance; + } + for (int i = 0; i < windowSize_z; i++) { + int distance = i - halfWindowSize_z; + gaussianKernel_z[i] = exp(distance * distance * spatialExpConstant_z); + zDistanceSquared[i] = distance * distance; + } + + // Writing constant memory. + cudaMemcpyToSymbol(cBatchStrideBack, &desc.batchStride, sizeof(int)); + cudaMemcpyToSymbol(cColorStrideBack, &desc.channelStride, sizeof(int)); + cudaMemcpyToSymbol(cSizesBack, desc.sizes, sizeof(int) * 3); + cudaMemcpyToSymbol(cStridesBack, desc.strides, sizeof(int) * 3); + cudaMemcpyToSymbol(cKernelSizesBack, kernelSizes, sizeof(int) * desc.dimensions); + cudaMemcpyToSymbol(cHalfWindowSize_arrBack, halfWindowSize_arr, sizeof(int) * desc.dimensions); + cudaMemcpyToSymbol(cGaussianKernel_xBack, gaussianKernel_x, sizeof(float) * windowSize_x); + cudaMemcpyToSymbol(cGaussianKernel_yBack, gaussianKernel_y, sizeof(float) * windowSize_y); + cudaMemcpyToSymbol(cGaussianKernel_zBack, gaussianKernel_z, sizeof(float) * windowSize_z); + cudaMemcpyToSymbol(cXDistanceSquaredBack, xDistanceSquared, sizeof(float) * windowSize_x); + cudaMemcpyToSymbol(cYDistanceSquaredBack, yDistanceSquared, sizeof(float) * windowSize_y); + cudaMemcpyToSymbol(cZDistanceSquaredBack, zDistanceSquared, sizeof(float) * windowSize_z); + cudaMemcpyToSymbol(cColorExponentConstantBack, &colorExpConstant, sizeof(float)); + cudaMemcpyToSymbol(cSigma_xBack, &sigma_x, sizeof(float)); + cudaMemcpyToSymbol(cSigma_yBack, &sigma_y, sizeof(float)); + cudaMemcpyToSymbol(cSigma_zBack, &sigma_z, sizeof(float)); + cudaMemcpyToSymbol(cColorSigmaBack, &colorSigma, sizeof(float)); + + // cuda_error_check("Cuda check before kernel call."); + +#define BLOCK_SIZE 32 + + AT_DISPATCH_FLOATING_TYPES_AND_HALF( + inputTensor.scalar_type(), "BilateralFilterCudaKernel3DBackward", ([&] { + BilateralFilterCudaKernel3DBackward + <<>>( + gradientInputTensor.data_ptr(), + gradientOutputTensor.data_ptr(), + inputTensor.data_ptr(), + outputTensor.data_ptr(), + outputWeightsTensor.data_ptr(), + dO_dx_ki.data_ptr()); + })); + + // cuda_error_check("Cuda check after kernel call."); + // delete[] kernel; + delete[] kernelSizes; + delete[] gaussianKernel_x; + delete[] gaussianKernel_y; + delete[] gaussianKernel_z; + delete[] xDistanceSquared; + delete[] yDistanceSquared; + delete[] zDistanceSquared; +} + +// Function to choose template implementation based on dynamic, channels and dimensions +torch::Tensor BilateralFilterCudaBackward( + torch::Tensor gradientInputTensor, + torch::Tensor inputTensor, + torch::Tensor outputTensor, + torch::Tensor outputWeightsTensor, + torch::Tensor dO_dx_ki, + float sigma_x, + float sigma_y, + float sigma_z, + float colorSigma) { + torch::Tensor gradientOutputTensor = torch::zeros_like(gradientInputTensor); + // cuda_error_check("beginning"); + +#define CASE(c, d) \ + BilateralFilterCudaBackwardFunction( \ + gradientInputTensor, \ + gradientOutputTensor, \ + inputTensor, \ + outputTensor, \ + outputWeightsTensor, \ + dO_dx_ki, \ + sigma_x, \ + sigma_y, \ + sigma_z, \ + colorSigma); + SWITCH_AB( + CASE, + BF_CUDA_MAX_CHANNELS, + BF_CUDA_MAX_SPATIAL_DIMENSION, + gradientInputTensor.size(1), + gradientInputTensor.dim() - 2); + + return gradientOutputTensor; +} diff --git a/source_code/SegMamba/monai/csrc/filtering/trainable_bilateral/trainable_bilateral.cpp b/source_code/SegMamba/monai/csrc/filtering/trainable_bilateral/trainable_bilateral.cpp new file mode 100644 index 0000000000000000000000000000000000000000..0c8d38fd6c1cb145ec373432cd5186743b486b78 --- /dev/null +++ b/source_code/SegMamba/monai/csrc/filtering/trainable_bilateral/trainable_bilateral.cpp @@ -0,0 +1,121 @@ +/* +Copyright (c) MONAI Consortium +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + http://www.apache.org/licenses/LICENSE-2.0 +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + +========================================================================= +Adapted from https://github.com/faebstn96/trainable-bilateral-filter-source +which has the following license... +https://github.com/faebstn96/trainable-bilateral-filter-source/blob/main/LICENSE.md + +Copyright 2022 Fabian Wagner, Pattern Recognition Lab, FAU Erlangen-Nuernberg, Erlangen, Germany +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + http://www.apache.org/licenses/LICENSE-2.0 +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +#include +#include +#include + +#include "trainable_bilateral.h" +#include "utils/common_utils.h" + +std::tuple +TrainableBilateralFilterForward( + torch::Tensor inputTensor, + float sigma_x, + float sigma_y, + float sigma_z, + float colorSigma) { + std::tuple ( + *filterFunction)(torch::Tensor, float, float, float, float); + +#ifdef WITH_CUDA + + if (torch::cuda::is_available() && inputTensor.is_cuda()) { + CHECK_CONTIGUOUS_CUDA(inputTensor); + + if (inputTensor.size(1) > BF_CUDA_MAX_CHANNELS) { + throw std::runtime_error( + "Bilateral filtering not implemented for channel count > " + std::to_string(BF_CUDA_MAX_CHANNELS)); + } + + if (inputTensor.dim() - 2 > BF_CUDA_MAX_SPATIAL_DIMENSION) { + throw std::runtime_error( + "Bilateral filtering not implemented for spatial dimension > " + + std::to_string(BF_CUDA_MAX_SPATIAL_DIMENSION)); + } + + filterFunction = &BilateralFilterCudaForward; + } else { + filterFunction = &BilateralFilterCpuForward; + } +#else + filterFunction = &BilateralFilterCpuForward; +#endif + + return filterFunction(inputTensor, sigma_x, sigma_y, sigma_z, colorSigma); +} + +torch::Tensor TrainableBilateralFilterBackward( + torch::Tensor gradientInputTensor, + torch::Tensor inputTensor, + torch::Tensor outputTensor, + torch::Tensor outputWeightsTensor, + torch::Tensor dO_dx_ki, + float sigma_x, + float sigma_y, + float sigma_z, + float colorSigma) { + torch::Tensor (*filterFunction)( + torch::Tensor, torch::Tensor, torch::Tensor, torch::Tensor, torch::Tensor, float, float, float, float); + +#ifdef WITH_CUDA + + if (torch::cuda::is_available() && gradientInputTensor.is_cuda()) { + CHECK_CONTIGUOUS_CUDA(gradientInputTensor); + + if (gradientInputTensor.size(1) > BF_CUDA_MAX_CHANNELS) { + throw std::runtime_error( + "Bilateral filtering not implemented for channel count > " + std::to_string(BF_CUDA_MAX_CHANNELS)); + } + + if (gradientInputTensor.dim() - 2 > BF_CUDA_MAX_SPATIAL_DIMENSION) { + throw std::runtime_error( + "Bilateral filtering not implemented for spatial dimension > " + + std::to_string(BF_CUDA_MAX_SPATIAL_DIMENSION)); + } + + filterFunction = &BilateralFilterCudaBackward; + } else { + filterFunction = &BilateralFilterCpuBackward; + } +#else + filterFunction = &BilateralFilterCpuBackward; +#endif + + return filterFunction( + gradientInputTensor, + inputTensor, + outputTensor, + outputWeightsTensor, + dO_dx_ki, + sigma_x, + sigma_y, + sigma_z, + colorSigma); +} diff --git a/source_code/SegMamba/monai/csrc/filtering/trainable_bilateral/trainable_bilateral.h b/source_code/SegMamba/monai/csrc/filtering/trainable_bilateral/trainable_bilateral.h new file mode 100644 index 0000000000000000000000000000000000000000..7420fe82fd25479bcaf7e59f017bae8baf4fc0fb --- /dev/null +++ b/source_code/SegMamba/monai/csrc/filtering/trainable_bilateral/trainable_bilateral.h @@ -0,0 +1,88 @@ +/* +Copyright (c) MONAI Consortium +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + http://www.apache.org/licenses/LICENSE-2.0 +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + +========================================================================= +Adapted from https://github.com/faebstn96/trainable-bilateral-filter-source +which has the following license... +https://github.com/faebstn96/trainable-bilateral-filter-source/blob/main/LICENSE.md + +Copyright 2022 Fabian Wagner, Pattern Recognition Lab, FAU Erlangen-Nuernberg, Erlangen, Germany +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + http://www.apache.org/licenses/LICENSE-2.0 +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +#pragma once + +#include +#include +#include +#include +#include "utils/common_utils.h" +//#include "utils/tensor_description.h" + +#define BF_CUDA_MAX_CHANNELS 16 +#define BF_CUDA_MAX_SPATIAL_DIMENSION 3 + +#ifdef WITH_CUDA +std::tuple +BilateralFilterCudaForward(torch::Tensor inputTensor, float sigma_x, float sigma_y, float sigma_z, float colorSigma); +torch::Tensor BilateralFilterCudaBackward( + torch::Tensor gradientInputTensor, + torch::Tensor inputTensor, + torch::Tensor outputTensor, + torch::Tensor outputWeightsTensor, + torch::Tensor dO_dx_ki, + float sigma_x, + float sigma_y, + float sigma_z, + float colorSigma); +#endif + +std::tuple +BilateralFilterCpuForward(torch::Tensor inputTensor, float sigma_x, float sigma_y, float sigma_z, float colorSigma); + +torch::Tensor BilateralFilterCpuBackward( + torch::Tensor gradientInputTensor, + torch::Tensor inputTensor, + torch::Tensor outputTensor, + torch::Tensor outputWeightsTensor, + torch::Tensor dO_dx_ki, + float sigma_x, + float sigma_y, + float sigma_z, + float colorSigma); + +std::tuple +TrainableBilateralFilterForward( + torch::Tensor inputTensor, + float sigma_x, + float sigma_y, + float sigma_z, + float colorSigma); + +torch::Tensor TrainableBilateralFilterBackward( + torch::Tensor gradientInputTensor, + torch::Tensor inputTensor, + torch::Tensor outputTensor, + torch::Tensor outputWeightsTensor, + torch::Tensor dO_dx_ki, + float sigma_x, + float sigma_y, + float sigma_z, + float colorSigma); diff --git a/source_code/SegMamba/monai/csrc/filtering/trainable_joint_bilateral/jbf_layer_cpu_backward.cpp b/source_code/SegMamba/monai/csrc/filtering/trainable_joint_bilateral/jbf_layer_cpu_backward.cpp new file mode 100644 index 0000000000000000000000000000000000000000..810c0b3fdacb402fe396ab14b731457690194f63 --- /dev/null +++ b/source_code/SegMamba/monai/csrc/filtering/trainable_joint_bilateral/jbf_layer_cpu_backward.cpp @@ -0,0 +1,246 @@ +/* +Copyright (c) MONAI Consortium +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + http://www.apache.org/licenses/LICENSE-2.0 +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + +========================================================================= +Adapted from https://github.com/faebstn96/trainable-joint-bilateral-filter-source +which has the following license... +https://github.com/faebstn96/trainable-joint-bilateral-filter-source/blob/main/LICENSE + +Copyright 2022 Fabian Wagner, Pattern Recognition Lab, FAU Erlangen-Nuernberg, Erlangen, Germany +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + http://www.apache.org/licenses/LICENSE-2.0 +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +#include "trainable_joint_bilateral.h" +#include "utils/tensor_description.h" +#include "utils/tensor_indexing.h" + +template +void JointBilateralFilterCpuBackward_3d( + torch::Tensor gradientInputTensor, + torch::Tensor gradientGuidanceTensor, + torch::Tensor gradientOutputTensor, + torch::Tensor inputTensor, + torch::Tensor guidanceTensor, + torch::Tensor outputTensor, + torch::Tensor outputWeightsTensor, + torch::Tensor dO_dz_ki, + float sigma_x, + float sigma_y, + float sigma_z, + float colorSigma) { + // Getting tensor description. + TensorDescription desc = TensorDescription(gradientInputTensor); + + // Raw tensor data pointers. + scalar_t* gradientInputTensorData = gradientInputTensor.data_ptr(); + scalar_t* gradientGuidanceTensorData = gradientGuidanceTensor.data_ptr(); + scalar_t* gradientOutputTensorData = gradientOutputTensor.data_ptr(); + scalar_t* inputTensorData = inputTensor.data_ptr(); + scalar_t* guidanceTensorData = guidanceTensor.data_ptr(); + scalar_t* outputTensorData = outputTensor.data_ptr(); + scalar_t* outputWeightsTensorData = outputWeightsTensor.data_ptr(); + scalar_t* dO_dz_kiData = dO_dz_ki.data_ptr(); + // scalar_t* dw_dx_kiData = dw_dx_ki_Tensor.data_ptr(); + // scalar_t* dfilter_dx_kiData = dfilter_dx_ki_Tensor.data_ptr(); + + // Pre-calculate common values + int windowSize_x = std::max(((int)ceil(5.0f * sigma_x) | 1), 5); // ORing last bit to ensure odd window size + int windowSize_y = std::max(((int)ceil(5.0f * sigma_y) | 1), 5); // ORing last bit to ensure odd window size + int windowSize_z = std::max(((int)ceil(5.0f * sigma_z) | 1), 5); // ORing last bit to ensure odd window size + int halfWindowSize_x = floor(0.5f * windowSize_x); + int halfWindowSize_y = floor(0.5f * windowSize_y); + int halfWindowSize_z = floor(0.5f * windowSize_z); + int halfWindowSize_arr[] = {halfWindowSize_x, halfWindowSize_y, halfWindowSize_z}; + scalar_t spatialExpConstant_x = -1.0f / (2 * sigma_x * sigma_x); + scalar_t spatialExpConstant_y = -1.0f / (2 * sigma_y * sigma_y); + scalar_t spatialExpConstant_z = -1.0f / (2 * sigma_z * sigma_z); + scalar_t colorExpConstant = -1.0f / (2 * colorSigma * colorSigma); + + // Set kernel sizes with respect to the defined spatial sigmas. + int* kernelSizes = new int[desc.dimensions]; + + kernelSizes[0] = windowSize_x; + kernelSizes[1] = windowSize_y; + kernelSizes[2] = windowSize_z; + + // Pre-calculate gaussian kernel and distance map in 1D. + scalar_t* gaussianKernel_x = new scalar_t[windowSize_x]; + scalar_t* gaussianKernel_y = new scalar_t[windowSize_y]; + scalar_t* gaussianKernel_z = new scalar_t[windowSize_z]; + scalar_t* xDistanceSquared = new scalar_t[windowSize_x]; + scalar_t* yDistanceSquared = new scalar_t[windowSize_y]; + scalar_t* zDistanceSquared = new scalar_t[windowSize_z]; + + for (int i = 0; i < windowSize_x; i++) { + int distance = i - halfWindowSize_x; + gaussianKernel_x[i] = exp(distance * distance * spatialExpConstant_x); + xDistanceSquared[i] = distance * distance; + } + for (int i = 0; i < windowSize_y; i++) { + int distance = i - halfWindowSize_y; + gaussianKernel_y[i] = exp(distance * distance * spatialExpConstant_y); + yDistanceSquared[i] = distance * distance; + } + for (int i = 0; i < windowSize_z; i++) { + int distance = i - halfWindowSize_z; + gaussianKernel_z[i] = exp(distance * distance * spatialExpConstant_z); + zDistanceSquared[i] = distance * distance; + } + + // Looping over the batches + for (int b = 0; b < desc.batchCount; b++) { + int batchOffset = b * desc.batchStride; + + // Looping over all dimensions for the home element + for (int z = 0; z < desc.sizes[2]; z++) +#pragma omp parallel for + for (int y = 0; y < desc.sizes[1]; y++) { + for (int x = 0; x < desc.sizes[0]; x++) { + // Calculating indexing offset for the home element + int homeOffset = batchOffset; + + int homeIndex[] = {x, y, z}; + homeOffset += x * desc.strides[0]; + homeOffset += y * desc.strides[1]; + homeOffset += z * desc.strides[2]; + + // Zero kernel aggregates. + scalar_t filter_kernel_guidance = 0; + scalar_t valueSumGuidance = 0; + scalar_t valueSumInput = 0; + + // Looping over all dimensions for the neighbour element + Indexer kernelIndex = Indexer(desc.dimensions, kernelSizes); + do // while(kernelIndex++) + { + // Calculating buffer offset for the neighbour element + // Index is clamped to the border in each dimension. + int neighbourOffset = batchOffset; + bool flagNotClamped = true; + + for (int i = 0; i < desc.dimensions; i++) { + int neighbourIndex = homeIndex[i] + kernelIndex[i] - halfWindowSize_arr[i]; + int neighbourIndexClamped = std::min(desc.sizes[i] - 1, std::max(0, neighbourIndex)); + neighbourOffset += neighbourIndexClamped * desc.strides[i]; + if (neighbourIndex != neighbourIndexClamped) { + flagNotClamped = false; + } + } + + // Euclidean color distance. + scalar_t colorDistance = 0; + scalar_t colorDistanceSquared = 0; + + for (int i = 0; i < desc.channelCount; i++) { + scalar_t diff = guidanceTensorData[neighbourOffset + i * desc.channelStride] - + guidanceTensorData[homeOffset + i * desc.channelStride]; // Be careful: Here it is (Z_k - Z_i) and not + // (Z_i - Z_q) + colorDistance += diff; // Do not take the absolute value here. Be careful with the signs. + colorDistanceSquared += diff * diff; + } + + // Calculating and combining the spatial + // and color weights. + scalar_t spatialWeight = 1; + + spatialWeight = + gaussianKernel_x[kernelIndex[0]] * gaussianKernel_y[kernelIndex[1]] * gaussianKernel_z[kernelIndex[2]]; + + scalar_t colorWeight = exp(colorDistanceSquared * colorExpConstant); + scalar_t totalWeight = spatialWeight * colorWeight; + + // Aggregating values. Only do this if flagNotClamped: Pixels outside the image are disregarded. + if (flagNotClamped) { + for (int i = 0; i < desc.channelCount; i++) { + // Distinguish cases for k!=i (calculation is done here) + // and k==i (partial derivatives are precalculated). + // If statement replaces center element of neighborhood/kernel. + if (kernelIndex[0] != halfWindowSize_x || kernelIndex[1] != halfWindowSize_y || + kernelIndex[2] != halfWindowSize_z) { + filter_kernel_guidance = -(1 / outputWeightsTensorData[neighbourOffset + i * desc.channelStride]) * + outputTensorData[neighbourOffset + i * desc.channelStride] * totalWeight * colorDistance / + (colorSigma * colorSigma) + + (1 / outputWeightsTensorData[neighbourOffset + i * desc.channelStride]) * totalWeight * + (inputTensorData[homeOffset + i * desc.channelStride] * colorDistance / + (colorSigma * colorSigma)); // inputTensorData[homeOffset] !!, no +1!! + } else { + filter_kernel_guidance = dO_dz_kiData[homeOffset + i * desc.channelStride]; + } + + valueSumGuidance += + gradientInputTensorData[neighbourOffset + i * desc.channelStride] * filter_kernel_guidance; + valueSumInput += gradientInputTensorData[neighbourOffset + i * desc.channelStride] * + (1 / outputWeightsTensorData[neighbourOffset + i * desc.channelStride]) * totalWeight; + } + } + } while (kernelIndex++); + + // Do the filtering and calculate the values for the backward pass. + for (int i = 0; i < desc.channelCount; i++) { + // Filtering: + gradientGuidanceTensorData[homeOffset + i * desc.channelStride] = valueSumGuidance; + gradientOutputTensorData[homeOffset + i * desc.channelStride] = valueSumInput; + } + } + } + } + + delete[] kernelSizes; + delete[] gaussianKernel_x; + delete[] gaussianKernel_y; + delete[] gaussianKernel_z; + delete[] xDistanceSquared; + delete[] yDistanceSquared; + delete[] zDistanceSquared; +} + +std::tuple JointBilateralFilterCpuBackward( + torch::Tensor gradientInputTensor, + torch::Tensor inputTensor, + torch::Tensor guidanceTensor, + torch::Tensor outputTensor, + torch::Tensor outputWeightsTensor, + torch::Tensor dO_dz_ki, + float sigma_x, + float sigma_y, + float sigma_z, + float colorSigma) { + // Preparing output tensor. + torch::Tensor gradientOutputTensor = torch::zeros_like(gradientInputTensor); + torch::Tensor gradientGuidanceTensor = torch::zeros_like(gradientInputTensor); + + AT_DISPATCH_FLOATING_TYPES_AND_HALF(gradientInputTensor.scalar_type(), "JointBilateralFilterCpuBackward_3d", ([&] { + JointBilateralFilterCpuBackward_3d( + gradientInputTensor, + gradientGuidanceTensor, + gradientOutputTensor, + inputTensor, + guidanceTensor, + outputTensor, + outputWeightsTensor, + dO_dz_ki, + sigma_x, + sigma_y, + sigma_z, + colorSigma); + })); + + return {gradientOutputTensor, gradientGuidanceTensor}; +} diff --git a/source_code/SegMamba/monai/csrc/filtering/trainable_joint_bilateral/jbf_layer_cpu_forward.cpp b/source_code/SegMamba/monai/csrc/filtering/trainable_joint_bilateral/jbf_layer_cpu_forward.cpp new file mode 100644 index 0000000000000000000000000000000000000000..041b10f7d832cc5725dd8955ad11e0ee043ff3fd --- /dev/null +++ b/source_code/SegMamba/monai/csrc/filtering/trainable_joint_bilateral/jbf_layer_cpu_forward.cpp @@ -0,0 +1,278 @@ +/* +Copyright (c) MONAI Consortium +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + http://www.apache.org/licenses/LICENSE-2.0 +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + +========================================================================= +Adapted from https://github.com/faebstn96/trainable-joint-bilateral-filter-source +which has the following license... +https://github.com/faebstn96/trainable-joint-bilateral-filter-source/blob/main/LICENSE + +Copyright 2022 Fabian Wagner, Pattern Recognition Lab, FAU Erlangen-Nuernberg, Erlangen, Germany +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + http://www.apache.org/licenses/LICENSE-2.0 +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +#include "trainable_joint_bilateral.h" +#include "utils/tensor_description.h" +#include "utils/tensor_indexing.h" + +template +void JointBilateralFilterCpuForward_3d( + torch::Tensor inputTensor, + torch::Tensor guidanceTensor, + torch::Tensor outputTensor, + torch::Tensor outputWeightsTensor, + torch::Tensor dO_dz_ki, + torch::Tensor dO_dsig_r, + torch::Tensor dO_dsig_x, + torch::Tensor dO_dsig_y, + torch::Tensor dO_dsig_z, + float sigma_x, + float sigma_y, + float sigma_z, + float colorSigma) { + // Getting tensor description. + TensorDescription desc = TensorDescription(inputTensor); + + // Raw tensor data pointers. + scalar_t* inputTensorData = inputTensor.data_ptr(); + scalar_t* guidanceTensorData = guidanceTensor.data_ptr(); + scalar_t* outputTensorData = outputTensor.data_ptr(); + scalar_t* outputWeightsTensorData = outputWeightsTensor.data_ptr(); + scalar_t* dO_dz_kiData = dO_dz_ki.data_ptr(); + scalar_t* dO_dsig_rData = dO_dsig_r.data_ptr(); + scalar_t* dO_dsig_xData = dO_dsig_x.data_ptr(); + scalar_t* dO_dsig_yData = dO_dsig_y.data_ptr(); + scalar_t* dO_dsig_zData = dO_dsig_z.data_ptr(); + + // Pre-calculate common values + int windowSize_x = std::max(((int)ceil(5.0f * sigma_x) | 1), 5); // ORing last bit to ensure odd window size + int windowSize_y = std::max(((int)ceil(5.0f * sigma_y) | 1), 5); // ORing last bit to ensure odd window size + int windowSize_z = std::max(((int)ceil(5.0f * sigma_z) | 1), 5); // ORing last bit to ensure odd window size + int halfWindowSize_x = floor(0.5f * windowSize_x); + int halfWindowSize_y = floor(0.5f * windowSize_y); + int halfWindowSize_z = floor(0.5f * windowSize_z); + int halfWindowSize_arr[] = {halfWindowSize_x, halfWindowSize_y, halfWindowSize_z}; + scalar_t spatialExpConstant_x = -1.0f / (2 * sigma_x * sigma_x); + scalar_t spatialExpConstant_y = -1.0f / (2 * sigma_y * sigma_y); + scalar_t spatialExpConstant_z = -1.0f / (2 * sigma_z * sigma_z); + scalar_t colorExpConstant = -1.0f / (2 * colorSigma * colorSigma); + + // Set kernel sizes with respect to the defined spatial sigmas. + int* kernelSizes = new int[desc.dimensions]; + + kernelSizes[0] = windowSize_x; + kernelSizes[1] = windowSize_y; + kernelSizes[2] = windowSize_z; + + // Pre-calculate gaussian kernel and distance map in 1D. + scalar_t* gaussianKernel_x = new scalar_t[windowSize_x]; + scalar_t* gaussianKernel_y = new scalar_t[windowSize_y]; + scalar_t* gaussianKernel_z = new scalar_t[windowSize_z]; + scalar_t* xDistanceSquared = new scalar_t[windowSize_x]; + scalar_t* yDistanceSquared = new scalar_t[windowSize_y]; + scalar_t* zDistanceSquared = new scalar_t[windowSize_z]; + + for (int i = 0; i < windowSize_x; i++) { + int distance = i - halfWindowSize_x; + gaussianKernel_x[i] = exp(distance * distance * spatialExpConstant_x); + xDistanceSquared[i] = distance * distance; + } + for (int i = 0; i < windowSize_y; i++) { + int distance = i - halfWindowSize_y; + gaussianKernel_y[i] = exp(distance * distance * spatialExpConstant_y); + yDistanceSquared[i] = distance * distance; + } + for (int i = 0; i < windowSize_z; i++) { + int distance = i - halfWindowSize_z; + gaussianKernel_z[i] = exp(distance * distance * spatialExpConstant_z); + zDistanceSquared[i] = distance * distance; + } + + // Looping over the batches + for (int b = 0; b < desc.batchCount; b++) { + int batchOffset = b * desc.batchStride; + + // Looping over all dimensions for the home element + for (int z = 0; z < desc.sizes[2]; z++) +#pragma omp parallel for + for (int y = 0; y < desc.sizes[1]; y++) { + for (int x = 0; x < desc.sizes[0]; x++) { + // Calculating indexing offset for the home element + int homeOffset = batchOffset; + + int homeIndex[] = {x, y, z}; + homeOffset += x * desc.strides[0]; + homeOffset += y * desc.strides[1]; + homeOffset += z * desc.strides[2]; + + // Zero kernel aggregates. + scalar_t valueSum = 0; + scalar_t dw_dz_ki = 0; + scalar_t dfilter_dz_ki = 0; + scalar_t colorSum_w = 0; + scalar_t colorSum_alpha = 0; + scalar_t xSum_w = 0; + scalar_t xSum_alpha = 0; + scalar_t ySum_w = 0; + scalar_t ySum_alpha = 0; + scalar_t zSum_w = 0; + scalar_t zSum_alpha = 0; + + scalar_t weightSum = 0.0f; + + // Looping over all dimensions for the neighbour element + Indexer kernelIndex = Indexer(desc.dimensions, kernelSizes); + do // while(kernelIndex++) + { + // Calculating buffer offset for the neighbour element + // Index is clamped to the border in each dimension. + int neighbourOffset = batchOffset; + bool flagNotClamped = true; + + for (int i = 0; i < desc.dimensions; i++) { + int neighbourIndex = homeIndex[i] + kernelIndex[i] - halfWindowSize_arr[i]; + int neighbourIndexClamped = std::min(desc.sizes[i] - 1, std::max(0, neighbourIndex)); + neighbourOffset += neighbourIndexClamped * desc.strides[i]; + if (neighbourIndex != neighbourIndexClamped) { + flagNotClamped = false; + } + } + + // Euclidean color distance. + scalar_t colorDistance = 0; + scalar_t colorDistanceSquared = 0; + + for (int i = 0; i < desc.channelCount; i++) { + scalar_t diff = guidanceTensorData[homeOffset + i * desc.channelStride] - + guidanceTensorData[neighbourOffset + i * desc.channelStride]; + colorDistance += diff; // Do not take the absolute value here. Be careful with the signs. + colorDistanceSquared += diff * diff; + } + + // Calculating and combining the spatial + // and color weights. + scalar_t spatialWeight = 1; + + spatialWeight = + gaussianKernel_x[kernelIndex[0]] * gaussianKernel_y[kernelIndex[1]] * gaussianKernel_z[kernelIndex[2]]; + + scalar_t colorWeight = exp(colorDistanceSquared * colorExpConstant); + scalar_t totalWeight = spatialWeight * colorWeight; + + // Aggregating values. Only do this if flagNotClamped: Pixels outside the image are disregarded. + if (flagNotClamped) { + for (int i = 0; i < desc.channelCount; i++) { + valueSum += inputTensorData[neighbourOffset + i * desc.channelStride] * totalWeight; + + // Derivative of weights with respect to X_i while i=k. + dw_dz_ki += (-1) * totalWeight * colorDistance / (colorSigma * colorSigma); + // Derivative of convolved image with respect to X_i while i=k. + dfilter_dz_ki += (-1) * totalWeight * inputTensorData[neighbourOffset + i * desc.channelStride] * + colorDistance / + (colorSigma * + colorSigma); // Be careful, the +1 is missing here -> Added before filling dfilter_dx_kiData + + colorSum_w += totalWeight * colorDistanceSquared / std::abs(colorSigma * colorSigma * colorSigma); + colorSum_alpha += totalWeight * inputTensorData[neighbourOffset + i * desc.channelStride] * + colorDistanceSquared / std::abs(colorSigma * colorSigma * colorSigma); + + xSum_w += totalWeight * xDistanceSquared[kernelIndex[0]] / std::abs(sigma_x * sigma_x * sigma_x); + xSum_alpha += totalWeight * inputTensorData[neighbourOffset + i * desc.channelStride] * + xDistanceSquared[kernelIndex[0]] / std::abs(sigma_x * sigma_x * sigma_x); + + ySum_w += totalWeight * yDistanceSquared[kernelIndex[1]] / std::abs(sigma_y * sigma_y * sigma_y); + ySum_alpha += totalWeight * inputTensorData[neighbourOffset + i * desc.channelStride] * + yDistanceSquared[kernelIndex[1]] / std::abs(sigma_y * sigma_y * sigma_y); + + zSum_w += totalWeight * zDistanceSquared[kernelIndex[2]] / std::abs(sigma_z * sigma_z * sigma_z); + zSum_alpha += totalWeight * inputTensorData[neighbourOffset + i * desc.channelStride] * + zDistanceSquared[kernelIndex[2]] / std::abs(sigma_z * sigma_z * sigma_z); + } + + weightSum += totalWeight; + } + } while (kernelIndex++); + + // Do the filtering and calculate the values for the backward pass. + for (int i = 0; i < desc.channelCount; i++) { + // Filtering: + outputTensorData[homeOffset + i * desc.channelStride] = valueSum / weightSum; + + // Pre-computations for the backward pass: + outputWeightsTensorData[homeOffset + i * desc.channelStride] = weightSum; + dO_dz_kiData[homeOffset + i * desc.channelStride] = -(1 / weightSum) * (valueSum / weightSum) * dw_dz_ki + + (1 / weightSum) * (dfilter_dz_ki); // no +1 for dfilter_dz_ki for JBF added here! + dO_dsig_rData[homeOffset + i * desc.channelStride] = + -(1 / weightSum) * (valueSum / weightSum) * colorSum_w + (1 / weightSum) * colorSum_alpha; + dO_dsig_xData[homeOffset + i * desc.channelStride] = + -(1 / weightSum) * (valueSum / weightSum) * xSum_w + (1 / weightSum) * xSum_alpha; + dO_dsig_yData[homeOffset + i * desc.channelStride] = + -(1 / weightSum) * (valueSum / weightSum) * ySum_w + (1 / weightSum) * ySum_alpha; + dO_dsig_zData[homeOffset + i * desc.channelStride] = + -(1 / weightSum) * (valueSum / weightSum) * zSum_w + (1 / weightSum) * zSum_alpha; + } + } + } + } + + delete[] kernelSizes; + delete[] gaussianKernel_x; + delete[] gaussianKernel_y; + delete[] gaussianKernel_z; + delete[] xDistanceSquared; + delete[] yDistanceSquared; + delete[] zDistanceSquared; +} + +std::tuple +JointBilateralFilterCpuForward( + torch::Tensor inputTensor, + torch::Tensor guidanceTensor, + float sigma_x, + float sigma_y, + float sigma_z, + float colorSigma) { + // Preparing output tensor. + torch::Tensor outputTensor = torch::zeros_like(inputTensor); + torch::Tensor outputWeightsTensor = torch::zeros_like(inputTensor); + torch::Tensor dO_dz_ki = torch::zeros_like(inputTensor); + torch::Tensor dO_dsig_r = torch::zeros_like(inputTensor); + torch::Tensor dO_dsig_x = torch::zeros_like(inputTensor); + torch::Tensor dO_dsig_y = torch::zeros_like(inputTensor); + torch::Tensor dO_dsig_z = torch::zeros_like(inputTensor); + + AT_DISPATCH_FLOATING_TYPES_AND_HALF(inputTensor.scalar_type(), "JointBilateralFilterCpuForward_3d", ([&] { + JointBilateralFilterCpuForward_3d( + inputTensor, + guidanceTensor, + outputTensor, + outputWeightsTensor, + dO_dz_ki, + dO_dsig_r, + dO_dsig_x, + dO_dsig_y, + dO_dsig_z, + sigma_x, + sigma_y, + sigma_z, + colorSigma); + })); + + return {outputTensor, outputWeightsTensor, dO_dz_ki, dO_dsig_r, dO_dsig_x, dO_dsig_y, dO_dsig_z}; +} diff --git a/source_code/SegMamba/monai/csrc/filtering/trainable_joint_bilateral/jbf_layer_gpu_backward.cu b/source_code/SegMamba/monai/csrc/filtering/trainable_joint_bilateral/jbf_layer_gpu_backward.cu new file mode 100644 index 0000000000000000000000000000000000000000..39899140157fb0f35e6d78dc935ba9d8a5eb0ee2 --- /dev/null +++ b/source_code/SegMamba/monai/csrc/filtering/trainable_joint_bilateral/jbf_layer_gpu_backward.cu @@ -0,0 +1,311 @@ +/* +Copyright (c) MONAI Consortium +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + http://www.apache.org/licenses/LICENSE-2.0 +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + +========================================================================= +Adapted from https://github.com/faebstn96/trainable-joint-bilateral-filter-source +which has the following license... +https://github.com/faebstn96/trainable-joint-bilateral-filter-source/blob/main/LICENSE + +Copyright 2022 Fabian Wagner, Pattern Recognition Lab, FAU Erlangen-Nuernberg, Erlangen, Germany +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + http://www.apache.org/licenses/LICENSE-2.0 +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +#include +#include + +#include "trainable_joint_bilateral.h" +//#include "../utils/cuda_error_check.h" +#include "utils/meta_macros.h" +#include "utils/tensor_description.h" + +__constant__ int cBatchStrideBack; +__constant__ int cColorStrideBack; + +__constant__ int cSizesBack[3]; +__constant__ int cStridesBack[3]; + +__constant__ int cKernelSizesBack[3]; +__constant__ int cHalfWindowSize_arrBack[3]; +__constant__ float cGaussianKernel_xBack[256]; +__constant__ float cGaussianKernel_yBack[256]; +__constant__ float cGaussianKernel_zBack[256]; +__constant__ float cXDistanceSquaredBack[256]; +__constant__ float cYDistanceSquaredBack[256]; +__constant__ float cZDistanceSquaredBack[256]; +__constant__ float cColorExponentConstantBack; +__constant__ float cSigma_xBack; +__constant__ float cSigma_yBack; +__constant__ float cSigma_zBack; +__constant__ float cColorSigmaBack; + +template +__global__ void JointBilateralFilterCudaKernel3DBackward( + scalar_t* gradientInputTensor, + scalar_t* gradientGuidanceTensor, + scalar_t* gradientOutputTensor, + scalar_t* inputTensor, + scalar_t* guidanceTensor, + scalar_t* outputTensor, + scalar_t* outputWeightsTensor, + scalar_t* dO_dz_ki) { + int homeOffset = blockIdx.x * blockDim.x + threadIdx.x; + int batchOffset = blockIdx.y * cBatchStrideBack; + + if (homeOffset >= cColorStrideBack) + return; + + int homeX = homeOffset / cStridesBack[0]; + int homeY = (homeOffset - homeX * cStridesBack[0]) / cStridesBack[1]; + int homeZ = (homeOffset - homeX * cStridesBack[0] - homeY * cStridesBack[1]) / cStridesBack[2]; + int homeIndex[] = {homeX, homeY, homeZ}; + + // Zero kernel aggregates. + scalar_t valueSumGuidance = 0; + scalar_t valueSumInput = 0; + + for (int kernelX = 0; kernelX < cKernelSizesBack[0]; kernelX++) { + int neighbourX = max(0, min(homeX + (kernelX - cHalfWindowSize_arrBack[0]), cSizesBack[0] - 1)); + scalar_t gaussianX = cGaussianKernel_xBack[kernelX]; + + for (int kernelY = 0; kernelY < cKernelSizesBack[1]; kernelY++) { + int neighbourY = max(0, min(homeY + (kernelY - cHalfWindowSize_arrBack[1]), cSizesBack[1] - 1)); + scalar_t gaussianY = cGaussianKernel_yBack[kernelY]; + + for (int kernelZ = 0; kernelZ < cKernelSizesBack[2]; kernelZ++) { + int neighbourZ = max(0, min(homeZ + (kernelZ - cHalfWindowSize_arrBack[2]), cSizesBack[2] - 1)); + scalar_t gaussianZ = cGaussianKernel_zBack[kernelZ]; + + int neighbourOffset = neighbourX * cStridesBack[0] + neighbourY * cStridesBack[1] + neighbourZ; + + bool flagNotClamped = true; + int kernelIndex[] = {kernelX, kernelY, kernelZ}; + int dimensions = 3; // Must equal the number of spatial dimensions. + + for (int i = 0; i < dimensions; i++) { + int HalfWindowSizeBack = cHalfWindowSize_arrBack[i]; // Define constant memory as new variable here (!!), + // otherwise: cudaErrorMisalignedAddress + int neighbourIndex = homeIndex[i] + kernelIndex[i] - HalfWindowSizeBack; + int neighbourIndexClamped = min(cSizesBack[i] - 1, max(0, neighbourIndex)); + if (neighbourIndex != neighbourIndexClamped) { + flagNotClamped = false; + } + } + + scalar_t colorDistance = 0; + scalar_t colorDistanceSquared = 0; + +#pragma unroll + for (int c = 0; c < C; c++) { + scalar_t a = guidanceTensor[batchOffset + neighbourOffset + c * cColorStrideBack]; + scalar_t b = guidanceTensor[batchOffset + homeOffset + c * cColorStrideBack]; // Be careful: Here it is (Z_k - + // Z_i) and not (Z_i - Z_q) + scalar_t diff = a - b; + colorDistance += diff; // Do not take the absolute value here. Be careful with the signs. + colorDistanceSquared += diff * diff; + } + + scalar_t spatialWeight = gaussianX * gaussianY * gaussianZ; + scalar_t colorWeight = exp(cColorExponentConstantBack * colorDistanceSquared); + scalar_t totalWeight = spatialWeight * colorWeight; + + // Aggregating values. Only do this if flagNotClamped: Pixels outside the image are disregarded. + if (flagNotClamped) { + scalar_t filter_kernel_guidance_back; + +#pragma unroll + for (int c = 0; c < C; c++) { + // Distinguish cases for k!=i (calculation is done here) + // and k==i (partial derivatives are precalculated). + // If statement replaces center element of neighborhood/kernel. + if (kernelX != cHalfWindowSize_arrBack[0] || kernelY != cHalfWindowSize_arrBack[1] || + kernelZ != cHalfWindowSize_arrBack[2]) { + filter_kernel_guidance_back = + -(1 / outputWeightsTensor[batchOffset + neighbourOffset + c * cColorStrideBack]) * + outputTensor[batchOffset + neighbourOffset + c * cColorStrideBack] * totalWeight * colorDistance / + (cColorSigmaBack * cColorSigmaBack) + + (1 / outputWeightsTensor[batchOffset + neighbourOffset + c * cColorStrideBack]) * totalWeight * + (inputTensor[batchOffset + homeOffset + c * cColorStrideBack] * colorDistance / + (cColorSigmaBack * cColorSigmaBack)); // inputTensorData[homeOffset] !!, no +1!! + } else { + filter_kernel_guidance_back = dO_dz_ki[batchOffset + homeOffset + c * cColorStrideBack]; + } + + valueSumGuidance += + gradientInputTensor[batchOffset + neighbourOffset + c * cColorStrideBack] * filter_kernel_guidance_back; + valueSumInput += gradientInputTensor[batchOffset + neighbourOffset + c * cColorStrideBack] * + (1 / outputWeightsTensor[batchOffset + neighbourOffset + c * cColorStrideBack]) * totalWeight; + } + } + } + } + } + +#pragma unroll + for (int c = 0; c < C; c++) { + gradientGuidanceTensor[batchOffset + homeOffset + c * cColorStrideBack] = valueSumGuidance; + gradientOutputTensor[batchOffset + homeOffset + c * cColorStrideBack] = valueSumInput; + } +} + +template +void JointBilateralFilterCudaBackwardFunction( + torch::Tensor gradientInputTensor, + torch::Tensor gradientGuidanceTensor, + torch::Tensor gradientOutputTensor, + torch::Tensor inputTensor, + torch::Tensor guidanceTensor, + torch::Tensor outputTensor, + torch::Tensor outputWeightsTensor, + torch::Tensor dO_dz_ki, + float sigma_x, + float sigma_y, + float sigma_z, + float colorSigma) { + // Getting tensor description. + TensorDescription desc = TensorDescription(inputTensor); + + // Pre-calculating gaussian kernel. + int windowSize_x = std::max(((int)ceil(5.0f * sigma_x) | 1), 5); // ORing last bit to ensure odd window size + int windowSize_y = std::max(((int)ceil(5.0f * sigma_y) | 1), 5); // ORing last bit to ensure odd window size + int windowSize_z = std::max(((int)ceil(5.0f * sigma_z) | 1), 5); // ORing last bit to ensure odd window size + int halfWindowSize_x = floor(0.5f * windowSize_x); + int halfWindowSize_y = floor(0.5f * windowSize_y); + int halfWindowSize_z = floor(0.5f * windowSize_z); + int halfWindowSize_arr[] = {halfWindowSize_x, halfWindowSize_y, halfWindowSize_z}; + float spatialExpConstant_x = -1.0f / (2 * sigma_x * sigma_x); + float spatialExpConstant_y = -1.0f / (2 * sigma_y * sigma_y); + float spatialExpConstant_z = -1.0f / (2 * sigma_z * sigma_z); + float colorExpConstant = -1.0f / (2 * colorSigma * colorSigma); + + int* kernelSizes = new int[desc.dimensions]; + kernelSizes[0] = windowSize_x; + kernelSizes[1] = windowSize_y; + kernelSizes[2] = windowSize_z; + + auto* gaussianKernel_x = new float[windowSize_x]; + auto* gaussianKernel_y = new float[windowSize_y]; + auto* gaussianKernel_z = new float[windowSize_z]; + auto* xDistanceSquared = new float[windowSize_x]; + auto* yDistanceSquared = new float[windowSize_y]; + auto* zDistanceSquared = new float[windowSize_z]; + + for (int i = 0; i < windowSize_x; i++) { + int distance = i - halfWindowSize_x; + gaussianKernel_x[i] = exp(distance * distance * spatialExpConstant_x); + xDistanceSquared[i] = distance * distance; + } + for (int i = 0; i < windowSize_y; i++) { + int distance = i - halfWindowSize_y; + gaussianKernel_y[i] = exp(distance * distance * spatialExpConstant_y); + yDistanceSquared[i] = distance * distance; + } + for (int i = 0; i < windowSize_z; i++) { + int distance = i - halfWindowSize_z; + gaussianKernel_z[i] = exp(distance * distance * spatialExpConstant_z); + zDistanceSquared[i] = distance * distance; + } + + // Writing constant memory. + cudaMemcpyToSymbol(cBatchStrideBack, &desc.batchStride, sizeof(int)); + cudaMemcpyToSymbol(cColorStrideBack, &desc.channelStride, sizeof(int)); + cudaMemcpyToSymbol(cSizesBack, desc.sizes, sizeof(int) * 3); + cudaMemcpyToSymbol(cStridesBack, desc.strides, sizeof(int) * 3); + cudaMemcpyToSymbol(cKernelSizesBack, kernelSizes, sizeof(int) * desc.dimensions); + cudaMemcpyToSymbol(cHalfWindowSize_arrBack, halfWindowSize_arr, sizeof(int) * desc.dimensions); + cudaMemcpyToSymbol(cGaussianKernel_xBack, gaussianKernel_x, sizeof(float) * windowSize_x); + cudaMemcpyToSymbol(cGaussianKernel_yBack, gaussianKernel_y, sizeof(float) * windowSize_y); + cudaMemcpyToSymbol(cGaussianKernel_zBack, gaussianKernel_z, sizeof(float) * windowSize_z); + cudaMemcpyToSymbol(cXDistanceSquaredBack, xDistanceSquared, sizeof(float) * windowSize_x); + cudaMemcpyToSymbol(cYDistanceSquaredBack, yDistanceSquared, sizeof(float) * windowSize_y); + cudaMemcpyToSymbol(cZDistanceSquaredBack, zDistanceSquared, sizeof(float) * windowSize_z); + cudaMemcpyToSymbol(cColorExponentConstantBack, &colorExpConstant, sizeof(float)); + cudaMemcpyToSymbol(cSigma_xBack, &sigma_x, sizeof(float)); + cudaMemcpyToSymbol(cSigma_yBack, &sigma_y, sizeof(float)); + cudaMemcpyToSymbol(cSigma_zBack, &sigma_z, sizeof(float)); + cudaMemcpyToSymbol(cColorSigmaBack, &colorSigma, sizeof(float)); + + // cuda_error_check("Cuda check before kernel call."); + +#define BLOCK_SIZE 32 + + AT_DISPATCH_FLOATING_TYPES_AND_HALF( + inputTensor.scalar_type(), "JointBilateralFilterCudaKernel3DBackward", ([&] { + JointBilateralFilterCudaKernel3DBackward + <<>>( + gradientInputTensor.data_ptr(), + gradientGuidanceTensor.data_ptr(), + gradientOutputTensor.data_ptr(), + inputTensor.data_ptr(), + guidanceTensor.data_ptr(), + outputTensor.data_ptr(), + outputWeightsTensor.data_ptr(), + dO_dz_ki.data_ptr()); + })); + + // cuda_error_check("Cuda check after kernel call."); + // delete[] kernel; + delete[] kernelSizes; + delete[] gaussianKernel_x; + delete[] gaussianKernel_y; + delete[] gaussianKernel_z; + delete[] xDistanceSquared; + delete[] yDistanceSquared; + delete[] zDistanceSquared; +} + +// Function to choose template implementation based on dynamic, channels and dimensions +std::tuple JointBilateralFilterCudaBackward( + torch::Tensor gradientInputTensor, + torch::Tensor inputTensor, + torch::Tensor guidanceTensor, + torch::Tensor outputTensor, + torch::Tensor outputWeightsTensor, + torch::Tensor dO_dz_ki, + float sigma_x, + float sigma_y, + float sigma_z, + float colorSigma) { + torch::Tensor gradientOutputTensor = torch::zeros_like(gradientInputTensor); + torch::Tensor gradientGuidanceTensor = torch::zeros_like(gradientInputTensor); + // cuda_error_check("beginning"); + +#define CASE(c, d) \ + JointBilateralFilterCudaBackwardFunction( \ + gradientInputTensor, \ + gradientGuidanceTensor, \ + gradientOutputTensor, \ + inputTensor, \ + guidanceTensor, \ + outputTensor, \ + outputWeightsTensor, \ + dO_dz_ki, \ + sigma_x, \ + sigma_y, \ + sigma_z, \ + colorSigma); + SWITCH_AB( + CASE, + BF_CUDA_MAX_CHANNELS, + BF_CUDA_MAX_SPATIAL_DIMENSION, + gradientInputTensor.size(1), + gradientInputTensor.dim() - 2); + + return {gradientOutputTensor, gradientGuidanceTensor}; +} diff --git a/source_code/SegMamba/monai/csrc/filtering/trainable_joint_bilateral/trainable_joint_bilateral.cpp b/source_code/SegMamba/monai/csrc/filtering/trainable_joint_bilateral/trainable_joint_bilateral.cpp new file mode 100644 index 0000000000000000000000000000000000000000..e06b97113a971da67e14b5f05e04e06e0c1f0d16 --- /dev/null +++ b/source_code/SegMamba/monai/csrc/filtering/trainable_joint_bilateral/trainable_joint_bilateral.cpp @@ -0,0 +1,133 @@ +/* +Copyright (c) MONAI Consortium +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + http://www.apache.org/licenses/LICENSE-2.0 +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + +========================================================================= +Adapted from https://github.com/faebstn96/trainable-joint-bilateral-filter-source +which has the following license... +https://github.com/faebstn96/trainable-joint-bilateral-filter-source/blob/main/LICENSE + +Copyright 2022 Fabian Wagner, Pattern Recognition Lab, FAU Erlangen-Nuernberg, Erlangen, Germany +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + http://www.apache.org/licenses/LICENSE-2.0 +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +#include +#include +#include + +#include "trainable_joint_bilateral.h" +#include "utils/common_utils.h" + +std::tuple +TrainableJointBilateralFilterForward( + torch::Tensor inputTensor, + torch::Tensor guidanceTensor, + float sigma_x, + float sigma_y, + float sigma_z, + float colorSigma) { + std::tuple ( + *filterFunction)(torch::Tensor, torch::Tensor, float, float, float, float); + +#ifdef WITH_CUDA + + if (torch::cuda::is_available() && inputTensor.is_cuda()) { + CHECK_CONTIGUOUS_CUDA(inputTensor); + + if (inputTensor.size(1) > BF_CUDA_MAX_CHANNELS) { + throw std::runtime_error( + "Bilateral filtering not implemented for channel count > " + std::to_string(BF_CUDA_MAX_CHANNELS)); + } + + if (inputTensor.dim() - 2 > BF_CUDA_MAX_SPATIAL_DIMENSION) { + throw std::runtime_error( + "Bilateral filtering not implemented for spatial dimension > " + + std::to_string(BF_CUDA_MAX_SPATIAL_DIMENSION)); + } + + filterFunction = &JointBilateralFilterCudaForward; + } else { + filterFunction = &JointBilateralFilterCpuForward; + } +#else + filterFunction = &JointBilateralFilterCpuForward; +#endif + + return filterFunction(inputTensor, guidanceTensor, sigma_x, sigma_y, sigma_z, colorSigma); +} + +std::tuple TrainableJointBilateralFilterBackward( + torch::Tensor gradientInputTensor, + torch::Tensor inputTensor, + torch::Tensor guidanceTensor, + torch::Tensor outputTensor, + torch::Tensor outputWeightsTensor, + torch::Tensor dO_dx_ki, + float sigma_x, + float sigma_y, + float sigma_z, + float colorSigma) { + std::tuple (*filterFunction)( + torch::Tensor, + torch::Tensor, + torch::Tensor, + torch::Tensor, + torch::Tensor, + torch::Tensor, + float, + float, + float, + float); + +#ifdef WITH_CUDA + + if (torch::cuda::is_available() && gradientInputTensor.is_cuda()) { + CHECK_CONTIGUOUS_CUDA(gradientInputTensor); + + if (gradientInputTensor.size(1) > BF_CUDA_MAX_CHANNELS) { + throw std::runtime_error( + "Bilateral filtering not implemented for channel count > " + std::to_string(BF_CUDA_MAX_CHANNELS)); + } + + if (gradientInputTensor.dim() - 2 > BF_CUDA_MAX_SPATIAL_DIMENSION) { + throw std::runtime_error( + "Bilateral filtering not implemented for spatial dimension > " + + std::to_string(BF_CUDA_MAX_SPATIAL_DIMENSION)); + } + + filterFunction = &JointBilateralFilterCudaBackward; + } else { + filterFunction = &JointBilateralFilterCpuBackward; + } +#else + filterFunction = &JointBilateralFilterCpuBackward; +#endif + + return filterFunction( + gradientInputTensor, + inputTensor, + guidanceTensor, + outputTensor, + outputWeightsTensor, + dO_dx_ki, + sigma_x, + sigma_y, + sigma_z, + colorSigma); +} diff --git a/source_code/SegMamba/monai/csrc/lltm/lltm_cpu.cpp b/source_code/SegMamba/monai/csrc/lltm/lltm_cpu.cpp new file mode 100644 index 0000000000000000000000000000000000000000..7cd2251f9fe6ac7c1d2dd12b630295680147b387 --- /dev/null +++ b/source_code/SegMamba/monai/csrc/lltm/lltm_cpu.cpp @@ -0,0 +1,90 @@ +/* +Copyright (c) MONAI Consortium +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + http://www.apache.org/licenses/LICENSE-2.0 +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +#include +#include + +// s'(z) = (1 - s(z)) * s(z) +torch::Tensor d_sigmoid(torch::Tensor z) { + auto s = torch::sigmoid(z); + return (1 - s) * s; +} + +// tanh'(z) = 1 - tanh^2(z) +torch::Tensor d_tanh(torch::Tensor z) { + return 1 - z.tanh().pow(2); +} + +// elu'(z) = relu'(z) + { alpha * exp(z) if (alpha * (exp(z) - 1)) < 0, else 0} +torch::Tensor d_elu(torch::Tensor z, torch::Scalar alpha = 1.0) { + auto e = z.exp(); + auto mask = (alpha * (e - 1)) < 0; + return (z > 0).type_as(z) + mask.type_as(z) * (alpha * e); +} + +std::vector lltm_cpu_forward( + torch::Tensor input, + torch::Tensor weights, + torch::Tensor bias, + torch::Tensor old_h, + torch::Tensor old_cell) { + auto X = torch::cat({old_h, input}, /*dim=*/1); + + auto gate_weights = torch::addmm(bias, X, weights.transpose(0, 1)); + auto gates = gate_weights.chunk(3, /*dim=*/1); + + auto input_gate = torch::sigmoid(gates[0]); + auto output_gate = torch::sigmoid(gates[1]); + auto candidate_cell = torch::elu(gates[2], /*alpha=*/1.0); + + auto new_cell = old_cell + candidate_cell * input_gate; + auto new_h = torch::tanh(new_cell) * output_gate; + + return {new_h, new_cell, input_gate, output_gate, candidate_cell, X, gate_weights}; +} + +std::vector lltm_cpu_backward( + torch::Tensor grad_h, + torch::Tensor grad_cell, + torch::Tensor new_cell, + torch::Tensor input_gate, + torch::Tensor output_gate, + torch::Tensor candidate_cell, + torch::Tensor X, + torch::Tensor gate_weights, + torch::Tensor weights) { + auto d_output_gate = torch::tanh(new_cell) * grad_h; + auto d_tanh_new_cell = output_gate * grad_h; + auto d_new_cell = d_tanh(new_cell) * d_tanh_new_cell + grad_cell; + + auto d_old_cell = d_new_cell; + auto d_candidate_cell = input_gate * d_new_cell; + auto d_input_gate = candidate_cell * d_new_cell; + + auto gates = gate_weights.chunk(3, /*dim=*/1); + d_input_gate *= d_sigmoid(gates[0]); + d_output_gate *= d_sigmoid(gates[1]); + d_candidate_cell *= d_elu(gates[2]); + + auto d_gates = torch::cat({d_input_gate, d_output_gate, d_candidate_cell}, /*dim=*/1); + + auto d_weights = d_gates.t().mm(X); + auto d_bias = d_gates.sum(/*dim=*/0, /*keepdim=*/true); + + auto d_X = d_gates.mm(weights); + const auto state_size = grad_h.size(1); + auto d_old_h = d_X.slice(/*dim=*/1, 0, state_size); + auto d_input = d_X.slice(/*dim=*/1, state_size); + + return {d_old_h, d_input, d_weights, d_bias, d_old_cell}; +} diff --git a/source_code/SegMamba/monai/csrc/resample/pushpull_cpu.cpp b/source_code/SegMamba/monai/csrc/resample/pushpull_cpu.cpp new file mode 100644 index 0000000000000000000000000000000000000000..c638958a4762a59f00183e14a9b910f0d8b0123b --- /dev/null +++ b/source_code/SegMamba/monai/csrc/resample/pushpull_cpu.cpp @@ -0,0 +1,2270 @@ +/* +Copyright (c) MONAI Consortium +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + http://www.apache.org/licenses/LICENSE-2.0 +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// adapted from https://github.com/balbasty/nitorch + +// This file implements spline interpolation / sampling and its adjoint +// operations. It corresponds loosely to torch's `GridSampler`. +// It handles boundary conditions and interpolation orders defined in +// `utils/resample_utils.h` and `utils/resample_utils.h`. +// These parameters can be specified per dimension. +// Isotropic 0-th and 1-st order interpolation have their own (faster) +// implementations. Sliding boundary conditions are also implemented +// separately. + +// TODO: +// . [DONE] generic 3d +// . [DONE] generic 2d +// . [DONE] generic 1d +// . sliding nearest 3d +// . sliding nearest 2d +// . sliding linear 3d +// . sliding linear 2d +// . sliding generic 3d +// . sliding generic 2d +// . [DONE] spatial gradient mode (without multiplication with output gradient) +// . [DONE] second order gradients (backward pass for spatial gradients) +// . performance tests +// . input bound/inter are always vectors -> clean unused constructors + +#include +#include +#include +#include "bounds_common.h" +#include "interpolation_common.h" +#include "utils/resample_utils.h" +//#include + +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// CPU-specific parameters +#include +namespace { +// This parameter specifies the minimum number of voxels that should be +// processed on a single processor in the parallel for loop . +int64_t GRAIN_SIZE = static_cast(at::internal::GRAIN_SIZE); +} // namespace + +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +// maximum number of channels +// > not used in mode isotropic nearest/linear +#ifndef MONAI_MAX_NUM_CHANNELS +#define MONAI_MAX_NUM_CHANNELS 1024 +#endif + +// This parameter allows for a little bit of tolerance when considering +// a coordinate as "out-of-bound" (if !extrapolate) +#define TINY 5e-2 + +using at::Tensor; +using at::TensorOptions; +using c10::IntArrayRef; + +namespace monai { +MONAI_NAMESPACE_DEVICE { // cpu + + namespace { // anonymous namespace > everything inside has internal linkage + + // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + // INDEXING UTILS + // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + + // This class reads and sets all the parameters that will later be used + // by the algorithm in PushPullImpl. All of this is done outside of the + // implementation class so that we do not depend on generic types. The + // point is to pre-allocate all necessary tensors so that we can check + // if they're all compatible with 32 bit math. If it's the case, we can + // dispatch to a 32b cuda implementation, which might increase + // performance. Else, we use 64 bit math to compute offsets. + // (On CPU, we always use 64 bit offsets because it doesn't make a huge + // difference. It would be different if we had a vectorized + // implementation as in PyTorch). + class PushPullAllocator { + public: + static constexpr int64_t max_int32 = std::numeric_limits::max(); + + // ~~~ CONSTRUCTORS ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + + MONAI_HOST + PushPullAllocator( + int dim, + BoundVectorRef bound, + InterpolationVectorRef interpolation, + bool extrapolate, + bool do_pull, + bool do_push, + bool do_count, + bool do_grad, + bool do_sgrad) + : dim(dim), + bound0(bound.size() > 0 ? bound[0] : BoundType::Replicate), + bound1( + bound.size() > 1 ? bound[1] + : bound.size() > 0 ? bound[0] + : BoundType::Replicate), + bound2( + bound.size() > 2 ? bound[2] + : bound.size() > 1 ? bound[1] + : bound.size() > 0 ? bound[0] + : BoundType::Replicate), + interpolation0(interpolation.size() > 0 ? interpolation[0] : InterpolationType::Linear), + interpolation1( + interpolation.size() > 1 ? interpolation[1] + : interpolation.size() > 0 ? interpolation[0] + : InterpolationType::Linear), + interpolation2( + interpolation.size() > 2 ? interpolation[2] + : interpolation.size() > 1 ? interpolation[1] + : interpolation.size() > 0 ? interpolation[0] + : InterpolationType::Linear), + extrapolate(extrapolate), + do_pull(do_pull), + do_push(do_push), + do_count(do_count), + do_grad(do_grad), + do_sgrad(do_sgrad) { + iso = interpolation0 == interpolation1 && interpolation0 == interpolation2; + } + + // ~~~ FUNCTORS ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + + // Usually used for pull: + // - do_pull -> return source[grid] + // - do_push -> fails + // - do_grad -> return J(source)[grid] + // - do_sgrad -> return H(source)[grid] + MONAI_HOST void ioset(const Tensor& source, const Tensor& grid) { + init_all(); + init_source(source); + init_grid(grid); + init_output(); + } + + // Usually used for pull_backward: + // - do_pull -> return source[grid] + // - do_push -> return push(target, grid, source.shape) + // - do_grad -> return J(source)[grid] + // - do_sgrad -> return H(source)[grid] + MONAI_HOST void ioset(const Tensor& source, const Tensor& grid, const Tensor& target) { + init_all(); + init_source(source); + init_grid(grid); + init_target(target); + init_output(); + } + + // Usually used for push: + // - do_pull -> fails + // - do_push -> return push(target, grid, source_size) + // - do_grad -> fails + // - do_sgrad -> fails + MONAI_HOST void ioset(IntArrayRef source_size, const Tensor& grid, const Tensor& target) { + init_all(); + init_source(source_size); + init_grid(grid); + init_target(target); + init_output(); + } + + // Usually used for count: + // - do_pull -> fails + // - do_push -> return push(ones, grid, source_size) + // - do_grad -> fails + // - do_sgrad -> fails + MONAI_HOST void ioset(IntArrayRef source_size, const Tensor& grid) { + init_all(); + init_source(source_size); + init_grid(grid); + init_output(); + } + + // We just check that all tensors that we own are compatible with 32b math + bool canUse32BitIndexMath(int64_t max_elem = max_int32) const { + return src_32b_ok && trgt_32b_ok && grid_32b_ok && grad_32b_ok && out_32b_ok; + } + + private: + // Copied from aten/src/ATen/native/IndexingUtils.cpp in PyTorch 1.6. + // It is used to decide to which pointer type we should dispatch to. + // Basically, we need to make sure that the "furthest" element we need + // to reach is less than max_elem away. + static bool tensorCanUse32BitIndexMath(const Tensor& t, int64_t max_elem = max_int32) { + int64_t elements = t.numel(); + if (elements >= max_elem) { + return false; + } + if (elements == 0) { + return max_elem > 0; + } + + int64_t offset = 0; + int64_t linearId = elements - 1; + + // NOTE: Assumes all strides are positive, which is true for now + for (int i = t.dim() - 1; i >= 0; --i) { + int64_t curDimIndex = linearId % t.size(i); + int64_t curDimOffset = curDimIndex * t.stride(i); + offset += curDimOffset; + linearId /= t.size(i); + } + + if (offset >= max_elem) { + return false; + } + + return true; + } + + // ~~~ COMPONENTS ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + MONAI_HOST void init_all(); + MONAI_HOST void init_source(const Tensor& source); + MONAI_HOST void init_source(IntArrayRef source_size); + MONAI_HOST void init_grid(const Tensor& grid); + MONAI_HOST void init_target(const Tensor& target); + MONAI_HOST void init_output(); + + // ~~~ OPTIONS ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + int dim; // dimensionality (2 or 3) + BoundType bound0; // boundary condition // x|W + BoundType bound1; // boundary condition // y|H + BoundType bound2; // boundary condition // z|D + InterpolationType interpolation0; // interpolation order // x|W + InterpolationType interpolation1; // interpolation order // y|H + InterpolationType interpolation2; // interpolation order // z|D + bool iso; // isotropic interpolation? + bool extrapolate; // compute out-of-bound values + bool do_pull; // sample a volume + bool do_push; // splat a volume + bool do_count; // splatting weights (= jacobian determinant) + bool do_grad; // backprop: gradient of grid // pull + bool do_sgrad; // sample spatial gradients + + // ~~~ NAVIGATORS ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + std::deque output; + TensorOptions src_opt; + TensorOptions grid_opt; + TensorOptions trgt_opt; + int64_t N; + int64_t C; + int64_t src_X; + int64_t src_Y; + int64_t src_Z; + int64_t trgt_X; + int64_t trgt_Y; + int64_t trgt_Z; + int64_t trgt_K; + int64_t src_sN; + int64_t src_sC; + int64_t src_sX; + int64_t src_sY; + int64_t src_sZ; + bool src_32b_ok; + void* src_ptr; + int64_t trgt_sN; + int64_t trgt_sC; + int64_t trgt_sX; + int64_t trgt_sY; + int64_t trgt_sZ; + int64_t trgt_sK; + bool trgt_32b_ok; + void* trgt_ptr; + int64_t grid_sN; + int64_t grid_sC; + int64_t grid_sX; + int64_t grid_sY; + int64_t grid_sZ; + bool grid_32b_ok; + void* grid_ptr; + int64_t out_sN; + int64_t out_sC; + int64_t out_sX; + int64_t out_sY; + int64_t out_sZ; + int64_t out_sK; // gradient dimension + bool out_32b_ok; + void* out_ptr; + int64_t grad_sN; + int64_t grad_sC; + int64_t grad_sX; + int64_t grad_sY; + int64_t grad_sZ; + bool grad_32b_ok; + void* grad_ptr; + + // Allow PushPullImpl's constructor to access PushPullAllocator's + // private members. + template + friend class PushPullImpl; + }; + + // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + // INITIALISATION + // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + + MONAI_HOST + void PushPullAllocator::init_all() { + src_opt = grid_opt = trgt_opt = TensorOptions(); + N = C = 1L; + src_X = src_Y = src_Z = 1L; + trgt_X = trgt_Y = trgt_Z = 1L; + trgt_K = 0L; + src_sN = src_sC = src_sX = src_sY = src_sZ = 0L; + grid_sN = grid_sC = grid_sX = grid_sY = grid_sZ = 0L; + grad_sN = grad_sC = grad_sX = grad_sY = grad_sZ = 0L; + trgt_sN = trgt_sC = trgt_sX = trgt_sY = trgt_sZ = trgt_sK = 0L; + out_sN = out_sC = out_sX = out_sY = out_sZ = out_sK = 0L; + src_ptr = trgt_ptr = grid_ptr = out_ptr = grad_ptr = static_cast(0); + src_32b_ok = trgt_32b_ok = grid_32b_ok = out_32b_ok = grad_32b_ok = true; + } + + MONAI_HOST + void PushPullAllocator::init_source(const Tensor& source) { + N = source.size(0); + C = source.size(1); + src_X = source.size(2); + src_Y = dim < 2 ? 1L : source.size(3); + src_Z = dim < 3 ? 1L : source.size(4); + src_sN = source.stride(0); + src_sC = source.stride(1); + src_sX = source.stride(2); + src_sY = dim < 2 ? 0L : source.stride(3); + src_sZ = dim < 3 ? 0L : source.stride(4); + src_ptr = source.data_ptr(); + src_opt = source.options(); + src_32b_ok = tensorCanUse32BitIndexMath(source); + } + + MONAI_HOST + void PushPullAllocator::init_source(IntArrayRef source_size) { + src_X = source_size[0]; + src_Y = dim < 2 ? 1L : source_size[1]; + src_Z = dim < 3 ? 1L : source_size[2]; + } + + MONAI_HOST + void PushPullAllocator::init_grid(const Tensor& grid) { + N = grid.size(0); + trgt_X = grid.size(1); + trgt_Y = dim < 2 ? 1L : grid.size(2); + trgt_Z = dim < 3 ? 1L : grid.size(3); + grid_sN = grid.stride(0); + grid_sX = grid.stride(1); + grid_sY = dim < 2 ? 0L : grid.stride(2); + grid_sZ = dim < 3 ? 0L : grid.stride(3); + grid_sC = grid.stride(dim == 1 ? 2 : dim == 2 ? 3 : 4); + grid_ptr = grid.data_ptr(); + grid_opt = grid.options(); + grid_32b_ok = tensorCanUse32BitIndexMath(grid); + } + + MONAI_HOST + void PushPullAllocator::init_target(const Tensor& target) { + N = target.size(0); + C = target.size(1); + trgt_X = target.size(2); + trgt_Y = dim < 2 ? 1L : target.size(3); + trgt_Z = dim < 3 ? 1L : target.size(4); + trgt_K = target.dim() == dim + 3 ? target.size(dim == 1 ? 3 : dim == 2 ? 4 : 5) : 0L; + trgt_sN = target.stride(0); + trgt_sC = target.stride(1); + trgt_sX = target.stride(2); + trgt_sY = dim < 2 ? 0L : target.stride(3); + trgt_sZ = dim < 3 ? 0L : target.stride(4); + trgt_sK = target.dim() == dim + 3 ? target.stride(dim == 1 ? 3 : dim == 2 ? 4 : 5) : 0L; + trgt_ptr = target.data_ptr(); + trgt_opt = target.options(); + trgt_32b_ok = tensorCanUse32BitIndexMath(target); + } + + MONAI_HOST + void PushPullAllocator::init_output() { + output.clear(); + if (do_pull) { + if (dim == 1) + output.push_back(at::empty({N, C, trgt_X}, src_opt)); + else if (dim == 2) + output.push_back(at::empty({N, C, trgt_X, trgt_Y}, src_opt)); + else + output.push_back(at::empty({N, C, trgt_X, trgt_Y, trgt_Z}, src_opt)); + auto pull = output.back(); + out_sN = pull.stride(0); + out_sC = pull.stride(1); + out_sX = pull.stride(2); + out_sY = dim < 2 ? 0L : pull.stride(3); + out_sZ = dim < 3 ? 0L : pull.stride(4); + out_sK = 0L; + out_ptr = pull.data_ptr(); + out_32b_ok = tensorCanUse32BitIndexMath(pull); + } else if (do_sgrad) { + if (dim == 1) + output.push_back(at::empty({N, C, trgt_X, 1}, src_opt)); + else if (dim == 2) + output.push_back(at::empty({N, C, trgt_X, trgt_Y, 2}, src_opt)); + else + output.push_back(at::empty({N, C, trgt_X, trgt_Y, trgt_Z, 3}, src_opt)); + auto sgrad = output.back(); + out_sN = sgrad.stride(0); + out_sC = sgrad.stride(1); + out_sX = sgrad.stride(2); + out_sY = dim < 2 ? 0L : sgrad.stride(3); + out_sZ = dim < 3 ? 0L : sgrad.stride(4); + out_sK = sgrad.stride(dim == 1 ? 3 : dim == 2 ? 4 : 5); + out_ptr = sgrad.data_ptr(); + out_32b_ok = tensorCanUse32BitIndexMath(sgrad); + + if (iso && interpolation0 == InterpolationType::Nearest) + sgrad.zero_(); + if (iso && interpolation0 == InterpolationType::Linear && dim == 1) + sgrad.zero_(); + } else if (do_push) { + if (dim == 1) + output.push_back(at::zeros({N, C, src_X}, trgt_opt)); + else if (dim == 2) + output.push_back(at::zeros({N, C, src_X, src_Y}, trgt_opt)); + else + output.push_back(at::zeros({N, C, src_X, src_Y, src_Z}, trgt_opt)); + auto push = output.back(); + out_sN = push.stride(0); + out_sC = push.stride(1); + out_sX = push.stride(2); + out_sY = dim < 2 ? 0L : push.stride(3); + out_sZ = dim < 3 ? 0L : push.stride(4); + out_sK = 0L; + out_ptr = push.data_ptr(); + out_32b_ok = tensorCanUse32BitIndexMath(push); + } else if (do_count) { + if (dim == 1) + output.push_back(at::zeros({N, 1, src_X}, grid_opt)); + else if (dim == 2) + output.push_back(at::zeros({N, 1, src_X, src_Y}, grid_opt)); + else + output.push_back(at::zeros({N, 1, src_X, src_Y, src_Z}, grid_opt)); + auto count = output.back(); + out_sN = count.stride(0); + out_sC = count.stride(1); + out_sX = count.stride(2); + out_sY = dim < 2 ? 0L : count.stride(3); + out_sZ = dim < 3 ? 0L : count.stride(4); + out_sK = 0L; + out_ptr = count.data_ptr(); + out_32b_ok = tensorCanUse32BitIndexMath(count); + } + if (do_grad) { + if (dim == 1) + output.push_back(at::zeros({N, trgt_X, 1}, grid_opt)); + else if (dim == 2) + output.push_back(at::zeros({N, trgt_X, trgt_Y, 2}, grid_opt)); + else + output.push_back(at::zeros({N, trgt_X, trgt_Y, trgt_Z, 3}, grid_opt)); + auto grad = output.back(); + grad_sN = grad.stride(0); + grad_sX = grad.stride(1); + grad_sY = dim < 2 ? 0L : grad.stride(2); + grad_sZ = dim < 3 ? 0L : grad.stride(3); + grad_sC = grad.stride(dim == 1 ? 2 : dim == 2 ? 3 : 4); + grad_ptr = grad.data_ptr(); + out_32b_ok = tensorCanUse32BitIndexMath(grad); + + if (iso && interpolation0 == InterpolationType::Nearest) + grad.zero_(); + } + } + + // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + // GENERIC PUSHPULL CLASS + // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + // This class implements the bulk of the code. + // /!\ No type and shape checking is performed here. + + template + class PushPullImpl { + public: + // ~~~ CONSTRUCTOR ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + PushPullImpl(const PushPullAllocator& info) + : output(info.output), + dim(info.dim), + bound0(info.bound0), + bound1(info.bound1), + bound2(info.bound2), + interpolation0(info.interpolation0), + interpolation1(info.interpolation1), + interpolation2(info.interpolation1), + iso(info.iso), + extrapolate(info.extrapolate), + do_pull(info.do_pull), + do_push(info.do_push), + do_count(info.do_count), + do_grad(info.do_grad), + do_sgrad(info.do_sgrad), + N(static_cast(info.N)), + C(static_cast(info.C)), + src_X(static_cast(info.src_X)), + src_Y(static_cast(info.src_Y)), + src_Z(static_cast(info.src_Z)), + trgt_X(static_cast(info.trgt_X)), + trgt_Y(static_cast(info.trgt_Y)), + trgt_Z(static_cast(info.trgt_Z)), + trgt_K(static_cast(info.trgt_K)), + src_sN(static_cast(info.src_sN)), + src_sC(static_cast(info.src_sC)), + src_sX(static_cast(info.src_sX)), + src_sY(static_cast(info.src_sY)), + src_sZ(static_cast(info.src_sZ)), + src_ptr(static_cast(info.src_ptr)), + trgt_sN(static_cast(info.trgt_sN)), + trgt_sC(static_cast(info.trgt_sC)), + trgt_sX(static_cast(info.trgt_sX)), + trgt_sY(static_cast(info.trgt_sY)), + trgt_sZ(static_cast(info.trgt_sZ)), + trgt_sK(static_cast(info.trgt_sK)), + trgt_ptr(static_cast(info.trgt_ptr)), + grid_sN(static_cast(info.grid_sN)), + grid_sC(static_cast(info.grid_sC)), + grid_sX(static_cast(info.grid_sX)), + grid_sY(static_cast(info.grid_sY)), + grid_sZ(static_cast(info.grid_sZ)), + grid_ptr(static_cast(info.grid_ptr)), + out_sN(static_cast(info.out_sN)), + out_sC(static_cast(info.out_sC)), + out_sX(static_cast(info.out_sX)), + out_sY(static_cast(info.out_sY)), + out_sZ(static_cast(info.out_sZ)), + out_sK(static_cast(info.out_sK)), + out_ptr(static_cast(info.out_ptr)), + grad_sN(static_cast(info.grad_sN)), + grad_sC(static_cast(info.grad_sC)), + grad_sX(static_cast(info.grad_sX)), + grad_sY(static_cast(info.grad_sY)), + grad_sZ(static_cast(info.grad_sZ)), + grad_ptr(static_cast(info.grad_ptr)) {} + + // ~~~ PUBLIC VALUE ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + + std::deque output; + + // MONAI_HOST MONAI_DEVICE void printInfo() const { + // printf("dim: %d\n", dim); + // printf("do_pull: %d\n", do_pull); + // printf("do_push: %d\n", do_push); + // printf("do_count: %d\n", do_count); + // printf("do_sgrad: %d\n", do_sgrad); + // printf("do_grad: %d\n", do_grad); + // printf("bound: [%d %d %d]\n", static_cast(bound0), + // static_cast(bound1), static_cast(bound2)); + // printf("interpolation: [%d %d %d]\n", static_cast(interpolation0), + // static_cast(interpolation1), static_cast(interpolation2)); + // printf("src: [%d %d %d]\n", src_Z, src_Y, src_X); + // printf("trgt: [%d %d %d (%d)]\n", trgt_Z, trgt_Y, trgt_X, trgt_K); + // printf("N: %d\n", N); + // printf("C: %d\n", C); + // printf("src -> %lu\n", reinterpret_cast(src_ptr)); + // printf("trgt -> %lu\n", reinterpret_cast(trgt_ptr)); + // printf("grid -> %lu\n", reinterpret_cast(grid_ptr)); + // printf("out -> %lu\n", reinterpret_cast(out_ptr)); + // printf("grad -> %lu\n", reinterpret_cast(grad_ptr)); + // } + + // ~~~ FUNCTORS ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + + // Loop over all voxels + void loop() const; + + MONAI_HOST MONAI_DEVICE int64_t voxcount() const { + return N * trgt_X * trgt_Y * trgt_Z; + } + + private: + // ~~~ COMPONENTS ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + MONAI_DEVICE void check1d(offset_t w, offset_t n) const; + MONAI_DEVICE void check2d(offset_t w, offset_t h, offset_t n) const; + MONAI_DEVICE void check3d(offset_t w, offset_t h, offset_t d, offset_t n) const; + MONAI_DEVICE void interpolate1d(scalar_t x, offset_t w, offset_t n) const; + MONAI_DEVICE void interpolate1d_nearest(scalar_t x, offset_t w, offset_t n) const; + MONAI_DEVICE void interpolate1d_linear(scalar_t x, offset_t w, offset_t n) const; + MONAI_DEVICE void interpolate1d_sliding(scalar_t x, offset_t w, offset_t n) const { /*TODO*/ + } + MONAI_DEVICE void interpolate1d_sliding_nearest(scalar_t x, offset_t w, offset_t n) const { /*TODO*/ + } + MONAI_DEVICE void interpolate1d_sliding_linear(scalar_t x, offset_t w, offset_t n) const { /*TODO*/ + } + MONAI_DEVICE void interpolate2d(scalar_t x, scalar_t y, offset_t w, offset_t h, offset_t n) const; + MONAI_DEVICE void interpolate2d_nearest(scalar_t x, scalar_t y, offset_t w, offset_t h, offset_t n) const; + MONAI_DEVICE void interpolate2d_bilinear(scalar_t x, scalar_t y, offset_t w, offset_t h, offset_t n) const; + MONAI_DEVICE void interpolate2d_sliding(scalar_t x, scalar_t y, offset_t w, offset_t h, offset_t n) const { /*TODO*/ + } + MONAI_DEVICE void interpolate2d_sliding_nearest(scalar_t x, scalar_t y, offset_t w, offset_t h, offset_t n) + const { /*TODO*/ + } + MONAI_DEVICE void interpolate2d_sliding_bilinear(scalar_t x, scalar_t y, offset_t w, offset_t h, offset_t n) + const { /*TODO*/ + } + MONAI_DEVICE void interpolate3d(scalar_t x, scalar_t y, scalar_t z, offset_t w, offset_t h, offset_t d, offset_t n) + const; + MONAI_DEVICE void interpolate3d_nearest( + scalar_t x, + scalar_t y, + scalar_t z, + offset_t w, + offset_t h, + offset_t d, + offset_t n) const; + MONAI_DEVICE void interpolate3d_trilinear( + scalar_t x, + scalar_t y, + scalar_t z, + offset_t w, + offset_t h, + offset_t d, + offset_t n) const; + MONAI_DEVICE void interpolate3d_sliding( + scalar_t x, + scalar_t y, + scalar_t z, + offset_t w, + offset_t h, + offset_t d, + offset_t n) const { /*TODO*/ + } + MONAI_DEVICE void interpolate3d_sliding_nearest( + scalar_t x, + scalar_t y, + scalar_t z, + offset_t w, + offset_t h, + offset_t d, + offset_t n) const { /*TODO*/ + } + MONAI_DEVICE void interpolate3d_sliding_trilinear( + scalar_t x, + scalar_t y, + scalar_t z, + offset_t w, + offset_t h, + offset_t d, + offset_t n) const { /*TODO*/ + } + + // ~~~ OPTIONS ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + int dim; // dimensionality (2 or 3) + BoundType bound0; // boundary condition // x|W + BoundType bound1; // boundary condition // y|H + BoundType bound2; // boundary condition // z|D + InterpolationType interpolation0; // interpolation order // x|W + InterpolationType interpolation1; // interpolation order // y|H + InterpolationType interpolation2; // interpolation order // z|D + bool iso; // isotropic interpolation? + bool extrapolate; // compute out-of-bound values + bool do_pull; // sample a volume + bool do_push; // splat a volume + bool do_count; // splatting weights (= jacobian determinant) + bool do_grad; // backprop: gradient of grid // pull + bool do_sgrad; // sample spatial gradients + + // ~~~ NAVIGATORS ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + offset_t N; + offset_t C; + offset_t src_X; + offset_t src_Y; + offset_t src_Z; + offset_t trgt_X; + offset_t trgt_Y; + offset_t trgt_Z; + offset_t trgt_K; + offset_t src_sN; + offset_t src_sC; + offset_t src_sX; + offset_t src_sY; + offset_t src_sZ; + scalar_t* src_ptr; + offset_t trgt_sN; + offset_t trgt_sC; + offset_t trgt_sX; + offset_t trgt_sY; + offset_t trgt_sZ; + offset_t trgt_sK; + scalar_t* trgt_ptr; + offset_t grid_sN; + offset_t grid_sC; + offset_t grid_sX; + offset_t grid_sY; + offset_t grid_sZ; + scalar_t* grid_ptr; + offset_t out_sN; + offset_t out_sC; + offset_t out_sX; + offset_t out_sY; + offset_t out_sZ; + offset_t out_sK; // gradient dimension + scalar_t* out_ptr; + offset_t grad_sN; + offset_t grad_sC; + offset_t grad_sX; + offset_t grad_sY; + offset_t grad_sZ; + scalar_t* grad_ptr; + }; + + // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + // LOOP + // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + + // This bit loops over all target voxels. We therefore need to + // convert linear indices to multivariate indices. The way I do it + // might not be optimal. + // Note that I parallelize across all voxels (whereas ATen's grid + // sampler is only parallelized across batches). + // + // TODO: check that the default grain size is optimal. We do quite a lot + // of compute per voxel, so a smaller value might be better suited. + template + MONAI_HOST void PushPullImpl::loop() const { +#if !(AT_PARALLEL_OPENMP) + if (do_push) { + // I do not have access to atomic operations so I cannot + // parallelize across voxels. + at::parallel_for(0, N, 0, [&](offset_t start, offset_t end) { + for (offset_t n = start; n < end; ++n) { + if (dim == 1) { + for (offset_t w = 0; w < trgt_X; ++w) + check1d(w, n); + } else if (dim == 2) { + for (offset_t h = 0; h < trgt_Y; ++h) + for (offset_t w = 0; w < trgt_X; ++w) + check2d(w, h, n); + } else { + for (offset_t d = 0; d < trgt_Z; ++d) + for (offset_t h = 0; h < trgt_Y; ++h) + for (offset_t w = 0; w < trgt_X; ++w) + check3d(w, h, d, n); + } + } + }); + return; + } + +#endif + // Parallelize across voxels + offset_t trgt_NXYZ = trgt_Z * trgt_Y * trgt_X * N; + offset_t trgt_XYZ = trgt_Z * trgt_Y * trgt_X; + offset_t trgt_YZ = trgt_Z * trgt_Y; + at::parallel_for(0, trgt_NXYZ, GRAIN_SIZE, [&](offset_t start, offset_t end) { + offset_t n, w, h, d; + for (offset_t i = start; i < end; ++i) { + // Convert index: linear to sub + n = (i / trgt_XYZ); + w = (i / trgt_YZ) % trgt_X; + h = (i / trgt_Z) % trgt_Y; + d = i % trgt_Z; + + if (dim == 1) + check1d(w, n); + else if (dim == 2) + check2d(w, h, n); + else + check3d(w, h, d, n); + } + }); + } + + // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + // CHECK OUT-OF-BOUND + // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + + // Here, we: + // 1) read the [x,y,z] source coordinate for the current target voxel + // 3) check if the source coordinate is in bounds + + template + MONAI_DEVICE void PushPullImpl::check3d(offset_t w, offset_t h, offset_t d, offset_t n) const { + // get the corresponding input x, y, z co-ordinates from grid + scalar_t* grid_ptr_NXYZ = grid_ptr + n * grid_sN + w * grid_sX + h * grid_sY + d * grid_sZ; + scalar_t x = *grid_ptr_NXYZ; + scalar_t y = grid_ptr_NXYZ[grid_sC]; + scalar_t z = grid_ptr_NXYZ[grid_sC * 2]; + + // Check if out-of-bound + if (!(extrapolate || + (inbounds(x, src_X, static_cast(TINY)) && inbounds(y, src_Y, static_cast(TINY)) && + inbounds(z, src_Z, static_cast(TINY))))) { + if (do_pull || do_sgrad) { + scalar_t* out_ptr_NCXYZ = out_ptr + n * out_sN + w * out_sX + h * out_sY + d * out_sZ; + for (offset_t c = 0; c < C; ++c, out_ptr_NCXYZ += out_sC) { + *out_ptr_NCXYZ = static_cast(0); + if (do_sgrad) { + out_ptr_NCXYZ[out_sK] = static_cast(0); + out_ptr_NCXYZ[out_sK * 2] = static_cast(0); + } + } + } + if (do_grad) { + scalar_t* grad_ptr_NXYZ = grad_ptr + n * grad_sN + w * grad_sX + h * grad_sY + d * grad_sZ; + (*grad_ptr_NXYZ) = static_cast(0); + grad_ptr_NXYZ[grad_sC] = static_cast(0); + grad_ptr_NXYZ[grad_sC * 2] = static_cast(0); + } + return; + } + + // Next step + if (bound0 == BoundType::Sliding) { + if (iso) + switch (static_cast(interpolation0)) { + case 0: + return interpolate3d_sliding_nearest(x, y, z, w, h, d, n); + case 1: + return interpolate3d_sliding_trilinear(x, y, z, w, h, d, n); + } + return interpolate3d_sliding(x, y, z, w, h, d, n); + } else { + if (iso) + switch (static_cast(interpolation0)) { + case 0: + return interpolate3d_nearest(x, y, z, w, h, d, n); + case 1: + return interpolate3d_trilinear(x, y, z, w, h, d, n); + } + return interpolate3d(x, y, z, w, h, d, n); + } + } + + template + MONAI_DEVICE void PushPullImpl::check2d(offset_t w, offset_t h, offset_t n) const { + // get the corresponding input x, y, z co-ordinates from grid + scalar_t* grid_ptr_NXY = grid_ptr + n * grid_sN + w * grid_sX + h * grid_sY; + scalar_t x = *grid_ptr_NXY; + scalar_t y = grid_ptr_NXY[grid_sC]; + + // Check if out-of-bound + if (!(extrapolate || + (inbounds(x, src_X, static_cast(TINY)) && inbounds(y, src_Y, static_cast(TINY))))) { + if (do_pull || do_sgrad) { + scalar_t* out_ptr_NCXY = out_ptr + n * out_sN + w * out_sX + h * out_sY; + for (offset_t c = 0; c < C; ++c, out_ptr_NCXY += out_sC) { + *out_ptr_NCXY = static_cast(0); + if (do_sgrad) + out_ptr_NCXY[out_sK] = static_cast(0); + } + } + if (do_grad) { + scalar_t* grad_ptr_NXY = grad_ptr + n * grad_sN + w * grad_sX + h * grad_sY; + (*grad_ptr_NXY) = static_cast(0); + grad_ptr_NXY[grad_sC] = static_cast(0); + } + return; + } + + // Next step + if (bound0 == BoundType::Sliding) { + if (iso) + switch (static_cast(interpolation0)) { + case 0: + return interpolate2d_sliding_nearest(x, y, w, h, n); + case 1: + return interpolate2d_sliding_bilinear(x, y, w, h, n); + } + return interpolate2d_sliding(x, y, w, h, n); + } else { + if (iso) + switch (static_cast(interpolation0)) { + case 0: + return interpolate2d_nearest(x, y, w, h, n); + case 1: + return interpolate2d_bilinear(x, y, w, h, n); + } + return interpolate2d(x, y, w, h, n); + } + } + + template + MONAI_DEVICE void PushPullImpl::check1d(offset_t w, offset_t n) const { + // get the corresponding input x, y, z co-ordinates from grid + scalar_t* grid_ptr_NX = grid_ptr + n * grid_sN + w * grid_sX; + scalar_t x = *grid_ptr_NX; + + // Check if out-of-bound + if (!(extrapolate || inbounds(x, src_X, static_cast(TINY)))) { + if (do_pull || do_sgrad) { + scalar_t* out_ptr_NCX = out_ptr + n * out_sN + w * out_sX; + for (offset_t c = 0; c < C; ++c, out_ptr_NCX += out_sC) { + *out_ptr_NCX = static_cast(0); + if (do_sgrad) + out_ptr_NCX[out_sK] = static_cast(0); + } + } + if (do_grad) { + scalar_t* grad_ptr_NX = grad_ptr + n * grad_sN + w * grad_sX; + (*grad_ptr_NX) = static_cast(0); + grad_ptr_NX[grad_sC] = static_cast(0); + } + return; + } + + // Next step + if (bound0 == BoundType::Sliding) { + if (iso) + switch (static_cast(interpolation0)) { + case 0: + return interpolate1d_sliding_nearest(x, w, n); + case 1: + return interpolate1d_sliding_linear(x, w, n); + } + return interpolate1d_sliding(x, w, n); + } else { + if (iso) + switch (static_cast(interpolation0)) { + case 0: + return interpolate1d_nearest(x, w, n); + case 1: + return interpolate1d_linear(x, w, n); + } + return interpolate1d(x, w, n); + } + } + + // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + // GENERIC INTERPOLATION 3D + // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + + template + MONAI_DEVICE void PushPullImpl::interpolate3d( + scalar_t x, + scalar_t y, + scalar_t z, + offset_t w, + offset_t h, + offset_t d, + offset_t n) const { + // Get corner pixel values from (x, y, z) + offset_t bx0, bx1, by0, by1, bz0, bz1; + interpolation::bounds(interpolation0, x, bx0, bx1); + interpolation::bounds(interpolation1, y, by0, by1); + interpolation::bounds(interpolation2, z, bz0, bz1); + offset_t dbx = bx1 - bx0; + offset_t dby = by1 - by0; + offset_t dbz = bz1 - bz0; + + // Pre-compute offsets and target value + scalar_t* src_ptr_NC0 = src_ptr + n * src_sN; + scalar_t* out_ptr_NC0 = out_ptr + n * out_sN; + scalar_t* out_ptr_NCXYZ0 = out_ptr + n * out_sN + w * out_sX + h * out_sY + d * out_sZ; + scalar_t* trgt_ptr_NCXYZ = trgt_ptr + n * trgt_sN + w * trgt_sX + h * trgt_sY + d * trgt_sZ; + scalar_t target[3 * MONAI_MAX_NUM_CHANNELS]; + if (trgt_ptr && (do_push || do_grad)) + for (offset_t c = 0; c < C; ++c, trgt_ptr_NCXYZ += trgt_sC) { + target[c] = *trgt_ptr_NCXYZ; + if (trgt_K > 0) { + target[c + C] = trgt_ptr_NCXYZ[trgt_sK]; + target[c + C * 2] = trgt_ptr_NCXYZ[trgt_sK * 2]; + } + } + + // Initialize output + scalar_t* out_ptr_NCXYZ = out_ptr_NCXYZ0; + if (do_pull || do_sgrad) { + for (offset_t c = 0; c < C; ++c, out_ptr_NCXYZ += out_sC) { + *out_ptr_NCXYZ = static_cast(0); + if (do_sgrad) { + out_ptr_NCXYZ[out_sK] = static_cast(0); + out_ptr_NCXYZ[out_sK * 2] = static_cast(0); + } + } + } + + // Pre-compute indices/weights/grad + scalar_t wx[8], wy[8], wz[8]; // B-spline weights + scalar_t gx[8], gy[8], gz[8]; // B-spline derivatives + scalar_t hx[8], hy[8], hz[8]; // B-spline 2nd derivatives + offset_t ix[8], iy[8], iz[8]; // Warped indices + uint8_t sx[8], sy[8], sz[8]; // Warped indices + + { + scalar_t *owz = static_cast(wz), *ogz = static_cast(gz), *ohz = static_cast(hz); + offset_t* oiz = static_cast(iz); + uint8_t* osz = static_cast(sz); + for (offset_t bz = bz0; bz <= bz1; ++bz) { + scalar_t dz = z - bz; + *(owz++) = interpolation::fastweight(interpolation2, dz); + if (do_grad || do_sgrad) + *(ogz++) = interpolation::fastgrad(interpolation2, dz); + if (do_grad && trgt_sK > 1) + *(ohz++) = interpolation::fasthess(interpolation2, dz); + *(osz++) = bound::sign(bound2, bz, src_Z); + *(oiz++) = bound::index(bound2, bz, src_Z); + } + } + { + scalar_t *owy = static_cast(wy), *ogy = static_cast(gy), *ohy = static_cast(hy); + offset_t* oiy = static_cast(iy); + uint8_t* osy = static_cast(sy); + for (offset_t by = by0; by <= by1; ++by) { + scalar_t dy = y - by; + *(owy++) = interpolation::fastweight(interpolation1, dy); + if (do_grad || do_sgrad) + *(ogy++) = interpolation::fastgrad(interpolation1, dy); + if (do_grad && trgt_sK > 1) + *(ohy++) = interpolation::fasthess(interpolation1, dy); + *(osy++) = bound::sign(bound1, by, src_Y); + *(oiy++) = bound::index(bound1, by, src_Y); + } + } + { + scalar_t *owx = static_cast(wx), *ogx = static_cast(gx), *ohx = static_cast(hx); + offset_t* oix = static_cast(ix); + uint8_t* osx = static_cast(sx); + for (offset_t bx = bx0; bx <= bx1; ++bx) { + scalar_t dx = x - bx; + *(owx++) = interpolation::fastweight(interpolation0, dx); + if (do_grad || do_sgrad) + *(ogx++) = interpolation::fastgrad(interpolation0, dx); + if (do_grad && trgt_sK > 1) + *(ohx++) = interpolation::fasthess(interpolation0, dx); + *(osx++) = bound::sign(bound0, bx, src_X); + *(oix++) = bound::index(bound0, bx, src_X); + } + } + + // Convolve coefficients with basis functions + scalar_t ogx, ogy, ogz; + ogx = ogy = ogz = static_cast(0); + for (offset_t k = 0; k <= dbz; ++k) { + offset_t ooz = iz[k] * out_sZ; + offset_t osz = iz[k] * src_sZ; + uint8_t szz = sz[k]; + scalar_t wzz = wz[k]; + scalar_t gzz = gz[k]; + scalar_t hzz = hz[k]; + for (offset_t j = 0; j <= dby; ++j) { + offset_t ooyz = ooz + iy[j] * out_sY; + offset_t osyz = osz + iy[j] * src_sY; + uint8_t syz = szz * sy[j]; + scalar_t wyy = wy[j]; + scalar_t gyy = gy[j]; + scalar_t hyy = hy[j]; + for (offset_t i = 0; i <= dbx; ++i) { + offset_t ooxyz = ooyz + ix[i] * out_sX; + offset_t osxyz = osyz + ix[i] * src_sX; + uint8_t sxyz = syz * sx[i]; + scalar_t wxx = wx[i]; + scalar_t gxx = gx[i]; + scalar_t hxx = hx[i]; + + // ~~~~~~~~~~~~~~~~~~~~~~~~~~~ Pull ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + if (do_pull) { + scalar_t* src_ptr_NC = src_ptr_NC0; + scalar_t* out_ptr_NCXYZ = out_ptr_NCXYZ0; + for (offset_t c = 0; c < C; ++c, out_ptr_NCXYZ += out_sC, src_ptr_NC += src_sC) + *out_ptr_NCXYZ += bound::get(src_ptr_NC, osxyz, sxyz) * (wxx * wyy * wzz); + } + + // ~~~~~~~~~~~~~~~~~~~~~~~~~~~ SGrad ~~~~~~~~~~~~~~~~~~~~~~~~~~~ + else if (do_sgrad) { + scalar_t* src_ptr_NC = src_ptr_NC0; + scalar_t* out_ptr_NCXYZ = out_ptr_NCXYZ0; + for (offset_t c = 0; c < C; ++c, out_ptr_NCXYZ += out_sC, src_ptr_NC += src_sC) { + scalar_t src = bound::get(src_ptr_NC, osxyz, sxyz); + *out_ptr_NCXYZ += src * (gxx * wyy * wzz); + out_ptr_NCXYZ[out_sK] += src * (wxx * gyy * wzz); + out_ptr_NCXYZ[2 * out_sK] += src * (wxx * wyy * gzz); + } + } + + // ~~~~~~~~~~~~~~~~~~~~~~~~~~~ Push ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + else if (do_push) { + if (trgt_K == 0) { + // Diff w.r.t. push/pull + scalar_t* out_ptr_NC = out_ptr_NC0; + for (offset_t c = 0; c < C; ++c, out_ptr_NC += out_sC) + bound::add(out_ptr_NC, ooxyz, (wxx * wyy * wzz) * target[c], sxyz); + } else { + // Diff w.r.t. sgrad + scalar_t* out_ptr_NC = out_ptr_NC0; + for (offset_t c = 0; c < C; ++c, out_ptr_NC += out_sC) { + scalar_t val = (gxx * wyy * wzz) * target[c] + (wxx * gyy * wzz) * target[c + C] + + (wxx * wyy * gzz) * target[c + C * 2]; + bound::add(out_ptr_NC, ooxyz, val, sxyz); + } + } + } + + // ~~~~~~~~~~~~~~~~~~~~~~~~~~~ Count ~~~~~~~~~~~~~~~~~~~~~~~~~~~ + else if (do_count) { + bound::add(out_ptr_NC0, ooxyz, (wxx * wyy * wzz), sxyz); + } + + // ~~~~~~~~~~~~~~~~~~~~~~~~~~~ Grad ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + if (do_grad) { + if (trgt_K == 0) { + // Diff w.r.t. pull/push + scalar_t* src_ptr_NC = src_ptr_NC0; + scalar_t dot = static_cast(0); + for (offset_t c = 0; c < C; ++c, src_ptr_NC += src_sC) { + scalar_t src = bound::get(src_ptr_NC, osxyz, sxyz); + dot += (trgt_ptr ? src * target[c] : src); + // trgt_ptr == 0 in the backward pass of 'count' + } + ogx += (gxx * wyy * wzz) * dot; + ogy += (wxx * gyy * wzz) * dot; + ogz += (wxx * wyy * gzz) * dot; + } else { + // Diff w.r.t. sgrad + scalar_t* src_ptr_NC = src_ptr_NC0; + scalar_t dot0, dot1, dot2; + dot0 = dot1 = dot2 = static_cast(0); + for (offset_t c = 0; c < C; ++c, src_ptr_NC += src_sC) { + scalar_t src = bound::get(src_ptr_NC, osxyz, sxyz); + dot0 += src * target[c]; + dot1 += src * target[c + C]; + dot2 += src * target[c + C * 2]; + } + ogx += (hxx * wyy * wzz) * dot0 + (gxx * gyy * wzz) * dot1 + (gxx * wyy * gzz) * dot2; + ogy += (gxx * gyy * wzz) * dot0 + (wxx * hyy * wzz) * dot1 + (wxx * gyy * gzz) * dot2; + ogz += (gxx * wyy * gzz) * dot0 + (wxx * gyy * gzz) * dot1 + (wxx * wyy * hzz) * dot2; + } + } + + } // x + } // y + } // z + + // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Grad ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + if (do_grad) { + scalar_t* grad_ptr_NXYZ = grad_ptr + n * grad_sN + w * grad_sX + h * grad_sY + d * grad_sZ; + (*grad_ptr_NXYZ) = ogx; + grad_ptr_NXYZ[grad_sC] = ogy; + grad_ptr_NXYZ[grad_sC * 2] = ogz; + } + } + + // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + // GENERIC INTERPOLATION 2D + // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + + template + MONAI_DEVICE void PushPullImpl::interpolate2d( + scalar_t x, + scalar_t y, + offset_t w, + offset_t h, + offset_t n) const { + // Get corner pixel values from (x, y) + offset_t bx0, bx1, by0, by1; + interpolation::bounds(interpolation0, x, bx0, bx1); + interpolation::bounds(interpolation1, y, by0, by1); + offset_t dbx = bx1 - bx0; + offset_t dby = by1 - by0; + + // Pre-compute offsets and target value + scalar_t* src_ptr_NC0 = src_ptr + n * src_sN; + scalar_t* out_ptr_NC0 = out_ptr + n * out_sN; + scalar_t* out_ptr_NCXY0 = out_ptr + n * out_sN + w * out_sX + h * out_sY; + scalar_t* trgt_ptr_NCXY = trgt_ptr + n * trgt_sN + w * trgt_sX + h * trgt_sY; + scalar_t target[2 * MONAI_MAX_NUM_CHANNELS]; + if (trgt_ptr && (do_push || do_grad)) + for (offset_t c = 0; c < C; ++c, trgt_ptr_NCXY += trgt_sC) { + target[c] = *trgt_ptr_NCXY; + if (trgt_K > 0) { + target[c + C] = trgt_ptr_NCXY[trgt_sK]; + } + } + + // Initialize output + scalar_t* out_ptr_NCXY = out_ptr_NCXY0; + if (do_pull || do_sgrad) { + for (offset_t c = 0; c < C; ++c, out_ptr_NCXY += out_sC) { + *out_ptr_NCXY = static_cast(0); + if (do_sgrad) { + out_ptr_NCXY[out_sK] = static_cast(0); + } + } + } + + // Pre-compute indices/weights/grad + scalar_t wx[8], wy[8]; // B-spline weights + scalar_t gx[8], gy[8]; // B-spline derivatives + scalar_t hx[8], hy[8]; // B-spline 2nd derivatives + offset_t ix[8], iy[8]; // Warped indices + uint8_t sx[8], sy[8]; // Warped indices + + { + scalar_t *owy = static_cast(wy), *ogy = static_cast(gy), *ohy = static_cast(hy); + offset_t* oiy = static_cast(iy); + uint8_t* osy = static_cast(sy); + for (offset_t by = by0; by <= by1; ++by) { + scalar_t dy = y - by; + *(owy++) = interpolation::fastweight(interpolation1, dy); + if (do_grad || do_sgrad) + *(ogy++) = interpolation::fastgrad(interpolation1, dy); + if (do_grad && trgt_sK > 1) + *(ohy++) = interpolation::fasthess(interpolation1, dy); + *(osy++) = bound::sign(bound1, by, src_Y); + *(oiy++) = bound::index(bound1, by, src_Y); + } + } + { + scalar_t *owx = static_cast(wx), *ogx = static_cast(gx), *ohx = static_cast(hx); + offset_t* oix = static_cast(ix); + uint8_t* osx = static_cast(sx); + for (offset_t bx = bx0; bx <= bx1; ++bx) { + scalar_t dx = x - bx; + *(owx++) = interpolation::fastweight(interpolation0, dx); + if (do_grad || do_sgrad) + *(ogx++) = interpolation::fastgrad(interpolation0, dx); + if (do_grad && trgt_sK > 1) + *(ohx++) = interpolation::fasthess(interpolation0, dx); + *(osx++) = bound::sign(bound0, bx, src_X); + *(oix++) = bound::index(bound0, bx, src_X); + } + } + + // Convolve coefficients with basis functions + scalar_t ogx, ogy; + ogx = ogy = static_cast(0); + for (offset_t j = 0; j <= dby; ++j) { + offset_t ooy = iy[j] * out_sY; + offset_t osy = iy[j] * src_sY; + uint8_t syy = sy[j]; + scalar_t wyy = wy[j]; + scalar_t gyy = gy[j]; + scalar_t hyy = hy[j]; + for (offset_t i = 0; i <= dbx; ++i) { + offset_t ooxy = ooy + ix[i] * out_sX; + offset_t osxy = osy + ix[i] * src_sX; + uint8_t sxy = syy * sx[i]; + scalar_t wxx = wx[i]; + scalar_t gxx = gx[i]; + scalar_t hxx = hx[i]; + + // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Pull ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + if (do_pull) { + scalar_t* src_ptr_NC = src_ptr_NC0; + scalar_t* out_ptr_NCXY = out_ptr_NCXY0; + for (offset_t c = 0; c < C; ++c, out_ptr_NCXY += out_sC, src_ptr_NC += src_sC) + *out_ptr_NCXY += bound::get(src_ptr_NC, osxy, sxy) * (wxx * wyy); + } + + // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ SGrad ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + else if (do_sgrad) { + scalar_t* src_ptr_NC = src_ptr_NC0; + scalar_t* out_ptr_NCXY = out_ptr_NCXY0; + for (offset_t c = 0; c < C; ++c, out_ptr_NCXY += out_sC, src_ptr_NC += src_sC) { + scalar_t src = bound::get(src_ptr_NC, osxy, sxy); + *out_ptr_NCXY += src * (gxx * wyy); + out_ptr_NCXY[out_sK] += src * (wxx * gyy); + } + } + + // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Push ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + else if (do_push) { + if (trgt_K == 0) { + // Diff w.r.t. push/pull + scalar_t* out_ptr_NC = out_ptr_NC0; + for (offset_t c = 0; c < C; ++c, out_ptr_NC += out_sC) + bound::add(out_ptr_NC, ooxy, (wxx * wyy) * target[c], sxy); + } else { + // Diff w.r.t. sgrad + scalar_t* out_ptr_NC = out_ptr_NC0; + for (offset_t c = 0; c < C; ++c, out_ptr_NC += out_sC) { + scalar_t val = (gxx * wyy) * target[c] + (wxx * gyy) * target[c + C]; + bound::add(out_ptr_NC, ooxy, val, sxy); + } + } + } + + // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Count ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + else if (do_count) { + bound::add(out_ptr_NC0, ooxy, (wxx * wyy), sxy); + } + + // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Grad ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + if (do_grad) { + if (trgt_K == 0) { + // Diff w.r.t. pull/push + scalar_t* src_ptr_NC = src_ptr_NC0; + scalar_t dot = static_cast(0); + for (offset_t c = 0; c < C; ++c, src_ptr_NC += src_sC) { + scalar_t src = bound::get(src_ptr_NC, osxy, sxy); + dot += (trgt_ptr ? src * target[c] : src); + // trgt_ptr == 0 in the backward pass of 'count' + } + ogx += (gxx * wyy) * dot; + ogy += (wxx * gyy) * dot; + } else { + // Diff w.r.t. sgrad + scalar_t* src_ptr_NC = src_ptr_NC0; + scalar_t dot0, dot1; + dot0 = dot1 = static_cast(0); + for (offset_t c = 0; c < C; ++c, src_ptr_NC += src_sC) { + scalar_t src = bound::get(src_ptr_NC, osxy, sxy); + dot0 += src * target[c]; + dot1 += src * target[c + C]; + } + ogx += (hxx * wyy) * dot0 + (gxx * gyy) * dot1; + ogy += (gxx * gyy) * dot0 + (wxx * hyy) * dot1; + } + } + + } // x + } // y + + // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Grad ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + if (do_grad) { + scalar_t* grad_ptr_NXY = grad_ptr + n * grad_sN + w * grad_sX + h * grad_sY; + (*grad_ptr_NXY) = ogx; + grad_ptr_NXY[grad_sC] = ogy; + } + } + + // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + // GENERIC INTERPOLATION 1D + // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + + template + MONAI_DEVICE void PushPullImpl::interpolate1d(scalar_t x, offset_t w, offset_t n) const { + // Get corner pixel values from (x, y) + offset_t bx0, bx1; + interpolation::bounds(interpolation0, x, bx0, bx1); + offset_t dbx = bx1 - bx0; + + // Pre-compute offsets and target value + scalar_t* src_ptr_NC0 = src_ptr + n * src_sN; + scalar_t* out_ptr_NC0 = out_ptr + n * out_sN; + scalar_t* out_ptr_NCX0 = out_ptr + n * out_sN + w * out_sX; + scalar_t* trgt_ptr_NCX = trgt_ptr + n * trgt_sN + w * trgt_sX; + scalar_t target[2 * MONAI_MAX_NUM_CHANNELS]; + if (trgt_ptr && (do_push || do_grad)) + for (offset_t c = 0; c < C; ++c, trgt_ptr_NCX += trgt_sC) { + target[c] = *trgt_ptr_NCX; + if (trgt_K > 0) { + target[c + C] = trgt_ptr_NCX[trgt_sK]; + } + } + + // Initialize output + scalar_t* out_ptr_NCX = out_ptr_NCX0; + if (do_pull || do_sgrad) { + for (offset_t c = 0; c < C; ++c, out_ptr_NCX += out_sC) { + *out_ptr_NCX = static_cast(0); + if (do_sgrad) { + out_ptr_NCX[out_sK] = static_cast(0); + } + } + } + + // Pre-compute indices/weights/grad + scalar_t wx[8]; // B-spline weights + scalar_t gx[8]; // B-spline derivatives + scalar_t hx[8]; // B-spline 2nd derivatives + offset_t ix[8]; // Warped indices + uint8_t sx[8]; // Warped indices + + { + scalar_t *owx = static_cast(wx), *ogx = static_cast(gx), *ohx = static_cast(hx); + offset_t* oix = static_cast(ix); + uint8_t* osx = static_cast(sx); + for (offset_t bx = bx0; bx <= bx1; ++bx) { + scalar_t dx = x - bx; + *(owx++) = interpolation::fastweight(interpolation0, dx); + if (do_grad || do_sgrad) + *(ogx++) = interpolation::fastgrad(interpolation0, dx); + if (do_grad && trgt_sK > 1) + *(ohx++) = interpolation::fasthess(interpolation0, dx); + *(osx++) = bound::sign(bound0, bx, src_X); + *(oix++) = bound::index(bound0, bx, src_X); + } + } + + // Convolve coefficients with basis functions + scalar_t ogx; + ogx = static_cast(0); + for (offset_t i = 0; i <= dbx; ++i) { + offset_t oox = ix[i] * out_sX; + offset_t osx = ix[i] * src_sX; + uint8_t sxx = sx[i]; + scalar_t wxx = wx[i]; + scalar_t gxx = gx[i]; + scalar_t hxx = hx[i]; + + // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Pull ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + if (do_pull) { + scalar_t* src_ptr_NC = src_ptr_NC0; + scalar_t* out_ptr_NCX = out_ptr_NCX0; + for (offset_t c = 0; c < C; ++c, out_ptr_NCX += out_sC, src_ptr_NC += src_sC) + *out_ptr_NCX += bound::get(src_ptr_NC, osx, sxx) * wxx; + } + + // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ SGrad ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + else if (do_sgrad) { + scalar_t* src_ptr_NC = src_ptr_NC0; + scalar_t* out_ptr_NCX = out_ptr_NCX0; + for (offset_t c = 0; c < C; ++c, out_ptr_NCX += out_sC, src_ptr_NC += src_sC) { + scalar_t src = bound::get(src_ptr_NC, osx, sxx); + *out_ptr_NCX += src * gxx; + } + } + + // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Push ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + else if (do_push) { + if (trgt_K == 0) { + // Diff w.r.t. push/pull + scalar_t* out_ptr_NC = out_ptr_NC0; + for (offset_t c = 0; c < C; ++c, out_ptr_NC += out_sC) + bound::add(out_ptr_NC, oox, wxx * target[c], sxx); + } else { + // Diff w.r.t. sgrad + scalar_t* out_ptr_NC = out_ptr_NC0; + for (offset_t c = 0; c < C; ++c, out_ptr_NC += out_sC) { + scalar_t val = gxx * target[c]; + bound::add(out_ptr_NC, oox, val, sxx); + } + } + } + + // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Count ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + else if (do_count) { + bound::add(out_ptr_NC0, oox, wxx, sxx); + } + + // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Grad ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + if (do_grad) { + if (trgt_K == 0) { + // Diff w.r.t. pull/push + scalar_t* src_ptr_NC = src_ptr_NC0; + scalar_t dot = static_cast(0); + for (offset_t c = 0; c < C; ++c, src_ptr_NC += src_sC) { + scalar_t src = bound::get(src_ptr_NC, osx, sxx); + dot += (trgt_ptr ? src * target[c] : src); + // trgt_ptr == 0 in the backward pass of 'count' + } + ogx += gxx * dot; + } else { + // Diff w.r.t. sgrad + scalar_t* src_ptr_NC = src_ptr_NC0; + scalar_t dot; + dot = static_cast(0); + for (offset_t c = 0; c < C; ++c, src_ptr_NC += src_sC) { + scalar_t src = bound::get(src_ptr_NC, osx, sxx); + dot += src * target[c]; + } + ogx += hxx * dot; + } + } + + } // x + + // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Grad ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + if (do_grad) { + scalar_t* grad_ptr_NX = grad_ptr + n * grad_sN + w * grad_sX; + (*grad_ptr_NX) = ogx; + } + } + + // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + // LINEAR INTERPOLATION 3D + // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + + template + MONAI_DEVICE void PushPullImpl::interpolate3d_trilinear( + scalar_t x, + scalar_t y, + scalar_t z, + offset_t w, + offset_t h, + offset_t d, + offset_t n) const { + // Get corner pixel values from (x, y, z) + offset_t ix0 = static_cast(std::floor(x)); + offset_t iy0 = static_cast(std::floor(y)); + offset_t iz0 = static_cast(std::floor(z)); + + // Interpolation weights (inversely proportional to distance) + scalar_t dx1 = x - ix0; + scalar_t dy1 = y - iy0; + scalar_t dz1 = z - iz0; + scalar_t dx0 = 1. - dx1; + scalar_t dy0 = 1. - dy1; + scalar_t dz0 = 1. - dz1; + scalar_t w000 = dx0 * dy0 * dz0; + scalar_t w100 = dx1 * dy0 * dz0; + scalar_t w010 = dx0 * dy1 * dz0; + scalar_t w001 = dx0 * dy0 * dz1; + scalar_t w110 = dx1 * dy1 * dz0; + scalar_t w011 = dx0 * dy1 * dz1; + scalar_t w101 = dx1 * dy0 * dz1; + scalar_t w111 = dx1 * dy1 * dz1; + + // Sign (/!\ compute sign before warping indices) + int8_t sx1 = bound::sign(bound0, ix0 + 1, src_X); + int8_t sy1 = bound::sign(bound1, iy0 + 1, src_Y); + int8_t sz1 = bound::sign(bound2, iz0 + 1, src_Z); + int8_t sx0 = bound::sign(bound0, ix0, src_X); + int8_t sy0 = bound::sign(bound1, iy0, src_Y); + int8_t sz0 = bound::sign(bound2, iz0, src_Z); + int8_t s000 = sx0 * sy0 * sz0; + int8_t s100 = sx1 * sy0 * sz0; + int8_t s010 = sx0 * sy1 * sz0; + int8_t s001 = sx0 * sy0 * sz1; + int8_t s110 = sx1 * sy1 * sz0; + int8_t s011 = sx0 * sy1 * sz1; + int8_t s101 = sx1 * sy0 * sz1; + int8_t s111 = sx1 * sy1 * sz1; + + // Warp indices + offset_t ix1, iy1, iz1; + ix1 = bound::index(bound0, ix0 + 1, src_X); + iy1 = bound::index(bound1, iy0 + 1, src_Y); + iz1 = bound::index(bound2, iz0 + 1, src_Z); + ix0 = bound::index(bound0, ix0, src_X); + iy0 = bound::index(bound1, iy0, src_Y); + iz0 = bound::index(bound2, iz0, src_Z); + + offset_t o000, o100, o010, o001, o110, o011, o101, o111; + + if (do_pull || do_grad || do_sgrad) { + // Offsets into source volume + o000 = ix0 * src_sX + iy0 * src_sY + iz0 * src_sZ; + o100 = ix1 * src_sX + iy0 * src_sY + iz0 * src_sZ; + o010 = ix0 * src_sX + iy1 * src_sY + iz0 * src_sZ; + o001 = ix0 * src_sX + iy0 * src_sY + iz1 * src_sZ; + o110 = ix1 * src_sX + iy1 * src_sY + iz0 * src_sZ; + o011 = ix0 * src_sX + iy1 * src_sY + iz1 * src_sZ; + o101 = ix1 * src_sX + iy0 * src_sY + iz1 * src_sZ; + o111 = ix1 * src_sX + iy1 * src_sY + iz1 * src_sZ; + } else if (!(do_push || do_count)) { + o000 = o100 = o010 = o001 = o110 = o011 = o101 = o111 = 0; + } + + // ~~~~~~~~~~~~~~~~~~~~~~~~~~ Grid gradient ~~~~~~~~~~~~~~~~~~~~~~~~~~ + if (do_grad) { + scalar_t gx = static_cast(0); + scalar_t gy = static_cast(0); + scalar_t gz = static_cast(0); + scalar_t* trgt_ptr_NCXYZ = trgt_ptr + n * trgt_sN + w * trgt_sX + h * trgt_sY + d * trgt_sZ; + scalar_t* src_ptr_NC = src_ptr + n * src_sN; + + if (trgt_K == 0) { + // backward w.r.t. push/pull + for (offset_t c = 0; c < C; ++c, trgt_ptr_NCXYZ += trgt_sC, src_ptr_NC += src_sC) { + scalar_t src; + scalar_t trgt = trgt_ptr ? *trgt_ptr_NCXYZ : static_cast(1); + // ^ trgt_ptr == 0 during the backward pass of count + src = bound::get(src_ptr_NC, o000, s000); + if (trgt_ptr) + src *= trgt; + gx -= dy0 * dz0 * src; + gy -= dx0 * dz0 * src; + gz -= dx0 * dy0 * src; + src = bound::get(src_ptr_NC, o100, s100); + if (trgt_ptr) + src *= trgt; + gx += dy0 * dz0 * src; + gy -= dx1 * dz0 * src; + gz -= dx1 * dy0 * src; + src = bound::get(src_ptr_NC, o010, s010); + if (trgt_ptr) + src *= trgt; + gx -= dy1 * dz0 * src; + gy += dx0 * dz0 * src; + gz -= dx0 * dy1 * src; + src = bound::get(src_ptr_NC, o110, s110); + if (trgt_ptr) + src *= trgt; + gx += dy1 * dz0 * src; + gy += dx1 * dz0 * src; + gz -= dx1 * dy1 * src; + src = bound::get(src_ptr_NC, o001, s001); + if (trgt_ptr) + src *= trgt; + gx -= dy0 * dz1 * src; + gy -= dx0 * dz1 * src; + gz += dx0 * dy0 * src; + src = bound::get(src_ptr_NC, o101, s101); + if (trgt_ptr) + src *= trgt; + gx += dy0 * dz1 * src; + gy -= dx1 * dz1 * src; + gz += dx1 * dy0 * src; + src = bound::get(src_ptr_NC, o011, s011); + if (trgt_ptr) + src *= trgt; + gx -= dy1 * dz1 * src; + gy += dx0 * dz1 * src; + gz += dx0 * dy1 * src; + src = bound::get(src_ptr_NC, o111, s111); + if (trgt_ptr) + src *= trgt; + gx += dy1 * dz1 * src; + gy += dx1 * dz1 * src; + gz += dx1 * dy1 * src; + } + } else { + // backward w.r.t. sgrad + for (offset_t c = 0; c < C; ++c, trgt_ptr_NCXYZ += trgt_sC, src_ptr_NC += src_sC) { + scalar_t src; + scalar_t trgt0 = *trgt_ptr_NCXYZ, trgt1 = trgt_ptr_NCXYZ[trgt_sK], trgt2 = trgt_ptr_NCXYZ[trgt_sK * 2]; + src = bound::get(src_ptr_NC, o000, s000); + gx += (dz0 * trgt1 + dy0 * trgt2) * src; + gy += (dz0 * trgt0 + dx0 * trgt2) * src; + gz += (dy0 * trgt0 + dx0 * trgt1) * src; + src = bound::get(src_ptr_NC, o100, s100); + gx += (-dz0 * trgt1 - dy0 * trgt2) * src; + gy += (-dz0 * trgt0 + dx1 * trgt2) * src; + gz += (-dy0 * trgt0 + dx1 * trgt1) * src; + src = bound::get(src_ptr_NC, o010, s010); + gx += (-dz0 * trgt1 + dy1 * trgt2) * src; + gy += (-dz0 * trgt0 - dx0 * trgt2) * src; + gz += (dy1 * trgt0 - dx0 * trgt1) * src; + src = bound::get(src_ptr_NC, o110, s110); + gx += (dz0 * trgt1 - dy1 * trgt2) * src; + gy += (dz0 * trgt0 - dx1 * trgt2) * src; + gz += (-dy1 * trgt0 - dx1 * trgt1) * src; + src = bound::get(src_ptr_NC, o001, s001); + gx += (dz1 * trgt1 - dy0 * trgt2) * src; + gy += (dz1 * trgt0 - dx0 * trgt2) * src; + gz += (-dy0 * trgt0 - dx0 * trgt1) * src; + src = bound::get(src_ptr_NC, o101, s101); + gx += (-dz1 * trgt1 + dy0 * trgt2) * src; + gy += (-dz1 * trgt0 - dx1 * trgt2) * src; + gz += (dy0 * trgt0 - dx1 * trgt1) * src; + src = bound::get(src_ptr_NC, o011, s011); + gx += (-dz1 * trgt1 - dy1 * trgt2) * src; + gy += (-dz1 * trgt0 + dx0 * trgt2) * src; + gz += (-dy1 * trgt0 + dx0 * trgt1) * src; + src = bound::get(src_ptr_NC, o111, s111); + gx += (dz1 * trgt1 + dy1 * trgt2) * src; + gy += (dz1 * trgt0 + dx1 * trgt2) * src; + gz += (dy1 * trgt0 + dx1 * trgt1) * src; + } + } + + scalar_t* grad_ptr_NXYZ = grad_ptr + n * grad_sN + w * grad_sX + h * grad_sY + d * grad_sZ; + (*grad_ptr_NXYZ) = gx; + grad_ptr_NXYZ[grad_sC] = gy; + grad_ptr_NXYZ[grad_sC * 2] = gz; + } + if (do_push || do_count) { + // Offsets into 'push' volume + o000 = ix0 * out_sX + iy0 * out_sY + iz0 * out_sZ; + o100 = ix1 * out_sX + iy0 * out_sY + iz0 * out_sZ; + o010 = ix0 * out_sX + iy1 * out_sY + iz0 * out_sZ; + o001 = ix0 * out_sX + iy0 * out_sY + iz1 * out_sZ; + o110 = ix1 * out_sX + iy1 * out_sY + iz0 * out_sZ; + o011 = ix0 * out_sX + iy1 * out_sY + iz1 * out_sZ; + o101 = ix1 * out_sX + iy0 * out_sY + iz1 * out_sZ; + o111 = ix1 * out_sX + iy1 * out_sY + iz1 * out_sZ; + } + // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Pull ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + if (do_pull) { + scalar_t* out_ptr_NCXYZ = out_ptr + n * out_sN + w * out_sX + h * out_sY + d * out_sZ; + scalar_t* src_ptr_NC = src_ptr + n * src_sN; + for (offset_t c = 0; c < C; ++c, out_ptr_NCXYZ += out_sC, src_ptr_NC += src_sC) { + *out_ptr_NCXYZ = bound::get(src_ptr_NC, o000, s000) * w000 + bound::get(src_ptr_NC, o100, s100) * w100 + + bound::get(src_ptr_NC, o010, s010) * w010 + bound::get(src_ptr_NC, o110, s110) * w110 + + bound::get(src_ptr_NC, o001, s001) * w001 + bound::get(src_ptr_NC, o101, s101) * w101 + + bound::get(src_ptr_NC, o011, s011) * w011 + bound::get(src_ptr_NC, o111, s111) * w111; + } + } + // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ SGrad ~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~ + else if (do_sgrad) { + scalar_t* out_ptr_NCXYZ = out_ptr + n * out_sN + w * out_sX + h * out_sY + d * out_sZ; + scalar_t* src_ptr_NC = src_ptr + n * src_sN; + + for (offset_t c = 0; c < C; ++c, out_ptr_NCXYZ += out_sC, src_ptr_NC += src_sC) { + scalar_t src000 = bound::get(src_ptr_NC, o000, s000); + scalar_t src100 = bound::get(src_ptr_NC, o100, s100); + scalar_t src010 = bound::get(src_ptr_NC, o010, s010); + scalar_t src110 = bound::get(src_ptr_NC, o110, s110); + scalar_t src001 = bound::get(src_ptr_NC, o001, s001); + scalar_t src101 = bound::get(src_ptr_NC, o101, s101); + scalar_t src011 = bound::get(src_ptr_NC, o011, s011); + scalar_t src111 = bound::get(src_ptr_NC, o111, s111); + *out_ptr_NCXYZ = -dy0 * dz0 * src000 + dy0 * dz0 * src100 - dy1 * dz0 * src010 + dy1 * dz0 * src110 - + dy0 * dz1 * src001 + dy0 * dz1 * src101 - dy1 * dz1 * src011 + dy1 * dz1 * src111; + out_ptr_NCXYZ[out_sK] = -dx0 * dz0 * src000 - dx1 * dz0 * src100 + dx0 * dz0 * src010 + dx1 * dz0 * src110 - + dx0 * dz1 * src001 - dx1 * dz1 * src101 + dx0 * dz1 * src011 + dx1 * dz1 * src111; + out_ptr_NCXYZ[out_sK * 2] = -dx0 * dy0 * src000 - dx1 * dy0 * src100 - dx0 * dy1 * src010 - dx1 * dy1 * src110 + + dx0 * dy0 * src001 + dx1 * dy0 * src101 + dx0 * dy1 * src011 + dx1 * dy1 * src111; + } + } + // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Push ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + else if (do_push) { + // Offsets into 'push' volume + o000 = ix0 * out_sX + iy0 * out_sY + iz0 * out_sZ; + o100 = ix1 * out_sX + iy0 * out_sY + iz0 * out_sZ; + o010 = ix0 * out_sX + iy1 * out_sY + iz0 * out_sZ; + o001 = ix0 * out_sX + iy0 * out_sY + iz1 * out_sZ; + o110 = ix1 * out_sX + iy1 * out_sY + iz0 * out_sZ; + o011 = ix0 * out_sX + iy1 * out_sY + iz1 * out_sZ; + o101 = ix1 * out_sX + iy0 * out_sY + iz1 * out_sZ; + o111 = ix1 * out_sX + iy1 * out_sY + iz1 * out_sZ; + scalar_t* trgt_ptr_NCXYZ = trgt_ptr + n * trgt_sN + w * trgt_sX + h * trgt_sY + d * trgt_sZ; + scalar_t* out_ptr_NC = out_ptr + n * out_sN; + if (trgt_K == 0) { + // Diff w.r.t. push/pull + for (offset_t c = 0; c < C; ++c, trgt_ptr_NCXYZ += trgt_sC, out_ptr_NC += out_sC) { + scalar_t trgt = *trgt_ptr_NCXYZ; + bound::add(out_ptr_NC, o000, w000 * trgt, s000); + bound::add(out_ptr_NC, o100, w100 * trgt, s100); + bound::add(out_ptr_NC, o010, w010 * trgt, s010); + bound::add(out_ptr_NC, o110, w110 * trgt, s110); + bound::add(out_ptr_NC, o001, w001 * trgt, s001); + bound::add(out_ptr_NC, o101, w101 * trgt, s101); + bound::add(out_ptr_NC, o011, w011 * trgt, s011); + bound::add(out_ptr_NC, o111, w111 * trgt, s111); + } + } else { + // Diff w.r.t. sgrad + scalar_t val; + for (offset_t c = 0; c < C; ++c, trgt_ptr_NCXYZ += trgt_sC, out_ptr_NC += out_sC) { + scalar_t trgt0 = *trgt_ptr_NCXYZ, trgt1 = trgt_ptr_NCXYZ[trgt_sK], trgt2 = trgt_ptr_NCXYZ[trgt_sK * 2]; + val = -dy0 * dz0 * trgt0 - dx0 * dz0 * trgt1 - dx0 * dy0 * trgt2; + bound::add(out_ptr_NC, o000, val, s000); + val = dy0 * dz0 * trgt0 - dx1 * dz0 * trgt1 - dx1 * dy0 * trgt2; + bound::add(out_ptr_NC, o100, val, s100); + val = -dy1 * dz0 * trgt0 + dx0 * dz0 * trgt1 - dx0 * dy1 * trgt2; + bound::add(out_ptr_NC, o010, val, s010); + val = dy1 * dz0 * trgt0 + dx1 * dz0 * trgt1 - dx1 * dy1 * trgt2; + bound::add(out_ptr_NC, o110, val, s110); + val = -dy0 * dz1 * trgt0 - dx0 * dz1 * trgt1 + dx0 * dy0 * trgt2; + bound::add(out_ptr_NC, o001, val, s001); + val = dy0 * dz1 * trgt0 - dx1 * dz1 * trgt1 + dx1 * dy0 * trgt2; + bound::add(out_ptr_NC, o101, val, s101); + val = -dy1 * dz1 * trgt0 + dx0 * dz1 * trgt1 + dx0 * dy1 * trgt2; + bound::add(out_ptr_NC, o011, val, s011); + val = dy1 * dz1 * trgt0 + dx1 * dz1 * trgt1 + dx1 * dy1 * trgt2; + bound::add(out_ptr_NC, o111, val, s111); + } + } + } + // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Push ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + else if (do_count) { + scalar_t* out_ptr_N = out_ptr + n * out_sN; + bound::add(out_ptr_N, o000, w000, s000); + bound::add(out_ptr_N, o100, w100, s100); + bound::add(out_ptr_N, o010, w010, s010); + bound::add(out_ptr_N, o110, w110, s110); + bound::add(out_ptr_N, o001, w001, s001); + bound::add(out_ptr_N, o101, w101, s101); + bound::add(out_ptr_N, o011, w011, s011); + bound::add(out_ptr_N, o111, w111, s111); + } + } + + // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + // LINEAR INTERPOLATION 2D + // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + + template + MONAI_DEVICE void PushPullImpl::interpolate2d_bilinear( + scalar_t x, + scalar_t y, + offset_t w, + offset_t h, + offset_t n) const { + // Get corner pixel values from (x, y, z) + offset_t ix0 = static_cast(std::floor(x)); + offset_t iy0 = static_cast(std::floor(y)); + + // Interpolation weights (inversely proportional to distance) + scalar_t dx1 = x - ix0; + scalar_t dy1 = y - iy0; + scalar_t dx0 = 1. - dx1; + scalar_t dy0 = 1. - dy1; + scalar_t w00 = dx0 * dy0; + scalar_t w10 = dx1 * dy0; + scalar_t w01 = dx0 * dy1; + scalar_t w11 = dx1 * dy1; + + // Sign (/!\ compute sign before warping indices) + int8_t sx1 = bound::sign(bound0, ix0 + 1, src_X); + int8_t sy1 = bound::sign(bound1, iy0 + 1, src_Y); + int8_t sx0 = bound::sign(bound0, ix0, src_X); + int8_t sy0 = bound::sign(bound1, iy0, src_Y); + int8_t s00 = sx0 * sy0; + int8_t s10 = sx1 * sy0; + int8_t s01 = sx0 * sy1; + int8_t s11 = sx1 * sy1; + + // Warp indices + offset_t ix1, iy1; + ix1 = bound::index(bound0, ix0 + 1, src_X); + iy1 = bound::index(bound1, iy0 + 1, src_Y); + ix0 = bound::index(bound0, ix0, src_X); + iy0 = bound::index(bound1, iy0, src_Y); + + offset_t o00, o10, o01, o11; + if (do_pull || do_grad || do_sgrad) { + // Offsets into source volume + o00 = ix0 * src_sX + iy0 * src_sY; + o10 = ix1 * src_sX + iy0 * src_sY; + o01 = ix0 * src_sX + iy1 * src_sY; + o11 = ix1 * src_sX + iy1 * src_sY; + } else if (!(do_push || do_count)) { + o00 = o10 = o01 = o11 = 0; + } + + // ~~~~~~~~~~~~~~~~~~~~~~~~~~ Grid gradient ~~~~~~~~~~~~~~~~~~~~~~~~~~ + if (do_grad) { + scalar_t gx = static_cast(0); + scalar_t gy = static_cast(0); + scalar_t* trgt_ptr_NCXY = trgt_ptr + n * trgt_sN + w * trgt_sX + h * trgt_sY; + scalar_t* src_ptr_NC = src_ptr + n * src_sN; + + if (trgt_K == 0) { + // backward w.r.t. push/pull + for (offset_t c = 0; c < C; ++c, trgt_ptr_NCXY += trgt_sC, src_ptr_NC += src_sC) { + scalar_t src; + scalar_t trgt = trgt_ptr ? *trgt_ptr_NCXY : static_cast(1); + // ^ trgt_ptr == 0 during the backward pass of count + src = bound::get(src_ptr_NC, o00, s00); + if (trgt_ptr) + src *= trgt; + gx -= dy0 * src; + gy -= dx0 * src; + src = bound::get(src_ptr_NC, o10, s10); + if (trgt_ptr) + src *= trgt; + gx += dy0 * src; + gy -= dx1 * src; + src = bound::get(src_ptr_NC, o01, s01); + if (trgt_ptr) + src *= trgt; + gx -= dy1 * src; + gy += dx0 * src; + src = bound::get(src_ptr_NC, o11, s11); + if (trgt_ptr) + src *= trgt; + gx += dy1 * src; + gy += dx1 * src; + } + } else { + // backward w.r.t. sgrad + for (offset_t c = 0; c < C; ++c, trgt_ptr_NCXY += trgt_sC, src_ptr_NC += src_sC) { + scalar_t src; + scalar_t trgt0 = *trgt_ptr_NCXY, trgt1 = trgt_ptr_NCXY[trgt_sK]; + src = bound::get(src_ptr_NC, o00, s00); + gx += trgt1 * src; + gy += trgt0 * src; + src = bound::get(src_ptr_NC, o10, s10); + gx -= trgt1 * src; + gy -= trgt0 * src; + src = bound::get(src_ptr_NC, o01, s01); + gx -= trgt1 * src; + gy -= trgt0 * src; + src = bound::get(src_ptr_NC, o11, s11); + gx += trgt1 * src; + gy += trgt0 * src; + } + } + + scalar_t* grad_ptr_NXY = grad_ptr + n * grad_sN + w * grad_sX + h * grad_sY; + (*grad_ptr_NXY) = gx; + grad_ptr_NXY[grad_sC] = gy; + } + if (do_push || do_count) { + // Offsets into 'push' volume + o00 = ix0 * out_sX + iy0 * out_sY; + o10 = ix1 * out_sX + iy0 * out_sY; + o01 = ix0 * out_sX + iy1 * out_sY; + o11 = ix1 * out_sX + iy1 * out_sY; + } + // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Pull ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + if (do_pull) { + scalar_t* out_ptr_NCXY = out_ptr + n * out_sN + w * out_sX + h * out_sY; + scalar_t* src_ptr_NC = src_ptr + n * src_sN; + for (offset_t c = 0; c < C; ++c, out_ptr_NCXY += out_sC, src_ptr_NC += src_sC) { + *out_ptr_NCXY = bound::get(src_ptr_NC, o00, s00) * w00 + bound::get(src_ptr_NC, o10, s10) * w10 + + bound::get(src_ptr_NC, o01, s01) * w01 + bound::get(src_ptr_NC, o11, s11) * w11; + } + } + // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ SGrad ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + else if (do_sgrad) { + scalar_t* out_ptr_NCXY = out_ptr + n * out_sN + w * out_sX + h * out_sY; + scalar_t* src_ptr_NC = src_ptr + n * src_sN; + + for (offset_t c = 0; c < C; ++c, out_ptr_NCXY += out_sC, src_ptr_NC += src_sC) { + scalar_t src00 = bound::get(src_ptr_NC, o00, s00); + scalar_t src10 = bound::get(src_ptr_NC, o10, s10); + scalar_t src01 = bound::get(src_ptr_NC, o01, s01); + scalar_t src11 = bound::get(src_ptr_NC, o11, s11); + *out_ptr_NCXY = -dy0 * src00 + dy0 * src10 - dy1 * src01 + dy1 * src11; + out_ptr_NCXY[out_sK] = -dx0 * src00 - dx1 * src10 + dx0 * src01 + dx1 * src11; + } + } + // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Push ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + else if (do_push) { + scalar_t* trgt_ptr_NCXY = trgt_ptr + n * trgt_sN + w * trgt_sX + h * trgt_sY; + scalar_t* out_ptr_NC = out_ptr + n * out_sN; + if (trgt_K == 0) { + // Diff w.r.t. push/pull + for (offset_t c = 0; c < C; ++c, trgt_ptr_NCXY += trgt_sC, out_ptr_NC += out_sC) { + scalar_t trgt = *trgt_ptr_NCXY; + bound::add(out_ptr_NC, o00, w00 * trgt, s00); + bound::add(out_ptr_NC, o10, w10 * trgt, s10); + bound::add(out_ptr_NC, o01, w01 * trgt, s01); + bound::add(out_ptr_NC, o11, w11 * trgt, s11); + } + } else { + // Diff w.r.t. sgrad + scalar_t val; + for (offset_t c = 0; c < C; ++c, trgt_ptr_NCXY += trgt_sC, out_ptr_NC += out_sC) { + scalar_t trgt0 = *trgt_ptr_NCXY, trgt1 = trgt_ptr_NCXY[trgt_sK]; + val = -dy0 * trgt0 - dx0 * trgt1; + bound::add(out_ptr_NC, o00, val, s00); + val = dy0 * trgt0 - dx1 * trgt1; + bound::add(out_ptr_NC, o10, val, s10); + val = -dy1 * trgt0 + dx0 * trgt1; + bound::add(out_ptr_NC, o01, val, s01); + val = dy1 * trgt0 + dx1 * trgt1; + bound::add(out_ptr_NC, o11, val, s11); + } + } + } + // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Push ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + else if (do_count) { + scalar_t* out_ptr_N = out_ptr + n * out_sN; + bound::add(out_ptr_N, o00, w00, s00); + bound::add(out_ptr_N, o10, w10, s10); + bound::add(out_ptr_N, o01, w01, s01); + bound::add(out_ptr_N, o11, w11, s11); + } + } + + // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + // LINEAR INTERPOLATION 1D + // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + + template + MONAI_DEVICE void PushPullImpl::interpolate1d_linear(scalar_t x, offset_t w, offset_t n) const { + // Get corner pixel values from (x) + offset_t ix0 = static_cast(std::floor(x)); + + // Interpolation weights (inversely proportional to distance) + scalar_t w1 = x - ix0; + scalar_t w0 = 1. - w1; + + // Sign (/!\ compute sign before warping indices) + int8_t s1 = bound::sign(bound0, ix0 + 1, src_X); + int8_t s0 = bound::sign(bound0, ix0, src_X); + + // Warp indices + offset_t ix1; + ix1 = bound::index(bound0, ix0 + 1, src_X); + ix0 = bound::index(bound0, ix0, src_X); + + offset_t o0, o1; + if (do_pull || do_grad || do_sgrad) { + // Offsets into source volume + o0 = ix0 * src_sX; + o1 = ix1 * src_sX; + } else if (!(do_push || do_count)) { + o0 = o1 = 0; + } + + // ~~~~~~~~~~~~~~~~~~~~~~~~~~ Grid gradient ~~~~~~~~~~~~~~~~~~~~~~~~~~ + if (do_grad) { + if (trgt_K == 0) { + // backward w.r.t. push/pull + scalar_t gx = static_cast(0); + scalar_t* trgt_ptr_NCX = trgt_ptr + n * trgt_sN + w * trgt_sX; + scalar_t* src_ptr_NC = src_ptr + n * src_sN; + + for (offset_t c = 0; c < C; ++c, trgt_ptr_NCX += trgt_sC, src_ptr_NC += src_sC) { + scalar_t src; + scalar_t trgt = trgt_ptr ? *trgt_ptr_NCX : static_cast(1); + // ^ trgt_ptr == 0 during the backward pass of count + src = bound::get(src_ptr_NC, o0, s0); + if (trgt_ptr) + src *= trgt; + gx -= src; + src = bound::get(src_ptr_NC, o1, s1); + if (trgt_ptr) + src *= trgt; + gx += src; + } + + scalar_t* grad_ptr_NX = grad_ptr + n * grad_sN + w * grad_sX; + (*grad_ptr_NX) = gx; + } else { + // backward w.r.t. sgrad + // -> zero (make sure this is done at initialization) + } + } + if (do_push || do_count) { + // Offsets into 'push' volume + o0 = ix0 * out_sX; + o1 = ix1 * out_sX; + } + // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Pull ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + if (do_pull) { + scalar_t* out_ptr_NCX = out_ptr + n * out_sN + w * out_sX; + scalar_t* src_ptr_NC = src_ptr + n * src_sN; + for (offset_t c = 0; c < C; ++c, out_ptr_NCX += out_sC, src_ptr_NC += src_sC) { + *out_ptr_NCX = bound::get(src_ptr_NC, o0, s0) * w0 + bound::get(src_ptr_NC, o1, s1) * w1; + } + } + // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ SGrad ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + else if (do_sgrad) { + scalar_t* out_ptr_NCX = out_ptr + n * out_sN + w * out_sX; + scalar_t* src_ptr_NC = src_ptr + n * src_sN; + + for (offset_t c = 0; c < C; ++c, out_ptr_NCX += out_sC, src_ptr_NC += src_sC) { + *out_ptr_NCX = bound::get(src_ptr_NC, o1, s1) - bound::get(src_ptr_NC, o0, s0); + } + } + // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Push ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + else if (do_push) { + scalar_t* trgt_ptr_NCX = trgt_ptr + n * trgt_sN + w * trgt_sX; + scalar_t* out_ptr_NC = out_ptr + n * out_sN; + if (trgt_K == 0) { + // Diff w.r.t. push/pull + for (offset_t c = 0; c < C; ++c, trgt_ptr_NCX += trgt_sC, out_ptr_NC += out_sC) { + scalar_t trgt = *trgt_ptr_NCX; + bound::add(out_ptr_NC, o0, w0 * trgt, s0); + bound::add(out_ptr_NC, o1, w1 * trgt, s1); + } + } else { + // Diff w.r.t. sgrad + for (offset_t c = 0; c < C; ++c, trgt_ptr_NCX += trgt_sC, out_ptr_NC += out_sC) { + scalar_t trgt0 = *trgt_ptr_NCX; + bound::add(out_ptr_NC, o0, -trgt0, s0); + bound::add(out_ptr_NC, o1, trgt0, s1); + } + } + } + // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Push ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + else if (do_count) { + scalar_t* out_ptr_N = out_ptr + n * out_sN; + bound::add(out_ptr_N, o0, w0, s0); + bound::add(out_ptr_N, o1, w1, s1); + } + } + + // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + // NEAREST NEIGHBOR INTERPOLATION 3D + // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + + template + MONAI_DEVICE void PushPullImpl::interpolate3d_nearest( + scalar_t x, + scalar_t y, + scalar_t z, + offset_t w, + offset_t h, + offset_t d, + offset_t n) const { + offset_t ix = static_cast(std::round(x)); + offset_t iy = static_cast(std::round(y)); + offset_t iz = static_cast(std::round(z)); + + // Boundary condition (/!\ compute sign before warping indices) + int8_t sx = bound::sign(bound0, ix, src_X); + int8_t sy = bound::sign(bound1, iy, src_Y); + int8_t sz = bound::sign(bound2, iz, src_Z); + ix = bound::index(bound0, ix, src_X); + iy = bound::index(bound1, iy, src_Y); + iz = bound::index(bound2, iz, src_Z); + + // Sign + int8_t s = sz * sy * sx; + + if (do_pull) { + offset_t o = iz * src_sZ + iy * src_sY + ix * src_sX; + scalar_t* out_ptr_NCXYZ = out_ptr + n * out_sN + w * out_sX + h * out_sY + d * out_sZ; + scalar_t* src_ptr_NC = src_ptr + n * src_sN; + for (offset_t c = 0; c < C; ++c, out_ptr_NCXYZ += out_sC, src_ptr_NC += src_sC) + *out_ptr_NCXYZ = bound::get(src_ptr_NC, o, s); + } else if (do_push && trgt_K == 0) { + offset_t o = iz * out_sZ + iy * out_sY + ix * out_sX; + scalar_t* trgt_ptr_NCXYZ = trgt_ptr + n * trgt_sN + w * trgt_sX + h * trgt_sY + d * trgt_sZ; + scalar_t* out_ptr_NC = out_ptr + n * out_sN; + for (offset_t c = 0; c < C; ++c, trgt_ptr_NCXYZ += trgt_sC, out_ptr_NC += out_sC) + bound::add(out_ptr_NC, o, *trgt_ptr_NCXYZ, s); + } else if (do_count) { + offset_t o = iz * out_sZ + iy * out_sY + ix * out_sX; + scalar_t* out_ptr_NC = out_ptr + n * out_sN; + for (offset_t c = 0; c < C; ++c, out_ptr_NC += out_sC) + bound::add(out_ptr_NC, o, static_cast(1), s); + } + } + + // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + // NEAREST NEIGHBOR INTERPOLATION 2D + // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + + template + MONAI_DEVICE void PushPullImpl::interpolate2d_nearest( + scalar_t x, + scalar_t y, + offset_t w, + offset_t h, + offset_t n) const { + offset_t ix = static_cast(std::round(x)); + offset_t iy = static_cast(std::round(y)); + + // Boundary condition (/!\ compute sign before warping indices) + int8_t sx = bound::sign(bound0, ix, src_X); + int8_t sy = bound::sign(bound1, iy, src_Y); + ix = bound::index(bound0, ix, src_X); + iy = bound::index(bound1, iy, src_Y); + + // Sign + int8_t s = sy * sx; + + if (do_pull) { + offset_t o = iy * src_sY + ix * src_sX; + scalar_t* out_ptr_NCXY = out_ptr + n * out_sN + w * out_sX + h * out_sY; + scalar_t* src_ptr_NC = src_ptr + n * src_sN; + for (offset_t c = 0; c < C; ++c, out_ptr_NCXY += out_sC, src_ptr_NC += src_sC) + *out_ptr_NCXY = bound::get(src_ptr_NC, o, s); + } else if (do_push && trgt_K == 0) { + offset_t o = iy * out_sY + ix * out_sX; + scalar_t* trgt_ptr_NCXY = trgt_ptr + n * trgt_sN + w * trgt_sX + h * trgt_sY; + scalar_t* out_ptr_NC = out_ptr + n * out_sN; + for (offset_t c = 0; c < C; ++c, trgt_ptr_NCXY += trgt_sC, out_ptr_NC += out_sC) + bound::add(out_ptr_NC, o, *trgt_ptr_NCXY, s); + } else if (do_count) { + offset_t o = iy * out_sY + ix * out_sX; + scalar_t* out_ptr_NC = out_ptr + n * out_sN; + for (offset_t c = 0; c < C; ++c, out_ptr_NC += out_sC) + bound::add(out_ptr_NC, o, static_cast(1), s); + } + } + + // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + // NEAREST NEIGHBOR INTERPOLATION 1D + // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + + template + MONAI_DEVICE void PushPullImpl::interpolate1d_nearest(scalar_t x, offset_t w, offset_t n) const { + offset_t i = static_cast(std::round(x)); + + // Boundary condition (/!\ compute sign before warping indices) + int8_t s = bound::sign(bound0, i, src_X); + i = bound::index(bound0, i, src_X); + + if (do_pull) { + offset_t o = i * src_sX; + scalar_t* out_ptr_NCX = out_ptr + n * out_sN + w * out_sX; + scalar_t* src_ptr_NC = src_ptr + n * src_sN; + for (offset_t c = 0; c < C; ++c, out_ptr_NCX += out_sC, src_ptr_NC += src_sC) + *out_ptr_NCX = bound::get(src_ptr_NC, o, s); + } else if (do_push && trgt_K == 0) { + offset_t o = i * out_sX; + scalar_t* trgt_ptr_NCX = trgt_ptr + n * trgt_sN + w * trgt_sX; + scalar_t* out_ptr_NC = out_ptr + n * out_sN; + for (offset_t c = 0; c < C; ++c, trgt_ptr_NCX += trgt_sC, out_ptr_NC += out_sC) + bound::add(out_ptr_NC, o, *trgt_ptr_NCX, s); + } else if (do_count) { + offset_t o = i * out_sX; + scalar_t* out_ptr_NC = out_ptr + n * out_sN; + for (offset_t c = 0; c < C; ++c, out_ptr_NC += out_sC) + bound::add(out_ptr_NC, o, static_cast(1), s); + } + } + + // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + // LINEAR INTERPOLATION 3D + SLIDING BOUNDARY + // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + // TODO + + // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + // CUDA KERNEL (MUST BE OUT OF CLASS) + // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + + } // namespace + + // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + // FUNCTIONAL FORM WITH DISPATCH + // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +#define PUSHPULL_INSTANTIATE3(BoundType0, InterpolationType0, SourceType0) \ + template std::deque pushpull( \ + const SourceType0&, \ + const Tensor&, \ + const Tensor&, \ + BoundType0, \ + InterpolationType0, \ + bool, \ + bool, \ + bool, \ + bool, \ + bool, \ + bool); \ + template std::deque pushpull( \ + const SourceType0&, const Tensor&, BoundType0, InterpolationType0, bool, bool, bool, bool, bool, bool) +#define PUSHPULL_INSTANTIATE2(BoundType0, InterpolationType0) \ + PUSHPULL_INSTANTIATE3(BoundType0, InterpolationType0, IntArrayRef); \ + PUSHPULL_INSTANTIATE3(BoundType0, InterpolationType0, Tensor) +#define PUSHPULL_INSTANTIATE1(BoundType0) \ + PUSHPULL_INSTANTIATE2(BoundType0, InterpolationType); \ + PUSHPULL_INSTANTIATE2(BoundType0, InterpolationVectorRef) +#define PUSHPULL_INSTANTIATE \ + PUSHPULL_INSTANTIATE1(BoundType); \ + PUSHPULL_INSTANTIATE1(BoundVectorRef) + + // Two arguments (source, grid) + // > `bound` and `interpolation` can be single arguments or vectors. + template + MONAI_HOST std::deque pushpull( + const SourceType& source, + const Tensor& grid, + BoundType bound, + InterpolationType interpolation, + bool extrapolate, + bool do_pull, + bool do_push, + bool do_count, + bool do_grad, + bool do_sgrad) { + PushPullAllocator info( + grid.dim() - 2, bound, interpolation, extrapolate, do_pull, do_push, do_count, do_grad, do_sgrad); + info.ioset(source, grid); + + return AT_DISPATCH_FLOATING_TYPES(grid.scalar_type(), "pushpull", [&] { + PushPullImpl algo(info); + algo.loop(); + return algo.output; + }); + } + + // Three arguments (source, grid, target) + // > `bound` and `interpolation` can be single arguments or vectors. + // > `source` can be a tensor or a vector of dimensions. + template + MONAI_HOST std::deque pushpull( + const SourceType& source, + const Tensor& grid, + const Tensor& target, + BoundType bound, + InterpolationType interpolation, + bool extrapolate, + bool do_pull, + bool do_push, + bool do_count, + bool do_grad, + bool do_sgrad) { + PushPullAllocator info( + grid.dim() - 2, bound, interpolation, extrapolate, do_pull, do_push, do_count, do_grad, do_sgrad); + info.ioset(source, grid, target); + + return AT_DISPATCH_FLOATING_TYPES(grid.scalar_type(), "pushpull", [&] { + PushPullImpl algo(info); + algo.loop(); + return algo.output; + }); + } + + PUSHPULL_INSTANTIATE; + +} // namespace cpu +} // namespace monai diff --git a/source_code/SegMamba/monai/csrc/resample/pushpull_cuda.cu b/source_code/SegMamba/monai/csrc/resample/pushpull_cuda.cu new file mode 100644 index 0000000000000000000000000000000000000000..461962cb80c1dbb919229408a6c8c74ed610bfc3 --- /dev/null +++ b/source_code/SegMamba/monai/csrc/resample/pushpull_cuda.cu @@ -0,0 +1,2244 @@ +/* +Copyright (c) MONAI Consortium +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + http://www.apache.org/licenses/LICENSE-2.0 +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// adapted from https://github.com/balbasty/nitorch + +// This file implements spline interpolation / sampling and its adjoint +// operations. It corresponds loosely to torch's `GridSampler`. +// It handles boundary conditions and interpolation orders defined in +// `utils/resample_utils.h` and `utils/resample_utils.h`. +// These parameters can be specified per dimension. +// Isotropic 0-th and 1-st order interpolation have their own (faster) +// implementations. Sliding boundary conditions are also implemented +// separately. + +// TODO: +// . [DONE] generic 3d +// . [DONE] generic 2d +// . [DONE] generic 1d +// . sliding nearest 3d +// . sliding nearest 2d +// . sliding linear 3d +// . sliding linear 2d +// . sliding generic 3d +// . sliding generic 2d +// . [DONE] spatial gradient mode (without multiplication with output gradient) +// . [DONE] second order gradients (backward pass for spatial gradients) +// . performance tests +// . input bound/inter are always vectors -> clean unused constructors + +#include +#include +#include +#include "bounds_common.h" +#include "interpolation_common.h" +#include "utils/resample_utils.h" +//#include + +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// GPU-specific parameters +#include +#include +#include +using namespace at::cuda::detail; +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +// maximum number of channels +// > not used in mode isotropic nearest/linear +#ifndef MONAI_MAX_NUM_CHANNELS +#define MONAI_MAX_NUM_CHANNELS 1024 +#endif + +// This parameter allows for a little bit of tolerance when considering +// a coordinate as "out-of-bound" (if !extrapolate) +#define TINY 5e-2 + +using at::Tensor; +using at::TensorOptions; +using c10::IntArrayRef; + +namespace monai { +MONAI_NAMESPACE_DEVICE { // cuda + + namespace { // anonymous namespace > everything inside has internal linkage + + // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + // INDEXING UTILS + // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + + // This class reads and sets all the parameters that will later be used + // by the algorithm in PushPullImpl. All of this is done outside of the + // implementation class so that we do not depend on generic types. The + // point is to pre-allocate all necessary tensors so that we can check + // if they're all compatible with 32 bit math. If it's the case, we can + // dispatch to a 32b cuda implementation, which might increase + // performance. Else, we use 64 bit math to compute offsets. + // (On CPU, we always use 64 bit offsets because it doesn't make a huge + // difference. It would be different if we had a vectorized + // implementation as in PyTorch). + class PushPullAllocator { + public: + static constexpr int64_t max_int32 = std::numeric_limits::max(); + + // ~~~ CONSTRUCTORS ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + + MONAI_HOST + PushPullAllocator( + int dim, + BoundVectorRef bound, + InterpolationVectorRef interpolation, + bool extrapolate, + bool do_pull, + bool do_push, + bool do_count, + bool do_grad, + bool do_sgrad) + : dim(dim), + bound0(bound.size() > 0 ? bound[0] : BoundType::Replicate), + bound1( + bound.size() > 1 ? bound[1] + : bound.size() > 0 ? bound[0] + : BoundType::Replicate), + bound2( + bound.size() > 2 ? bound[2] + : bound.size() > 1 ? bound[1] + : bound.size() > 0 ? bound[0] + : BoundType::Replicate), + interpolation0(interpolation.size() > 0 ? interpolation[0] : InterpolationType::Linear), + interpolation1( + interpolation.size() > 1 ? interpolation[1] + : interpolation.size() > 0 ? interpolation[0] + : InterpolationType::Linear), + interpolation2( + interpolation.size() > 2 ? interpolation[2] + : interpolation.size() > 1 ? interpolation[1] + : interpolation.size() > 0 ? interpolation[0] + : InterpolationType::Linear), + extrapolate(extrapolate), + do_pull(do_pull), + do_push(do_push), + do_count(do_count), + do_grad(do_grad), + do_sgrad(do_sgrad) { + iso = interpolation0 == interpolation1 && interpolation0 == interpolation2; + } + + // ~~~ FUNCTORS ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + + // Usually used for pull: + // - do_pull -> return source[grid] + // - do_push -> fails + // - do_grad -> return J(source)[grid] + // - do_sgrad -> return H(source)[grid] + MONAI_HOST void ioset(const Tensor& source, const Tensor& grid) { + init_all(); + init_source(source); + init_grid(grid); + init_output(); + } + + // Usually used for pull_backward: + // - do_pull -> return source[grid] + // - do_push -> return push(target, grid, source.shape) + // - do_grad -> return J(source)[grid] + // - do_sgrad -> return H(source)[grid] + MONAI_HOST void ioset(const Tensor& source, const Tensor& grid, const Tensor& target) { + init_all(); + init_source(source); + init_grid(grid); + init_target(target); + init_output(); + } + + // Usually used for push: + // - do_pull -> fails + // - do_push -> return push(target, grid, source_size) + // - do_grad -> fails + // - do_sgrad -> fails + MONAI_HOST void ioset(IntArrayRef source_size, const Tensor& grid, const Tensor& target) { + init_all(); + init_source(source_size); + init_grid(grid); + init_target(target); + init_output(); + } + + // Usually used for count: + // - do_pull -> fails + // - do_push -> return push(ones, grid, source_size) + // - do_grad -> fails + // - do_sgrad -> fails + MONAI_HOST void ioset(IntArrayRef source_size, const Tensor& grid) { + init_all(); + init_source(source_size); + init_grid(grid); + init_output(); + } + + // We just check that all tensors that we own are compatible with 32b math + bool canUse32BitIndexMath(int64_t max_elem = max_int32) const { + return src_32b_ok && trgt_32b_ok && grid_32b_ok && grad_32b_ok && out_32b_ok; + } + + private: + // Copied from aten/src/ATen/native/IndexingUtils.cpp in PyTorch 1.6. + // It is used to decide to which pointer type we should dispatch to. + // Basically, we need to make sure that the "furthest" element we need + // to reach is less than max_elem away. + static bool tensorCanUse32BitIndexMath(const Tensor& t, int64_t max_elem = max_int32) { + int64_t elements = t.numel(); + if (elements >= max_elem) { + return false; + } + if (elements == 0) { + return max_elem > 0; + } + + int64_t offset = 0; + int64_t linearId = elements - 1; + + // NOTE: Assumes all strides are positive, which is true for now + for (int i = t.dim() - 1; i >= 0; --i) { + int64_t curDimIndex = linearId % t.size(i); + int64_t curDimOffset = curDimIndex * t.stride(i); + offset += curDimOffset; + linearId /= t.size(i); + } + + if (offset >= max_elem) { + return false; + } + + return true; + } + + // ~~~ COMPONENTS ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + MONAI_HOST void init_all(); + MONAI_HOST void init_source(const Tensor& source); + MONAI_HOST void init_source(IntArrayRef source_size); + MONAI_HOST void init_grid(const Tensor& grid); + MONAI_HOST void init_target(const Tensor& target); + MONAI_HOST void init_output(); + + // ~~~ OPTIONS ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + int dim; // dimensionality (2 or 3) + BoundType bound0; // boundary condition // x|W + BoundType bound1; // boundary condition // y|H + BoundType bound2; // boundary condition // z|D + InterpolationType interpolation0; // interpolation order // x|W + InterpolationType interpolation1; // interpolation order // y|H + InterpolationType interpolation2; // interpolation order // z|D + bool iso; // isotropic interpolation? + bool extrapolate; // compute out-of-bound values + bool do_pull; // sample a volume + bool do_push; // splat a volume + bool do_count; // splatting weights (= jacobian determinant) + bool do_grad; // backprop: gradient of grid // pull + bool do_sgrad; // sample spatial gradients + + // ~~~ NAVIGATORS ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + std::deque output; + TensorOptions src_opt; + TensorOptions grid_opt; + TensorOptions trgt_opt; + int64_t N; + int64_t C; + int64_t src_X; + int64_t src_Y; + int64_t src_Z; + int64_t trgt_X; + int64_t trgt_Y; + int64_t trgt_Z; + int64_t trgt_K; + int64_t src_sN; + int64_t src_sC; + int64_t src_sX; + int64_t src_sY; + int64_t src_sZ; + bool src_32b_ok; + void* src_ptr; + int64_t trgt_sN; + int64_t trgt_sC; + int64_t trgt_sX; + int64_t trgt_sY; + int64_t trgt_sZ; + int64_t trgt_sK; + bool trgt_32b_ok; + void* trgt_ptr; + int64_t grid_sN; + int64_t grid_sC; + int64_t grid_sX; + int64_t grid_sY; + int64_t grid_sZ; + bool grid_32b_ok; + void* grid_ptr; + int64_t out_sN; + int64_t out_sC; + int64_t out_sX; + int64_t out_sY; + int64_t out_sZ; + int64_t out_sK; // gradient dimension + bool out_32b_ok; + void* out_ptr; + int64_t grad_sN; + int64_t grad_sC; + int64_t grad_sX; + int64_t grad_sY; + int64_t grad_sZ; + bool grad_32b_ok; + void* grad_ptr; + + // Allow PushPullImpl's constructor to access PushPullAllocator's + // private members. + template + friend class PushPullImpl; + }; + + // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + // INITIALISATION + // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + + MONAI_HOST + void PushPullAllocator::init_all() { + src_opt = grid_opt = trgt_opt = TensorOptions(); + N = C = 1L; + src_X = src_Y = src_Z = 1L; + trgt_X = trgt_Y = trgt_Z = 1L; + trgt_K = 0L; + src_sN = src_sC = src_sX = src_sY = src_sZ = 0L; + grid_sN = grid_sC = grid_sX = grid_sY = grid_sZ = 0L; + grad_sN = grad_sC = grad_sX = grad_sY = grad_sZ = 0L; + trgt_sN = trgt_sC = trgt_sX = trgt_sY = trgt_sZ = trgt_sK = 0L; + out_sN = out_sC = out_sX = out_sY = out_sZ = out_sK = 0L; + src_ptr = trgt_ptr = grid_ptr = out_ptr = grad_ptr = static_cast(0); + src_32b_ok = trgt_32b_ok = grid_32b_ok = out_32b_ok = grad_32b_ok = true; + } + + MONAI_HOST + void PushPullAllocator::init_source(const Tensor& source) { + N = source.size(0); + C = source.size(1); + src_X = source.size(2); + src_Y = dim < 2 ? 1L : source.size(3); + src_Z = dim < 3 ? 1L : source.size(4); + src_sN = source.stride(0); + src_sC = source.stride(1); + src_sX = source.stride(2); + src_sY = dim < 2 ? 0L : source.stride(3); + src_sZ = dim < 3 ? 0L : source.stride(4); + src_ptr = source.data_ptr(); + src_opt = source.options(); + src_32b_ok = tensorCanUse32BitIndexMath(source); + } + + MONAI_HOST + void PushPullAllocator::init_source(IntArrayRef source_size) { + src_X = source_size[0]; + src_Y = dim < 2 ? 1L : source_size[1]; + src_Z = dim < 3 ? 1L : source_size[2]; + } + + MONAI_HOST + void PushPullAllocator::init_grid(const Tensor& grid) { + N = grid.size(0); + trgt_X = grid.size(1); + trgt_Y = dim < 2 ? 1L : grid.size(2); + trgt_Z = dim < 3 ? 1L : grid.size(3); + grid_sN = grid.stride(0); + grid_sX = grid.stride(1); + grid_sY = dim < 2 ? 0L : grid.stride(2); + grid_sZ = dim < 3 ? 0L : grid.stride(3); + grid_sC = grid.stride(dim == 1 ? 2 : dim == 2 ? 3 : 4); + grid_ptr = grid.data_ptr(); + grid_opt = grid.options(); + grid_32b_ok = tensorCanUse32BitIndexMath(grid); + } + + MONAI_HOST + void PushPullAllocator::init_target(const Tensor& target) { + N = target.size(0); + C = target.size(1); + trgt_X = target.size(2); + trgt_Y = dim < 2 ? 1L : target.size(3); + trgt_Z = dim < 3 ? 1L : target.size(4); + trgt_K = target.dim() == dim + 3 ? target.size(dim == 1 ? 3 : dim == 2 ? 4 : 5) : 0L; + trgt_sN = target.stride(0); + trgt_sC = target.stride(1); + trgt_sX = target.stride(2); + trgt_sY = dim < 2 ? 0L : target.stride(3); + trgt_sZ = dim < 3 ? 0L : target.stride(4); + trgt_sK = target.dim() == dim + 3 ? target.stride(dim == 1 ? 3 : dim == 2 ? 4 : 5) : 0L; + trgt_ptr = target.data_ptr(); + trgt_opt = target.options(); + trgt_32b_ok = tensorCanUse32BitIndexMath(target); + } + + MONAI_HOST + void PushPullAllocator::init_output() { + output.clear(); + if (do_pull) { + if (dim == 1) + output.push_back(at::empty({N, C, trgt_X}, src_opt)); + else if (dim == 2) + output.push_back(at::empty({N, C, trgt_X, trgt_Y}, src_opt)); + else + output.push_back(at::empty({N, C, trgt_X, trgt_Y, trgt_Z}, src_opt)); + auto pull = output.back(); + out_sN = pull.stride(0); + out_sC = pull.stride(1); + out_sX = pull.stride(2); + out_sY = dim < 2 ? 0L : pull.stride(3); + out_sZ = dim < 3 ? 0L : pull.stride(4); + out_sK = 0L; + out_ptr = pull.data_ptr(); + out_32b_ok = tensorCanUse32BitIndexMath(pull); + } else if (do_sgrad) { + if (dim == 1) + output.push_back(at::empty({N, C, trgt_X, 1}, src_opt)); + else if (dim == 2) + output.push_back(at::empty({N, C, trgt_X, trgt_Y, 2}, src_opt)); + else + output.push_back(at::empty({N, C, trgt_X, trgt_Y, trgt_Z, 3}, src_opt)); + auto sgrad = output.back(); + out_sN = sgrad.stride(0); + out_sC = sgrad.stride(1); + out_sX = sgrad.stride(2); + out_sY = dim < 2 ? 0L : sgrad.stride(3); + out_sZ = dim < 3 ? 0L : sgrad.stride(4); + out_sK = sgrad.stride(dim == 1 ? 3 : dim == 2 ? 4 : 5); + out_ptr = sgrad.data_ptr(); + out_32b_ok = tensorCanUse32BitIndexMath(sgrad); + + if (iso && interpolation0 == InterpolationType::Nearest) + sgrad.zero_(); + if (iso && interpolation0 == InterpolationType::Linear && dim == 1) + sgrad.zero_(); + } else if (do_push) { + if (dim == 1) + output.push_back(at::zeros({N, C, src_X}, trgt_opt)); + else if (dim == 2) + output.push_back(at::zeros({N, C, src_X, src_Y}, trgt_opt)); + else + output.push_back(at::zeros({N, C, src_X, src_Y, src_Z}, trgt_opt)); + auto push = output.back(); + out_sN = push.stride(0); + out_sC = push.stride(1); + out_sX = push.stride(2); + out_sY = dim < 2 ? 0L : push.stride(3); + out_sZ = dim < 3 ? 0L : push.stride(4); + out_sK = 0L; + out_ptr = push.data_ptr(); + out_32b_ok = tensorCanUse32BitIndexMath(push); + } else if (do_count) { + if (dim == 1) + output.push_back(at::zeros({N, 1, src_X}, grid_opt)); + else if (dim == 2) + output.push_back(at::zeros({N, 1, src_X, src_Y}, grid_opt)); + else + output.push_back(at::zeros({N, 1, src_X, src_Y, src_Z}, grid_opt)); + auto count = output.back(); + out_sN = count.stride(0); + out_sC = count.stride(1); + out_sX = count.stride(2); + out_sY = dim < 2 ? 0L : count.stride(3); + out_sZ = dim < 3 ? 0L : count.stride(4); + out_sK = 0L; + out_ptr = count.data_ptr(); + out_32b_ok = tensorCanUse32BitIndexMath(count); + } + if (do_grad) { + if (dim == 1) + output.push_back(at::zeros({N, trgt_X, 1}, grid_opt)); + else if (dim == 2) + output.push_back(at::zeros({N, trgt_X, trgt_Y, 2}, grid_opt)); + else + output.push_back(at::zeros({N, trgt_X, trgt_Y, trgt_Z, 3}, grid_opt)); + auto grad = output.back(); + grad_sN = grad.stride(0); + grad_sX = grad.stride(1); + grad_sY = dim < 2 ? 0L : grad.stride(2); + grad_sZ = dim < 3 ? 0L : grad.stride(3); + grad_sC = grad.stride(dim == 1 ? 2 : dim == 2 ? 3 : 4); + grad_ptr = grad.data_ptr(); + out_32b_ok = tensorCanUse32BitIndexMath(grad); + + if (iso && interpolation0 == InterpolationType::Nearest) + grad.zero_(); + } + } + + // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + // GENERIC PUSHPULL CLASS + // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + // This class implements the bulk of the code. + // /!\ No type and shape checking is performed here. + + template + class PushPullImpl { + public: + // ~~~ CONSTRUCTOR ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + PushPullImpl(const PushPullAllocator& info) + : output(info.output), + dim(info.dim), + bound0(info.bound0), + bound1(info.bound1), + bound2(info.bound2), + interpolation0(info.interpolation0), + interpolation1(info.interpolation1), + interpolation2(info.interpolation1), + iso(info.iso), + extrapolate(info.extrapolate), + do_pull(info.do_pull), + do_push(info.do_push), + do_count(info.do_count), + do_grad(info.do_grad), + do_sgrad(info.do_sgrad), + N(static_cast(info.N)), + C(static_cast(info.C)), + src_X(static_cast(info.src_X)), + src_Y(static_cast(info.src_Y)), + src_Z(static_cast(info.src_Z)), + trgt_X(static_cast(info.trgt_X)), + trgt_Y(static_cast(info.trgt_Y)), + trgt_Z(static_cast(info.trgt_Z)), + trgt_K(static_cast(info.trgt_K)), + src_sN(static_cast(info.src_sN)), + src_sC(static_cast(info.src_sC)), + src_sX(static_cast(info.src_sX)), + src_sY(static_cast(info.src_sY)), + src_sZ(static_cast(info.src_sZ)), + src_ptr(static_cast(info.src_ptr)), + trgt_sN(static_cast(info.trgt_sN)), + trgt_sC(static_cast(info.trgt_sC)), + trgt_sX(static_cast(info.trgt_sX)), + trgt_sY(static_cast(info.trgt_sY)), + trgt_sZ(static_cast(info.trgt_sZ)), + trgt_sK(static_cast(info.trgt_sK)), + trgt_ptr(static_cast(info.trgt_ptr)), + grid_sN(static_cast(info.grid_sN)), + grid_sC(static_cast(info.grid_sC)), + grid_sX(static_cast(info.grid_sX)), + grid_sY(static_cast(info.grid_sY)), + grid_sZ(static_cast(info.grid_sZ)), + grid_ptr(static_cast(info.grid_ptr)), + out_sN(static_cast(info.out_sN)), + out_sC(static_cast(info.out_sC)), + out_sX(static_cast(info.out_sX)), + out_sY(static_cast(info.out_sY)), + out_sZ(static_cast(info.out_sZ)), + out_sK(static_cast(info.out_sK)), + out_ptr(static_cast(info.out_ptr)), + grad_sN(static_cast(info.grad_sN)), + grad_sC(static_cast(info.grad_sC)), + grad_sX(static_cast(info.grad_sX)), + grad_sY(static_cast(info.grad_sY)), + grad_sZ(static_cast(info.grad_sZ)), + grad_ptr(static_cast(info.grad_ptr)) {} + + // ~~~ PUBLIC VALUE ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + + std::deque output; + + // MONAI_HOST MONAI_DEVICE void printInfo() const { + // printf("dim: %d\n", dim); + // printf("do_pull: %d\n", do_pull); + // printf("do_push: %d\n", do_push); + // printf("do_count: %d\n", do_count); + // printf("do_sgrad: %d\n", do_sgrad); + // printf("do_grad: %d\n", do_grad); + // printf("bound: [%d %d %d]\n", static_cast(bound0), + // static_cast(bound1), static_cast(bound2)); + // printf("interpolation: [%d %d %d]\n", static_cast(interpolation0), + // static_cast(interpolation1), static_cast(interpolation2)); + // printf("src: [%d %d %d]\n", src_Z, src_Y, src_X); + // printf("trgt: [%d %d %d (%d)]\n", trgt_Z, trgt_Y, trgt_X, trgt_K); + // printf("N: %d\n", N); + // printf("C: %d\n", C); + // printf("src -> %lu\n", reinterpret_cast(src_ptr)); + // printf("trgt -> %lu\n", reinterpret_cast(trgt_ptr)); + // printf("grid -> %lu\n", reinterpret_cast(grid_ptr)); + // printf("out -> %lu\n", reinterpret_cast(out_ptr)); + // printf("grad -> %lu\n", reinterpret_cast(grad_ptr)); + // } + + // ~~~ FUNCTORS ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + + // Loop over voxels that belong to one CUDA block + // This function is called by the CUDA kernel + MONAI_DEVICE void loop(int threadIdx, int blockIdx, int blockDim, int gridDim) const; + + MONAI_HOST MONAI_DEVICE int64_t voxcount() const { + return N * trgt_X * trgt_Y * trgt_Z; + } + + private: + // ~~~ COMPONENTS ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + MONAI_DEVICE void check1d(offset_t w, offset_t n) const; + MONAI_DEVICE void check2d(offset_t w, offset_t h, offset_t n) const; + MONAI_DEVICE void check3d(offset_t w, offset_t h, offset_t d, offset_t n) const; + MONAI_DEVICE void interpolate1d(scalar_t x, offset_t w, offset_t n) const; + MONAI_DEVICE void interpolate1d_nearest(scalar_t x, offset_t w, offset_t n) const; + MONAI_DEVICE void interpolate1d_linear(scalar_t x, offset_t w, offset_t n) const; + MONAI_DEVICE void interpolate1d_sliding(scalar_t x, offset_t w, offset_t n) const { /*TODO*/ + } + MONAI_DEVICE void interpolate1d_sliding_nearest(scalar_t x, offset_t w, offset_t n) const { /*TODO*/ + } + MONAI_DEVICE void interpolate1d_sliding_linear(scalar_t x, offset_t w, offset_t n) const { /*TODO*/ + } + MONAI_DEVICE void interpolate2d(scalar_t x, scalar_t y, offset_t w, offset_t h, offset_t n) const; + MONAI_DEVICE void interpolate2d_nearest(scalar_t x, scalar_t y, offset_t w, offset_t h, offset_t n) const; + MONAI_DEVICE void interpolate2d_bilinear(scalar_t x, scalar_t y, offset_t w, offset_t h, offset_t n) const; + MONAI_DEVICE void interpolate2d_sliding(scalar_t x, scalar_t y, offset_t w, offset_t h, offset_t n) const { /*TODO*/ + } + MONAI_DEVICE void interpolate2d_sliding_nearest(scalar_t x, scalar_t y, offset_t w, offset_t h, offset_t n) + const { /*TODO*/ + } + MONAI_DEVICE void interpolate2d_sliding_bilinear(scalar_t x, scalar_t y, offset_t w, offset_t h, offset_t n) + const { /*TODO*/ + } + MONAI_DEVICE void interpolate3d(scalar_t x, scalar_t y, scalar_t z, offset_t w, offset_t h, offset_t d, offset_t n) + const; + MONAI_DEVICE void interpolate3d_nearest( + scalar_t x, + scalar_t y, + scalar_t z, + offset_t w, + offset_t h, + offset_t d, + offset_t n) const; + MONAI_DEVICE void interpolate3d_trilinear( + scalar_t x, + scalar_t y, + scalar_t z, + offset_t w, + offset_t h, + offset_t d, + offset_t n) const; + MONAI_DEVICE void interpolate3d_sliding( + scalar_t x, + scalar_t y, + scalar_t z, + offset_t w, + offset_t h, + offset_t d, + offset_t n) const { /*TODO*/ + } + MONAI_DEVICE void interpolate3d_sliding_nearest( + scalar_t x, + scalar_t y, + scalar_t z, + offset_t w, + offset_t h, + offset_t d, + offset_t n) const { /*TODO*/ + } + MONAI_DEVICE void interpolate3d_sliding_trilinear( + scalar_t x, + scalar_t y, + scalar_t z, + offset_t w, + offset_t h, + offset_t d, + offset_t n) const { /*TODO*/ + } + + // ~~~ OPTIONS ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + int dim; // dimensionality (2 or 3) + BoundType bound0; // boundary condition // x|W + BoundType bound1; // boundary condition // y|H + BoundType bound2; // boundary condition // z|D + InterpolationType interpolation0; // interpolation order // x|W + InterpolationType interpolation1; // interpolation order // y|H + InterpolationType interpolation2; // interpolation order // z|D + bool iso; // isotropic interpolation? + bool extrapolate; // compute out-of-bound values + bool do_pull; // sample a volume + bool do_push; // splat a volume + bool do_count; // splatting weights (= jacobian determinant) + bool do_grad; // backprop: gradient of grid // pull + bool do_sgrad; // sample spatial gradients + + // ~~~ NAVIGATORS ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + offset_t N; + offset_t C; + offset_t src_X; + offset_t src_Y; + offset_t src_Z; + offset_t trgt_X; + offset_t trgt_Y; + offset_t trgt_Z; + offset_t trgt_K; + offset_t src_sN; + offset_t src_sC; + offset_t src_sX; + offset_t src_sY; + offset_t src_sZ; + scalar_t* src_ptr; + offset_t trgt_sN; + offset_t trgt_sC; + offset_t trgt_sX; + offset_t trgt_sY; + offset_t trgt_sZ; + offset_t trgt_sK; + scalar_t* trgt_ptr; + offset_t grid_sN; + offset_t grid_sC; + offset_t grid_sX; + offset_t grid_sY; + offset_t grid_sZ; + scalar_t* grid_ptr; + offset_t out_sN; + offset_t out_sC; + offset_t out_sX; + offset_t out_sY; + offset_t out_sZ; + offset_t out_sK; // gradient dimension + scalar_t* out_ptr; + offset_t grad_sN; + offset_t grad_sC; + offset_t grad_sX; + offset_t grad_sY; + offset_t grad_sZ; + scalar_t* grad_ptr; + }; + + // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + // LOOP + // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + + template + MONAI_DEVICE void PushPullImpl::loop(int threadIdx, int blockIdx, int blockDim, int gridDim) + const { + int64_t index = blockIdx * blockDim + threadIdx; + int64_t nthreads = voxcount(); + offset_t trgt_XYZ = trgt_Z * trgt_Y * trgt_X; + offset_t trgt_YZ = trgt_Z * trgt_Y; + offset_t n, w, h, d; + for (offset_t i = index; index < nthreads; index += blockDim * gridDim, i = index) { + // Convert index: linear to sub + n = (i / trgt_XYZ); + w = (i / trgt_YZ) % trgt_X; + h = (i / trgt_Z) % trgt_Y; + d = i % trgt_Z; + + if (dim == 1) + check1d(w, n); + else if (dim == 2) + check2d(w, h, n); + else + check3d(w, h, d, n); + } + } + + // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + // CHECK OUT-OF-BOUND + // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + + // Here, we: + // 1) read the [x,y,z] source coordinate for the current target voxel + // 3) check if the source coordinate is in bounds + + template + MONAI_DEVICE void PushPullImpl::check3d(offset_t w, offset_t h, offset_t d, offset_t n) const { + // get the corresponding input x, y, z co-ordinates from grid + scalar_t* grid_ptr_NXYZ = grid_ptr + n * grid_sN + w * grid_sX + h * grid_sY + d * grid_sZ; + scalar_t x = *grid_ptr_NXYZ; + scalar_t y = grid_ptr_NXYZ[grid_sC]; + scalar_t z = grid_ptr_NXYZ[grid_sC * 2]; + + // Check if out-of-bound + if (!(extrapolate || + (inbounds(x, src_X, static_cast(TINY)) && inbounds(y, src_Y, static_cast(TINY)) && + inbounds(z, src_Z, static_cast(TINY))))) { + if (do_pull || do_sgrad) { + scalar_t* out_ptr_NCXYZ = out_ptr + n * out_sN + w * out_sX + h * out_sY + d * out_sZ; + for (offset_t c = 0; c < C; ++c, out_ptr_NCXYZ += out_sC) { + *out_ptr_NCXYZ = static_cast(0); + if (do_sgrad) { + out_ptr_NCXYZ[out_sK] = static_cast(0); + out_ptr_NCXYZ[out_sK * 2] = static_cast(0); + } + } + } + if (do_grad) { + scalar_t* grad_ptr_NXYZ = grad_ptr + n * grad_sN + w * grad_sX + h * grad_sY + d * grad_sZ; + (*grad_ptr_NXYZ) = static_cast(0); + grad_ptr_NXYZ[grad_sC] = static_cast(0); + grad_ptr_NXYZ[grad_sC * 2] = static_cast(0); + } + return; + } + + // Next step + if (bound0 == BoundType::Sliding) { + if (iso) + switch (static_cast(interpolation0)) { + case 0: + return interpolate3d_sliding_nearest(x, y, z, w, h, d, n); + case 1: + return interpolate3d_sliding_trilinear(x, y, z, w, h, d, n); + } + return interpolate3d_sliding(x, y, z, w, h, d, n); + } else { + if (iso) + switch (static_cast(interpolation0)) { + case 0: + return interpolate3d_nearest(x, y, z, w, h, d, n); + case 1: + return interpolate3d_trilinear(x, y, z, w, h, d, n); + } + return interpolate3d(x, y, z, w, h, d, n); + } + } + + template + MONAI_DEVICE void PushPullImpl::check2d(offset_t w, offset_t h, offset_t n) const { + // get the corresponding input x, y, z co-ordinates from grid + scalar_t* grid_ptr_NXY = grid_ptr + n * grid_sN + w * grid_sX + h * grid_sY; + scalar_t x = *grid_ptr_NXY; + scalar_t y = grid_ptr_NXY[grid_sC]; + + // Check if out-of-bound + if (!(extrapolate || + (inbounds(x, src_X, static_cast(TINY)) && inbounds(y, src_Y, static_cast(TINY))))) { + if (do_pull || do_sgrad) { + scalar_t* out_ptr_NCXY = out_ptr + n * out_sN + w * out_sX + h * out_sY; + for (offset_t c = 0; c < C; ++c, out_ptr_NCXY += out_sC) { + *out_ptr_NCXY = static_cast(0); + if (do_sgrad) + out_ptr_NCXY[out_sK] = static_cast(0); + } + } + if (do_grad) { + scalar_t* grad_ptr_NXY = grad_ptr + n * grad_sN + w * grad_sX + h * grad_sY; + (*grad_ptr_NXY) = static_cast(0); + grad_ptr_NXY[grad_sC] = static_cast(0); + } + return; + } + + // Next step + if (bound0 == BoundType::Sliding) { + if (iso) + switch (static_cast(interpolation0)) { + case 0: + return interpolate2d_sliding_nearest(x, y, w, h, n); + case 1: + return interpolate2d_sliding_bilinear(x, y, w, h, n); + } + return interpolate2d_sliding(x, y, w, h, n); + } else { + if (iso) + switch (static_cast(interpolation0)) { + case 0: + return interpolate2d_nearest(x, y, w, h, n); + case 1: + return interpolate2d_bilinear(x, y, w, h, n); + } + return interpolate2d(x, y, w, h, n); + } + } + + template + MONAI_DEVICE void PushPullImpl::check1d(offset_t w, offset_t n) const { + // get the corresponding input x, y, z co-ordinates from grid + scalar_t* grid_ptr_NX = grid_ptr + n * grid_sN + w * grid_sX; + scalar_t x = *grid_ptr_NX; + + // Check if out-of-bound + if (!(extrapolate || inbounds(x, src_X, static_cast(TINY)))) { + if (do_pull || do_sgrad) { + scalar_t* out_ptr_NCX = out_ptr + n * out_sN + w * out_sX; + for (offset_t c = 0; c < C; ++c, out_ptr_NCX += out_sC) { + *out_ptr_NCX = static_cast(0); + if (do_sgrad) + out_ptr_NCX[out_sK] = static_cast(0); + } + } + if (do_grad) { + scalar_t* grad_ptr_NX = grad_ptr + n * grad_sN + w * grad_sX; + (*grad_ptr_NX) = static_cast(0); + grad_ptr_NX[grad_sC] = static_cast(0); + } + return; + } + + // Next step + if (bound0 == BoundType::Sliding) { + if (iso) + switch (static_cast(interpolation0)) { + case 0: + return interpolate1d_sliding_nearest(x, w, n); + case 1: + return interpolate1d_sliding_linear(x, w, n); + } + return interpolate1d_sliding(x, w, n); + } else { + if (iso) + switch (static_cast(interpolation0)) { + case 0: + return interpolate1d_nearest(x, w, n); + case 1: + return interpolate1d_linear(x, w, n); + } + return interpolate1d(x, w, n); + } + } + + // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + // GENERIC INTERPOLATION 3D + // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + + template + MONAI_DEVICE void PushPullImpl::interpolate3d( + scalar_t x, + scalar_t y, + scalar_t z, + offset_t w, + offset_t h, + offset_t d, + offset_t n) const { + // Get corner pixel values from (x, y, z) + offset_t bx0, bx1, by0, by1, bz0, bz1; + interpolation::bounds(interpolation0, x, bx0, bx1); + interpolation::bounds(interpolation1, y, by0, by1); + interpolation::bounds(interpolation2, z, bz0, bz1); + offset_t dbx = bx1 - bx0; + offset_t dby = by1 - by0; + offset_t dbz = bz1 - bz0; + + // Pre-compute offsets and target value + scalar_t* src_ptr_NC0 = src_ptr + n * src_sN; + scalar_t* out_ptr_NC0 = out_ptr + n * out_sN; + scalar_t* out_ptr_NCXYZ0 = out_ptr + n * out_sN + w * out_sX + h * out_sY + d * out_sZ; + scalar_t* trgt_ptr_NCXYZ = trgt_ptr + n * trgt_sN + w * trgt_sX + h * trgt_sY + d * trgt_sZ; + scalar_t target[3 * MONAI_MAX_NUM_CHANNELS]; + if (trgt_ptr && (do_push || do_grad)) + for (offset_t c = 0; c < C; ++c, trgt_ptr_NCXYZ += trgt_sC) { + target[c] = *trgt_ptr_NCXYZ; + if (trgt_K > 0) { + target[c + C] = trgt_ptr_NCXYZ[trgt_sK]; + target[c + C * 2] = trgt_ptr_NCXYZ[trgt_sK * 2]; + } + } + + // Initialize output + scalar_t* out_ptr_NCXYZ = out_ptr_NCXYZ0; + if (do_pull || do_sgrad) { + for (offset_t c = 0; c < C; ++c, out_ptr_NCXYZ += out_sC) { + *out_ptr_NCXYZ = static_cast(0); + if (do_sgrad) { + out_ptr_NCXYZ[out_sK] = static_cast(0); + out_ptr_NCXYZ[out_sK * 2] = static_cast(0); + } + } + } + + // Pre-compute indices/weights/grad + scalar_t wx[8], wy[8], wz[8]; // B-spline weights + scalar_t gx[8], gy[8], gz[8]; // B-spline derivatives + scalar_t hx[8], hy[8], hz[8]; // B-spline 2nd derivatives + offset_t ix[8], iy[8], iz[8]; // Warped indices + uint8_t sx[8], sy[8], sz[8]; // Warped indices + + { + scalar_t *owz = static_cast(wz), *ogz = static_cast(gz), *ohz = static_cast(hz); + offset_t* oiz = static_cast(iz); + uint8_t* osz = static_cast(sz); + for (offset_t bz = bz0; bz <= bz1; ++bz) { + scalar_t dz = z - bz; + *(owz++) = interpolation::fastweight(interpolation2, dz); + if (do_grad || do_sgrad) + *(ogz++) = interpolation::fastgrad(interpolation2, dz); + if (do_grad && trgt_sK > 1) + *(ohz++) = interpolation::fasthess(interpolation2, dz); + *(osz++) = bound::sign(bound2, bz, src_Z); + *(oiz++) = bound::index(bound2, bz, src_Z); + } + } + { + scalar_t *owy = static_cast(wy), *ogy = static_cast(gy), *ohy = static_cast(hy); + offset_t* oiy = static_cast(iy); + uint8_t* osy = static_cast(sy); + for (offset_t by = by0; by <= by1; ++by) { + scalar_t dy = y - by; + *(owy++) = interpolation::fastweight(interpolation1, dy); + if (do_grad || do_sgrad) + *(ogy++) = interpolation::fastgrad(interpolation1, dy); + if (do_grad && trgt_sK > 1) + *(ohy++) = interpolation::fasthess(interpolation1, dy); + *(osy++) = bound::sign(bound1, by, src_Y); + *(oiy++) = bound::index(bound1, by, src_Y); + } + } + { + scalar_t *owx = static_cast(wx), *ogx = static_cast(gx), *ohx = static_cast(hx); + offset_t* oix = static_cast(ix); + uint8_t* osx = static_cast(sx); + for (offset_t bx = bx0; bx <= bx1; ++bx) { + scalar_t dx = x - bx; + *(owx++) = interpolation::fastweight(interpolation0, dx); + if (do_grad || do_sgrad) + *(ogx++) = interpolation::fastgrad(interpolation0, dx); + if (do_grad && trgt_sK > 1) + *(ohx++) = interpolation::fasthess(interpolation0, dx); + *(osx++) = bound::sign(bound0, bx, src_X); + *(oix++) = bound::index(bound0, bx, src_X); + } + } + + // Convolve coefficients with basis functions + scalar_t ogx, ogy, ogz; + ogx = ogy = ogz = static_cast(0); + for (offset_t k = 0; k <= dbz; ++k) { + offset_t ooz = iz[k] * out_sZ; + offset_t osz = iz[k] * src_sZ; + uint8_t szz = sz[k]; + scalar_t wzz = wz[k]; + scalar_t gzz = gz[k]; + scalar_t hzz = hz[k]; + for (offset_t j = 0; j <= dby; ++j) { + offset_t ooyz = ooz + iy[j] * out_sY; + offset_t osyz = osz + iy[j] * src_sY; + uint8_t syz = szz * sy[j]; + scalar_t wyy = wy[j]; + scalar_t gyy = gy[j]; + scalar_t hyy = hy[j]; + for (offset_t i = 0; i <= dbx; ++i) { + offset_t ooxyz = ooyz + ix[i] * out_sX; + offset_t osxyz = osyz + ix[i] * src_sX; + uint8_t sxyz = syz * sx[i]; + scalar_t wxx = wx[i]; + scalar_t gxx = gx[i]; + scalar_t hxx = hx[i]; + + // ~~~~~~~~~~~~~~~~~~~~~~~~~~~ Pull ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + if (do_pull) { + scalar_t* src_ptr_NC = src_ptr_NC0; + scalar_t* out_ptr_NCXYZ = out_ptr_NCXYZ0; + for (offset_t c = 0; c < C; ++c, out_ptr_NCXYZ += out_sC, src_ptr_NC += src_sC) + *out_ptr_NCXYZ += bound::get(src_ptr_NC, osxyz, sxyz) * (wxx * wyy * wzz); + } + + // ~~~~~~~~~~~~~~~~~~~~~~~~~~~ SGrad ~~~~~~~~~~~~~~~~~~~~~~~~~~~ + else if (do_sgrad) { + scalar_t* src_ptr_NC = src_ptr_NC0; + scalar_t* out_ptr_NCXYZ = out_ptr_NCXYZ0; + for (offset_t c = 0; c < C; ++c, out_ptr_NCXYZ += out_sC, src_ptr_NC += src_sC) { + scalar_t src = bound::get(src_ptr_NC, osxyz, sxyz); + *out_ptr_NCXYZ += src * (gxx * wyy * wzz); + out_ptr_NCXYZ[out_sK] += src * (wxx * gyy * wzz); + out_ptr_NCXYZ[2 * out_sK] += src * (wxx * wyy * gzz); + } + } + + // ~~~~~~~~~~~~~~~~~~~~~~~~~~~ Push ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + else if (do_push) { + if (trgt_K == 0) { + // Diff w.r.t. push/pull + scalar_t* out_ptr_NC = out_ptr_NC0; + for (offset_t c = 0; c < C; ++c, out_ptr_NC += out_sC) + bound::add(out_ptr_NC, ooxyz, (wxx * wyy * wzz) * target[c], sxyz); + } else { + // Diff w.r.t. sgrad + scalar_t* out_ptr_NC = out_ptr_NC0; + for (offset_t c = 0; c < C; ++c, out_ptr_NC += out_sC) { + scalar_t val = (gxx * wyy * wzz) * target[c] + (wxx * gyy * wzz) * target[c + C] + + (wxx * wyy * gzz) * target[c + C * 2]; + bound::add(out_ptr_NC, ooxyz, val, sxyz); + } + } + } + + // ~~~~~~~~~~~~~~~~~~~~~~~~~~~ Count ~~~~~~~~~~~~~~~~~~~~~~~~~~~ + else if (do_count) { + bound::add(out_ptr_NC0, ooxyz, (wxx * wyy * wzz), sxyz); + } + + // ~~~~~~~~~~~~~~~~~~~~~~~~~~~ Grad ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + if (do_grad) { + if (trgt_K == 0) { + // Diff w.r.t. pull/push + scalar_t* src_ptr_NC = src_ptr_NC0; + scalar_t dot = static_cast(0); + for (offset_t c = 0; c < C; ++c, src_ptr_NC += src_sC) { + scalar_t src = bound::get(src_ptr_NC, osxyz, sxyz); + dot += (trgt_ptr ? src * target[c] : src); + // trgt_ptr == 0 in the backward pass of 'count' + } + ogx += (gxx * wyy * wzz) * dot; + ogy += (wxx * gyy * wzz) * dot; + ogz += (wxx * wyy * gzz) * dot; + } else { + // Diff w.r.t. sgrad + scalar_t* src_ptr_NC = src_ptr_NC0; + scalar_t dot0, dot1, dot2; + dot0 = dot1 = dot2 = static_cast(0); + for (offset_t c = 0; c < C; ++c, src_ptr_NC += src_sC) { + scalar_t src = bound::get(src_ptr_NC, osxyz, sxyz); + dot0 += src * target[c]; + dot1 += src * target[c + C]; + dot2 += src * target[c + C * 2]; + } + ogx += (hxx * wyy * wzz) * dot0 + (gxx * gyy * wzz) * dot1 + (gxx * wyy * gzz) * dot2; + ogy += (gxx * gyy * wzz) * dot0 + (wxx * hyy * wzz) * dot1 + (wxx * gyy * gzz) * dot2; + ogz += (gxx * wyy * gzz) * dot0 + (wxx * gyy * gzz) * dot1 + (wxx * wyy * hzz) * dot2; + } + } + + } // x + } // y + } // z + + // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Grad ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + if (do_grad) { + scalar_t* grad_ptr_NXYZ = grad_ptr + n * grad_sN + w * grad_sX + h * grad_sY + d * grad_sZ; + (*grad_ptr_NXYZ) = ogx; + grad_ptr_NXYZ[grad_sC] = ogy; + grad_ptr_NXYZ[grad_sC * 2] = ogz; + } + } + + // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + // GENERIC INTERPOLATION 2D + // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + + template + MONAI_DEVICE void PushPullImpl::interpolate2d( + scalar_t x, + scalar_t y, + offset_t w, + offset_t h, + offset_t n) const { + // Get corner pixel values from (x, y) + offset_t bx0, bx1, by0, by1; + interpolation::bounds(interpolation0, x, bx0, bx1); + interpolation::bounds(interpolation1, y, by0, by1); + offset_t dbx = bx1 - bx0; + offset_t dby = by1 - by0; + + // Pre-compute offsets and target value + scalar_t* src_ptr_NC0 = src_ptr + n * src_sN; + scalar_t* out_ptr_NC0 = out_ptr + n * out_sN; + scalar_t* out_ptr_NCXY0 = out_ptr + n * out_sN + w * out_sX + h * out_sY; + scalar_t* trgt_ptr_NCXY = trgt_ptr + n * trgt_sN + w * trgt_sX + h * trgt_sY; + scalar_t target[2 * MONAI_MAX_NUM_CHANNELS]; + if (trgt_ptr && (do_push || do_grad)) + for (offset_t c = 0; c < C; ++c, trgt_ptr_NCXY += trgt_sC) { + target[c] = *trgt_ptr_NCXY; + if (trgt_K > 0) { + target[c + C] = trgt_ptr_NCXY[trgt_sK]; + } + } + + // Initialize output + scalar_t* out_ptr_NCXY = out_ptr_NCXY0; + if (do_pull || do_sgrad) { + for (offset_t c = 0; c < C; ++c, out_ptr_NCXY += out_sC) { + *out_ptr_NCXY = static_cast(0); + if (do_sgrad) { + out_ptr_NCXY[out_sK] = static_cast(0); + } + } + } + + // Pre-compute indices/weights/grad + scalar_t wx[8], wy[8]; // B-spline weights + scalar_t gx[8], gy[8]; // B-spline derivatives + scalar_t hx[8], hy[8]; // B-spline 2nd derivatives + offset_t ix[8], iy[8]; // Warped indices + uint8_t sx[8], sy[8]; // Warped indices + + { + scalar_t *owy = static_cast(wy), *ogy = static_cast(gy), *ohy = static_cast(hy); + offset_t* oiy = static_cast(iy); + uint8_t* osy = static_cast(sy); + for (offset_t by = by0; by <= by1; ++by) { + scalar_t dy = y - by; + *(owy++) = interpolation::fastweight(interpolation1, dy); + if (do_grad || do_sgrad) + *(ogy++) = interpolation::fastgrad(interpolation1, dy); + if (do_grad && trgt_sK > 1) + *(ohy++) = interpolation::fasthess(interpolation1, dy); + *(osy++) = bound::sign(bound1, by, src_Y); + *(oiy++) = bound::index(bound1, by, src_Y); + } + } + { + scalar_t *owx = static_cast(wx), *ogx = static_cast(gx), *ohx = static_cast(hx); + offset_t* oix = static_cast(ix); + uint8_t* osx = static_cast(sx); + for (offset_t bx = bx0; bx <= bx1; ++bx) { + scalar_t dx = x - bx; + *(owx++) = interpolation::fastweight(interpolation0, dx); + if (do_grad || do_sgrad) + *(ogx++) = interpolation::fastgrad(interpolation0, dx); + if (do_grad && trgt_sK > 1) + *(ohx++) = interpolation::fasthess(interpolation0, dx); + *(osx++) = bound::sign(bound0, bx, src_X); + *(oix++) = bound::index(bound0, bx, src_X); + } + } + + // Convolve coefficients with basis functions + scalar_t ogx, ogy; + ogx = ogy = static_cast(0); + for (offset_t j = 0; j <= dby; ++j) { + offset_t ooy = iy[j] * out_sY; + offset_t osy = iy[j] * src_sY; + uint8_t syy = sy[j]; + scalar_t wyy = wy[j]; + scalar_t gyy = gy[j]; + scalar_t hyy = hy[j]; + for (offset_t i = 0; i <= dbx; ++i) { + offset_t ooxy = ooy + ix[i] * out_sX; + offset_t osxy = osy + ix[i] * src_sX; + uint8_t sxy = syy * sx[i]; + scalar_t wxx = wx[i]; + scalar_t gxx = gx[i]; + scalar_t hxx = hx[i]; + + // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Pull ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + if (do_pull) { + scalar_t* src_ptr_NC = src_ptr_NC0; + scalar_t* out_ptr_NCXY = out_ptr_NCXY0; + for (offset_t c = 0; c < C; ++c, out_ptr_NCXY += out_sC, src_ptr_NC += src_sC) + *out_ptr_NCXY += bound::get(src_ptr_NC, osxy, sxy) * (wxx * wyy); + } + + // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ SGrad ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + else if (do_sgrad) { + scalar_t* src_ptr_NC = src_ptr_NC0; + scalar_t* out_ptr_NCXY = out_ptr_NCXY0; + for (offset_t c = 0; c < C; ++c, out_ptr_NCXY += out_sC, src_ptr_NC += src_sC) { + scalar_t src = bound::get(src_ptr_NC, osxy, sxy); + *out_ptr_NCXY += src * (gxx * wyy); + out_ptr_NCXY[out_sK] += src * (wxx * gyy); + } + } + + // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Push ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + else if (do_push) { + if (trgt_K == 0) { + // Diff w.r.t. push/pull + scalar_t* out_ptr_NC = out_ptr_NC0; + for (offset_t c = 0; c < C; ++c, out_ptr_NC += out_sC) + bound::add(out_ptr_NC, ooxy, (wxx * wyy) * target[c], sxy); + } else { + // Diff w.r.t. sgrad + scalar_t* out_ptr_NC = out_ptr_NC0; + for (offset_t c = 0; c < C; ++c, out_ptr_NC += out_sC) { + scalar_t val = (gxx * wyy) * target[c] + (wxx * gyy) * target[c + C]; + bound::add(out_ptr_NC, ooxy, val, sxy); + } + } + } + + // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Count ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + else if (do_count) { + bound::add(out_ptr_NC0, ooxy, (wxx * wyy), sxy); + } + + // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Grad ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + if (do_grad) { + if (trgt_K == 0) { + // Diff w.r.t. pull/push + scalar_t* src_ptr_NC = src_ptr_NC0; + scalar_t dot = static_cast(0); + for (offset_t c = 0; c < C; ++c, src_ptr_NC += src_sC) { + scalar_t src = bound::get(src_ptr_NC, osxy, sxy); + dot += (trgt_ptr ? src * target[c] : src); + // trgt_ptr == 0 in the backward pass of 'count' + } + ogx += (gxx * wyy) * dot; + ogy += (wxx * gyy) * dot; + } else { + // Diff w.r.t. sgrad + scalar_t* src_ptr_NC = src_ptr_NC0; + scalar_t dot0, dot1; + dot0 = dot1 = static_cast(0); + for (offset_t c = 0; c < C; ++c, src_ptr_NC += src_sC) { + scalar_t src = bound::get(src_ptr_NC, osxy, sxy); + dot0 += src * target[c]; + dot1 += src * target[c + C]; + } + ogx += (hxx * wyy) * dot0 + (gxx * gyy) * dot1; + ogy += (gxx * gyy) * dot0 + (wxx * hyy) * dot1; + } + } + + } // x + } // y + + // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Grad ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + if (do_grad) { + scalar_t* grad_ptr_NXY = grad_ptr + n * grad_sN + w * grad_sX + h * grad_sY; + (*grad_ptr_NXY) = ogx; + grad_ptr_NXY[grad_sC] = ogy; + } + } + + // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + // GENERIC INTERPOLATION 1D + // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + + template + MONAI_DEVICE void PushPullImpl::interpolate1d(scalar_t x, offset_t w, offset_t n) const { + // Get corner pixel values from (x, y) + offset_t bx0, bx1; + interpolation::bounds(interpolation0, x, bx0, bx1); + offset_t dbx = bx1 - bx0; + + // Pre-compute offsets and target value + scalar_t* src_ptr_NC0 = src_ptr + n * src_sN; + scalar_t* out_ptr_NC0 = out_ptr + n * out_sN; + scalar_t* out_ptr_NCX0 = out_ptr + n * out_sN + w * out_sX; + scalar_t* trgt_ptr_NCX = trgt_ptr + n * trgt_sN + w * trgt_sX; + scalar_t target[2 * MONAI_MAX_NUM_CHANNELS]; + if (trgt_ptr && (do_push || do_grad)) + for (offset_t c = 0; c < C; ++c, trgt_ptr_NCX += trgt_sC) { + target[c] = *trgt_ptr_NCX; + if (trgt_K > 0) { + target[c + C] = trgt_ptr_NCX[trgt_sK]; + } + } + + // Initialize output + scalar_t* out_ptr_NCX = out_ptr_NCX0; + if (do_pull || do_sgrad) { + for (offset_t c = 0; c < C; ++c, out_ptr_NCX += out_sC) { + *out_ptr_NCX = static_cast(0); + if (do_sgrad) { + out_ptr_NCX[out_sK] = static_cast(0); + } + } + } + + // Pre-compute indices/weights/grad + scalar_t wx[8]; // B-spline weights + scalar_t gx[8]; // B-spline derivatives + scalar_t hx[8]; // B-spline 2nd derivatives + offset_t ix[8]; // Warped indices + uint8_t sx[8]; // Warped indices + + { + scalar_t *owx = static_cast(wx), *ogx = static_cast(gx), *ohx = static_cast(hx); + offset_t* oix = static_cast(ix); + uint8_t* osx = static_cast(sx); + for (offset_t bx = bx0; bx <= bx1; ++bx) { + scalar_t dx = x - bx; + *(owx++) = interpolation::fastweight(interpolation0, dx); + if (do_grad || do_sgrad) + *(ogx++) = interpolation::fastgrad(interpolation0, dx); + if (do_grad && trgt_sK > 1) + *(ohx++) = interpolation::fasthess(interpolation0, dx); + *(osx++) = bound::sign(bound0, bx, src_X); + *(oix++) = bound::index(bound0, bx, src_X); + } + } + + // Convolve coefficients with basis functions + scalar_t ogx; + ogx = static_cast(0); + for (offset_t i = 0; i <= dbx; ++i) { + offset_t oox = ix[i] * out_sX; + offset_t osx = ix[i] * src_sX; + uint8_t sxx = sx[i]; + scalar_t wxx = wx[i]; + scalar_t gxx = gx[i]; + scalar_t hxx = hx[i]; + + // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Pull ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + if (do_pull) { + scalar_t* src_ptr_NC = src_ptr_NC0; + scalar_t* out_ptr_NCX = out_ptr_NCX0; + for (offset_t c = 0; c < C; ++c, out_ptr_NCX += out_sC, src_ptr_NC += src_sC) + *out_ptr_NCX += bound::get(src_ptr_NC, osx, sxx) * wxx; + } + + // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ SGrad ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + else if (do_sgrad) { + scalar_t* src_ptr_NC = src_ptr_NC0; + scalar_t* out_ptr_NCX = out_ptr_NCX0; + for (offset_t c = 0; c < C; ++c, out_ptr_NCX += out_sC, src_ptr_NC += src_sC) { + scalar_t src = bound::get(src_ptr_NC, osx, sxx); + *out_ptr_NCX += src * gxx; + } + } + + // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Push ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + else if (do_push) { + if (trgt_K == 0) { + // Diff w.r.t. push/pull + scalar_t* out_ptr_NC = out_ptr_NC0; + for (offset_t c = 0; c < C; ++c, out_ptr_NC += out_sC) + bound::add(out_ptr_NC, oox, wxx * target[c], sxx); + } else { + // Diff w.r.t. sgrad + scalar_t* out_ptr_NC = out_ptr_NC0; + for (offset_t c = 0; c < C; ++c, out_ptr_NC += out_sC) { + scalar_t val = gxx * target[c]; + bound::add(out_ptr_NC, oox, val, sxx); + } + } + } + + // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Count ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + else if (do_count) { + bound::add(out_ptr_NC0, oox, wxx, sxx); + } + + // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Grad ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + if (do_grad) { + if (trgt_K == 0) { + // Diff w.r.t. pull/push + scalar_t* src_ptr_NC = src_ptr_NC0; + scalar_t dot = static_cast(0); + for (offset_t c = 0; c < C; ++c, src_ptr_NC += src_sC) { + scalar_t src = bound::get(src_ptr_NC, osx, sxx); + dot += (trgt_ptr ? src * target[c] : src); + // trgt_ptr == 0 in the backward pass of 'count' + } + ogx += gxx * dot; + } else { + // Diff w.r.t. sgrad + scalar_t* src_ptr_NC = src_ptr_NC0; + scalar_t dot; + dot = static_cast(0); + for (offset_t c = 0; c < C; ++c, src_ptr_NC += src_sC) { + scalar_t src = bound::get(src_ptr_NC, osx, sxx); + dot += src * target[c]; + } + ogx += hxx * dot; + } + } + + } // x + + // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Grad ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + if (do_grad) { + scalar_t* grad_ptr_NX = grad_ptr + n * grad_sN + w * grad_sX; + (*grad_ptr_NX) = ogx; + } + } + + // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + // LINEAR INTERPOLATION 3D + // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + + template + MONAI_DEVICE void PushPullImpl::interpolate3d_trilinear( + scalar_t x, + scalar_t y, + scalar_t z, + offset_t w, + offset_t h, + offset_t d, + offset_t n) const { + // Get corner pixel values from (x, y, z) + offset_t ix0 = static_cast(std::floor(x)); + offset_t iy0 = static_cast(std::floor(y)); + offset_t iz0 = static_cast(std::floor(z)); + + // Interpolation weights (inversely proportional to distance) + scalar_t dx1 = x - ix0; + scalar_t dy1 = y - iy0; + scalar_t dz1 = z - iz0; + scalar_t dx0 = 1. - dx1; + scalar_t dy0 = 1. - dy1; + scalar_t dz0 = 1. - dz1; + scalar_t w000 = dx0 * dy0 * dz0; + scalar_t w100 = dx1 * dy0 * dz0; + scalar_t w010 = dx0 * dy1 * dz0; + scalar_t w001 = dx0 * dy0 * dz1; + scalar_t w110 = dx1 * dy1 * dz0; + scalar_t w011 = dx0 * dy1 * dz1; + scalar_t w101 = dx1 * dy0 * dz1; + scalar_t w111 = dx1 * dy1 * dz1; + + // Sign (/!\ compute sign before warping indices) + int8_t sx1 = bound::sign(bound0, ix0 + 1, src_X); + int8_t sy1 = bound::sign(bound1, iy0 + 1, src_Y); + int8_t sz1 = bound::sign(bound2, iz0 + 1, src_Z); + int8_t sx0 = bound::sign(bound0, ix0, src_X); + int8_t sy0 = bound::sign(bound1, iy0, src_Y); + int8_t sz0 = bound::sign(bound2, iz0, src_Z); + int8_t s000 = sx0 * sy0 * sz0; + int8_t s100 = sx1 * sy0 * sz0; + int8_t s010 = sx0 * sy1 * sz0; + int8_t s001 = sx0 * sy0 * sz1; + int8_t s110 = sx1 * sy1 * sz0; + int8_t s011 = sx0 * sy1 * sz1; + int8_t s101 = sx1 * sy0 * sz1; + int8_t s111 = sx1 * sy1 * sz1; + + // Warp indices + offset_t ix1, iy1, iz1; + ix1 = bound::index(bound0, ix0 + 1, src_X); + iy1 = bound::index(bound1, iy0 + 1, src_Y); + iz1 = bound::index(bound2, iz0 + 1, src_Z); + ix0 = bound::index(bound0, ix0, src_X); + iy0 = bound::index(bound1, iy0, src_Y); + iz0 = bound::index(bound2, iz0, src_Z); + + offset_t o000, o100, o010, o001, o110, o011, o101, o111; + + if (do_pull || do_grad || do_sgrad) { + // Offsets into source volume + o000 = ix0 * src_sX + iy0 * src_sY + iz0 * src_sZ; + o100 = ix1 * src_sX + iy0 * src_sY + iz0 * src_sZ; + o010 = ix0 * src_sX + iy1 * src_sY + iz0 * src_sZ; + o001 = ix0 * src_sX + iy0 * src_sY + iz1 * src_sZ; + o110 = ix1 * src_sX + iy1 * src_sY + iz0 * src_sZ; + o011 = ix0 * src_sX + iy1 * src_sY + iz1 * src_sZ; + o101 = ix1 * src_sX + iy0 * src_sY + iz1 * src_sZ; + o111 = ix1 * src_sX + iy1 * src_sY + iz1 * src_sZ; + } else if (!(do_push || do_count)) { + o000 = o100 = o010 = o001 = o110 = o011 = o101 = o111 = 0; + } + + // ~~~~~~~~~~~~~~~~~~~~~~~~~~ Grid gradient ~~~~~~~~~~~~~~~~~~~~~~~~~~ + if (do_grad) { + scalar_t gx = static_cast(0); + scalar_t gy = static_cast(0); + scalar_t gz = static_cast(0); + scalar_t* trgt_ptr_NCXYZ = trgt_ptr + n * trgt_sN + w * trgt_sX + h * trgt_sY + d * trgt_sZ; + scalar_t* src_ptr_NC = src_ptr + n * src_sN; + + if (trgt_K == 0) { + // backward w.r.t. push/pull + for (offset_t c = 0; c < C; ++c, trgt_ptr_NCXYZ += trgt_sC, src_ptr_NC += src_sC) { + scalar_t src; + scalar_t trgt = trgt_ptr ? *trgt_ptr_NCXYZ : static_cast(1); + // ^ trgt_ptr == 0 during the backward pass of count + src = bound::get(src_ptr_NC, o000, s000); + if (trgt_ptr) + src *= trgt; + gx -= dy0 * dz0 * src; + gy -= dx0 * dz0 * src; + gz -= dx0 * dy0 * src; + src = bound::get(src_ptr_NC, o100, s100); + if (trgt_ptr) + src *= trgt; + gx += dy0 * dz0 * src; + gy -= dx1 * dz0 * src; + gz -= dx1 * dy0 * src; + src = bound::get(src_ptr_NC, o010, s010); + if (trgt_ptr) + src *= trgt; + gx -= dy1 * dz0 * src; + gy += dx0 * dz0 * src; + gz -= dx0 * dy1 * src; + src = bound::get(src_ptr_NC, o110, s110); + if (trgt_ptr) + src *= trgt; + gx += dy1 * dz0 * src; + gy += dx1 * dz0 * src; + gz -= dx1 * dy1 * src; + src = bound::get(src_ptr_NC, o001, s001); + if (trgt_ptr) + src *= trgt; + gx -= dy0 * dz1 * src; + gy -= dx0 * dz1 * src; + gz += dx0 * dy0 * src; + src = bound::get(src_ptr_NC, o101, s101); + if (trgt_ptr) + src *= trgt; + gx += dy0 * dz1 * src; + gy -= dx1 * dz1 * src; + gz += dx1 * dy0 * src; + src = bound::get(src_ptr_NC, o011, s011); + if (trgt_ptr) + src *= trgt; + gx -= dy1 * dz1 * src; + gy += dx0 * dz1 * src; + gz += dx0 * dy1 * src; + src = bound::get(src_ptr_NC, o111, s111); + if (trgt_ptr) + src *= trgt; + gx += dy1 * dz1 * src; + gy += dx1 * dz1 * src; + gz += dx1 * dy1 * src; + } + } else { + // backward w.r.t. sgrad + for (offset_t c = 0; c < C; ++c, trgt_ptr_NCXYZ += trgt_sC, src_ptr_NC += src_sC) { + scalar_t src; + scalar_t trgt0 = *trgt_ptr_NCXYZ, trgt1 = trgt_ptr_NCXYZ[trgt_sK], trgt2 = trgt_ptr_NCXYZ[trgt_sK * 2]; + src = bound::get(src_ptr_NC, o000, s000); + gx += (dz0 * trgt1 + dy0 * trgt2) * src; + gy += (dz0 * trgt0 + dx0 * trgt2) * src; + gz += (dy0 * trgt0 + dx0 * trgt1) * src; + src = bound::get(src_ptr_NC, o100, s100); + gx += (-dz0 * trgt1 - dy0 * trgt2) * src; + gy += (-dz0 * trgt0 + dx1 * trgt2) * src; + gz += (-dy0 * trgt0 + dx1 * trgt1) * src; + src = bound::get(src_ptr_NC, o010, s010); + gx += (-dz0 * trgt1 + dy1 * trgt2) * src; + gy += (-dz0 * trgt0 - dx0 * trgt2) * src; + gz += (dy1 * trgt0 - dx0 * trgt1) * src; + src = bound::get(src_ptr_NC, o110, s110); + gx += (dz0 * trgt1 - dy1 * trgt2) * src; + gy += (dz0 * trgt0 - dx1 * trgt2) * src; + gz += (-dy1 * trgt0 - dx1 * trgt1) * src; + src = bound::get(src_ptr_NC, o001, s001); + gx += (dz1 * trgt1 - dy0 * trgt2) * src; + gy += (dz1 * trgt0 - dx0 * trgt2) * src; + gz += (-dy0 * trgt0 - dx0 * trgt1) * src; + src = bound::get(src_ptr_NC, o101, s101); + gx += (-dz1 * trgt1 + dy0 * trgt2) * src; + gy += (-dz1 * trgt0 - dx1 * trgt2) * src; + gz += (dy0 * trgt0 - dx1 * trgt1) * src; + src = bound::get(src_ptr_NC, o011, s011); + gx += (-dz1 * trgt1 - dy1 * trgt2) * src; + gy += (-dz1 * trgt0 + dx0 * trgt2) * src; + gz += (-dy1 * trgt0 + dx0 * trgt1) * src; + src = bound::get(src_ptr_NC, o111, s111); + gx += (dz1 * trgt1 + dy1 * trgt2) * src; + gy += (dz1 * trgt0 + dx1 * trgt2) * src; + gz += (dy1 * trgt0 + dx1 * trgt1) * src; + } + } + + scalar_t* grad_ptr_NXYZ = grad_ptr + n * grad_sN + w * grad_sX + h * grad_sY + d * grad_sZ; + (*grad_ptr_NXYZ) = gx; + grad_ptr_NXYZ[grad_sC] = gy; + grad_ptr_NXYZ[grad_sC * 2] = gz; + } + if (do_push || do_count) { + // Offsets into 'push' volume + o000 = ix0 * out_sX + iy0 * out_sY + iz0 * out_sZ; + o100 = ix1 * out_sX + iy0 * out_sY + iz0 * out_sZ; + o010 = ix0 * out_sX + iy1 * out_sY + iz0 * out_sZ; + o001 = ix0 * out_sX + iy0 * out_sY + iz1 * out_sZ; + o110 = ix1 * out_sX + iy1 * out_sY + iz0 * out_sZ; + o011 = ix0 * out_sX + iy1 * out_sY + iz1 * out_sZ; + o101 = ix1 * out_sX + iy0 * out_sY + iz1 * out_sZ; + o111 = ix1 * out_sX + iy1 * out_sY + iz1 * out_sZ; + } + // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Pull ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + if (do_pull) { + scalar_t* out_ptr_NCXYZ = out_ptr + n * out_sN + w * out_sX + h * out_sY + d * out_sZ; + scalar_t* src_ptr_NC = src_ptr + n * src_sN; + for (offset_t c = 0; c < C; ++c, out_ptr_NCXYZ += out_sC, src_ptr_NC += src_sC) { + *out_ptr_NCXYZ = bound::get(src_ptr_NC, o000, s000) * w000 + bound::get(src_ptr_NC, o100, s100) * w100 + + bound::get(src_ptr_NC, o010, s010) * w010 + bound::get(src_ptr_NC, o110, s110) * w110 + + bound::get(src_ptr_NC, o001, s001) * w001 + bound::get(src_ptr_NC, o101, s101) * w101 + + bound::get(src_ptr_NC, o011, s011) * w011 + bound::get(src_ptr_NC, o111, s111) * w111; + } + } + // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ SGrad ~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~ + else if (do_sgrad) { + scalar_t* out_ptr_NCXYZ = out_ptr + n * out_sN + w * out_sX + h * out_sY + d * out_sZ; + scalar_t* src_ptr_NC = src_ptr + n * src_sN; + + for (offset_t c = 0; c < C; ++c, out_ptr_NCXYZ += out_sC, src_ptr_NC += src_sC) { + scalar_t src000 = bound::get(src_ptr_NC, o000, s000); + scalar_t src100 = bound::get(src_ptr_NC, o100, s100); + scalar_t src010 = bound::get(src_ptr_NC, o010, s010); + scalar_t src110 = bound::get(src_ptr_NC, o110, s110); + scalar_t src001 = bound::get(src_ptr_NC, o001, s001); + scalar_t src101 = bound::get(src_ptr_NC, o101, s101); + scalar_t src011 = bound::get(src_ptr_NC, o011, s011); + scalar_t src111 = bound::get(src_ptr_NC, o111, s111); + *out_ptr_NCXYZ = -dy0 * dz0 * src000 + dy0 * dz0 * src100 - dy1 * dz0 * src010 + dy1 * dz0 * src110 - + dy0 * dz1 * src001 + dy0 * dz1 * src101 - dy1 * dz1 * src011 + dy1 * dz1 * src111; + out_ptr_NCXYZ[out_sK] = -dx0 * dz0 * src000 - dx1 * dz0 * src100 + dx0 * dz0 * src010 + dx1 * dz0 * src110 - + dx0 * dz1 * src001 - dx1 * dz1 * src101 + dx0 * dz1 * src011 + dx1 * dz1 * src111; + out_ptr_NCXYZ[out_sK * 2] = -dx0 * dy0 * src000 - dx1 * dy0 * src100 - dx0 * dy1 * src010 - dx1 * dy1 * src110 + + dx0 * dy0 * src001 + dx1 * dy0 * src101 + dx0 * dy1 * src011 + dx1 * dy1 * src111; + } + } + // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Push ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + else if (do_push) { + scalar_t* trgt_ptr_NCXYZ = trgt_ptr + n * trgt_sN + w * trgt_sX + h * trgt_sY + d * trgt_sZ; + scalar_t* out_ptr_NC = out_ptr + n * out_sN; + if (trgt_K == 0) { + // Diff w.r.t. push/pull + for (offset_t c = 0; c < C; ++c, trgt_ptr_NCXYZ += trgt_sC, out_ptr_NC += out_sC) { + scalar_t trgt = *trgt_ptr_NCXYZ; + bound::add(out_ptr_NC, o000, w000 * trgt, s000); + bound::add(out_ptr_NC, o100, w100 * trgt, s100); + bound::add(out_ptr_NC, o010, w010 * trgt, s010); + bound::add(out_ptr_NC, o110, w110 * trgt, s110); + bound::add(out_ptr_NC, o001, w001 * trgt, s001); + bound::add(out_ptr_NC, o101, w101 * trgt, s101); + bound::add(out_ptr_NC, o011, w011 * trgt, s011); + bound::add(out_ptr_NC, o111, w111 * trgt, s111); + } + } else { + // Diff w.r.t. sgrad + scalar_t val; + for (offset_t c = 0; c < C; ++c, trgt_ptr_NCXYZ += trgt_sC, out_ptr_NC += out_sC) { + scalar_t trgt0 = *trgt_ptr_NCXYZ, trgt1 = trgt_ptr_NCXYZ[trgt_sK], trgt2 = trgt_ptr_NCXYZ[trgt_sK * 2]; + val = -dy0 * dz0 * trgt0 - dx0 * dz0 * trgt1 - dx0 * dy0 * trgt2; + bound::add(out_ptr_NC, o000, val, s000); + val = dy0 * dz0 * trgt0 - dx1 * dz0 * trgt1 - dx1 * dy0 * trgt2; + bound::add(out_ptr_NC, o100, val, s100); + val = -dy1 * dz0 * trgt0 + dx0 * dz0 * trgt1 - dx0 * dy1 * trgt2; + bound::add(out_ptr_NC, o010, val, s010); + val = dy1 * dz0 * trgt0 + dx1 * dz0 * trgt1 - dx1 * dy1 * trgt2; + bound::add(out_ptr_NC, o110, val, s110); + val = -dy0 * dz1 * trgt0 - dx0 * dz1 * trgt1 + dx0 * dy0 * trgt2; + bound::add(out_ptr_NC, o001, val, s001); + val = dy0 * dz1 * trgt0 - dx1 * dz1 * trgt1 + dx1 * dy0 * trgt2; + bound::add(out_ptr_NC, o101, val, s101); + val = -dy1 * dz1 * trgt0 + dx0 * dz1 * trgt1 + dx0 * dy1 * trgt2; + bound::add(out_ptr_NC, o011, val, s011); + val = dy1 * dz1 * trgt0 + dx1 * dz1 * trgt1 + dx1 * dy1 * trgt2; + bound::add(out_ptr_NC, o111, val, s111); + } + } + } + // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Push ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + else if (do_count) { + scalar_t* out_ptr_N = out_ptr + n * out_sN; + bound::add(out_ptr_N, o000, w000, s000); + bound::add(out_ptr_N, o100, w100, s100); + bound::add(out_ptr_N, o010, w010, s010); + bound::add(out_ptr_N, o110, w110, s110); + bound::add(out_ptr_N, o001, w001, s001); + bound::add(out_ptr_N, o101, w101, s101); + bound::add(out_ptr_N, o011, w011, s011); + bound::add(out_ptr_N, o111, w111, s111); + } + } + + // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + // LINEAR INTERPOLATION 2D + // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + + template + MONAI_DEVICE void PushPullImpl::interpolate2d_bilinear( + scalar_t x, + scalar_t y, + offset_t w, + offset_t h, + offset_t n) const { + // Get corner pixel values from (x, y, z) + offset_t ix0 = static_cast(std::floor(x)); + offset_t iy0 = static_cast(std::floor(y)); + + // Interpolation weights (inversely proportional to distance) + scalar_t dx1 = x - ix0; + scalar_t dy1 = y - iy0; + scalar_t dx0 = 1. - dx1; + scalar_t dy0 = 1. - dy1; + scalar_t w00 = dx0 * dy0; + scalar_t w10 = dx1 * dy0; + scalar_t w01 = dx0 * dy1; + scalar_t w11 = dx1 * dy1; + + // Sign (/!\ compute sign before warping indices) + int8_t sx1 = bound::sign(bound0, ix0 + 1, src_X); + int8_t sy1 = bound::sign(bound1, iy0 + 1, src_Y); + int8_t sx0 = bound::sign(bound0, ix0, src_X); + int8_t sy0 = bound::sign(bound1, iy0, src_Y); + int8_t s00 = sx0 * sy0; + int8_t s10 = sx1 * sy0; + int8_t s01 = sx0 * sy1; + int8_t s11 = sx1 * sy1; + + // Warp indices + offset_t ix1, iy1; + ix1 = bound::index(bound0, ix0 + 1, src_X); + iy1 = bound::index(bound1, iy0 + 1, src_Y); + ix0 = bound::index(bound0, ix0, src_X); + iy0 = bound::index(bound1, iy0, src_Y); + + offset_t o00, o10, o01, o11; + if (do_pull || do_grad || do_sgrad) { + // Offsets into source volume + o00 = ix0 * src_sX + iy0 * src_sY; + o10 = ix1 * src_sX + iy0 * src_sY; + o01 = ix0 * src_sX + iy1 * src_sY; + o11 = ix1 * src_sX + iy1 * src_sY; + } else if (!(do_push || do_count)) { + o00 = o10 = o01 = o11 = 0; + } + + // ~~~~~~~~~~~~~~~~~~~~~~~~~~ Grid gradient ~~~~~~~~~~~~~~~~~~~~~~~~~~ + if (do_grad) { + scalar_t gx = static_cast(0); + scalar_t gy = static_cast(0); + scalar_t* trgt_ptr_NCXY = trgt_ptr + n * trgt_sN + w * trgt_sX + h * trgt_sY; + scalar_t* src_ptr_NC = src_ptr + n * src_sN; + + if (trgt_K == 0) { + // backward w.r.t. push/pull + for (offset_t c = 0; c < C; ++c, trgt_ptr_NCXY += trgt_sC, src_ptr_NC += src_sC) { + scalar_t src; + scalar_t trgt = trgt_ptr ? *trgt_ptr_NCXY : static_cast(1); + // ^ trgt_ptr == 0 during the backward pass of count + src = bound::get(src_ptr_NC, o00, s00); + if (trgt_ptr) + src *= trgt; + gx -= dy0 * src; + gy -= dx0 * src; + src = bound::get(src_ptr_NC, o10, s10); + if (trgt_ptr) + src *= trgt; + gx += dy0 * src; + gy -= dx1 * src; + src = bound::get(src_ptr_NC, o01, s01); + if (trgt_ptr) + src *= trgt; + gx -= dy1 * src; + gy += dx0 * src; + src = bound::get(src_ptr_NC, o11, s11); + if (trgt_ptr) + src *= trgt; + gx += dy1 * src; + gy += dx1 * src; + } + } else { + // backward w.r.t. sgrad + for (offset_t c = 0; c < C; ++c, trgt_ptr_NCXY += trgt_sC, src_ptr_NC += src_sC) { + scalar_t src; + scalar_t trgt0 = *trgt_ptr_NCXY, trgt1 = trgt_ptr_NCXY[trgt_sK]; + src = bound::get(src_ptr_NC, o00, s00); + gx += trgt1 * src; + gy += trgt0 * src; + src = bound::get(src_ptr_NC, o10, s10); + gx -= trgt1 * src; + gy -= trgt0 * src; + src = bound::get(src_ptr_NC, o01, s01); + gx -= trgt1 * src; + gy -= trgt0 * src; + src = bound::get(src_ptr_NC, o11, s11); + gx += trgt1 * src; + gy += trgt0 * src; + } + } + + scalar_t* grad_ptr_NXY = grad_ptr + n * grad_sN + w * grad_sX + h * grad_sY; + (*grad_ptr_NXY) = gx; + grad_ptr_NXY[grad_sC] = gy; + } + if (do_push || do_count) { + // Offsets into 'push' volume + o00 = ix0 * out_sX + iy0 * out_sY; + o10 = ix1 * out_sX + iy0 * out_sY; + o01 = ix0 * out_sX + iy1 * out_sY; + o11 = ix1 * out_sX + iy1 * out_sY; + } + // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Pull ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + if (do_pull) { + scalar_t* out_ptr_NCXY = out_ptr + n * out_sN + w * out_sX + h * out_sY; + scalar_t* src_ptr_NC = src_ptr + n * src_sN; + for (offset_t c = 0; c < C; ++c, out_ptr_NCXY += out_sC, src_ptr_NC += src_sC) { + *out_ptr_NCXY = bound::get(src_ptr_NC, o00, s00) * w00 + bound::get(src_ptr_NC, o10, s10) * w10 + + bound::get(src_ptr_NC, o01, s01) * w01 + bound::get(src_ptr_NC, o11, s11) * w11; + } + } + // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ SGrad ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + else if (do_sgrad) { + scalar_t* out_ptr_NCXY = out_ptr + n * out_sN + w * out_sX + h * out_sY; + scalar_t* src_ptr_NC = src_ptr + n * src_sN; + + for (offset_t c = 0; c < C; ++c, out_ptr_NCXY += out_sC, src_ptr_NC += src_sC) { + scalar_t src00 = bound::get(src_ptr_NC, o00, s00); + scalar_t src10 = bound::get(src_ptr_NC, o10, s10); + scalar_t src01 = bound::get(src_ptr_NC, o01, s01); + scalar_t src11 = bound::get(src_ptr_NC, o11, s11); + *out_ptr_NCXY = -dy0 * src00 + dy0 * src10 - dy1 * src01 + dy1 * src11; + out_ptr_NCXY[out_sK] = -dx0 * src00 - dx1 * src10 + dx0 * src01 + dx1 * src11; + } + } + // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Push ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + else if (do_push) { + scalar_t* trgt_ptr_NCXY = trgt_ptr + n * trgt_sN + w * trgt_sX + h * trgt_sY; + scalar_t* out_ptr_NC = out_ptr + n * out_sN; + if (trgt_K == 0) { + // Diff w.r.t. push/pull + for (offset_t c = 0; c < C; ++c, trgt_ptr_NCXY += trgt_sC, out_ptr_NC += out_sC) { + scalar_t trgt = *trgt_ptr_NCXY; + bound::add(out_ptr_NC, o00, w00 * trgt, s00); + bound::add(out_ptr_NC, o10, w10 * trgt, s10); + bound::add(out_ptr_NC, o01, w01 * trgt, s01); + bound::add(out_ptr_NC, o11, w11 * trgt, s11); + } + } else { + // Diff w.r.t. sgrad + scalar_t val; + for (offset_t c = 0; c < C; ++c, trgt_ptr_NCXY += trgt_sC, out_ptr_NC += out_sC) { + scalar_t trgt0 = *trgt_ptr_NCXY, trgt1 = trgt_ptr_NCXY[trgt_sK]; + val = -dy0 * trgt0 - dx0 * trgt1; + bound::add(out_ptr_NC, o00, val, s00); + val = dy0 * trgt0 - dx1 * trgt1; + bound::add(out_ptr_NC, o10, val, s10); + val = -dy1 * trgt0 + dx0 * trgt1; + bound::add(out_ptr_NC, o01, val, s01); + val = dy1 * trgt0 + dx1 * trgt1; + bound::add(out_ptr_NC, o11, val, s11); + } + } + } + // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Push ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + else if (do_count) { + scalar_t* out_ptr_N = out_ptr + n * out_sN; + bound::add(out_ptr_N, o00, w00, s00); + bound::add(out_ptr_N, o10, w10, s10); + bound::add(out_ptr_N, o01, w01, s01); + bound::add(out_ptr_N, o11, w11, s11); + } + } + + // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + // LINEAR INTERPOLATION 1D + // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + + template + MONAI_DEVICE void PushPullImpl::interpolate1d_linear(scalar_t x, offset_t w, offset_t n) const { + // Get corner pixel values from (x) + offset_t ix0 = static_cast(std::floor(x)); + + // Interpolation weights (inversely proportional to distance) + scalar_t w1 = x - ix0; + scalar_t w0 = 1. - w1; + + // Sign (/!\ compute sign before warping indices) + int8_t s1 = bound::sign(bound0, ix0 + 1, src_X); + int8_t s0 = bound::sign(bound0, ix0, src_X); + + // Warp indices + offset_t ix1; + ix1 = bound::index(bound0, ix0 + 1, src_X); + ix0 = bound::index(bound0, ix0, src_X); + + // Offsets into source volume + offset_t o0, o1; + if (do_pull || do_grad || do_sgrad) { + o0 = ix0 * src_sX; + o1 = ix1 * src_sX; + } else if (!(do_push || do_count)) { + o0 = o1 = 0; + } + + // ~~~~~~~~~~~~~~~~~~~~~~~~~~ Grid gradient ~~~~~~~~~~~~~~~~~~~~~~~~~~ + if (do_grad) { + if (trgt_K == 0) { + // backward w.r.t. push/pull + scalar_t gx = static_cast(0); + scalar_t* trgt_ptr_NCX = trgt_ptr + n * trgt_sN + w * trgt_sX; + scalar_t* src_ptr_NC = src_ptr + n * src_sN; + + for (offset_t c = 0; c < C; ++c, trgt_ptr_NCX += trgt_sC, src_ptr_NC += src_sC) { + scalar_t src; + scalar_t trgt = trgt_ptr ? *trgt_ptr_NCX : static_cast(1); + // ^ trgt_ptr == 0 during the backward pass of count + src = bound::get(src_ptr_NC, o0, s0); + if (trgt_ptr) + src *= trgt; + gx -= src; + src = bound::get(src_ptr_NC, o1, s1); + if (trgt_ptr) + src *= trgt; + gx += src; + } + + scalar_t* grad_ptr_NX = grad_ptr + n * grad_sN + w * grad_sX; + (*grad_ptr_NX) = gx; + } else { + // backward w.r.t. sgrad + // -> zero (make sure this is done at initialization) + } + } + if (do_push || do_count) { + // Offsets into 'push' volume + o0 = ix0 * out_sX; + o1 = ix1 * out_sX; + } + // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Pull ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + if (do_pull) { + scalar_t* out_ptr_NCX = out_ptr + n * out_sN + w * out_sX; + scalar_t* src_ptr_NC = src_ptr + n * src_sN; + for (offset_t c = 0; c < C; ++c, out_ptr_NCX += out_sC, src_ptr_NC += src_sC) { + *out_ptr_NCX = bound::get(src_ptr_NC, o0, s0) * w0 + bound::get(src_ptr_NC, o1, s1) * w1; + } + } + // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ SGrad ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + else if (do_sgrad) { + scalar_t* out_ptr_NCX = out_ptr + n * out_sN + w * out_sX; + scalar_t* src_ptr_NC = src_ptr + n * src_sN; + + for (offset_t c = 0; c < C; ++c, out_ptr_NCX += out_sC, src_ptr_NC += src_sC) { + *out_ptr_NCX = bound::get(src_ptr_NC, o1, s1) - bound::get(src_ptr_NC, o0, s0); + } + } + // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Push ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + else if (do_push) { + scalar_t* trgt_ptr_NCX = trgt_ptr + n * trgt_sN + w * trgt_sX; + scalar_t* out_ptr_NC = out_ptr + n * out_sN; + if (trgt_K == 0) { + // Diff w.r.t. push/pull + for (offset_t c = 0; c < C; ++c, trgt_ptr_NCX += trgt_sC, out_ptr_NC += out_sC) { + scalar_t trgt = *trgt_ptr_NCX; + bound::add(out_ptr_NC, o0, w0 * trgt, s0); + bound::add(out_ptr_NC, o1, w1 * trgt, s1); + } + } else { + // Diff w.r.t. sgrad + for (offset_t c = 0; c < C; ++c, trgt_ptr_NCX += trgt_sC, out_ptr_NC += out_sC) { + scalar_t trgt0 = *trgt_ptr_NCX; + bound::add(out_ptr_NC, o0, -trgt0, s0); + bound::add(out_ptr_NC, o1, trgt0, s1); + } + } + } + // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Push ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + else if (do_count) { + scalar_t* out_ptr_N = out_ptr + n * out_sN; + bound::add(out_ptr_N, o0, w0, s0); + bound::add(out_ptr_N, o1, w1, s1); + } + } + + // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + // NEAREST NEIGHBOR INTERPOLATION 3D + // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + + template + MONAI_DEVICE void PushPullImpl::interpolate3d_nearest( + scalar_t x, + scalar_t y, + scalar_t z, + offset_t w, + offset_t h, + offset_t d, + offset_t n) const { + offset_t ix = static_cast(std::round(x)); + offset_t iy = static_cast(std::round(y)); + offset_t iz = static_cast(std::round(z)); + + // Boundary condition (/!\ compute sign before warping indices) + int8_t sx = bound::sign(bound0, ix, src_X); + int8_t sy = bound::sign(bound1, iy, src_Y); + int8_t sz = bound::sign(bound2, iz, src_Z); + ix = bound::index(bound0, ix, src_X); + iy = bound::index(bound1, iy, src_Y); + iz = bound::index(bound2, iz, src_Z); + + // Sign + int8_t s = sz * sy * sx; + + if (do_pull) { + offset_t o = iz * src_sZ + iy * src_sY + ix * src_sX; + scalar_t* out_ptr_NCXYZ = out_ptr + n * out_sN + w * out_sX + h * out_sY + d * out_sZ; + scalar_t* src_ptr_NC = src_ptr + n * src_sN; + for (offset_t c = 0; c < C; ++c, out_ptr_NCXYZ += out_sC, src_ptr_NC += src_sC) + *out_ptr_NCXYZ = bound::get(src_ptr_NC, o, s); + } else if (do_push && trgt_K == 0) { + offset_t o = iz * out_sZ + iy * out_sY + ix * out_sX; + scalar_t* trgt_ptr_NCXYZ = trgt_ptr + n * trgt_sN + w * trgt_sX + h * trgt_sY + d * trgt_sZ; + scalar_t* out_ptr_NC = out_ptr + n * out_sN; + for (offset_t c = 0; c < C; ++c, trgt_ptr_NCXYZ += trgt_sC, out_ptr_NC += out_sC) + bound::add(out_ptr_NC, o, *trgt_ptr_NCXYZ, s); + } else if (do_count) { + offset_t o = iz * out_sZ + iy * out_sY + ix * out_sX; + scalar_t* out_ptr_NC = out_ptr + n * out_sN; + for (offset_t c = 0; c < C; ++c, out_ptr_NC += out_sC) + bound::add(out_ptr_NC, o, static_cast(1), s); + } + } + + // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + // NEAREST NEIGHBOR INTERPOLATION 2D + // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + + template + MONAI_DEVICE void PushPullImpl::interpolate2d_nearest( + scalar_t x, + scalar_t y, + offset_t w, + offset_t h, + offset_t n) const { + offset_t ix = static_cast(std::round(x)); + offset_t iy = static_cast(std::round(y)); + + // Boundary condition (/!\ compute sign before warping indices) + int8_t sx = bound::sign(bound0, ix, src_X); + int8_t sy = bound::sign(bound1, iy, src_Y); + ix = bound::index(bound0, ix, src_X); + iy = bound::index(bound1, iy, src_Y); + + // Sign + int8_t s = sy * sx; + + if (do_pull) { + offset_t o = iy * src_sY + ix * src_sX; + scalar_t* out_ptr_NCXY = out_ptr + n * out_sN + w * out_sX + h * out_sY; + scalar_t* src_ptr_NC = src_ptr + n * src_sN; + for (offset_t c = 0; c < C; ++c, out_ptr_NCXY += out_sC, src_ptr_NC += src_sC) + *out_ptr_NCXY = bound::get(src_ptr_NC, o, s); + } else if (do_push && trgt_K == 0) { + offset_t o = iy * out_sY + ix * out_sX; + scalar_t* trgt_ptr_NCXY = trgt_ptr + n * trgt_sN + w * trgt_sX + h * trgt_sY; + scalar_t* out_ptr_NC = out_ptr + n * out_sN; + for (offset_t c = 0; c < C; ++c, trgt_ptr_NCXY += trgt_sC, out_ptr_NC += out_sC) + bound::add(out_ptr_NC, o, *trgt_ptr_NCXY, s); + } else if (do_count) { + offset_t o = iy * out_sY + ix * out_sX; + scalar_t* out_ptr_NC = out_ptr + n * out_sN; + for (offset_t c = 0; c < C; ++c, out_ptr_NC += out_sC) + bound::add(out_ptr_NC, o, static_cast(1), s); + } + } + + // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + // NEAREST NEIGHBOR INTERPOLATION 1D + // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + + template + MONAI_DEVICE void PushPullImpl::interpolate1d_nearest(scalar_t x, offset_t w, offset_t n) const { + offset_t i = static_cast(std::round(x)); + + // Boundary condition (/!\ compute sign before warping indices) + int8_t s = bound::sign(bound0, i, src_X); + i = bound::index(bound0, i, src_X); + + if (do_pull) { + offset_t o = i * src_sX; + scalar_t* out_ptr_NCX = out_ptr + n * out_sN + w * out_sX; + scalar_t* src_ptr_NC = src_ptr + n * src_sN; + for (offset_t c = 0; c < C; ++c, out_ptr_NCX += out_sC, src_ptr_NC += src_sC) + *out_ptr_NCX = bound::get(src_ptr_NC, o, s); + } else if (do_push && trgt_K == 0) { + offset_t o = i * out_sX; + scalar_t* trgt_ptr_NCX = trgt_ptr + n * trgt_sN + w * trgt_sX; + scalar_t* out_ptr_NC = out_ptr + n * out_sN; + for (offset_t c = 0; c < C; ++c, trgt_ptr_NCX += trgt_sC, out_ptr_NC += out_sC) + bound::add(out_ptr_NC, o, *trgt_ptr_NCX, s); + } else if (do_count) { + offset_t o = i * out_sX; + scalar_t* out_ptr_NC = out_ptr + n * out_sN; + for (offset_t c = 0; c < C; ++c, out_ptr_NC += out_sC) + bound::add(out_ptr_NC, o, static_cast(1), s); + } + } + + // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + // LINEAR INTERPOLATION 3D + SLIDING BOUNDARY + // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + // TODO + + // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + // CUDA KERNEL (MUST BE OUT OF CLASS) + // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + + // CUDA Kernel + template + C10_LAUNCH_BOUNDS_1(1024) + __global__ void pushpull_kernel(PushPullImpl f) { + f.loop(threadIdx.x, blockIdx.x, blockDim.x, gridDim.x); + } + + } // namespace + + // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + // FUNCTIONAL FORM WITH DISPATCH + // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +#define PUSHPULL_INSTANTIATE3(BoundType0, InterpolationType0, SourceType0) \ + template std::deque pushpull( \ + const SourceType0&, \ + const Tensor&, \ + const Tensor&, \ + BoundType0, \ + InterpolationType0, \ + bool, \ + bool, \ + bool, \ + bool, \ + bool, \ + bool); \ + template std::deque pushpull( \ + const SourceType0&, const Tensor&, BoundType0, InterpolationType0, bool, bool, bool, bool, bool, bool) +#define PUSHPULL_INSTANTIATE2(BoundType0, InterpolationType0) \ + PUSHPULL_INSTANTIATE3(BoundType0, InterpolationType0, IntArrayRef); \ + PUSHPULL_INSTANTIATE3(BoundType0, InterpolationType0, Tensor) +#define PUSHPULL_INSTANTIATE1(BoundType0) \ + PUSHPULL_INSTANTIATE2(BoundType0, InterpolationType); \ + PUSHPULL_INSTANTIATE2(BoundType0, InterpolationVectorRef) +#define PUSHPULL_INSTANTIATE \ + PUSHPULL_INSTANTIATE1(BoundType); \ + PUSHPULL_INSTANTIATE1(BoundVectorRef) + + // Two arguments (source, grid) + // > `bound` and `interpolation` can be single arguments or vectors. + template + MONAI_HOST std::deque pushpull( + const SourceType& source, + const Tensor& grid, + BoundType bound, + InterpolationType interpolation, + bool extrapolate, + bool do_pull, + bool do_push, + bool do_count, + bool do_grad, + bool do_sgrad) { + PushPullAllocator info( + grid.dim() - 2, bound, interpolation, extrapolate, do_pull, do_push, do_count, do_grad, do_sgrad); + info.ioset(source, grid); + + return AT_DISPATCH_FLOATING_TYPES_AND_HALF(grid.scalar_type(), "pushpull", [&] { + if (info.canUse32BitIndexMath()) { + PushPullImpl algo(info); + pushpull_kernel<<>>(algo); + return algo.output; + } else { + PushPullImpl algo(info); + pushpull_kernel<<>>(algo); + return algo.output; + } + }); + } + + // Three arguments (source, grid, target) + // > `bound` and `interpolation` can be single arguments or vectors. + // > `source` can be a tensor or a vector of dimensions. + template + MONAI_HOST std::deque pushpull( + const SourceType& source, + const Tensor& grid, + const Tensor& target, + BoundType bound, + InterpolationType interpolation, + bool extrapolate, + bool do_pull, + bool do_push, + bool do_count, + bool do_grad, + bool do_sgrad) { + PushPullAllocator info( + grid.dim() - 2, bound, interpolation, extrapolate, do_pull, do_push, do_count, do_grad, do_sgrad); + info.ioset(source, grid, target); + + return AT_DISPATCH_FLOATING_TYPES_AND_HALF(grid.scalar_type(), "pushpull", [&] { + if (info.canUse32BitIndexMath()) { + PushPullImpl algo(info); + pushpull_kernel<<>>(algo); + return algo.output; + } else { + PushPullImpl algo(info); + pushpull_kernel<<>>(algo); + return algo.output; + } + }); + } + + PUSHPULL_INSTANTIATE; + +} // namespace gpu +} // namespace monai diff --git a/source_code/SegMamba/monai/csrc/utils/meta_macros.h b/source_code/SegMamba/monai/csrc/utils/meta_macros.h new file mode 100644 index 0000000000000000000000000000000000000000..0f15b623e357d852734b18fb0adcd35b909f5e1f --- /dev/null +++ b/source_code/SegMamba/monai/csrc/utils/meta_macros.h @@ -0,0 +1,131 @@ +/* +Copyright (c) MONAI Consortium +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + http://www.apache.org/licenses/LICENSE-2.0 +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +#pragma once + +// Helper Macros: for internal use (see below) +#define _DO_1(TARGET) TARGET(1) +#define _DO_2(TARGET) TARGET(2) _DO_1(TARGET) +#define _DO_3(TARGET) TARGET(3) _DO_2(TARGET) +#define _DO_4(TARGET) TARGET(4) _DO_3(TARGET) +#define _DO_5(TARGET) TARGET(5) _DO_4(TARGET) +#define _DO_6(TARGET) TARGET(6) _DO_5(TARGET) +#define _DO_7(TARGET) TARGET(7) _DO_6(TARGET) +#define _DO_8(TARGET) TARGET(8) _DO_7(TARGET) +#define _DO_9(TARGET) TARGET(9) _DO_8(TARGET) +#define _DO_10(TARGET) TARGET(10) _DO_9(TARGET) +#define _DO_11(TARGET) TARGET(11) _DO_10(TARGET) +#define _DO_12(TARGET) TARGET(12) _DO_11(TARGET) +#define _DO_13(TARGET) TARGET(13) _DO_12(TARGET) +#define _DO_14(TARGET) TARGET(14) _DO_13(TARGET) +#define _DO_15(TARGET) TARGET(15) _DO_14(TARGET) +#define _DO_16(TARGET) TARGET(16) _DO_15(TARGET) +#define _DO_17(TARGET) TARGET(17) _DO_16(TARGET) +#define _DO_18(TARGET) TARGET(18) _DO_17(TARGET) +#define _DO_19(TARGET) TARGET(19) _DO_18(TARGET) +#define _DO_20(TARGET) TARGET(20) _DO_19(TARGET) +#define _DO_21(TARGET) TARGET(21) _DO_20(TARGET) +#define _DO_22(TARGET) TARGET(22) _DO_21(TARGET) +#define _DO_23(TARGET) TARGET(23) _DO_22(TARGET) +#define _DO_24(TARGET) TARGET(24) _DO_23(TARGET) +#define _DO_25(TARGET) TARGET(25) _DO_24(TARGET) +#define _DO_26(TARGET) TARGET(26) _DO_25(TARGET) +#define _DO_27(TARGET) TARGET(27) _DO_26(TARGET) +#define _DO_28(TARGET) TARGET(28) _DO_27(TARGET) +#define _DO_29(TARGET) TARGET(29) _DO_28(TARGET) +#define _DO_30(TARGET) TARGET(30) _DO_29(TARGET) +#define _DO_31(TARGET) TARGET(31) _DO_30(TARGET) +#define _DO_32(TARGET) TARGET(32) _DO_31(TARGET) + +#define _DO_A_1(TARGET, A) TARGET(A, 1) +#define _DO_A_2(TARGET, A) TARGET(A, 2) _DO_A_1(TARGET, A) +#define _DO_A_3(TARGET, A) TARGET(A, 3) _DO_A_2(TARGET, A) +#define _DO_A_4(TARGET, A) TARGET(A, 4) _DO_A_3(TARGET, A) +#define _DO_A_5(TARGET, A) TARGET(A, 5) _DO_A_4(TARGET, A) +#define _DO_A_6(TARGET, A) TARGET(A, 6) _DO_A_5(TARGET, A) +#define _DO_A_7(TARGET, A) TARGET(A, 7) _DO_A_6(TARGET, A) +#define _DO_A_8(TARGET, A) TARGET(A, 8) _DO_A_7(TARGET, A) +#define _DO_A_9(TARGET, A) TARGET(A, 9) _DO_A_8(TARGET, A) +#define _DO_A_10(TARGET, A) TARGET(A, 10) _DO_A_9(TARGET, A) +#define _DO_A_11(TARGET, A) TARGET(A, 11) _DO_A_10(TARGET, A) +#define _DO_A_12(TARGET, A) TARGET(A, 12) _DO_A_11(TARGET, A) +#define _DO_A_13(TARGET, A) TARGET(A, 13) _DO_A_12(TARGET, A) +#define _DO_A_14(TARGET, A) TARGET(A, 14) _DO_A_13(TARGET, A) +#define _DO_A_15(TARGET, A) TARGET(A, 15) _DO_A_14(TARGET, A) +#define _DO_A_16(TARGET, A) TARGET(A, 16) _DO_A_15(TARGET, A) +#define _DO_A_17(TARGET, A) TARGET(A, 17) _DO_A_16(TARGET, A) +#define _DO_A_18(TARGET, A) TARGET(A, 18) _DO_A_17(TARGET, A) +#define _DO_A_19(TARGET, A) TARGET(A, 19) _DO_A_18(TARGET, A) +#define _DO_A_20(TARGET, A) TARGET(A, 20) _DO_A_19(TARGET, A) +#define _DO_A_21(TARGET, A) TARGET(A, 21) _DO_A_20(TARGET, A) +#define _DO_A_22(TARGET, A) TARGET(A, 22) _DO_A_21(TARGET, A) +#define _DO_A_23(TARGET, A) TARGET(A, 23) _DO_A_22(TARGET, A) +#define _DO_A_24(TARGET, A) TARGET(A, 24) _DO_A_23(TARGET, A) +#define _DO_A_25(TARGET, A) TARGET(A, 25) _DO_A_24(TARGET, A) +#define _DO_A_26(TARGET, A) TARGET(A, 26) _DO_A_25(TARGET, A) +#define _DO_A_27(TARGET, A) TARGET(A, 27) _DO_A_26(TARGET, A) +#define _DO_A_28(TARGET, A) TARGET(A, 28) _DO_A_27(TARGET, A) +#define _DO_A_29(TARGET, A) TARGET(A, 29) _DO_A_28(TARGET, A) +#define _DO_A_30(TARGET, A) TARGET(A, 30) _DO_A_29(TARGET, A) +#define _DO_A_31(TARGET, A) TARGET(A, 31) _DO_A_30(TARGET, A) +#define _DO_A_32(TARGET, A) TARGET(A, 32) _DO_A_31(TARGET, A) + +#define _DO_1_B(TARGET, B_RANGE) _DO_A_##B_RANGE(TARGET, 1) +#define _DO_2_B(TARGET, B_RANGE) _DO_A_##B_RANGE(TARGET, 2) _DO_1_B(TARGET, B_RANGE) +#define _DO_3_B(TARGET, B_RANGE) _DO_A_##B_RANGE(TARGET, 3) _DO_2_B(TARGET, B_RANGE) +#define _DO_4_B(TARGET, B_RANGE) _DO_A_##B_RANGE(TARGET, 4) _DO_3_B(TARGET, B_RANGE) +#define _DO_5_B(TARGET, B_RANGE) _DO_A_##B_RANGE(TARGET, 5) _DO_4_B(TARGET, B_RANGE) +#define _DO_6_B(TARGET, B_RANGE) _DO_A_##B_RANGE(TARGET, 6) _DO_5_B(TARGET, B_RANGE) +#define _DO_7_B(TARGET, B_RANGE) _DO_A_##B_RANGE(TARGET, 7) _DO_6_B(TARGET, B_RANGE) +#define _DO_8_B(TARGET, B_RANGE) _DO_A_##B_RANGE(TARGET, 8) _DO_7_B(TARGET, B_RANGE) +#define _DO_9_B(TARGET, B_RANGE) _DO_A_##B_RANGE(TARGET, 9) _DO_8_B(TARGET, B_RANGE) +#define _DO_10_B(TARGET, B_RANGE) _DO_A_##B_RANGE(TARGET, 10) _DO_9_B(TARGET, B_RANGE) +#define _DO_11_B(TARGET, B_RANGE) _DO_A_##B_RANGE(TARGET, 11) _DO_10_B(TARGET, B_RANGE) +#define _DO_12_B(TARGET, B_RANGE) _DO_A_##B_RANGE(TARGET, 12) _DO_11_B(TARGET, B_RANGE) +#define _DO_13_B(TARGET, B_RANGE) _DO_A_##B_RANGE(TARGET, 13) _DO_12_B(TARGET, B_RANGE) +#define _DO_14_B(TARGET, B_RANGE) _DO_A_##B_RANGE(TARGET, 14) _DO_13_B(TARGET, B_RANGE) +#define _DO_15_B(TARGET, B_RANGE) _DO_A_##B_RANGE(TARGET, 15) _DO_14_B(TARGET, B_RANGE) +#define _DO_16_B(TARGET, B_RANGE) _DO_A_##B_RANGE(TARGET, 16) _DO_15_B(TARGET, B_RANGE) +#define _DO_17_B(TARGET, B_RANGE) _DO_A_##B_RANGE(TARGET, 17) _DO_16_B(TARGET, B_RANGE) +#define _DO_18_B(TARGET, B_RANGE) _DO_A_##B_RANGE(TARGET, 18) _DO_17_B(TARGET, B_RANGE) +#define _DO_19_B(TARGET, B_RANGE) _DO_A_##B_RANGE(TARGET, 19) _DO_18_B(TARGET, B_RANGE) +#define _DO_20_B(TARGET, B_RANGE) _DO_A_##B_RANGE(TARGET, 20) _DO_19_B(TARGET, B_RANGE) +#define _DO_21_B(TARGET, B_RANGE) _DO_A_##B_RANGE(TARGET, 21) _DO_20_B(TARGET, B_RANGE) +#define _DO_22_B(TARGET, B_RANGE) _DO_A_##B_RANGE(TARGET, 22) _DO_21_B(TARGET, B_RANGE) +#define _DO_23_B(TARGET, B_RANGE) _DO_A_##B_RANGE(TARGET, 23) _DO_22_B(TARGET, B_RANGE) +#define _DO_24_B(TARGET, B_RANGE) _DO_A_##B_RANGE(TARGET, 24) _DO_23_B(TARGET, B_RANGE) +#define _DO_25_B(TARGET, B_RANGE) _DO_A_##B_RANGE(TARGET, 25) _DO_24_B(TARGET, B_RANGE) +#define _DO_26_B(TARGET, B_RANGE) _DO_A_##B_RANGE(TARGET, 26) _DO_25_B(TARGET, B_RANGE) +#define _DO_27_B(TARGET, B_RANGE) _DO_A_##B_RANGE(TARGET, 27) _DO_26_B(TARGET, B_RANGE) +#define _DO_28_B(TARGET, B_RANGE) _DO_A_##B_RANGE(TARGET, 28) _DO_27_B(TARGET, B_RANGE) +#define _DO_29_B(TARGET, B_RANGE) _DO_A_##B_RANGE(TARGET, 29) _DO_28_B(TARGET, B_RANGE) +#define _DO_30_B(TARGET, B_RANGE) _DO_A_##B_RANGE(TARGET, 30) _DO_29_B(TARGET, B_RANGE) +#define _DO_31_B(TARGET, B_RANGE) _DO_A_##B_RANGE(TARGET, 31) _DO_30_B(TARGET, B_RANGE) +#define _DO_32_B(TARGET, B_RANGE) _DO_A_##B_RANGE(TARGET, 32) _DO_31_B(TARGET, B_RANGE) + +#define _CASE_A(A) \ + case (A): \ + CASE(A) break; +#define _CASE_AB(A, B) \ + case (A * 100 + B): \ + CASE(A, B) break; + +// Preproccessor For Loops +#define DO_FOR_A(TARGET, A_RANGE) _DO_##A_RANGE(TARGET) +#define DO_FOR_AB(TARGET, A_RANGE, B_RANGE) _DO_##A_RANGE##_B(TARGET, B_RANGE) + +// Preproccessor Switch Statement Generators +#define SWITCH_A(CASE, A_RANGE, A) \ + switch (A) { DO_FOR_A(_CASE_A, A_RANGE) } +#define SWITCH_AB(CALL, A_RANGE, B_RANGE, A, B) \ + switch (A * 100 + B) { DO_FOR_AB(_CASE_AB, A_RANGE, B_RANGE) } diff --git a/source_code/SegMamba/monai/fl/client/__init__.py b/source_code/SegMamba/monai/fl/client/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e9f1ab86011c095b576038a4d8f770f0d0aa3e98 --- /dev/null +++ b/source_code/SegMamba/monai/fl/client/__init__.py @@ -0,0 +1,15 @@ +# Copyright (c) MONAI Consortium +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from __future__ import annotations + +from .client_algo import BaseClient, ClientAlgo, ClientAlgoStats +from .monai_algo import MonaiAlgo, MonaiAlgoStats diff --git a/source_code/SegMamba/monai/fl/utils/constants.py b/source_code/SegMamba/monai/fl/utils/constants.py new file mode 100644 index 0000000000000000000000000000000000000000..eda1a6b4f9127f2c3458cf7a429ecfee3b9d1d1b --- /dev/null +++ b/source_code/SegMamba/monai/fl/utils/constants.py @@ -0,0 +1,59 @@ +# Copyright (c) MONAI Consortium +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from __future__ import annotations + +from monai.utils.enums import StrEnum + + +class WeightType(StrEnum): + WEIGHTS = "fl_weights_full" + WEIGHT_DIFF = "fl_weight_diff" + + +class ModelType(StrEnum): + BEST_MODEL = "fl_best_model" + FINAL_MODEL = "fl_final_model" + + +class ExtraItems(StrEnum): + ABORT = "fl_abort" + MODEL_TYPE = "fl_model_type" + CLIENT_NAME = "fl_client_name" + APP_ROOT = "fl_app_root" + STATS_SENDER = "fl_stats_sender" + + +class FlPhase(StrEnum): + IDLE = "fl_idle" + TRAIN = "fl_train" + EVALUATE = "fl_evaluate" + GET_WEIGHTS = "fl_get_weights" + GET_DATA_STATS = "fl_get_data_stats" + + +class FlStatistics(StrEnum): + NUM_EXECUTED_ITERATIONS = "num_executed_iterations" + STATISTICS = "statistics" + HIST_BINS = "hist_bins" + HIST_RANGE = "hist_range" + DATA_STATS = "data_stats" + DATA_COUNT = "data_count" + FAIL_COUNT = "fail_count" + TOTAL_DATA = "total_data" + FEATURE_NAMES = "feature_names" + + +class FiltersType(StrEnum): + PRE_FILTERS = "pre_filters" + POST_WEIGHT_FILTERS = "post_weight_filters" + POST_EVALUATE_FILTERS = "post_evaluate_filters" + POST_STATISTICS_FILTERS = "post_statistics_filters" diff --git a/source_code/SegMamba/monai/fl/utils/exchange_object.py b/source_code/SegMamba/monai/fl/utils/exchange_object.py new file mode 100644 index 0000000000000000000000000000000000000000..b895d2d53e3a98944a18bddee82978b47e6513ad --- /dev/null +++ b/source_code/SegMamba/monai/fl/utils/exchange_object.py @@ -0,0 +1,107 @@ +# Copyright (c) MONAI Consortium +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from __future__ import annotations + +from monai.fl.utils.constants import WeightType + + +class ExchangeObject(dict): + """ + Contains the information shared between client and server. + + Args: + weights: model weights. + optim: optimizer weights. + metrics: evaluation metrics. + weight_type: type of weights (see monai.fl.utils.constants.WeightType). + statistics: training statistics, i.e. number executed iterations. + """ + + def __init__( + self, + weights: dict | None = None, + optim: dict | None = None, + metrics: dict | None = None, + weight_type: WeightType | None = None, + statistics: dict | None = None, + ): + super().__init__() + self.weights = weights + self.optim = optim + self.metrics = metrics + self.weight_type = weight_type + self.statistics = statistics + self._summary: dict = {} + + @property + def metrics(self): + return self._metrics + + @metrics.setter + def metrics(self, metrics): + if metrics is not None: + if not isinstance(metrics, dict): + raise ValueError(f"Expected metrics to be of type dict but received {type(metrics)}") + self._metrics = metrics + + @property + def statistics(self): + return self._statistics + + @statistics.setter + def statistics(self, statistics): + if statistics is not None: + if not isinstance(statistics, dict): + raise ValueError(f"Expected statistics to be of type dict but received {type(statistics)}") + self._statistics = statistics + + @property + def weight_type(self): + return self._weight_type + + @weight_type.setter + def weight_type(self, weight_type): + if weight_type is not None: + if weight_type not in [WeightType.WEIGHTS, WeightType.WEIGHT_DIFF]: + raise ValueError(f"Expected weight type to be either {WeightType.WEIGHTS} or {WeightType.WEIGHT_DIFF}") + self._weight_type = weight_type + + def is_valid_weights(self): + if not self.weights: + return False + if not self.weight_type: + return False + return True + + def _add_to_summary(self, key, value): + if value: + if isinstance(value, dict): + self._summary[key] = len(value) + elif isinstance(value, WeightType): + self._summary[key] = value + else: + self._summary[key] = type(value) + + def summary(self): + self._summary.update(self) + for k, v in zip( + ["weights", "optim", "metrics", "weight_type", "statistics"], + [self.weights, self.optim, self.metrics, self.weight_type, self.statistics], + ): + self._add_to_summary(k, v) + return self._summary + + def __repr__(self): + return str(self.summary()) + + def __str__(self): + return str(self.summary()) diff --git a/source_code/SegMamba/monai/handlers/hausdorff_distance.py b/source_code/SegMamba/monai/handlers/hausdorff_distance.py new file mode 100644 index 0000000000000000000000000000000000000000..669bf3006847b4110ee8978a9980513d52016e0b --- /dev/null +++ b/source_code/SegMamba/monai/handlers/hausdorff_distance.py @@ -0,0 +1,67 @@ +# Copyright (c) MONAI Consortium +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from __future__ import annotations + +from collections.abc import Callable + +from monai.handlers.ignite_metric import IgniteMetricHandler +from monai.metrics import HausdorffDistanceMetric +from monai.utils import MetricReduction + + +class HausdorffDistance(IgniteMetricHandler): + """ + Computes Hausdorff distance from full size Tensor and collects average over batch, class-channels, iterations. + """ + + def __init__( + self, + include_background: bool = False, + distance_metric: str = "euclidean", + percentile: float | None = None, + directed: bool = False, + reduction: MetricReduction | str = MetricReduction.MEAN, + output_transform: Callable = lambda x: x, + save_details: bool = True, + ) -> None: + """ + + Args: + include_background: whether to include distance computation on the first channel of the predicted output. + Defaults to ``False``. + distance_metric: : [``"euclidean"``, ``"chessboard"``, ``"taxicab"``] + the metric used to compute surface distance. Defaults to ``"euclidean"``. + percentile: an optional float number between 0 and 100. If specified, the corresponding + percentile of the Hausdorff Distance rather than the maximum result will be achieved. + Defaults to ``None``. + directed: whether to calculate directed Hausdorff distance. Defaults to ``False``. + reduction: define the mode to reduce metrics, will only execute reduction on `not-nan` values, + available reduction modes: {``"none"``, ``"mean"``, ``"sum"``, ``"mean_batch"``, ``"sum_batch"``, + ``"mean_channel"``, ``"sum_channel"``}, default to ``"mean"``. if "none", will not do reduction. + output_transform: callable to extract `y_pred` and `y` from `ignite.engine.state.output` then + construct `(y_pred, y)` pair, where `y_pred` and `y` can be `batch-first` Tensors or + lists of `channel-first` Tensors. the form of `(y_pred, y)` is required by the `update()`. + `engine.state` and `output_transform` inherit from the ignite concept: + https://pytorch.org/ignite/concepts.html#state, explanation and usage example are in the tutorial: + https://github.com/Project-MONAI/tutorials/blob/master/modules/batch_output_transform.ipynb. + save_details: whether to save metric computation details per image, for example: hausdorff distance + of every image. default to True, will save to `engine.state.metric_details` dict with the metric name as key. + + """ + metric_fn = HausdorffDistanceMetric( + include_background=include_background, + distance_metric=distance_metric, + percentile=percentile, + directed=directed, + reduction=reduction, + ) + super().__init__(metric_fn=metric_fn, output_transform=output_transform, save_details=save_details) diff --git a/source_code/SegMamba/monai/handlers/tensorboard_handlers.py b/source_code/SegMamba/monai/handlers/tensorboard_handlers.py new file mode 100644 index 0000000000000000000000000000000000000000..7b7e3968fb36ab5a09afbadad27c695f0c1cbce3 --- /dev/null +++ b/source_code/SegMamba/monai/handlers/tensorboard_handlers.py @@ -0,0 +1,454 @@ +# Copyright (c) MONAI Consortium +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from __future__ import annotations + +import warnings +from collections.abc import Callable, Sequence +from typing import TYPE_CHECKING, Any + +import numpy as np +import torch + +from monai.config import IgniteInfo +from monai.utils import is_scalar, min_version, optional_import +from monai.visualize import plot_2d_or_3d_image + +Events, _ = optional_import("ignite.engine", IgniteInfo.OPT_IMPORT_VERSION, min_version, "Events") + +if TYPE_CHECKING: + from ignite.engine import Engine + from tensorboardX import SummaryWriter as SummaryWriterX + from torch.utils.tensorboard import SummaryWriter +else: + Engine, _ = optional_import( + "ignite.engine", IgniteInfo.OPT_IMPORT_VERSION, min_version, "Engine", as_type="decorator" + ) + SummaryWriter, _ = optional_import("torch.utils.tensorboard", name="SummaryWriter") + SummaryWriterX, _ = optional_import("tensorboardX", name="SummaryWriter") + +DEFAULT_TAG = "Loss" + + +class TensorBoardHandler: + """ + Base class for the handlers to write data into TensorBoard. + + Args: + summary_writer: user can specify TensorBoard or TensorBoardX SummaryWriter, + default to create a new TensorBoard writer. + log_dir: if using default SummaryWriter, write logs to this directory, default is `./runs`. + + """ + + def __init__(self, summary_writer: SummaryWriter | SummaryWriterX | None = None, log_dir: str = "./runs"): + if summary_writer is None: + self._writer = SummaryWriter(log_dir=log_dir) + self.internal_writer = True + else: + self._writer = summary_writer + self.internal_writer = False + + def attach(self, engine: Engine) -> None: + raise NotImplementedError(f"Subclass {self.__class__.__name__} must implement this method.") + + def close(self): + """ + Close the summary writer if created in this TensorBoard handler. + + """ + if self.internal_writer: + self._writer.close() + + +class TensorBoardStatsHandler(TensorBoardHandler): + """ + TensorBoardStatsHandler defines a set of Ignite Event-handlers for all the TensorBoard logics. + It can be used for any Ignite Engine(trainer, validator and evaluator). + And it can support both epoch level and iteration level with pre-defined TensorBoard event writer. + The expected data source is Ignite ``engine.state.output`` and ``engine.state.metrics``. + + Default behaviors: + - When EPOCH_COMPLETED, write each dictionary item in + ``engine.state.metrics`` to TensorBoard. + - When ITERATION_COMPLETED, write each dictionary item in + ``self.output_transform(engine.state.output)`` to TensorBoard. + + Usage example is available in the tutorial: + https://github.com/Project-MONAI/tutorials/blob/master/3d_segmentation/unet_segmentation_3d_ignite.ipynb. + + """ + + def __init__( + self, + summary_writer: SummaryWriter | SummaryWriterX | None = None, + log_dir: str = "./runs", + iteration_log: bool | Callable[[Engine, int], bool] | int = True, + epoch_log: bool | Callable[[Engine, int], bool] | int = True, + epoch_event_writer: Callable[[Engine, Any], Any] | None = None, + iteration_event_writer: Callable[[Engine, Any], Any] | None = None, + output_transform: Callable = lambda x: x[0], + global_epoch_transform: Callable = lambda x: x, + state_attributes: Sequence[str] | None = None, + tag_name: str = DEFAULT_TAG, + ) -> None: + """ + Args: + summary_writer: user can specify TensorBoard or TensorBoardX SummaryWriter, + default to create a new TensorBoard writer. + log_dir: if using default SummaryWriter, write logs to this directory, default is `./runs`. + iteration_log: whether to write data to TensorBoard when iteration completed, default to `True`. + ``iteration_log`` can be also a function or int. If it is an int, it will be interpreted as the iteration interval + at which the iteration_event_writer is called. If it is a function, it will be interpreted as an event filter + (see https://pytorch.org/ignite/generated/ignite.engine.events.Events.html for details). + Event filter function accepts as input engine and event value (iteration) and should return True/False. + epoch_log: whether to write data to TensorBoard when epoch completed, default to `True`. + ``epoch_log`` can be also a function or int. If it is an int, it will be interpreted as the epoch interval + at which the epoch_event_writer is called. If it is a function, it will be interpreted as an event filter. + See ``iteration_log`` argument for more details. + epoch_event_writer: customized callable TensorBoard writer for epoch level. + Must accept parameter "engine" and "summary_writer", use default event writer if None. + iteration_event_writer: customized callable TensorBoard writer for iteration level. + Must accept parameter "engine" and "summary_writer", use default event writer if None. + output_transform: a callable that is used to transform the + ``ignite.engine.state.output`` into a scalar to plot, or a dictionary of {key: scalar}. + In the latter case, the output string will be formatted as key: value. + By default this value plotting happens when every iteration completed. + The default behavior is to print loss from output[0] as output is a decollated list + and we replicated loss value for every item of the decollated list. + `engine.state` and `output_transform` inherit from the ignite concept: + https://pytorch.org/ignite/concepts.html#state, explanation and usage example are in the tutorial: + https://github.com/Project-MONAI/tutorials/blob/master/modules/batch_output_transform.ipynb. + global_epoch_transform: a callable that is used to customize global epoch number. + For example, in evaluation, the evaluator engine might want to use trainer engines epoch number + when plotting epoch vs metric curves. + state_attributes: expected attributes from `engine.state`, if provided, will extract them + when epoch completed. + tag_name: when iteration output is a scalar, tag_name is used to plot, defaults to ``'Loss'``. + """ + + super().__init__(summary_writer=summary_writer, log_dir=log_dir) + self.iteration_log = iteration_log + self.epoch_log = epoch_log + self.epoch_event_writer = epoch_event_writer + self.iteration_event_writer = iteration_event_writer + self.output_transform = output_transform + self.global_epoch_transform = global_epoch_transform + self.state_attributes = state_attributes + self.tag_name = tag_name + + def attach(self, engine: Engine) -> None: + """ + Register a set of Ignite Event-Handlers to a specified Ignite engine. + + Args: + engine: Ignite Engine, it can be a trainer, validator or evaluator. + + """ + if self.iteration_log and not engine.has_event_handler(self.iteration_completed, Events.ITERATION_COMPLETED): + event = Events.ITERATION_COMPLETED + if callable(self.iteration_log): # substitute event with new one using filter callable + event = event(event_filter=self.iteration_log) + elif self.iteration_log > 1: + event = event(every=self.iteration_log) + engine.add_event_handler(event, self.iteration_completed) + if self.epoch_log and not engine.has_event_handler(self.epoch_completed, Events.EPOCH_COMPLETED): + event = Events.EPOCH_COMPLETED + if callable(self.epoch_log): # substitute event with new one using filter callable + event = event(event_filter=self.epoch_log) + elif self.epoch_log > 1: + event = event(every=self.epoch_log) + engine.add_event_handler(event, self.epoch_completed) + + def epoch_completed(self, engine: Engine) -> None: + """ + Handler for train or validation/evaluation epoch completed Event. + Write epoch level events, default values are from Ignite `engine.state.metrics` dict. + + Args: + engine: Ignite Engine, it can be a trainer, validator or evaluator. + + """ + if self.epoch_event_writer is not None: + self.epoch_event_writer(engine, self._writer) + else: + self._default_epoch_writer(engine, self._writer) + + def iteration_completed(self, engine: Engine) -> None: + """ + Handler for train or validation/evaluation iteration completed Event. + Write iteration level events, default values are from Ignite `engine.state.output`. + + Args: + engine: Ignite Engine, it can be a trainer, validator or evaluator. + + """ + if self.iteration_event_writer is not None: + self.iteration_event_writer(engine, self._writer) + else: + self._default_iteration_writer(engine, self._writer) + + def _write_scalar( + self, _engine: Engine, writer: SummaryWriter | SummaryWriterX, tag: str, value: Any, step: int + ) -> None: + """ + Write scale value into TensorBoard. + Default to call `SummaryWriter.add_scalar()`. + + Args: + _engine: Ignite Engine, unused argument. + writer: TensorBoard or TensorBoardX writer, passed or created in TensorBoardHandler. + tag: tag name in the TensorBoard. + value: value of the scalar data for current step. + step: index of current step. + + """ + writer.add_scalar(tag, value, step) + + def _default_epoch_writer(self, engine: Engine, writer: SummaryWriter | SummaryWriterX) -> None: + """ + Execute epoch level event write operation. + Default to write the values from Ignite `engine.state.metrics` dict and + write the values of specified attributes of `engine.state`. + + Args: + engine: Ignite Engine, it can be a trainer, validator or evaluator. + writer: TensorBoard or TensorBoardX writer, passed or created in TensorBoardHandler. + + """ + current_epoch = self.global_epoch_transform(engine.state.epoch) + summary_dict = engine.state.metrics + for name, value in summary_dict.items(): + if is_scalar(value): + self._write_scalar(engine, writer, name, value, current_epoch) + + if self.state_attributes is not None: + for attr in self.state_attributes: + self._write_scalar(engine, writer, attr, getattr(engine.state, attr, None), current_epoch) + writer.flush() + + def _default_iteration_writer(self, engine: Engine, writer: SummaryWriter | SummaryWriterX) -> None: + """ + Execute iteration level event write operation based on Ignite `engine.state.output` data. + Extract the values from `self.output_transform(engine.state.output)`. + Since `engine.state.output` is a decollated list and we replicated the loss value for every item + of the decollated list, the default behavior is to track the loss from `output[0]`. + + Args: + engine: Ignite Engine, it can be a trainer, validator or evaluator. + writer: TensorBoard or TensorBoardX writer, passed or created in TensorBoardHandler. + + """ + loss = self.output_transform(engine.state.output) + if loss is None: + return # do nothing if output is empty + if isinstance(loss, dict): + for name in sorted(loss): + value = loss[name] + if not is_scalar(value): + warnings.warn( + "ignoring non-scalar output in TensorBoardStatsHandler," + " make sure `output_transform(engine.state.output)` returns" + " a scalar or dictionary of key and scalar pairs to avoid this warning." + " {}:{}".format(name, type(value)) + ) + continue # not plot multi dimensional output + self._write_scalar( + _engine=engine, + writer=writer, + tag=name, + value=value.item() if isinstance(value, torch.Tensor) else value, + step=engine.state.iteration, + ) + elif is_scalar(loss): # not printing multi dimensional output + self._write_scalar( + _engine=engine, + writer=writer, + tag=self.tag_name, + value=loss.item() if isinstance(loss, torch.Tensor) else loss, + step=engine.state.iteration, + ) + else: + warnings.warn( + "ignoring non-scalar output in TensorBoardStatsHandler," + " make sure `output_transform(engine.state.output)` returns" + " a scalar or a dictionary of key and scalar pairs to avoid this warning." + " {}".format(type(loss)) + ) + writer.flush() + + +class TensorBoardImageHandler(TensorBoardHandler): + """ + TensorBoardImageHandler is an Ignite Event handler that can visualize images, labels and outputs as 2D/3D images. + 2D output (shape in Batch, channel, H, W) will be shown as simple image using the first element in the batch, + for 3D to ND output (shape in Batch, channel, H, W, D) input, each of ``self.max_channels`` number of images' + last three dimensions will be shown as animated GIF along the last axis (typically Depth). + And if writer is from TensorBoardX, data has 3 channels and `max_channels=3`, will plot as RGB video. + + It can be used for any Ignite Engine (trainer, validator and evaluator). + User can easily add it to engine for any expected Event, for example: ``EPOCH_COMPLETED``, + ``ITERATION_COMPLETED``. The expected data source is ignite's ``engine.state.batch`` and ``engine.state.output``. + + Default behavior: + - Show y_pred as images (GIF for 3D) on TensorBoard when Event triggered, + - Need to use ``batch_transform`` and ``output_transform`` to specify + how many images to show and show which channel. + - Expects ``batch_transform(engine.state.batch)`` to return data + format: (image[N, channel, ...], label[N, channel, ...]). + - Expects ``output_transform(engine.state.output)`` to return a torch + tensor in format (y_pred[N, channel, ...], loss). + + Usage example is available in the tutorial: + https://github.com/Project-MONAI/tutorials/blob/master/3d_segmentation/unet_segmentation_3d_ignite.ipynb. + + """ + + def __init__( + self, + summary_writer: SummaryWriter | SummaryWriterX | None = None, + log_dir: str = "./runs", + interval: int = 1, + epoch_level: bool = True, + batch_transform: Callable = lambda x: x, + output_transform: Callable = lambda x: x, + global_iter_transform: Callable = lambda x: x, + index: int = 0, + max_channels: int = 1, + frame_dim: int = -3, + max_frames: int = 64, + ) -> None: + """ + Args: + summary_writer: user can specify TensorBoard or TensorBoardX SummaryWriter, + default to create a new TensorBoard writer. + log_dir: if using default SummaryWriter, write logs to this directory, default is `./runs`. + interval: plot content from engine.state every N epochs or every N iterations, default is 1. + epoch_level: plot content from engine.state every N epochs or N iterations. `True` is epoch level, + `False` is iteration level. + batch_transform: a callable that is used to extract `image` and `label` from `ignite.engine.state.batch`, + then construct `(image, label)` pair. for example: if `ignite.engine.state.batch` is `{"image": xxx, + "label": xxx, "other": xxx}`, `batch_transform` can be `lambda x: (x["image"], x["label"])`. + will use the result to plot image from `result[0][index]` and plot label from `result[1][index]`. + `engine.state` and `batch_transform` inherit from the ignite concept: + https://pytorch.org/ignite/concepts.html#state, explanation and usage example are in the tutorial: + https://github.com/Project-MONAI/tutorials/blob/master/modules/batch_output_transform.ipynb. + output_transform: a callable that is used to extract the `predictions` data from + `ignite.engine.state.output`, will use the result to plot output from `result[index]`. + `engine.state` and `output_transform` inherit from the ignite concept: + https://pytorch.org/ignite/concepts.html#state, explanation and usage example are in the tutorial: + https://github.com/Project-MONAI/tutorials/blob/master/modules/batch_output_transform.ipynb. + global_iter_transform: a callable that is used to customize global step number for TensorBoard. + For example, in evaluation, the evaluator engine needs to know current epoch from trainer. + index: plot which element in a data batch, default is the first element. + max_channels: number of channels to plot. + frame_dim: if plotting 3D image as GIF, specify the dimension used as frames, + expect input data shape as `NCHWD`, default to `-3` (the first spatial dim) + max_frames: if plot 3D RGB image as video in TensorBoardX, set the FPS to `max_frames`. + """ + super().__init__(summary_writer=summary_writer, log_dir=log_dir) + self.interval = interval + self.epoch_level = epoch_level + self.batch_transform = batch_transform + self.output_transform = output_transform + self.global_iter_transform = global_iter_transform + self.index = index + self.frame_dim = frame_dim + self.max_frames = max_frames + self.max_channels = max_channels + + def attach(self, engine: Engine) -> None: + """ + Args: + engine: Ignite Engine, it can be a trainer, validator or evaluator. + """ + if self.epoch_level: + engine.add_event_handler(Events.EPOCH_COMPLETED(every=self.interval), self) + else: + engine.add_event_handler(Events.ITERATION_COMPLETED(every=self.interval), self) + + def __call__(self, engine: Engine) -> None: + """ + Args: + engine: Ignite Engine, it can be a trainer, validator or evaluator. + + Raises: + TypeError: When ``output_transform(engine.state.output)[0]`` type is not in + ``Optional[Union[numpy.ndarray, torch.Tensor]]``. + TypeError: When ``batch_transform(engine.state.batch)[1]`` type is not in + ``Optional[Union[numpy.ndarray, torch.Tensor]]``. + TypeError: When ``output_transform(engine.state.output)`` type is not in + ``Optional[Union[numpy.ndarray, torch.Tensor]]``. + + """ + step = self.global_iter_transform(engine.state.epoch if self.epoch_level else engine.state.iteration) + show_images = self.batch_transform(engine.state.batch)[0][self.index] + if isinstance(show_images, torch.Tensor): + show_images = show_images.detach().cpu().numpy() + if show_images is not None: + if not isinstance(show_images, np.ndarray): + raise TypeError( + "output_transform(engine.state.output)[0] must be None or one of " + f"(numpy.ndarray, torch.Tensor) but is {type(show_images).__name__}." + ) + plot_2d_or_3d_image( + # add batch dim and plot the first item + data=show_images[None], + step=step, + writer=self._writer, + index=0, + max_channels=self.max_channels, + frame_dim=self.frame_dim, + max_frames=self.max_frames, + tag="input_0", + ) + + show_labels = self.batch_transform(engine.state.batch)[1][self.index] + if isinstance(show_labels, torch.Tensor): + show_labels = show_labels.detach().cpu().numpy() + if show_labels is not None: + if not isinstance(show_labels, np.ndarray): + raise TypeError( + "batch_transform(engine.state.batch)[1] must be None or one of " + f"(numpy.ndarray, torch.Tensor) but is {type(show_labels).__name__}." + ) + plot_2d_or_3d_image( + data=show_labels[None], + step=step, + writer=self._writer, + index=0, + max_channels=self.max_channels, + frame_dim=self.frame_dim, + max_frames=self.max_frames, + tag="input_1", + ) + + show_outputs = self.output_transform(engine.state.output)[self.index] + if isinstance(show_outputs, torch.Tensor): + show_outputs = show_outputs.detach().cpu().numpy() + if show_outputs is not None: + if not isinstance(show_outputs, np.ndarray): + raise TypeError( + "output_transform(engine.state.output) must be None or one of " + f"(numpy.ndarray, torch.Tensor) but is {type(show_outputs).__name__}." + ) + plot_2d_or_3d_image( + data=show_outputs[None], + step=step, + writer=self._writer, + index=0, + max_channels=self.max_channels, + frame_dim=self.frame_dim, + max_frames=self.max_frames, + tag="output", + ) + + self._writer.flush() diff --git a/source_code/SegMamba/monai/inferers/inferer.py b/source_code/SegMamba/monai/inferers/inferer.py new file mode 100644 index 0000000000000000000000000000000000000000..0b4199938d297b638e75b05c077ff738fc079c9e --- /dev/null +++ b/source_code/SegMamba/monai/inferers/inferer.py @@ -0,0 +1,754 @@ +# Copyright (c) MONAI Consortium +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from __future__ import annotations + +import warnings +from abc import ABC, abstractmethod +from collections.abc import Callable, Iterable, Iterator, Mapping, Sequence +from pydoc import locate +from typing import Any + +import torch +import torch.nn as nn + +from monai.apps.utils import get_logger +from monai.data.meta_tensor import MetaTensor +from monai.data.thread_buffer import ThreadBuffer +from monai.inferers.merger import AvgMerger, Merger +from monai.inferers.splitter import Splitter +from monai.inferers.utils import compute_importance_map, sliding_window_inference +from monai.utils import BlendMode, PatchKeys, PytorchPadMode, ensure_tuple, optional_import +from monai.visualize import CAM, GradCAM, GradCAMpp + +logger = get_logger(__name__) + +__all__ = [ + "Inferer", + "PatchInferer", + "SimpleInferer", + "SlidingWindowInferer", + "SaliencyInferer", + "SliceInferer", + "SlidingWindowInfererAdapt", +] + + +class Inferer(ABC): + """ + A base class for model inference. + Extend this class to support operations during inference, e.g. a sliding window method. + + Example code:: + + device = torch.device("cuda:0") + transform = Compose([ToTensor(), LoadImage(image_only=True)]) + data = transform(img_path).to(device) + model = UNet(...).to(device) + inferer = SlidingWindowInferer(...) + + model.eval() + with torch.no_grad(): + pred = inferer(inputs=data, network=model) + ... + + """ + + @abstractmethod + def __call__(self, inputs: torch.Tensor, network: Callable, *args: Any, **kwargs: Any) -> Any: + """ + Run inference on `inputs` with the `network` model. + + Args: + inputs: input of the model inference. + network: model for inference. + args: optional args to be passed to ``network``. + kwargs: optional keyword args to be passed to ``network``. + + Raises: + NotImplementedError: When the subclass does not override this method. + + """ + raise NotImplementedError(f"Subclass {self.__class__.__name__} must implement this method.") + + +class PatchInferer(Inferer): + """ + Inference on patches instead of the whole image based on Splitter and Merger. + This splits the input image into patches and then merge the resulted patches. + + Args: + splitter: a `Splitter` object that split the inputs into patches. Defaults to None. + If not provided or None, the inputs are considered to be already split into patches. + In this case, the output `merged_shape` and the optional `cropped_shape` cannot be inferred + and should be explicitly provided. + merger_cls: a `Merger` subclass that can be instantiated to merges patch outputs. + It can also be a string that matches the name of a class inherited from `Merger` class. + Defaults to `AvgMerger`. + batch_size: batch size for patches. If the input tensor is already batched [BxCxWxH], + this adds additional batching [(Bp*B)xCxWpxHp] for inference on patches. + Defaults to 1. + preprocessing: a callable that process patches before the being fed to the network. + Defaults to None. + postprocessing: a callable that process the output of the network. + Defaults to None. + output_keys: if the network output is a dictionary, this defines the keys of + the output dictionary to be used for merging. + Defaults to None, where all the keys are used. + match_spatial_shape: whether to crop the output to match the input shape. Defaults to True. + buffer_size: number of patches to be held in the buffer with a separate thread for batch sampling. Defaults to 0. + merger_kwargs: arguments to be passed to `merger_cls` for instantiation. + `merged_shape` is calculated automatically based on the input shape and + the output patch shape unless it is passed here. + """ + + def __init__( + self, + splitter: Splitter | None = None, + merger_cls: type[Merger] | str = AvgMerger, + batch_size: int = 1, + preprocessing: Callable | None = None, + postprocessing: Callable | None = None, + output_keys: Sequence | None = None, + match_spatial_shape: bool = True, + buffer_size: int = 0, + **merger_kwargs: Any, + ) -> None: + Inferer.__init__(self) + # splitter + if not isinstance(splitter, (Splitter, type(None))): + if not isinstance(splitter, Splitter): + raise TypeError( + f"'splitter' should be a `Splitter` object that returns: " + "an iterable of pairs of (patch, location) or a MetaTensor that has `PatchKeys.LOCATION` metadata)." + f"{type(splitter)} is given." + ) + self.splitter = splitter + + # merger + if isinstance(merger_cls, str): + valid_merger_cls: type[Merger] + # search amongst implemented mergers in MONAI + valid_merger_cls, merger_found = optional_import("monai.inferers.merger", name=merger_cls) + if not merger_found: + # try to locate the requested merger class (with dotted path) + valid_merger_cls = locate(merger_cls) # type: ignore + if valid_merger_cls is None: + raise ValueError(f"The requested `merger_cls` ['{merger_cls}'] does not exist.") + merger_cls = valid_merger_cls + if not issubclass(merger_cls, Merger): + raise TypeError(f"'merger' should be a subclass of `Merger`, {merger_cls} is given.") + self.merger_cls = merger_cls + self.merger_kwargs = merger_kwargs + + # pre-processor (process patch before the network) + if preprocessing is not None and not callable(preprocessing): + raise TypeError(f"'preprocessing' should be a callable object, {type(preprocessing)} is given.") + self.preprocessing = preprocessing + + # post-processor (process the output of the network) + if postprocessing is not None and not callable(postprocessing): + raise TypeError(f"'postprocessing' should be a callable object, {type(postprocessing)} is given.") + self.postprocessing = postprocessing + + # batch size for patches + if batch_size < 1: + raise ValueError(f"`batch_size` must be a positive number, {batch_size} is given.") + self.batch_size = batch_size + + # model output keys + self.output_keys = output_keys + + # whether to crop the output to match the input shape + self.match_spatial_shape = match_spatial_shape + + # buffer size for multithreaded batch sampling + self.buffer_size = buffer_size + + def _batch_sampler( + self, patches: Iterable[tuple[torch.Tensor, Sequence[int]]] | MetaTensor + ) -> Iterator[tuple[torch.Tensor, Sequence, int]]: + """Generate batch of patches and locations + + Args: + patches: a tensor or list of tensors + + Yields: + A batch of patches (torch.Tensor or MetaTensor), a sequence of location tuples, and the batch size + """ + if isinstance(patches, MetaTensor): + total_size = len(patches) + for i in range(0, total_size, self.batch_size): + batch_size = min(self.batch_size, total_size - i) + yield patches[i : i + batch_size], patches[i : i + batch_size].meta[PatchKeys.LOCATION], batch_size # type: ignore + else: + buffer: Iterable | ThreadBuffer + if self.buffer_size > 0: + # Use multi-threading to sample patches with a buffer + buffer = ThreadBuffer(patches, buffer_size=self.buffer_size, timeout=0.1) + else: + buffer = patches + patch_batch: list[Any] = [None] * self.batch_size + location_batch: list[Any] = [None] * self.batch_size + idx_in_batch = 0 + for sample in buffer: + patch_batch[idx_in_batch] = sample[0] + location_batch[idx_in_batch] = sample[1] + idx_in_batch += 1 + if idx_in_batch == self.batch_size: + # concatenate batch of patches to create a tensor + yield torch.cat(patch_batch), location_batch, idx_in_batch + patch_batch = [None] * self.batch_size + location_batch = [None] * self.batch_size + idx_in_batch = 0 + if idx_in_batch > 0: + # concatenate batch of patches to create a tensor + yield torch.cat(patch_batch[:idx_in_batch]), location_batch, idx_in_batch + + def _ensure_tuple_outputs(self, outputs: Any) -> tuple: + if isinstance(outputs, dict): + if self.output_keys is None: + self.output_keys = list(outputs.keys()) # model's output keys + return tuple(outputs[k] for k in self.output_keys) + return ensure_tuple(outputs, wrap_array=True) + + def _run_inference(self, network: Callable, patch: torch.Tensor, *args: Any, **kwargs: Any) -> tuple: + # pre-process + if self.preprocessing: + patch = self.preprocessing(patch) + # inference + outputs = network(patch, *args, **kwargs) + # post-process + if self.postprocessing: + outputs = self.postprocessing(outputs) + # ensure we have a tuple of model outputs to support multiple outputs + return self._ensure_tuple_outputs(outputs) + + def _initialize_mergers(self, inputs, outputs, patches, batch_size): + in_patch = torch.chunk(patches, batch_size)[0] + mergers = [] + ratios = [] + for out_patch_batch in outputs: + out_patch = torch.chunk(out_patch_batch, batch_size)[0] + # calculate the ratio of input and output patch sizes + ratio = tuple(op / ip for ip, op in zip(in_patch.shape[2:], out_patch.shape[2:])) + + # calculate merged_shape and cropped_shape + merger_kwargs = self.merger_kwargs.copy() + cropped_shape, merged_shape = self._get_merged_shapes(inputs, out_patch, ratio) + if "merged_shape" not in merger_kwargs: + merger_kwargs["merged_shape"] = merged_shape + if merger_kwargs["merged_shape"] is None: + raise ValueError("`merged_shape` cannot be `None`.") + if "cropped_shape" not in merger_kwargs: + merger_kwargs["cropped_shape"] = cropped_shape + + # initialize the merger + merger = self.merger_cls(**merger_kwargs) + + # store mergers and input/output ratios + mergers.append(merger) + ratios.append(ratio) + + return mergers, ratios + + def _aggregate(self, outputs, locations, batch_size, mergers, ratios): + for output_patches, merger, ratio in zip(outputs, mergers, ratios): + # split batched output into individual patches and then aggregate + for in_loc, out_patch in zip(locations, torch.chunk(output_patches, batch_size)): + out_loc = [round(l * r) for l, r in zip(in_loc, ratio)] + merger.aggregate(out_patch, out_loc) + + def _get_merged_shapes(self, inputs, out_patch, ratio): + """Define the shape of merged tensors (non-padded and padded)""" + if self.splitter is None: + return None, None + + # input spatial shapes + original_spatial_shape = self.splitter.get_input_shape(inputs) + padded_spatial_shape = self.splitter.get_padded_shape(inputs) + + # output spatial shapes + output_spatial_shape = tuple(round(s * r) for s, r in zip(original_spatial_shape, ratio)) + padded_output_spatial_shape = tuple(round(s * r) for s, r in zip(padded_spatial_shape, ratio)) + + # output shapes + cropped_shape = out_patch.shape[:2] + output_spatial_shape + merged_shape = out_patch.shape[:2] + padded_output_spatial_shape + + if not self.match_spatial_shape: + cropped_shape = merged_shape + + return cropped_shape, merged_shape + + def __call__( + self, + inputs: torch.Tensor, + network: Callable[..., torch.Tensor | Sequence[torch.Tensor] | dict[Any, torch.Tensor]], + *args: Any, + **kwargs: Any, + ) -> Any: + """ + Args: + inputs: input data for inference, a torch.Tensor, representing an image or batch of images. + However if the data is already split, it can be fed by providing a list of tuple (patch, location), + or a MetaTensor that has metadata for `PatchKeys.LOCATION`. In both cases no splitter should be provided. + network: target model to execute inference. + supports callables such as ``lambda x: my_torch_model(x, additional_config)`` + args: optional args to be passed to ``network``. + kwargs: optional keyword args to be passed to ``network``. + + """ + patches_locations: Iterable[tuple[torch.Tensor, Sequence[int]]] | MetaTensor + if self.splitter is None: + # handle situations where the splitter is not provided + if isinstance(inputs, torch.Tensor): + if isinstance(inputs, MetaTensor): + if PatchKeys.LOCATION not in inputs.meta: + raise ValueError( + "`PatchKey.LOCATION` does not exists in `inputs.meta`. " + "If the inputs are already split into patches, the location of patches needs to be " + "provided as `PatchKey.LOCATION` metadata in a MetaTensor. " + "If the input is not already split, please provide `splitter`." + ) + else: + raise ValueError( + "`splitter` should be set if the input is not already split into patches. " + "For inputs that are split, the location of patches needs to be provided as " + "(image, location) pairs, or as `PatchKey.LOCATION` metadata in a MetaTensor. " + f"The provided inputs type is {type(inputs)}." + ) + patches_locations = inputs + else: + # apply splitter + patches_locations = self.splitter(inputs) + + ratios: list[float] = [] + mergers: list[Merger] = [] + for patches, locations, batch_size in self._batch_sampler(patches_locations): + # run inference + outputs = self._run_inference(network, patches, *args, **kwargs) + # initialize the mergers + if not mergers: + mergers, ratios = self._initialize_mergers(inputs, outputs, patches, batch_size) + # aggregate outputs + self._aggregate(outputs, locations, batch_size, mergers, ratios) + + # finalize the mergers and get the results + merged_outputs = [merger.finalize() for merger in mergers] + + # return according to the model output + if self.output_keys: + return dict(zip(self.output_keys, merged_outputs)) + if len(merged_outputs) == 1: + return merged_outputs[0] + return merged_outputs + + +class SimpleInferer(Inferer): + """ + SimpleInferer is the normal inference method that run model forward() directly. + Usage example can be found in the :py:class:`monai.inferers.Inferer` base class. + + """ + + def __init__(self) -> None: + Inferer.__init__(self) + + def __call__( + self, inputs: torch.Tensor, network: Callable[..., torch.Tensor], *args: Any, **kwargs: Any + ) -> torch.Tensor: + """Unified callable function API of Inferers. + + Args: + inputs: model input data for inference. + network: target model to execute inference. + supports callables such as ``lambda x: my_torch_model(x, additional_config)`` + args: optional args to be passed to ``network``. + kwargs: optional keyword args to be passed to ``network``. + + """ + return network(inputs, *args, **kwargs) + + +class SlidingWindowInferer(Inferer): + """ + Sliding window method for model inference, + with `sw_batch_size` windows for every model.forward(). + Usage example can be found in the :py:class:`monai.inferers.Inferer` base class. + + Args: + roi_size: the window size to execute SlidingWindow evaluation. + If it has non-positive components, the corresponding `inputs` size will be used. + if the components of the `roi_size` are non-positive values, the transform will use the + corresponding components of img size. For example, `roi_size=(32, -1)` will be adapted + to `(32, 64)` if the second spatial dimension size of img is `64`. + sw_batch_size: the batch size to run window slices. + overlap: Amount of overlap between scans along each spatial dimension, defaults to ``0.25``. + mode: {``"constant"``, ``"gaussian"``} + How to blend output of overlapping windows. Defaults to ``"constant"``. + + - ``"constant``": gives equal weight to all predictions. + - ``"gaussian``": gives less weight to predictions on edges of windows. + + sigma_scale: the standard deviation coefficient of the Gaussian window when `mode` is ``"gaussian"``. + Default: 0.125. Actual window sigma is ``sigma_scale`` * ``dim_size``. + When sigma_scale is a sequence of floats, the values denote sigma_scale at the corresponding + spatial dimensions. + padding_mode: {``"constant"``, ``"reflect"``, ``"replicate"``, ``"circular"``} + Padding mode when ``roi_size`` is larger than inputs. Defaults to ``"constant"`` + See also: https://pytorch.org/docs/stable/generated/torch.nn.functional.pad.html + cval: fill value for 'constant' padding mode. Default: 0 + sw_device: device for the window data. + By default the device (and accordingly the memory) of the `inputs` is used. + Normally `sw_device` should be consistent with the device where `predictor` is defined. + device: device for the stitched output prediction. + By default the device (and accordingly the memory) of the `inputs` is used. If for example + set to device=torch.device('cpu') the gpu memory consumption is less and independent of the + `inputs` and `roi_size`. Output is on the `device`. + progress: whether to print a tqdm progress bar. + cache_roi_weight_map: whether to precompute the ROI weight map. + cpu_thresh: when provided, dynamically switch to stitching on cpu (to save gpu memory) + when input image volume is larger than this threshold (in pixels/voxels). + Otherwise use ``"device"``. Thus, the output may end-up on either cpu or gpu. + buffer_steps: the number of sliding window iterations along the ``buffer_dim`` + to be buffered on ``sw_device`` before writing to ``device``. + (Typically, ``sw_device`` is ``cuda`` and ``device`` is ``cpu``.) + default is None, no buffering. For the buffer dim, when spatial size is divisible by buffer_steps*roi_size, + (i.e. no overlapping among the buffers) non_blocking copy may be automatically enabled for efficiency. + buffer_dim: the spatial dimension along which the buffers are created. + 0 indicates the first spatial dimension. Default is -1, the last spatial dimension. + with_coord: whether to pass the window coordinates to ``network``. Defaults to False. + If True, the ``network``'s 2nd input argument should accept the window coordinates. + + Note: + ``sw_batch_size`` denotes the max number of windows per network inference iteration, + not the batch size of inputs. + + """ + + def __init__( + self, + roi_size: Sequence[int] | int, + sw_batch_size: int = 1, + overlap: Sequence[float] | float = 0.25, + mode: BlendMode | str = BlendMode.CONSTANT, + sigma_scale: Sequence[float] | float = 0.125, + padding_mode: PytorchPadMode | str = PytorchPadMode.CONSTANT, + cval: float = 0.0, + sw_device: torch.device | str | None = None, + device: torch.device | str | None = None, + progress: bool = False, + cache_roi_weight_map: bool = False, + cpu_thresh: int | None = None, + buffer_steps: int | None = None, + buffer_dim: int = -1, + with_coord: bool = False, + ) -> None: + super().__init__() + self.roi_size = roi_size + self.sw_batch_size = sw_batch_size + self.overlap = overlap + self.mode: BlendMode = BlendMode(mode) + self.sigma_scale = sigma_scale + self.padding_mode = padding_mode + self.cval = cval + self.sw_device = sw_device + self.device = device + self.progress = progress + self.cpu_thresh = cpu_thresh + self.buffer_steps = buffer_steps + self.buffer_dim = buffer_dim + self.with_coord = with_coord + + # compute_importance_map takes long time when computing on cpu. We thus + # compute it once if it's static and then save it for future usage + self.roi_weight_map = None + try: + if cache_roi_weight_map and isinstance(roi_size, Sequence) and min(roi_size) > 0: # non-dynamic roi size + if device is None: + device = "cpu" + self.roi_weight_map = compute_importance_map( + ensure_tuple(self.roi_size), mode=mode, sigma_scale=sigma_scale, device=device + ) + if cache_roi_weight_map and self.roi_weight_map is None: + warnings.warn("cache_roi_weight_map=True, but cache is not created. (dynamic roi_size?)") + except BaseException as e: + raise RuntimeError( + f"roi size {self.roi_size}, mode={mode}, sigma_scale={sigma_scale}, device={device}\n" + "Seems to be OOM. Please try smaller patch size or mode='constant' instead of mode='gaussian'." + ) from e + + def __call__( + self, + inputs: torch.Tensor, + network: Callable[..., torch.Tensor | Sequence[torch.Tensor] | dict[Any, torch.Tensor]], + *args: Any, + **kwargs: Any, + ) -> torch.Tensor | tuple[torch.Tensor, ...] | dict[Any, torch.Tensor]: + """ + + Args: + inputs: model input data for inference. + network: target model to execute inference. + supports callables such as ``lambda x: my_torch_model(x, additional_config)`` + args: optional args to be passed to ``network``. + kwargs: optional keyword args to be passed to ``network``. + + """ + + device = kwargs.pop("device", self.device) + buffer_steps = kwargs.pop("buffer_steps", self.buffer_steps) + buffer_dim = kwargs.pop("buffer_dim", self.buffer_dim) + + if device is None and self.cpu_thresh is not None and inputs.shape[2:].numel() > self.cpu_thresh: + device = "cpu" # stitch in cpu memory if image is too large + + return sliding_window_inference( + inputs, + self.roi_size, + self.sw_batch_size, + network, + self.overlap, + self.mode, + self.sigma_scale, + self.padding_mode, + self.cval, + self.sw_device, + device, + self.progress, + self.roi_weight_map, + None, + buffer_steps, + buffer_dim, + self.with_coord, + *args, + **kwargs, + ) + + +class SlidingWindowInfererAdapt(SlidingWindowInferer): + """ + SlidingWindowInfererAdapt extends SlidingWindowInferer to automatically switch to buffered and then to CPU stitching, + when OOM on GPU. It also records a size of such large images to automatically + try CPU stitching for the next large image of a similar size. If the stitching 'device' input parameter is provided, + automatic adaptation won't be attempted, please keep the default option device = None for adaptive behavior. + Note: the output might be on CPU (even if the input was on GPU), if the GPU memory was not sufficient. + + """ + + def __call__( + self, + inputs: torch.Tensor, + network: Callable[..., torch.Tensor | Sequence[torch.Tensor] | dict[Any, torch.Tensor]], + *args: Any, + **kwargs: Any, + ) -> torch.Tensor | tuple[torch.Tensor, ...] | dict[Any, torch.Tensor]: + """ + + Args: + inputs: model input data for inference. + network: target model to execute inference. + supports callables such as ``lambda x: my_torch_model(x, additional_config)`` + args: optional args to be passed to ``network``. + kwargs: optional keyword args to be passed to ``network``. + + """ + + # if device is provided, use without any adaptations + if self.device is not None: + return super().__call__(inputs, network, *args, **kwargs) + + skip_buffer = self.buffer_steps is not None and self.buffer_steps <= 0 + cpu_cond = self.cpu_thresh is not None and inputs.shape[2:].numel() > self.cpu_thresh + gpu_stitching = inputs.is_cuda and not cpu_cond + buffered_stitching = inputs.is_cuda and cpu_cond and not skip_buffer + buffer_steps = max(1, self.buffer_steps) if self.buffer_steps is not None else 1 + buffer_dim = -1 + + sh = list(inputs.shape[2:]) + max_dim = sh.index(max(sh)) + if inputs.shape[max_dim + 2] / inputs.shape[-1] >= 2: + buffer_dim = max_dim + + for _ in range(10): # at most 10 trials + try: + return super().__call__( + inputs, + network, + *args, + device=inputs.device if gpu_stitching else torch.device("cpu"), + buffer_steps=buffer_steps if buffered_stitching else None, + buffer_dim=buffer_dim, + **kwargs, + ) + except RuntimeError as e: + if not gpu_stitching and not buffered_stitching or "OutOfMemoryError" not in str(type(e).__name__): + raise e + + logger.info(e) + + if gpu_stitching: # if failed on gpu + gpu_stitching = False + self.cpu_thresh = inputs.shape[2:].numel() - 1 # update thresh + + if skip_buffer: + buffered_stitching = False + logger.warning(f"GPU stitching failed, attempting on CPU, image dim {inputs.shape}.") + + else: + buffered_stitching = True + self.buffer_steps = buffer_steps + logger.warning( + f"GPU stitching failed, buffer {buffer_steps} dim {buffer_dim}, image dim {inputs.shape}." + ) + elif buffer_steps > 1: + buffer_steps = max(1, buffer_steps // 2) + self.buffer_steps = buffer_steps + logger.warning( + f"GPU buffered stitching failed, image dim {inputs.shape} reducing buffer to {buffer_steps}." + ) + else: + buffered_stitching = False + logger.warning(f"GPU buffered stitching failed, attempting on CPU, image dim {inputs.shape}.") + raise RuntimeError( # not possible to finish after the trials + f"SlidingWindowInfererAdapt {skip_buffer} {cpu_cond} {gpu_stitching} {buffered_stitching} {buffer_steps}" + ) + + +class SaliencyInferer(Inferer): + """ + SaliencyInferer is inference with activation maps. + + Args: + cam_name: expected CAM method name, should be: "CAM", "GradCAM" or "GradCAMpp". + target_layers: name of the model layer to generate the feature map. + class_idx: index of the class to be visualized. if None, default to argmax(logits). + args: other optional args to be passed to the `__init__` of cam. + kwargs: other optional keyword args to be passed to `__init__` of cam. + + """ + + def __init__( + self, cam_name: str, target_layers: str, class_idx: int | None = None, *args: Any, **kwargs: Any + ) -> None: + Inferer.__init__(self) + if cam_name.lower() not in ("cam", "gradcam", "gradcampp"): + raise ValueError("cam_name should be: 'CAM', 'GradCAM' or 'GradCAMpp'.") + self.cam_name = cam_name.lower() + self.target_layers = target_layers + self.class_idx = class_idx + self.args = args + self.kwargs = kwargs + + def __call__(self, inputs: torch.Tensor, network: nn.Module, *args: Any, **kwargs: Any): # type: ignore + """Unified callable function API of Inferers. + + Args: + inputs: model input data for inference. + network: target model to execute inference. + supports callables such as ``lambda x: my_torch_model(x, additional_config)`` + args: other optional args to be passed to the `__call__` of cam. + kwargs: other optional keyword args to be passed to `__call__` of cam. + + """ + cam: CAM | GradCAM | GradCAMpp + if self.cam_name == "cam": + cam = CAM(network, self.target_layers, *self.args, **self.kwargs) + elif self.cam_name == "gradcam": + cam = GradCAM(network, self.target_layers, *self.args, **self.kwargs) + else: + cam = GradCAMpp(network, self.target_layers, *self.args, **self.kwargs) + + return cam(inputs, self.class_idx, *args, **kwargs) + + +class SliceInferer(SlidingWindowInferer): + """ + SliceInferer extends SlidingWindowInferer to provide slice-by-slice (2D) inference when provided a 3D volume. + A typical use case could be a 2D model (like 2D segmentation UNet) operates on the slices from a 3D volume, + and the output is a 3D volume with 2D slices aggregated. Example:: + + # sliding over the `spatial_dim` + inferer = SliceInferer(roi_size=(64, 256), sw_batch_size=1, spatial_dim=1) + output = inferer(input_volume, net) + + Args: + spatial_dim: Spatial dimension over which the slice-by-slice inference runs on the 3D volume. + For example ``0`` could slide over axial slices. ``1`` over coronal slices and ``2`` over sagittal slices. + args: other optional args to be passed to the `__init__` of base class SlidingWindowInferer. + kwargs: other optional keyword args to be passed to `__init__` of base class SlidingWindowInferer. + + Note: + ``roi_size`` in SliceInferer is expected to be a 2D tuple when a 3D volume is provided. This allows + sliding across slices along the 3D volume using a selected ``spatial_dim``. + + """ + + def __init__(self, spatial_dim: int = 0, *args: Any, **kwargs: Any) -> None: + self.spatial_dim = spatial_dim + super().__init__(*args, **kwargs) + self.orig_roi_size = ensure_tuple(self.roi_size) + + def __call__( + self, + inputs: torch.Tensor, + network: Callable[..., torch.Tensor | Sequence[torch.Tensor] | dict[Any, torch.Tensor]], + *args: Any, + **kwargs: Any, + ) -> torch.Tensor | tuple[torch.Tensor, ...] | dict[Any, torch.Tensor]: + """ + Args: + inputs: 3D input for inference + network: 2D model to execute inference on slices in the 3D input + args: optional args to be passed to ``network``. + kwargs: optional keyword args to be passed to ``network``. + """ + if self.spatial_dim > 2: + raise ValueError("`spatial_dim` can only be `0, 1, 2` with `[H, W, D]` respectively.") + + # Check if ``roi_size`` tuple is 2D and ``inputs`` tensor is 3D + self.roi_size = ensure_tuple(self.roi_size) + if len(self.orig_roi_size) == 2 and len(inputs.shape[2:]) == 3: + self.roi_size = list(self.orig_roi_size) + self.roi_size.insert(self.spatial_dim, 1) + else: + raise RuntimeError( + f"Currently, only 2D `roi_size` ({self.orig_roi_size}) with 3D `inputs` tensor (shape={inputs.shape}) is supported." + ) + + return super().__call__(inputs=inputs, network=lambda x: self.network_wrapper(network, x, *args, **kwargs)) + + def network_wrapper( + self, + network: Callable[..., torch.Tensor | Sequence[torch.Tensor] | dict[Any, torch.Tensor]], + x: torch.Tensor, + *args: Any, + **kwargs: Any, + ) -> torch.Tensor | tuple[torch.Tensor, ...] | dict[Any, torch.Tensor]: + """ + Wrapper handles inference for 2D models over 3D volume inputs. + """ + # Pass 4D input [N, C, H, W]/[N, C, D, W]/[N, C, D, H] to the model as it is 2D. + x = x.squeeze(dim=self.spatial_dim + 2) + out = network(x, *args, **kwargs) + + # Unsqueeze the network output so it is [N, C, D, H, W] as expected by + # the default SlidingWindowInferer class + if isinstance(out, torch.Tensor): + return out.unsqueeze(dim=self.spatial_dim + 2) + + if isinstance(out, Mapping): + for k in out.keys(): + out[k] = out[k].unsqueeze(dim=self.spatial_dim + 2) + return out + + return tuple(out_i.unsqueeze(dim=self.spatial_dim + 2) for out_i in out) diff --git a/source_code/SegMamba/monai/losses/adversarial_loss.py b/source_code/SegMamba/monai/losses/adversarial_loss.py new file mode 100644 index 0000000000000000000000000000000000000000..c7be79243f9c75c61c01ed61cbda5c180f1bf272 --- /dev/null +++ b/source_code/SegMamba/monai/losses/adversarial_loss.py @@ -0,0 +1,173 @@ +# Copyright (c) MONAI Consortium +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from __future__ import annotations + +import warnings + +import torch +from torch.nn.modules.loss import _Loss + +from monai.networks.layers.utils import get_act_layer +from monai.utils import LossReduction +from monai.utils.enums import StrEnum + + +class AdversarialCriterions(StrEnum): + BCE = "bce" + HINGE = "hinge" + LEAST_SQUARE = "least_squares" + + +class PatchAdversarialLoss(_Loss): + """ + Calculates an adversarial loss on a Patch Discriminator or a Multi-scale Patch Discriminator. + Warning: due to the possibility of using different criterions, the output of the discrimination + mustn't be passed to a final activation layer. That is taken care of internally within the loss. + + Args: + reduction: {``"none"``, ``"mean"``, ``"sum"``} + Specifies the reduction to apply to the output. Defaults to ``"mean"``. + + - ``"none"``: no reduction will be applied. + - ``"mean"``: the sum of the output will be divided by the number of elements in the output. + - ``"sum"``: the output will be summed. + + criterion: which criterion (hinge, least_squares or bce) you want to use on the discriminators outputs. + Depending on the criterion, a different activation layer will be used. Make sure you don't run the outputs + through an activation layer prior to calling the loss. + no_activation_leastsq: if True, the activation layer in the case of least-squares is removed. + """ + + def __init__( + self, + reduction: LossReduction | str = LossReduction.MEAN, + criterion: str = AdversarialCriterions.LEAST_SQUARE, + no_activation_leastsq: bool = False, + ) -> None: + super().__init__(reduction=LossReduction(reduction)) + + if criterion.lower() not in list(AdversarialCriterions): + raise ValueError( + "Unrecognised criterion entered for Adversarial Loss. Must be one in: %s" + % ", ".join(AdversarialCriterions) + ) + + # Depending on the criterion, a different activation layer is used. + self.real_label = 1.0 + self.fake_label = 0.0 + self.loss_fct: _Loss + if criterion == AdversarialCriterions.BCE: + self.activation = get_act_layer("SIGMOID") + self.loss_fct = torch.nn.BCELoss(reduction=reduction) + elif criterion == AdversarialCriterions.HINGE: + self.activation = get_act_layer("TANH") + self.fake_label = -1.0 + elif criterion == AdversarialCriterions.LEAST_SQUARE: + if no_activation_leastsq: + self.activation = None + else: + self.activation = get_act_layer(name=("LEAKYRELU", {"negative_slope": 0.05})) + self.loss_fct = torch.nn.MSELoss(reduction=reduction) + + self.criterion = criterion + self.reduction = reduction + + def get_target_tensor(self, input: torch.Tensor, target_is_real: bool) -> torch.Tensor: + """ + Gets the ground truth tensor for the discriminator depending on whether the input is real or fake. + + Args: + input: input tensor from the discriminator (output of discriminator, or output of one of the multi-scale + discriminator). This is used to match the shape. + target_is_real: whether the input is real or wannabe-real (1s) or fake (0s). + Returns: + """ + filling_label = self.real_label if target_is_real else self.fake_label + label_tensor = torch.tensor(1).fill_(filling_label).type(input.type()).to(input[0].device) + label_tensor.requires_grad_(False) + return label_tensor.expand_as(input) + + def get_zero_tensor(self, input: torch.Tensor) -> torch.Tensor: + """ + Gets a zero tensor. + + Args: + input: tensor which shape you want the zeros tensor to correspond to. + Returns: + """ + + zero_label_tensor = torch.tensor(0).type(input[0].type()).to(input[0].device) + zero_label_tensor.requires_grad_(False) + return zero_label_tensor.expand_as(input) + + def forward( + self, input: torch.Tensor | list, target_is_real: bool, for_discriminator: bool + ) -> torch.Tensor | list[torch.Tensor]: + """ + + Args: + input: output of Multi-Scale Patch Discriminator or Patch Discriminator; being a list of tensors + or a tensor; they shouldn't have gone through an activation layer. + target_is_real: whereas the input corresponds to discriminator output for real or fake images + for_discriminator: whereas this is being calculated for discriminator or generator loss. In the last + case, target_is_real is set to True, as the generator wants the input to be dimmed as real. + Returns: if reduction is None, returns a list with the loss tensors of each discriminator if multi-scale + discriminator is active, or the loss tensor if there is just one discriminator. Otherwise, it returns the + summed or mean loss over the tensor and discriminator/s. + + """ + + if not for_discriminator and not target_is_real: + target_is_real = True # With generator, we always want this to be true! + warnings.warn( + "Variable target_is_real has been set to False, but for_discriminator is set" + "to False. To optimise a generator, target_is_real must be set to True." + ) + + if not isinstance(input, list): + input = [input] + target_ = [] + for _, disc_out in enumerate(input): + if self.criterion != AdversarialCriterions.HINGE: + target_.append(self.get_target_tensor(disc_out, target_is_real)) + else: + target_.append(self.get_zero_tensor(disc_out)) + + # Loss calculation + loss_list = [] + for disc_ind, disc_out in enumerate(input): + if self.activation is not None: + disc_out = self.activation(disc_out) + if self.criterion == AdversarialCriterions.HINGE and not target_is_real: + loss_ = self._forward_single(-disc_out, target_[disc_ind]) + else: + loss_ = self._forward_single(disc_out, target_[disc_ind]) + loss_list.append(loss_) + + loss: torch.Tensor | list[torch.Tensor] + if loss_list is not None: + if self.reduction == LossReduction.MEAN: + loss = torch.mean(torch.stack(loss_list)) + elif self.reduction == LossReduction.SUM: + loss = torch.sum(torch.stack(loss_list)) + else: + loss = loss_list + return loss + + def _forward_single(self, input: torch.Tensor, target: torch.Tensor) -> torch.Tensor: + forward: torch.Tensor + if self.criterion == AdversarialCriterions.BCE or self.criterion == AdversarialCriterions.LEAST_SQUARE: + forward = self.loss_fct(input, target) + elif self.criterion == AdversarialCriterions.HINGE: + minval = torch.min(input - 1, self.get_zero_tensor(input)) + forward = -torch.mean(minval) + return forward diff --git a/source_code/SegMamba/monai/losses/contrastive.py b/source_code/SegMamba/monai/losses/contrastive.py new file mode 100644 index 0000000000000000000000000000000000000000..d8b2c33e62ec6eeb4c2dda61bac418dc2e6fb295 --- /dev/null +++ b/source_code/SegMamba/monai/losses/contrastive.py @@ -0,0 +1,81 @@ +# Copyright (c) MONAI Consortium +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from __future__ import annotations + +from warnings import warn + +import torch +from torch.nn import functional as F +from torch.nn.modules.loss import _Loss + + +class ContrastiveLoss(_Loss): + """ + Compute the Contrastive loss defined in: + + Chen, Ting, et al. "A simple framework for contrastive learning of visual representations." International + conference on machine learning. PMLR, 2020. (http://proceedings.mlr.press/v119/chen20j.html) + + Adapted from: + https://github.com/Sara-Ahmed/SiT/blob/1aacd6adcd39b71efc903d16b4e9095b97dda76f/losses.py#L5 + + """ + + def __init__(self, temperature: float = 0.5, batch_size: int = -1) -> None: + """ + Args: + temperature: Can be scaled between 0 and 1 for learning from negative samples, ideally set to 0.5. + + Raises: + ValueError: When an input of dimension length > 2 is passed + ValueError: When input and target are of different shapes + + """ + super().__init__() + self.temperature = temperature + + if batch_size != -1: + warn("batch_size is no longer required to be set. It will be estimated dynamically in the forward call") + + def forward(self, input: torch.Tensor, target: torch.Tensor) -> torch.Tensor: + """ + Args: + input: the shape should be B[F]. + target: the shape should be B[F]. + """ + if len(target.shape) > 2 or len(input.shape) > 2: + raise ValueError( + f"Either target or input has dimensions greater than 2 where target " + f"shape is ({target.shape}) and input shape is ({input.shape})" + ) + + if target.shape != input.shape: + raise ValueError(f"ground truth has differing shape ({target.shape}) from input ({input.shape})") + + temperature_tensor = torch.as_tensor(self.temperature).to(input.device) + batch_size = input.shape[0] + + negatives_mask = ~torch.eye(batch_size * 2, batch_size * 2, dtype=torch.bool) + negatives_mask = torch.clone(negatives_mask.type(torch.float)).to(input.device) + + repr = torch.cat([input, target], dim=0) + sim_matrix = F.cosine_similarity(repr.unsqueeze(1), repr.unsqueeze(0), dim=2) + sim_ij = torch.diag(sim_matrix, batch_size) + sim_ji = torch.diag(sim_matrix, -batch_size) + + positives = torch.cat([sim_ij, sim_ji], dim=0) + nominator = torch.exp(positives / temperature_tensor) + denominator = negatives_mask * torch.exp(sim_matrix / temperature_tensor) + + loss_partial = -torch.log(nominator / torch.sum(denominator, dim=1)) + + return torch.sum(loss_partial) / (2 * batch_size) diff --git a/source_code/SegMamba/monai/losses/deform.py b/source_code/SegMamba/monai/losses/deform.py new file mode 100644 index 0000000000000000000000000000000000000000..37e4468d4b44d47bda48d76083600d02a410f869 --- /dev/null +++ b/source_code/SegMamba/monai/losses/deform.py @@ -0,0 +1,210 @@ +# Copyright (c) MONAI Consortium +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from __future__ import annotations + +import torch +from torch.nn.modules.loss import _Loss + +from monai.utils import LossReduction + + +def spatial_gradient(x: torch.Tensor, dim: int) -> torch.Tensor: + """ + Calculate gradients on single dimension of a tensor using central finite difference. + It moves the tensor along the dimension to calculate the approximate gradient + dx[i] = (x[i+1] - x[i-1]) / 2. + Adapted from: + DeepReg (https://github.com/DeepRegNet/DeepReg) + + Args: + x: the shape should be BCH(WD). + dim: dimension to calculate gradient along. + Returns: + gradient_dx: the shape should be BCH(WD) + """ + slice_1 = slice(1, -1) + slice_2_s = slice(2, None) + slice_2_e = slice(None, -2) + slice_all = slice(None) + slicing_s, slicing_e = [slice_all, slice_all], [slice_all, slice_all] + while len(slicing_s) < x.ndim: + slicing_s = slicing_s + [slice_1] + slicing_e = slicing_e + [slice_1] + slicing_s[dim] = slice_2_s + slicing_e[dim] = slice_2_e + return (x[slicing_s] - x[slicing_e]) / 2.0 + + +class BendingEnergyLoss(_Loss): + """ + Calculate the bending energy based on second-order differentiation of ``pred`` using central finite difference. + + For more information, + see https://github.com/Project-MONAI/tutorials/blob/main/modules/bending_energy_diffusion_loss_notes.ipynb. + + Adapted from: + DeepReg (https://github.com/DeepRegNet/DeepReg) + """ + + def __init__(self, normalize: bool = False, reduction: LossReduction | str = LossReduction.MEAN) -> None: + """ + Args: + normalize: + Whether to divide out spatial sizes in order to make the computation roughly + invariant to image scale (i.e. vector field sampling resolution). Defaults to False. + reduction: {``"none"``, ``"mean"``, ``"sum"``} + Specifies the reduction to apply to the output. Defaults to ``"mean"``. + + - ``"none"``: no reduction will be applied. + - ``"mean"``: the sum of the output will be divided by the number of elements in the output. + - ``"sum"``: the output will be summed. + """ + super().__init__(reduction=LossReduction(reduction).value) + self.normalize = normalize + + def forward(self, pred: torch.Tensor) -> torch.Tensor: + """ + Args: + pred: the shape should be BCH(WD) + + Raises: + ValueError: When ``self.reduction`` is not one of ["mean", "sum", "none"]. + ValueError: When ``pred`` is not 3-d, 4-d or 5-d. + ValueError: When any spatial dimension of ``pred`` has size less than or equal to 4. + ValueError: When the number of channels of ``pred`` does not match the number of spatial dimensions. + + """ + if pred.ndim not in [3, 4, 5]: + raise ValueError(f"Expecting 3-d, 4-d or 5-d pred, instead got pred of shape {pred.shape}") + for i in range(pred.ndim - 2): + if pred.shape[-i - 1] <= 4: + raise ValueError(f"All spatial dimensions must be > 4, got spatial dimensions {pred.shape[2:]}") + if pred.shape[1] != pred.ndim - 2: + raise ValueError( + f"Number of vector components, i.e. number of channels of the input DDF, {pred.shape[1]}, " + f"does not match number of spatial dimensions, {pred.ndim - 2}" + ) + + # first order gradient + first_order_gradient = [spatial_gradient(pred, dim) for dim in range(2, pred.ndim)] + + # spatial dimensions in a shape suited for broadcasting below + if self.normalize: + spatial_dims = torch.tensor(pred.shape, device=pred.device)[2:].reshape((1, -1) + (pred.ndim - 2) * (1,)) + + energy = torch.tensor(0) + for dim_1, g in enumerate(first_order_gradient): + dim_1 += 2 + if self.normalize: + g *= pred.shape[dim_1] / spatial_dims + energy = energy + (spatial_gradient(g, dim_1) * pred.shape[dim_1]) ** 2 + else: + energy = energy + spatial_gradient(g, dim_1) ** 2 + for dim_2 in range(dim_1 + 1, pred.ndim): + if self.normalize: + energy = energy + 2 * (spatial_gradient(g, dim_2) * pred.shape[dim_2]) ** 2 + else: + energy = energy + 2 * spatial_gradient(g, dim_2) ** 2 + + if self.reduction == LossReduction.MEAN.value: + energy = torch.mean(energy) # the batch and channel average + elif self.reduction == LossReduction.SUM.value: + energy = torch.sum(energy) # sum over the batch and channel dims + elif self.reduction != LossReduction.NONE.value: + raise ValueError(f'Unsupported reduction: {self.reduction}, available options are ["mean", "sum", "none"].') + + return energy + + +class DiffusionLoss(_Loss): + """ + Calculate the diffusion based on first-order differentiation of ``pred`` using central finite difference. + For the original paper, please refer to + VoxelMorph: A Learning Framework for Deformable Medical Image Registration, + Guha Balakrishnan, Amy Zhao, Mert R. Sabuncu, John Guttag, Adrian V. Dalca + IEEE TMI: Transactions on Medical Imaging. 2019. eprint arXiv:1809.05231. + + For more information, + see https://github.com/Project-MONAI/tutorials/blob/main/modules/bending_energy_diffusion_loss_notes.ipynb. + + Adapted from: + VoxelMorph (https://github.com/voxelmorph/voxelmorph) + """ + + def __init__(self, normalize: bool = False, reduction: LossReduction | str = LossReduction.MEAN) -> None: + """ + Args: + normalize: + Whether to divide out spatial sizes in order to make the computation roughly + invariant to image scale (i.e. vector field sampling resolution). Defaults to False. + reduction: {``"none"``, ``"mean"``, ``"sum"``} + Specifies the reduction to apply to the output. Defaults to ``"mean"``. + + - ``"none"``: no reduction will be applied. + - ``"mean"``: the sum of the output will be divided by the number of elements in the output. + - ``"sum"``: the output will be summed. + """ + super().__init__(reduction=LossReduction(reduction).value) + self.normalize = normalize + + def forward(self, pred: torch.Tensor) -> torch.Tensor: + """ + Args: + pred: + Predicted dense displacement field (DDF) with shape BCH[WD], + where C is the number of spatial dimensions. + Note that diffusion loss can only be calculated + when the sizes of the DDF along all spatial dimensions are greater than 2. + + Raises: + ValueError: When ``self.reduction`` is not one of ["mean", "sum", "none"]. + ValueError: When ``pred`` is not 3-d, 4-d or 5-d. + ValueError: When any spatial dimension of ``pred`` has size less than or equal to 2. + ValueError: When the number of channels of ``pred`` does not match the number of spatial dimensions. + + """ + if pred.ndim not in [3, 4, 5]: + raise ValueError(f"Expecting 3-d, 4-d or 5-d pred, instead got pred of shape {pred.shape}") + for i in range(pred.ndim - 2): + if pred.shape[-i - 1] <= 2: + raise ValueError(f"All spatial dimensions must be > 2, got spatial dimensions {pred.shape[2:]}") + if pred.shape[1] != pred.ndim - 2: + raise ValueError( + f"Number of vector components, i.e. number of channels of the input DDF, {pred.shape[1]}, " + f"does not match number of spatial dimensions, {pred.ndim - 2}" + ) + + # first order gradient + first_order_gradient = [spatial_gradient(pred, dim) for dim in range(2, pred.ndim)] + + # spatial dimensions in a shape suited for broadcasting below + if self.normalize: + spatial_dims = torch.tensor(pred.shape, device=pred.device)[2:].reshape((1, -1) + (pred.ndim - 2) * (1,)) + + diffusion = torch.tensor(0) + for dim_1, g in enumerate(first_order_gradient): + dim_1 += 2 + if self.normalize: + # We divide the partial derivative for each vector component at each voxel by the spatial size + # corresponding to that component relative to the spatial size of the vector component with respect + # to which the partial derivative is taken. + g *= pred.shape[dim_1] / spatial_dims + diffusion = diffusion + g**2 + + if self.reduction == LossReduction.MEAN.value: + diffusion = torch.mean(diffusion) # the batch and channel average + elif self.reduction == LossReduction.SUM.value: + diffusion = torch.sum(diffusion) # sum over the batch and channel dims + elif self.reduction != LossReduction.NONE.value: + raise ValueError(f'Unsupported reduction: {self.reduction}, available options are ["mean", "sum", "none"].') + + return diffusion diff --git a/source_code/SegMamba/monai/losses/giou_loss.py b/source_code/SegMamba/monai/losses/giou_loss.py new file mode 100644 index 0000000000000000000000000000000000000000..7940660a08c071dfd240e4aaa15228aaa6abc384 --- /dev/null +++ b/source_code/SegMamba/monai/losses/giou_loss.py @@ -0,0 +1,67 @@ +# Copyright (c) MONAI Consortium +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from __future__ import annotations + +import torch +from torch.nn.modules.loss import _Loss + +from monai.data.box_utils import COMPUTE_DTYPE, box_pair_giou +from monai.utils import LossReduction + + +class BoxGIoULoss(_Loss): + """ + Compute the generalized intersection over union (GIoU) loss of a pair of boxes. + The two inputs should have the same shape. giou_loss = 1.0 - giou + + The range of GIoU is (-1.0, 1.0]. Thus the range of GIoU loss is [0.0, 2.0). + + Args: + reduction: {``"none"``, ``"mean"``, ``"sum"``} + Specifies the reduction to apply to the output. Defaults to ``"mean"``. + - ``"none"``: no reduction will be applied. + - ``"mean"``: the sum of the output will be divided by the number of elements in the output. + - ``"sum"``: the output will be summed. + """ + + def __init__(self, reduction: LossReduction | str = LossReduction.MEAN) -> None: + super().__init__(reduction=LossReduction(reduction).value) + + def forward(self, input: torch.Tensor, target: torch.Tensor) -> torch.Tensor: + """ + Args: + input: predicted bounding boxes, Nx4 or Nx6 torch tensor. The box mode is assumed to be ``StandardMode`` + target: GT bounding boxes, Nx4 or Nx6 torch tensor. The box mode is assumed to be ``StandardMode`` + + Raises: + ValueError: When the two inputs have different shape. + """ + if target.shape != input.shape: + raise ValueError(f"ground truth has different shape ({target.shape}) from input ({input.shape})") + + box_dtype = input.dtype + giou: torch.Tensor = box_pair_giou( # type: ignore + target.to(dtype=COMPUTE_DTYPE), input.to(dtype=COMPUTE_DTYPE) + ) + loss: torch.Tensor = 1.0 - giou + if self.reduction == LossReduction.MEAN.value: + loss = loss.mean() + elif self.reduction == LossReduction.SUM.value: + loss = loss.sum() + elif self.reduction == LossReduction.NONE.value: + pass + else: + raise ValueError(f'Unsupported reduction: {self.reduction}, available options are ["mean", "sum", "none"].') + return loss.to(box_dtype) + + +giou = BoxGIoULoss diff --git a/source_code/SegMamba/monai/losses/tversky.py b/source_code/SegMamba/monai/losses/tversky.py new file mode 100644 index 0000000000000000000000000000000000000000..4f22bf84b4d80d173bd2a0a6097a282f7e998dfa --- /dev/null +++ b/source_code/SegMamba/monai/losses/tversky.py @@ -0,0 +1,162 @@ +# Copyright (c) MONAI Consortium +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from __future__ import annotations + +import warnings +from collections.abc import Callable + +import torch +from torch.nn.modules.loss import _Loss + +from monai.networks import one_hot +from monai.utils import LossReduction + + +class TverskyLoss(_Loss): + """ + Compute the Tversky loss defined in: + + Sadegh et al. (2017) Tversky loss function for image segmentation + using 3D fully convolutional deep networks. (https://arxiv.org/abs/1706.05721) + + Adapted from: + https://github.com/NifTK/NiftyNet/blob/v0.6.0/niftynet/layer/loss_segmentation.py#L631 + + """ + + def __init__( + self, + include_background: bool = True, + to_onehot_y: bool = False, + sigmoid: bool = False, + softmax: bool = False, + other_act: Callable | None = None, + alpha: float = 0.5, + beta: float = 0.5, + reduction: LossReduction | str = LossReduction.MEAN, + smooth_nr: float = 1e-5, + smooth_dr: float = 1e-5, + batch: bool = False, + ) -> None: + """ + Args: + include_background: If False channel index 0 (background category) is excluded from the calculation. + to_onehot_y: whether to convert `y` into the one-hot format. Defaults to False. + sigmoid: If True, apply a sigmoid function to the prediction. + softmax: If True, apply a softmax function to the prediction. + other_act: if don't want to use `sigmoid` or `softmax`, use other callable function to execute + other activation layers, Defaults to ``None``. for example: + `other_act = torch.tanh`. + alpha: weight of false positives + beta: weight of false negatives + reduction: {``"none"``, ``"mean"``, ``"sum"``} + Specifies the reduction to apply to the output. Defaults to ``"mean"``. + + - ``"none"``: no reduction will be applied. + - ``"mean"``: the sum of the output will be divided by the number of elements in the output. + - ``"sum"``: the output will be summed. + + smooth_nr: a small constant added to the numerator to avoid zero. + smooth_dr: a small constant added to the denominator to avoid nan. + batch: whether to sum the intersection and union areas over the batch dimension before the dividing. + Defaults to False, a Dice loss value is computed independently from each item in the batch + before any `reduction`. + + Raises: + TypeError: When ``other_act`` is not an ``Optional[Callable]``. + ValueError: When more than 1 of [``sigmoid=True``, ``softmax=True``, ``other_act is not None``]. + Incompatible values. + + """ + + super().__init__(reduction=LossReduction(reduction).value) + if other_act is not None and not callable(other_act): + raise TypeError(f"other_act must be None or callable but is {type(other_act).__name__}.") + if int(sigmoid) + int(softmax) + int(other_act is not None) > 1: + raise ValueError("Incompatible values: more than 1 of [sigmoid=True, softmax=True, other_act is not None].") + self.include_background = include_background + self.to_onehot_y = to_onehot_y + self.sigmoid = sigmoid + self.softmax = softmax + self.other_act = other_act + self.alpha = alpha + self.beta = beta + self.smooth_nr = float(smooth_nr) + self.smooth_dr = float(smooth_dr) + self.batch = batch + + def forward(self, input: torch.Tensor, target: torch.Tensor) -> torch.Tensor: + """ + Args: + input: the shape should be BNH[WD]. + target: the shape should be BNH[WD]. + + Raises: + ValueError: When ``self.reduction`` is not one of ["mean", "sum", "none"]. + + """ + if self.sigmoid: + input = torch.sigmoid(input) + + n_pred_ch = input.shape[1] + if self.softmax: + if n_pred_ch == 1: + warnings.warn("single channel prediction, `softmax=True` ignored.") + else: + input = torch.softmax(input, 1) + + if self.other_act is not None: + input = self.other_act(input) + + if self.to_onehot_y: + if n_pred_ch == 1: + warnings.warn("single channel prediction, `to_onehot_y=True` ignored.") + else: + target = one_hot(target, num_classes=n_pred_ch) + + if not self.include_background: + if n_pred_ch == 1: + warnings.warn("single channel prediction, `include_background=False` ignored.") + else: + # if skipping background, removing first channel + target = target[:, 1:] + input = input[:, 1:] + + if target.shape != input.shape: + raise AssertionError(f"ground truth has differing shape ({target.shape}) from input ({input.shape})") + + p0 = input + p1 = 1 - p0 + g0 = target + g1 = 1 - g0 + + # reducing only spatial dimensions (not batch nor channels) + reduce_axis: list[int] = torch.arange(2, len(input.shape)).tolist() + if self.batch: + # reducing spatial dimensions and batch + reduce_axis = [0] + reduce_axis + + tp = torch.sum(p0 * g0, reduce_axis) + fp = self.alpha * torch.sum(p0 * g1, reduce_axis) + fn = self.beta * torch.sum(p1 * g0, reduce_axis) + numerator = tp + self.smooth_nr + denominator = tp + fp + fn + self.smooth_dr + + score: torch.Tensor = 1.0 - numerator / denominator + + if self.reduction == LossReduction.SUM.value: + return torch.sum(score) # sum over the batch and channel dims + if self.reduction == LossReduction.NONE.value: + return score # returns [N, num_classes] losses + if self.reduction == LossReduction.MEAN.value: + return torch.mean(score) + raise ValueError(f'Unsupported reduction: {self.reduction}, available options are ["mean", "sum", "none"].') diff --git a/source_code/SegMamba/monai/losses/unified_focal_loss.py b/source_code/SegMamba/monai/losses/unified_focal_loss.py new file mode 100644 index 0000000000000000000000000000000000000000..8484eb67edef4ef27573e5427e8a5618eefc6d86 --- /dev/null +++ b/source_code/SegMamba/monai/losses/unified_focal_loss.py @@ -0,0 +1,240 @@ +# Copyright (c) MONAI Consortium +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from __future__ import annotations + +import warnings + +import torch +from torch.nn.modules.loss import _Loss + +from monai.networks import one_hot +from monai.utils import LossReduction + + +class AsymmetricFocalTverskyLoss(_Loss): + """ + AsymmetricFocalTverskyLoss is a variant of FocalTverskyLoss, which attentions to the foreground class. + + Actually, it's only supported for binary image segmentation now. + + Reimplementation of the Asymmetric Focal Tversky Loss described in: + + - "Unified Focal Loss: Generalising Dice and Cross Entropy-based Losses to Handle Class Imbalanced Medical Image Segmentation", + Michael Yeung, Computerized Medical Imaging and Graphics + """ + + def __init__( + self, + to_onehot_y: bool = False, + delta: float = 0.7, + gamma: float = 0.75, + epsilon: float = 1e-7, + reduction: LossReduction | str = LossReduction.MEAN, + ) -> None: + """ + Args: + to_onehot_y: whether to convert `y` into the one-hot format. Defaults to False. + delta : weight of the background. Defaults to 0.7. + gamma : value of the exponent gamma in the definition of the Focal loss . Defaults to 0.75. + epsilon : it defines a very small number each time. simmily smooth value. Defaults to 1e-7. + """ + super().__init__(reduction=LossReduction(reduction).value) + self.to_onehot_y = to_onehot_y + self.delta = delta + self.gamma = gamma + self.epsilon = epsilon + + def forward(self, y_pred: torch.Tensor, y_true: torch.Tensor) -> torch.Tensor: + n_pred_ch = y_pred.shape[1] + + if self.to_onehot_y: + if n_pred_ch == 1: + warnings.warn("single channel prediction, `to_onehot_y=True` ignored.") + else: + y_true = one_hot(y_true, num_classes=n_pred_ch) + + if y_true.shape != y_pred.shape: + raise ValueError(f"ground truth has different shape ({y_true.shape}) from input ({y_pred.shape})") + + # clip the prediction to avoid NaN + y_pred = torch.clamp(y_pred, self.epsilon, 1.0 - self.epsilon) + axis = list(range(2, len(y_pred.shape))) + + # Calculate true positives (tp), false negatives (fn) and false positives (fp) + tp = torch.sum(y_true * y_pred, dim=axis) + fn = torch.sum(y_true * (1 - y_pred), dim=axis) + fp = torch.sum((1 - y_true) * y_pred, dim=axis) + dice_class = (tp + self.epsilon) / (tp + self.delta * fn + (1 - self.delta) * fp + self.epsilon) + + # Calculate losses separately for each class, enhancing both classes + back_dice = 1 - dice_class[:, 0] + fore_dice = (1 - dice_class[:, 1]) * torch.pow(1 - dice_class[:, 1], -self.gamma) + + # Average class scores + loss = torch.mean(torch.stack([back_dice, fore_dice], dim=-1)) + return loss + + +class AsymmetricFocalLoss(_Loss): + """ + AsymmetricFocalLoss is a variant of FocalTverskyLoss, which attentions to the foreground class. + + Actually, it's only supported for binary image segmentation now. + + Reimplementation of the Asymmetric Focal Loss described in: + + - "Unified Focal Loss: Generalising Dice and Cross Entropy-based Losses to Handle Class Imbalanced Medical Image Segmentation", + Michael Yeung, Computerized Medical Imaging and Graphics + """ + + def __init__( + self, + to_onehot_y: bool = False, + delta: float = 0.7, + gamma: float = 2, + epsilon: float = 1e-7, + reduction: LossReduction | str = LossReduction.MEAN, + ): + """ + Args: + to_onehot_y : whether to convert `y` into the one-hot format. Defaults to False. + delta : weight of the background. Defaults to 0.7. + gamma : value of the exponent gamma in the definition of the Focal loss . Defaults to 0.75. + epsilon : it defines a very small number each time. simmily smooth value. Defaults to 1e-7. + """ + super().__init__(reduction=LossReduction(reduction).value) + self.to_onehot_y = to_onehot_y + self.delta = delta + self.gamma = gamma + self.epsilon = epsilon + + def forward(self, y_pred: torch.Tensor, y_true: torch.Tensor) -> torch.Tensor: + n_pred_ch = y_pred.shape[1] + + if self.to_onehot_y: + if n_pred_ch == 1: + warnings.warn("single channel prediction, `to_onehot_y=True` ignored.") + else: + y_true = one_hot(y_true, num_classes=n_pred_ch) + + if y_true.shape != y_pred.shape: + raise ValueError(f"ground truth has different shape ({y_true.shape}) from input ({y_pred.shape})") + + y_pred = torch.clamp(y_pred, self.epsilon, 1.0 - self.epsilon) + cross_entropy = -y_true * torch.log(y_pred) + + back_ce = torch.pow(1 - y_pred[:, 0], self.gamma) * cross_entropy[:, 0] + back_ce = (1 - self.delta) * back_ce + + fore_ce = cross_entropy[:, 1] + fore_ce = self.delta * fore_ce + + loss = torch.mean(torch.sum(torch.stack([back_ce, fore_ce], dim=1), dim=1)) + return loss + + +class AsymmetricUnifiedFocalLoss(_Loss): + """ + AsymmetricUnifiedFocalLoss is a variant of Focal Loss. + + Actually, it's only supported for binary image segmentation now + + Reimplementation of the Asymmetric Unified Focal Tversky Loss described in: + + - "Unified Focal Loss: Generalising Dice and Cross Entropy-based Losses to Handle Class Imbalanced Medical Image Segmentation", + Michael Yeung, Computerized Medical Imaging and Graphics + """ + + def __init__( + self, + to_onehot_y: bool = False, + num_classes: int = 2, + weight: float = 0.5, + gamma: float = 0.5, + delta: float = 0.7, + reduction: LossReduction | str = LossReduction.MEAN, + ): + """ + Args: + to_onehot_y : whether to convert `y` into the one-hot format. Defaults to False. + num_classes : number of classes, it only supports 2 now. Defaults to 2. + delta : weight of the background. Defaults to 0.7. + gamma : value of the exponent gamma in the definition of the Focal loss. Defaults to 0.75. + epsilon : it defines a very small number each time. simmily smooth value. Defaults to 1e-7. + weight : weight for each loss function, if it's none it's 0.5. Defaults to None. + + Example: + >>> import torch + >>> from monai.losses import AsymmetricUnifiedFocalLoss + >>> pred = torch.ones((1,1,32,32), dtype=torch.float32) + >>> grnd = torch.ones((1,1,32,32), dtype=torch.int64) + >>> fl = AsymmetricUnifiedFocalLoss(to_onehot_y=True) + >>> fl(pred, grnd) + """ + super().__init__(reduction=LossReduction(reduction).value) + self.to_onehot_y = to_onehot_y + self.num_classes = num_classes + self.gamma = gamma + self.delta = delta + self.weight: float = weight + self.asy_focal_loss = AsymmetricFocalLoss(gamma=self.gamma, delta=self.delta) + self.asy_focal_tversky_loss = AsymmetricFocalTverskyLoss(gamma=self.gamma, delta=self.delta) + + # TODO: Implement this function to support multiple classes segmentation + def forward(self, y_pred: torch.Tensor, y_true: torch.Tensor) -> torch.Tensor: + """ + Args: + y_pred : the shape should be BNH[WD], where N is the number of classes. + It only supports binary segmentation. + The input should be the original logits since it will be transformed by + a sigmoid in the forward function. + y_true : the shape should be BNH[WD], where N is the number of classes. + It only supports binary segmentation. + + Raises: + ValueError: When input and target are different shape + ValueError: When len(y_pred.shape) != 4 and len(y_pred.shape) != 5 + ValueError: When num_classes + ValueError: When the number of classes entered does not match the expected number + """ + if y_pred.shape != y_true.shape: + raise ValueError(f"ground truth has different shape ({y_true.shape}) from input ({y_pred.shape})") + + if len(y_pred.shape) != 4 and len(y_pred.shape) != 5: + raise ValueError(f"input shape must be 4 or 5, but got {y_pred.shape}") + + if y_pred.shape[1] == 1: + y_pred = one_hot(y_pred, num_classes=self.num_classes) + y_true = one_hot(y_true, num_classes=self.num_classes) + + if torch.max(y_true) != self.num_classes - 1: + raise ValueError(f"Please make sure the number of classes is {self.num_classes-1}") + + n_pred_ch = y_pred.shape[1] + if self.to_onehot_y: + if n_pred_ch == 1: + warnings.warn("single channel prediction, `to_onehot_y=True` ignored.") + else: + y_true = one_hot(y_true, num_classes=n_pred_ch) + + asy_focal_loss = self.asy_focal_loss(y_pred, y_true) + asy_focal_tversky_loss = self.asy_focal_tversky_loss(y_pred, y_true) + + loss: torch.Tensor = self.weight * asy_focal_loss + (1 - self.weight) * asy_focal_tversky_loss + + if self.reduction == LossReduction.SUM.value: + return torch.sum(loss) # sum over the batch and channel dims + if self.reduction == LossReduction.NONE.value: + return loss # returns [N, num_classes] losses + if self.reduction == LossReduction.MEAN.value: + return torch.mean(loss) + raise ValueError(f'Unsupported reduction: {self.reduction}, available options are ["mean", "sum", "none"].') diff --git a/source_code/SegMamba/monai/metrics/__init__.py b/source_code/SegMamba/monai/metrics/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..201acdfa5085753265e89017355867dc93e2d606 --- /dev/null +++ b/source_code/SegMamba/monai/metrics/__init__.py @@ -0,0 +1,42 @@ +# Copyright (c) MONAI Consortium +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from __future__ import annotations + +from .active_learning_metrics import LabelQualityScore, VarianceMetric, compute_variance, label_quality_score +from .confusion_matrix import ConfusionMatrixMetric, compute_confusion_matrix_metric, get_confusion_matrix +from .cumulative_average import CumulativeAverage +from .f_beta_score import FBetaScore +from .fid import FIDMetric, compute_frechet_distance +from .froc import compute_fp_tp_probs, compute_fp_tp_probs_nd, compute_froc_curve_data, compute_froc_score +from .generalized_dice import GeneralizedDiceScore, compute_generalized_dice +from .hausdorff_distance import HausdorffDistanceMetric, compute_hausdorff_distance, compute_percent_hausdorff_distance +from .loss_metric import LossMetric +from .meandice import DiceHelper, DiceMetric, compute_dice +from .meaniou import MeanIoU, compute_iou +from .metric import Cumulative, CumulativeIterationMetric, IterationMetric, Metric +from .mmd import MMDMetric, compute_mmd +from .panoptic_quality import PanopticQualityMetric, compute_panoptic_quality +from .regression import ( + MAEMetric, + MSEMetric, + MultiScaleSSIMMetric, + PSNRMetric, + RMSEMetric, + SSIMMetric, + compute_ms_ssim, + compute_ssim_and_cs, +) +from .rocauc import ROCAUCMetric, compute_roc_auc +from .surface_dice import SurfaceDiceMetric, compute_surface_dice +from .surface_distance import SurfaceDistanceMetric, compute_average_surface_distance +from .utils import do_metric_reduction, get_mask_edges, get_surface_distance, ignore_background, is_binary_tensor +from .wrapper import MetricsReloadedBinary, MetricsReloadedCategorical diff --git a/source_code/SegMamba/monai/metrics/active_learning_metrics.py b/source_code/SegMamba/monai/metrics/active_learning_metrics.py new file mode 100644 index 0000000000000000000000000000000000000000..7a1654191eca700f6bcaa7b6bb2959a9265ca5cb --- /dev/null +++ b/source_code/SegMamba/monai/metrics/active_learning_metrics.py @@ -0,0 +1,207 @@ +# Copyright (c) MONAI Consortium +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from __future__ import annotations + +import warnings +from typing import Any + +import torch + +from monai.metrics.utils import ignore_background +from monai.utils import MetricReduction + +from .metric import Metric + + +class VarianceMetric(Metric): + """ + Compute the Variance of a given T-repeats N-dimensional array/tensor. The primary usage is as an uncertainty based + metric for Active Learning. + + It can return the spatial variance/uncertainty map based on user choice or a single scalar value via mean/sum of the + variance for scoring purposes + + Args: + include_background: Whether to include the background of the spatial image or channel 0 of the 1-D vector + spatial_map: Boolean, if set to True, spatial map of variance will be returned corresponding to i/p image dimensions + scalar_reduction: reduction type of the metric, either 'sum' or 'mean' can be used + threshold: To avoid NaN's a threshold is used to replace zero's + + """ + + def __init__( + self, + include_background: bool = True, + spatial_map: bool = False, + scalar_reduction: str = "sum", + threshold: float = 0.0005, + ) -> None: + super().__init__() + self.include_background = include_background + self.spatial_map = spatial_map + self.scalar_reduction = scalar_reduction + self.threshold = threshold + + def __call__(self, y_pred: Any) -> Any: + """ + Args: + y_pred: Predicted segmentation, typically segmentation model output. + It must be N-repeats, repeat-first tensor [N,C,H,W,D]. + + Returns: + Pytorch tensor of scalar value of variance as uncertainty or a spatial map of uncertainty + + """ + return compute_variance( + y_pred=y_pred, + include_background=self.include_background, + spatial_map=self.spatial_map, + scalar_reduction=self.scalar_reduction, + threshold=self.threshold, + ) + + +class LabelQualityScore(Metric): + """ + The assumption is that the DL model makes better predictions than the provided label quality, hence the difference + can be treated as a label quality score + + It can be combined with variance/uncertainty for active learning frameworks to factor in the quality of label along + with uncertainty + Args: + include_background: Whether to include the background of the spatial image or channel 0 of the 1-D vector + spatial_map: Boolean, if set to True, spatial map of variance will be returned corresponding to i/p image + dimensions + scalar_reduction: reduction type of the metric, either 'sum' or 'mean' can be used + + """ + + def __init__(self, include_background: bool = True, scalar_reduction: str = "sum") -> None: + super().__init__() + self.include_background = include_background + self.scalar_reduction = scalar_reduction + + def __call__(self, y_pred: Any, y: Any) -> torch.Tensor | None: + """ + Args: + y_pred: Predicted segmentation, typically segmentation model output. + It must be N-repeats, repeat-first tensor [N,C,H,W,D]. + + Returns: + Pytorch tensor of scalar value of variance as uncertainty or a spatial map of uncertainty + + """ + return label_quality_score( + y_pred=y_pred, y=y, include_background=self.include_background, scalar_reduction=self.scalar_reduction + ) + + +def compute_variance( + y_pred: torch.Tensor, + include_background: bool = True, + spatial_map: bool = False, + scalar_reduction: str = "mean", + threshold: float = 0.0005, +) -> torch.Tensor | None: + """ + Args: + y_pred: [N, C, H, W, D] or [N, C, H, W] or [N, C, H] where N is repeats, C is channels and H, W, D stand for + Height, Width & Depth + include_background: Whether to include the background of the spatial image or channel 0 of the 1-D vector + spatial_map: Boolean, if set to True, spatial map of variance will be returned corresponding to i/p image + dimensions + scalar_reduction: reduction type of the metric, either 'sum' or 'mean' can be used + threshold: To avoid NaN's a threshold is used to replace zero's + Returns: + A single scalar uncertainty/variance value or the spatial map of uncertainty/variance + """ + + # The background utils is only applicable here because instead of Batch-dimension we have repeats here + y_pred = y_pred.float() + + if not include_background: + y = y_pred + # TODO If this utils is made to be optional for 'y' it would be nice + y_pred, y = ignore_background(y_pred=y_pred, y=y) + + # Set any values below 0 to threshold + y_pred[y_pred <= 0] = threshold + + n_len = len(y_pred.shape) + + if n_len < 4 and spatial_map: + warnings.warn("Spatial map requires a 2D/3D image with N-repeats and C-channels") + return None + + # Create new shape list + # The N-repeats are multiplied by channels + n_shape = y_pred.shape + new_shape = [n_shape[0] * n_shape[1]] + for each_dim_idx in range(2, n_len): + new_shape.append(n_shape[each_dim_idx]) + + y_reshaped = torch.reshape(y_pred, new_shape) + variance = torch.var(y_reshaped, dim=0, unbiased=False) + + if spatial_map: + return variance + + if scalar_reduction == MetricReduction.MEAN: + return torch.mean(variance) + if scalar_reduction == MetricReduction.SUM: + return torch.sum(variance) + raise ValueError(f"scalar_reduction={scalar_reduction} not supported.") + + +def label_quality_score( + y_pred: torch.Tensor, y: torch.Tensor, include_background: bool = True, scalar_reduction: str = "mean" +) -> torch.Tensor | None: + """ + The assumption is that the DL model makes better predictions than the provided label quality, hence the difference + can be treated as a label quality score + + Args: + y_pred: Input data of dimension [B, C, H, W, D] or [B, C, H, W] or [B, C, H] where B is Batch-size, C is + channels and H, W, D stand for Height, Width & Depth + y: Ground Truth of dimension [B, C, H, W, D] or [B, C, H, W] or [B, C, H] where B is Batch-size, C is channels + and H, W, D stand for Height, Width & Depth + include_background: Whether to include the background of the spatial image or channel 0 of the 1-D vector + scalar_reduction: reduction type of the metric, either 'sum' or 'mean' can be used to retrieve a single scalar + value, if set to 'none' a spatial map will be returned + + Returns: + A single scalar absolute difference value as score with a reduction based on sum/mean or the spatial map of + absolute difference + """ + + # The background utils is only applicable here because instead of Batch-dimension we have repeats here + y_pred = y_pred.float() + y = y.float() + + if not include_background: + y_pred, y = ignore_background(y_pred=y_pred, y=y) + + n_len = len(y_pred.shape) + if n_len < 4 and scalar_reduction == "none": + warnings.warn("Reduction set to None, Spatial map return requires a 2D/3D image of B-Batchsize and C-channels") + return None + + abs_diff_map = torch.abs(y_pred - y) + + if scalar_reduction == MetricReduction.NONE: + return abs_diff_map + + if scalar_reduction == MetricReduction.MEAN: + return torch.mean(abs_diff_map, dim=list(range(1, n_len))) + if scalar_reduction == MetricReduction.SUM: + return torch.sum(abs_diff_map, dim=list(range(1, n_len))) + raise ValueError(f"scalar_reduction={scalar_reduction} not supported.") diff --git a/source_code/SegMamba/monai/metrics/generalized_dice.py b/source_code/SegMamba/monai/metrics/generalized_dice.py new file mode 100644 index 0000000000000000000000000000000000000000..e56bd465927512fbc702bebeb4af2fb9895d5b47 --- /dev/null +++ b/source_code/SegMamba/monai/metrics/generalized_dice.py @@ -0,0 +1,178 @@ +# Copyright (c) MONAI Consortium +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from __future__ import annotations + +import torch + +from monai.metrics.utils import do_metric_reduction, ignore_background +from monai.utils import MetricReduction, Weight, look_up_option + +from .metric import CumulativeIterationMetric + + +class GeneralizedDiceScore(CumulativeIterationMetric): + """Compute the Generalized Dice Score metric between tensors, as the complement of the Generalized Dice Loss defined in: + + Sudre, C. et. al. (2017) Generalised Dice overlap as a deep learning + loss function for highly unbalanced segmentations. DLMIA 2017. + + The inputs `y_pred` and `y` are expected to be one-hot, binarized channel-first + or batch-first tensors, i.e., CHW[D] or BCHW[D]. + + Example of the typical execution steps of this metric class follows :py:class:`monai.metrics.metric.Cumulative`. + + Args: + include_background (bool, optional): whether to include the background class (assumed to be in channel 0), in the + score computation. Defaults to True. + reduction (str, optional): define mode of reduction to the metrics. Available reduction modes: + {``"none"``, ``"mean_batch"``, ``"sum_batch"``}. Default to ``"mean_batch"``. If "none", will not do reduction. + weight_type (Union[Weight, str], optional): {``"square"``, ``"simple"``, ``"uniform"``}. Type of function to transform + ground truth volume into a weight factor. Defaults to ``"square"``. + + Raises: + ValueError: when the `weight_type` is not one of {``"none"``, ``"mean"``, ``"sum"``}. + """ + + def __init__( + self, + include_background: bool = True, + reduction: MetricReduction | str = MetricReduction.MEAN_BATCH, + weight_type: Weight | str = Weight.SQUARE, + ) -> None: + super().__init__() + self.include_background = include_background + reduction_options = [ + "none", + "mean_batch", + "sum_batch", + MetricReduction.NONE, + MetricReduction.MEAN_BATCH, + MetricReduction.SUM_BATCH, + ] + self.reduction = reduction + if self.reduction not in reduction_options: + raise ValueError(f"reduction must be one of {reduction_options}") + self.weight_type = look_up_option(weight_type, Weight) + + def _compute_tensor(self, y_pred: torch.Tensor, y: torch.Tensor) -> torch.Tensor: # type: ignore[override] + """Computes the Generalized Dice Score and returns a tensor with its per image values. + + Args: + y_pred (torch.Tensor): binarized segmentation model output. It must be in one-hot format and in the NCHW[D] format, + where N is the batch dimension, C is the channel dimension, and the remaining are the spatial dimensions. + y (torch.Tensor): binarized ground-truth. It must be in one-hot format and have the same shape as `y_pred`. + + Raises: + ValueError: if `y_pred` and `y` have less than 3 dimensions, or `y_pred` and `y` don't have the same shape. + """ + return compute_generalized_dice( + y_pred=y_pred, y=y, include_background=self.include_background, weight_type=self.weight_type + ) + + def aggregate(self, reduction: MetricReduction | str | None = None) -> torch.Tensor: + """ + Execute reduction logic for the output of `compute_generalized_dice`. + + Args: + reduction (Union[MetricReduction, str, None], optional): define mode of reduction to the metrics. + Available reduction modes: {``"none"``, ``"mean"``, ``"sum"``, ``"mean_batch"``, ``"sum_batch"``}. + Defaults to ``"mean"``. If "none", will not do reduction. + """ + data = self.get_buffer() + if not isinstance(data, torch.Tensor): + raise ValueError("The data to aggregate must be a PyTorch Tensor.") + + # Validate reduction argument if specified + if reduction is not None: + reduction_options = ["none", "mean", "sum", "mean_batch", "sum_batch"] + if reduction not in reduction_options: + raise ValueError(f"reduction must be one of {reduction_options}") + + # Do metric reduction and return + f, _ = do_metric_reduction(data, reduction or self.reduction) + + return f + + +def compute_generalized_dice( + y_pred: torch.Tensor, y: torch.Tensor, include_background: bool = True, weight_type: Weight | str = Weight.SQUARE +) -> torch.Tensor: + """Computes the Generalized Dice Score and returns a tensor with its per image values. + + Args: + y_pred (torch.Tensor): binarized segmentation model output. It should be binarized, in one-hot format + and in the NCHW[D] format, where N is the batch dimension, C is the channel dimension, and the + remaining are the spatial dimensions. + y (torch.Tensor): binarized ground-truth. It should be binarized, in one-hot format and have the same shape as `y_pred`. + include_background (bool, optional): whether to include score computation on the first channel of the + predicted output. Defaults to True. + weight_type (Union[Weight, str], optional): {``"square"``, ``"simple"``, ``"uniform"``}. Type of function to + transform ground truth volume into a weight factor. Defaults to ``"square"``. + + Returns: + torch.Tensor: per batch and per class Generalized Dice Score, i.e., with the shape [batch_size, num_classes]. + + Raises: + ValueError: if `y_pred` or `y` are not PyTorch tensors, if `y_pred` and `y` have less than three dimensions, + or `y_pred` and `y` don't have the same shape. + """ + # Ensure tensors have at least 3 dimensions and have the same shape + dims = y_pred.dim() + if dims < 3: + raise ValueError(f"y_pred should have at least 3 dimensions (batch, channel, spatial), got {dims}.") + if y.shape != y_pred.shape: + raise ValueError(f"y_pred - {y_pred.shape} - and y - {y.shape} - should have the same shapes.") + + # Ignore background, if needed + if not include_background: + y_pred, y = ignore_background(y_pred=y_pred, y=y) + + # Reducing only spatial dimensions (not batch nor channels), compute the intersection and non-weighted denominator + reduce_axis = list(range(2, y_pred.dim())) + intersection = torch.sum(y * y_pred, dim=reduce_axis) + y_o = torch.sum(y, dim=reduce_axis) + y_pred_o = torch.sum(y_pred, dim=reduce_axis) + denominator = y_o + y_pred_o + + # Set the class weights + weight_type = look_up_option(weight_type, Weight) + if weight_type == Weight.SIMPLE: + w = torch.reciprocal(y_o.float()) + elif weight_type == Weight.SQUARE: + w = torch.reciprocal(y_o.float() * y_o.float()) + else: + w = torch.ones_like(y_o.float()) + + # Replace infinite values for non-appearing classes by the maximum weight + for b in w: + infs = torch.isinf(b) + b[infs] = 0 + b[infs] = torch.max(b) + + # Compute the weighted numerator and denominator, summing along the class axis + numer = 2.0 * (intersection * w).sum(dim=1) + denom = (denominator * w).sum(dim=1) + + # Compute the score + generalized_dice_score = numer / denom + + # Handle zero division. Where denom == 0 and the prediction volume is 0, score is 1. + # Where denom == 0 but the prediction volume is not 0, score is 0 + y_pred_o = y_pred_o.sum(dim=-1) + denom_zeros = denom == 0 + generalized_dice_score[denom_zeros] = torch.where( + (y_pred_o == 0)[denom_zeros], + torch.tensor(1.0, device=generalized_dice_score.device), + torch.tensor(0.0, device=generalized_dice_score.device), + ) + + return generalized_dice_score diff --git a/source_code/SegMamba/monai/metrics/meaniou.py b/source_code/SegMamba/monai/metrics/meaniou.py new file mode 100644 index 0000000000000000000000000000000000000000..65c53f7aa59c8da0a983ce94f38ee88b5ad7dd19 --- /dev/null +++ b/source_code/SegMamba/monai/metrics/meaniou.py @@ -0,0 +1,147 @@ +# Copyright (c) MONAI Consortium +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from __future__ import annotations + +import torch + +from monai.metrics.utils import do_metric_reduction, ignore_background +from monai.utils import MetricReduction + +from .metric import CumulativeIterationMetric + + +class MeanIoU(CumulativeIterationMetric): + """ + Compute average Intersection over Union (IoU) score between two tensors. + It supports both multi-classes and multi-labels tasks. + Input `y_pred` is compared with ground truth `y`. + `y_pred` is expected to have binarized predictions and `y` should be in one-hot format. You can use suitable transforms + in ``monai.transforms.post`` first to achieve binarized values. + The `include_background` parameter can be set to ``False`` to exclude + the first category (channel index 0) which is by convention assumed to be background. If the non-background + segmentations are small compared to the total image size they can get overwhelmed by the signal from the + background. + `y_pred` and `y` can be a list of channel-first Tensor (CHW[D]) or a batch-first Tensor (BCHW[D]). + + Example of the typical execution steps of this metric class follows :py:class:`monai.metrics.metric.Cumulative`. + + Args: + include_background: whether to include IoU computation on the first channel of + the predicted output. Defaults to ``True``. + reduction: define mode of reduction to the metrics, will only apply reduction on `not-nan` values, + available reduction modes: {``"none"``, ``"mean"``, ``"sum"``, ``"mean_batch"``, ``"sum_batch"``, + ``"mean_channel"``, ``"sum_channel"``}, default to ``"mean"``. if "none", will not do reduction. + get_not_nans: whether to return the `not_nans` count, if True, aggregate() returns (metric, not_nans). + Here `not_nans` count the number of not nans for the metric, thus its shape equals to the shape of the metric. + ignore_empty: whether to ignore empty ground truth cases during calculation. + If `True`, NaN value will be set for empty ground truth cases. + If `False`, 1 will be set if the predictions of empty ground truth cases are also empty. + + """ + + def __init__( + self, + include_background: bool = True, + reduction: MetricReduction | str = MetricReduction.MEAN, + get_not_nans: bool = False, + ignore_empty: bool = True, + ) -> None: + super().__init__() + self.include_background = include_background + self.reduction = reduction + self.get_not_nans = get_not_nans + self.ignore_empty = ignore_empty + + def _compute_tensor(self, y_pred: torch.Tensor, y: torch.Tensor) -> torch.Tensor: # type: ignore[override] + """ + Args: + y_pred: input data to compute, typical segmentation model output. + It must be one-hot format and first dim is batch, example shape: [16, 3, 32, 32]. The values + should be binarized. + y: ground truth to compute mean IoU metric. It must be one-hot format and first dim is batch. + The values should be binarized. + + Raises: + ValueError: when `y_pred` has less than three dimensions. + """ + dims = y_pred.ndimension() + if dims < 3: + raise ValueError(f"y_pred should have at least 3 dimensions (batch, channel, spatial), got {dims}.") + # compute IoU (BxC) for each channel for each batch + return compute_iou( + y_pred=y_pred, y=y, include_background=self.include_background, ignore_empty=self.ignore_empty + ) + + def aggregate( + self, reduction: MetricReduction | str | None = None + ) -> torch.Tensor | tuple[torch.Tensor, torch.Tensor]: + """ + Execute reduction logic for the output of `compute_iou`. + + Args: + reduction: define mode of reduction to the metrics, will only apply reduction on `not-nan` values, + available reduction modes: {``"none"``, ``"mean"``, ``"sum"``, ``"mean_batch"``, ``"sum_batch"``, + ``"mean_channel"``, ``"sum_channel"``}, default to `self.reduction`. if "none", will not do reduction. + + """ + data = self.get_buffer() + if not isinstance(data, torch.Tensor): + raise ValueError("the data to aggregate must be PyTorch Tensor.") + + # do metric reduction + f, not_nans = do_metric_reduction(data, reduction or self.reduction) + return (f, not_nans) if self.get_not_nans else f + + +def compute_iou( + y_pred: torch.Tensor, y: torch.Tensor, include_background: bool = True, ignore_empty: bool = True +) -> torch.Tensor: + """Computes Intersection over Union (IoU) score metric from a batch of predictions. + + Args: + y_pred: input data to compute, typical segmentation model output. + It must be one-hot format and first dim is batch, example shape: [16, 3, 32, 32]. The values + should be binarized. + y: ground truth to compute mean IoU metric. It must be one-hot format and first dim is batch. + The values should be binarized. + include_background: whether to include IoU computation on the first channel of + the predicted output. Defaults to True. + ignore_empty: whether to ignore empty ground truth cases during calculation. + If `True`, NaN value will be set for empty ground truth cases. + If `False`, 1 will be set if the predictions of empty ground truth cases are also empty. + + Returns: + IoU scores per batch and per class, (shape [batch_size, num_classes]). + + Raises: + ValueError: when `y_pred` and `y` have different shapes. + + """ + + if not include_background: + y_pred, y = ignore_background(y_pred=y_pred, y=y) + + if y.shape != y_pred.shape: + raise ValueError(f"y_pred and y should have same shapes, got {y_pred.shape} and {y.shape}.") + + # reducing only spatial dimensions (not batch nor channels) + n_len = len(y_pred.shape) + reduce_axis = list(range(2, n_len)) + intersection = torch.sum(y * y_pred, dim=reduce_axis) + + y_o = torch.sum(y, reduce_axis) + y_pred_o = torch.sum(y_pred, dim=reduce_axis) + union = y_o + y_pred_o - intersection + + if ignore_empty: + return torch.where(y_o > 0, (intersection) / union, torch.tensor(float("nan"), device=y_o.device)) + return torch.where(union > 0, (intersection) / union, torch.tensor(1.0, device=y_o.device)) diff --git a/source_code/SegMamba/monai/metrics/metric.py b/source_code/SegMamba/monai/metrics/metric.py new file mode 100644 index 0000000000000000000000000000000000000000..249b2dc951a17bb1149a47ed6dc970873d537aff --- /dev/null +++ b/source_code/SegMamba/monai/metrics/metric.py @@ -0,0 +1,353 @@ +# Copyright (c) MONAI Consortium +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from __future__ import annotations + +from abc import ABC, abstractmethod +from collections.abc import Sequence +from typing import Any + +import torch + +from monai.config import TensorOrList +from monai.utils import convert_data_type, evenly_divisible_all_gather + +__all__ = ["Metric", "IterationMetric", "Cumulative", "CumulativeIterationMetric"] + + +class Metric(ABC): + """ + Base class for metric computation for evaluating the performance of a model. + `__call__` is designed to execute the computation. + + """ + + @abstractmethod + def __call__(self, *args: Any, **kwargs: Any) -> Any: + """ + This method should take raw model outputs as inputs, and return values that measure the models' quality. + """ + raise NotImplementedError(f"Subclass {self.__class__.__name__} must implement this method.") + + def __str__(self): + return self.__class__.__name__ + + +class IterationMetric(Metric): + """ + Base class for metrics computation at the iteration level, that is, on a min-batch of samples + usually using the model outcome of one iteration. + + `__call__` is designed to handle `y_pred` and `y` (optional) in torch tensors or a list/tuple of tensors. + + Subclasses typically implement the `_compute_tensor` function for the actual tensor computation logic. + """ + + def __call__( + self, y_pred: TensorOrList, y: TensorOrList | None = None, **kwargs: Any + ) -> torch.Tensor | Sequence[torch.Tensor | Sequence[torch.Tensor]]: + """ + Execute basic computation for model prediction `y_pred` and ground truth `y` (optional). + It supports inputs of a list of "channel-first" Tensor and a "batch-first" Tensor. + + Args: + y_pred: the raw model prediction data at one iteration, must be a list of `channel-first` Tensor + or a `batch-first` Tensor. + y: the ground truth to compute, must be a list of `channel-first` Tensor + or a `batch-first` Tensor. + kwargs: additional parameters for specific metric computation logic (e.g. ``spacing`` for SurfaceDistanceMetric, etc.). + + Returns: + The computed metric values at the iteration level. + The output shape could be a `batch-first` tensor or a list of `batch-first` tensors. + When it's a list of tensors, each item in the list can represent a specific type of metric. + + """ + # handling a list of channel-first data + if isinstance(y_pred, (list, tuple)) or isinstance(y, (list, tuple)): + return self._compute_list(y_pred, y, **kwargs) + # handling a single batch-first data + if isinstance(y_pred, torch.Tensor): + y_ = y.detach() if isinstance(y, torch.Tensor) else None + return self._compute_tensor(y_pred.detach(), y_, **kwargs) + raise ValueError("y_pred or y must be a list/tuple of `channel-first` Tensors or a `batch-first` Tensor.") + + def _compute_list( + self, y_pred: TensorOrList, y: TensorOrList | None = None, **kwargs: Any + ) -> torch.Tensor | list[torch.Tensor | Sequence[torch.Tensor]]: + """ + Execute the metric computation for `y_pred` and `y` in a list of "channel-first" tensors. + + The return value is a "batch-first" tensor, or a list of "batch-first" tensors. + When it's a list of tensors, each item in the list can represent a specific type of metric values. + + For example, `self._compute_tensor` may be implemented as returning a list of `batch_size` items, + where each item is a tuple of three values `tp`, `fp`, `fn` for true positives, false positives, + and false negatives respectively. This function will return a list of three items, + (`tp_batched`, `fp_batched`, `fn_batched`), where each item is a `batch_size`-length tensor. + + Note: subclass may enhance the operation to have multi-thread support. + """ + if y is not None: + ret = [ + self._compute_tensor(p.detach().unsqueeze(0), y_.detach().unsqueeze(0), **kwargs) + for p, y_ in zip(y_pred, y) + ] + else: + ret = [self._compute_tensor(p_.detach().unsqueeze(0), None, **kwargs) for p_ in y_pred] + + # concat the list of results (e.g. a batch of evaluation scores) + if isinstance(ret[0], torch.Tensor): + return torch.cat(ret, dim=0) # type: ignore[arg-type] + # the result is a list of sequence of tensors (e.g. a batch of multi-class results) + if isinstance(ret[0], (list, tuple)) and all(isinstance(i, torch.Tensor) for i in ret[0]): + return [torch.cat(batch_i, dim=0) for batch_i in zip(*ret)] + return ret + + @abstractmethod + def _compute_tensor(self, y_pred: torch.Tensor, y: torch.Tensor | None = None, **kwargs: Any) -> TensorOrList: + """ + Computation logic for `y_pred` and `y` of an iteration, the data should be "batch-first" Tensors. + A subclass should implement its own computation logic. + The return value is usually a "batch_first" tensor, or a list of "batch_first" tensors. + """ + raise NotImplementedError(f"Subclass {self.__class__.__name__} must implement this method.") + + +class Cumulative: + """ + Utility class for the typical cumulative computation process based on PyTorch Tensors. + It provides interfaces to accumulate values in the local buffers, synchronize buffers across distributed nodes, + and aggregate the buffered values. + + In multi-processing, PyTorch programs usually distribute data to multiple nodes. Each node runs with a subset + of the data, adds values to its local buffers. Calling `get_buffer` could gather all the results and + `aggregate` can further handle the results to generate the final outcomes. + + Users can implement their own `aggregate` method to handle the results, + using `get_buffer` to get the buffered contents. + + Note: the data list should have the same length every time calling `add()` in a round, + it will automatically create buffers according to the length of data list. + + Typically, this class is expected to execute the following steps: + + .. code-block:: python + + from monai.metrics import Cumulative + + c = Cumulative() + c.append(1) # adds a value + c.extend([2, 3]) # adds a batch of values + c.extend([4, 5, 6]) # adds a batch of values + print(c.get_buffer()) # tensor([1, 2, 3, 4, 5, 6]) + print(len(c)) # 6 + c.reset() + print(len(c)) # 0 + + The following is an example of maintaining two internal buffers: + + .. code-block:: python + + from monai.metrics import Cumulative + + c = Cumulative() + c.append(1, 2) # adds a value to two buffers respectively + c.extend([3, 4], [5, 6]) # adds batches of values + print(c.get_buffer()) # [tensor([1, 3, 4]), tensor([2, 5, 6])] + print(len(c)) + + The following is an example of extending with variable length data: + + .. code-block:: python + + import torch + from monai.metrics import Cumulative + + c = Cumulative() + c.extend(torch.zeros((8, 2)), torch.zeros((6, 2))) # adds batches + c.append(torch.zeros((2, ))) # adds a value + print(c.get_buffer()) # [torch.zeros((9, 2)), torch.zeros((6, 2))] + print(len(c)) + + """ + + def __init__(self) -> None: + """ + Initialize the internal buffers. + `self._buffers` are local buffers, they are not usually used directly. + `self._sync_buffers` are the buffers with all the results across all the nodes. + """ + self._buffers: list[list[torch.Tensor]] | None = None + self._synced_tensors: list[torch.Tensor | None] | None = None + self._synced: bool = False + self.reset() + + def reset(self): + """ + Reset the buffers for cumulative tensors and the synced results. + + """ + self._buffers = None + self._synced_tensors = None + self._synced = False + + def extend(self, *data: Any) -> None: + """ + Extend the local buffers with new ("batch-first") data. + A buffer will be allocated for each `data` item. + Compared with `self.append`, this method adds a "batch" of data to the local buffers. + + Args: + data: each item can be a "batch-first" tensor or a list of "channel-first" tensors. + they will be concatenated at the 0-th dimension when `get_buffer()` is called. + """ + if self._buffers is None: + self._buffers = [[] for _ in data] + for b, d in zip(self._buffers, data): + # converting to pytorch tensors so that we can use the distributed API + d_t, *_ = convert_data_type(d, output_type=torch.Tensor, wrap_sequence=True) + try: # d_t must be a mini-batch of values + b.extend([x[0] for x in torch.split(d_t, 1, dim=0)]) + except (AttributeError, IndexError, RuntimeError) as e: + raise TypeError( + f"{e}. `data` should be a batch-first tensor or" + f" a list of channel-first tensors, got {type(d_t)}" + ) from e + self._synced = False + + def append(self, *data: Any) -> None: + """ + Add samples to the local cumulative buffers. + A buffer will be allocated for each `data` item. + Compared with `self.extend`, this method adds a single sample (instead + of a "batch") to the local buffers. + + Args: + data: each item will be converted into a torch tensor. + they will be stacked at the 0-th dim with a new dimension when `get_buffer()` is called. + + """ + if self._buffers is None: + self._buffers = [[] for _ in data] + for b, d in zip(self._buffers, data): + # converting to pytorch tensors so that we can use the distributed API + d_t, *_ = convert_data_type(d, output_type=torch.Tensor, wrap_sequence=True) + b.append(d_t) + self._synced = False + + @abstractmethod + def aggregate(self, *args: Any, **kwargs: Any) -> Any: + """ + Aggregate final results based on the gathered buffers. + This method is expected to use `get_buffer` to gather the local buffer contents. + + """ + raise NotImplementedError(f"Subclass {self.__class__.__name__} must implement this method.") + + def _sync(self): + """ + All gather the buffers across distributed ranks for aggregating. + Each buffer will be concatenated as a PyTorch Tensor. + + """ + if self._synced or self._buffers is None: + return + try: + self._synced_tensors = [ + evenly_divisible_all_gather(torch.stack(b, dim=0), concat=True) for b in self._buffers + ] + except (RuntimeError, TypeError, ValueError) as e: + raise TypeError(f"{e}. unable to sync buffer contents: {self._buffers}.") from e + self._synced = True + + def __len__(self): + """ + Return the length of the largest buffer. + Note that the method will trigger synchronization of the local buffers. + """ + self._sync() + if self._synced_tensors is None: + return 0 + return max(len(x) for x in self._synced_tensors if x is not None) + + def get_buffer(self): + """ + Get the synchronized list of buffers. + A typical usage is to generate the metrics report based on the raw metric details. + Each buffer is a PyTorch Tensor. + + """ + self._sync() + if self._synced_tensors is None: + return self._synced_tensors + buffers = [x.detach().clone() if isinstance(x, torch.Tensor) else x for x in self._synced_tensors] + return buffers[0] if len(buffers) == 1 else buffers + + +class CumulativeIterationMetric(Cumulative, IterationMetric): + """ + Base class of cumulative metric which collects metrics on each mini-batch data at the iteration level. + + Typically, it computes some intermediate results for each iteration, adds them to the buffers, + then the buffer contents could be gathered and aggregated for the final result when epoch completed. + Currently,``Cumulative.aggregate()`` and ``IterationMetric._compute_tensor()`` are expected to be implemented. + + For example, `MeanDice` inherits this class and the usage is as follows: + + .. code-block:: python + + dice_metric = DiceMetric(include_background=True, reduction="mean") + + for val_data in val_loader: + val_outputs = model(val_data["img"]) + val_outputs = [postprocessing_transform(i) for i in decollate_batch(val_outputs)] + # compute metric for current iteration + dice_metric(y_pred=val_outputs, y=val_data["seg"]) # callable to add metric to the buffer + + # aggregate the final mean dice result + metric = dice_metric.aggregate().item() + + # reset the status for next computation round + dice_metric.reset() + + And to load `predictions` and `labels` from files, then compute metrics with multi-processing, please refer to: + https://github.com/Project-MONAI/tutorials/blob/master/modules/compute_metric.py. + + """ + + def __call__( + self, y_pred: TensorOrList, y: TensorOrList | None = None, **kwargs: Any + ) -> torch.Tensor | Sequence[torch.Tensor | Sequence[torch.Tensor]]: + """ + Execute basic computation for model prediction and ground truth. + It can support both `list of channel-first Tensor` and `batch-first Tensor`. + Users call this API to execute computation on every batch of data, then accumulate the results, + or accumulate the original `y_pred` and `y`, then execute on the accumulated data. + + Args: + y_pred: the model prediction data to compute, must be a list of `channel-first` Tensor + or a `batch-first` Tensor. + y: the ground truth to compute, must be a list of `channel-first` Tensor + or a `batch-first` Tensor. + kwargs: additional parameters for specific metric computation logic (e.g. ``spacing`` for SurfaceDistanceMetric, etc.). + + Returns: + The computed metric values at the iteration level. The output shape should be + a `batch-first` tensor (BC[HWD]) or a list of `batch-first` tensors. + """ + ret = super().__call__(y_pred=y_pred, y=y, **kwargs) + if isinstance(ret, (tuple, list)): + self.extend(*ret) + else: + self.extend(ret) + + return ret diff --git a/source_code/SegMamba/monai/metrics/rocauc.py b/source_code/SegMamba/monai/metrics/rocauc.py new file mode 100644 index 0000000000000000000000000000000000000000..56d9faa9dd69d461385e43d66a6905c163235aaf --- /dev/null +++ b/source_code/SegMamba/monai/metrics/rocauc.py @@ -0,0 +1,182 @@ +# Copyright (c) MONAI Consortium +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from __future__ import annotations + +import warnings +from typing import TYPE_CHECKING, cast + +import numpy as np + +if TYPE_CHECKING: + import numpy.typing as npt + +import torch + +from monai.utils import Average, look_up_option + +from .metric import CumulativeIterationMetric + + +class ROCAUCMetric(CumulativeIterationMetric): + """ + Computes Area Under the Receiver Operating Characteristic Curve (ROC AUC). Referring to: + `sklearn.metrics.roc_auc_score `_. + The input `y_pred` and `y` can be a list of `channel-first` Tensor or a `batch-first` Tensor. + + Example of the typical execution steps of this metric class follows :py:class:`monai.metrics.metric.Cumulative`. + + Args: + average: {``"macro"``, ``"weighted"``, ``"micro"``, ``"none"``} + Type of averaging performed if not binary classification. + Defaults to ``"macro"``. + + - ``"macro"``: calculate metrics for each label, and find their unweighted mean. + This does not take label imbalance into account. + - ``"weighted"``: calculate metrics for each label, and find their average, + weighted by support (the number of true instances for each label). + - ``"micro"``: calculate metrics globally by considering each element of the label + indicator matrix as a label. + - ``"none"``: the scores for each class are returned. + + """ + + def __init__(self, average: Average | str = Average.MACRO) -> None: + super().__init__() + self.average = average + + def _compute_tensor(self, y_pred: torch.Tensor, y: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]: # type: ignore[override] + return y_pred, y + + def aggregate(self, average: Average | str | None = None) -> np.ndarray | float | npt.ArrayLike: + """ + Typically `y_pred` and `y` are stored in the cumulative buffers at each iteration, + This function reads the buffers and computes the area under the ROC. + + Args: + average: {``"macro"``, ``"weighted"``, ``"micro"``, ``"none"``} + Type of averaging performed if not binary classification. Defaults to `self.average`. + + """ + y_pred, y = self.get_buffer() + # compute final value and do metric reduction + if not isinstance(y_pred, torch.Tensor) or not isinstance(y, torch.Tensor): + raise ValueError("y_pred and y must be PyTorch Tensor.") + + return compute_roc_auc(y_pred=y_pred, y=y, average=average or self.average) + + +def _calculate(y_pred: torch.Tensor, y: torch.Tensor) -> float: + if not (y.ndimension() == y_pred.ndimension() == 1 and len(y) == len(y_pred)): + raise AssertionError("y and y_pred must be 1 dimension data with same length.") + y_unique = y.unique() + if len(y_unique) == 1: + warnings.warn(f"y values can not be all {y_unique.item()}, skip AUC computation and return `Nan`.") + return float("nan") + if not y_unique.equal(torch.tensor([0, 1], dtype=y.dtype, device=y.device)): + warnings.warn(f"y values must be 0 or 1, but in {y_unique.tolist()}, skip AUC computation and return `Nan`.") + return float("nan") + + n = len(y) + indices = y_pred.argsort() + y = y[indices].cpu().numpy() + y_pred = y_pred[indices].cpu().numpy() + nneg = auc = tmp_pos = tmp_neg = 0.0 + + for i in range(n): + y_i = cast(float, y[i]) + if i + 1 < n and y_pred[i] == y_pred[i + 1]: + tmp_pos += y_i + tmp_neg += 1 - y_i + continue + if tmp_pos + tmp_neg > 0: + tmp_pos += y_i + tmp_neg += 1 - y_i + nneg += tmp_neg + auc += tmp_pos * (nneg - tmp_neg / 2) + tmp_pos = tmp_neg = 0 + continue + if y_i == 1: + auc += nneg + else: + nneg += 1 + return auc / (nneg * (n - nneg)) + + +def compute_roc_auc( + y_pred: torch.Tensor, y: torch.Tensor, average: Average | str = Average.MACRO +) -> np.ndarray | float | npt.ArrayLike: + """Computes Area Under the Receiver Operating Characteristic Curve (ROC AUC). Referring to: + `sklearn.metrics.roc_auc_score `_. + + Args: + y_pred: input data to compute, typical classification model output. + the first dim must be batch, if multi-classes, it must be in One-Hot format. + for example: shape `[16]` or `[16, 1]` for a binary data, shape `[16, 2]` for 2 classes data. + y: ground truth to compute ROC AUC metric, the first dim must be batch. + if multi-classes, it must be in One-Hot format. + for example: shape `[16]` or `[16, 1]` for a binary data, shape `[16, 2]` for 2 classes data. + average: {``"macro"``, ``"weighted"``, ``"micro"``, ``"none"``} + Type of averaging performed if not binary classification. + Defaults to ``"macro"``. + + - ``"macro"``: calculate metrics for each label, and find their unweighted mean. + This does not take label imbalance into account. + - ``"weighted"``: calculate metrics for each label, and find their average, + weighted by support (the number of true instances for each label). + - ``"micro"``: calculate metrics globally by considering each element of the label + indicator matrix as a label. + - ``"none"``: the scores for each class are returned. + + Raises: + ValueError: When ``y_pred`` dimension is not one of [1, 2]. + ValueError: When ``y`` dimension is not one of [1, 2]. + ValueError: When ``average`` is not one of ["macro", "weighted", "micro", "none"]. + + Note: + ROCAUC expects y to be comprised of 0's and 1's. `y_pred` must be either prob. estimates or confidence values. + + """ + y_pred_ndim = y_pred.ndimension() + y_ndim = y.ndimension() + if y_pred_ndim not in (1, 2): + raise ValueError( + f"Predictions should be of shape (batch_size, num_classes) or (batch_size, ), got {y_pred.shape}." + ) + if y_ndim not in (1, 2): + raise ValueError(f"Targets should be of shape (batch_size, num_classes) or (batch_size, ), got {y.shape}.") + if y_pred_ndim == 2 and y_pred.shape[1] == 1: + y_pred = y_pred.squeeze(dim=-1) + y_pred_ndim = 1 + if y_ndim == 2 and y.shape[1] == 1: + y = y.squeeze(dim=-1) + + if y_pred_ndim == 1: + return _calculate(y_pred, y) + + if y.shape != y_pred.shape: + raise ValueError(f"data shapes of y_pred and y do not match, got {y_pred.shape} and {y.shape}.") + + average = look_up_option(average, Average) + if average == Average.MICRO: + return _calculate(y_pred.flatten(), y.flatten()) + y, y_pred = y.transpose(0, 1), y_pred.transpose(0, 1) + auc_values = [_calculate(y_pred_, y_) for y_pred_, y_ in zip(y_pred, y)] + if average == Average.NONE: + return auc_values + if average == Average.MACRO: + return np.mean(auc_values) + if average == Average.WEIGHTED: + weights = [sum(y_) for y_ in y] + return np.average(auc_values, weights=weights) # type: ignore[no-any-return] + raise ValueError(f'Unsupported average: {average}, available options are ["macro", "weighted", "micro", "none"].') diff --git a/source_code/SegMamba/monai/metrics/surface_dice.py b/source_code/SegMamba/monai/metrics/surface_dice.py new file mode 100644 index 0000000000000000000000000000000000000000..b20b47a1a50fd813b30b5ada28992247a69c8e5b --- /dev/null +++ b/source_code/SegMamba/monai/metrics/surface_dice.py @@ -0,0 +1,279 @@ +# Copyright (c) MONAI Consortium +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from __future__ import annotations + +from collections.abc import Sequence +from typing import Any + +import numpy as np +import torch + +from monai.metrics.utils import do_metric_reduction, get_edge_surface_distance, ignore_background, prepare_spacing +from monai.utils import MetricReduction + +from .metric import CumulativeIterationMetric + + +class SurfaceDiceMetric(CumulativeIterationMetric): + """ + Computes the Normalized Surface Dice (NSD) for each batch sample and class of + predicted segmentations `y_pred` and corresponding reference segmentations `y` according to equation :eq:`nsd`. + This implementation is based on https://arxiv.org/abs/2111.05408 and supports 2D and 3D images. + Be aware that by default (`use_subvoxels=False`), the computation of boundaries is different from DeepMind's + implementation https://github.com/deepmind/surface-distance. + In this implementation, the length/area of a segmentation boundary is + interpreted as the number of its edge pixels. In DeepMind's implementation, the length of a segmentation boundary + depends on the local neighborhood (cf. https://arxiv.org/abs/1809.04430). + This issue is discussed here: https://github.com/Project-MONAI/MONAI/issues/4103. + + The class- and batch sample-wise NSD values can be aggregated with the function `aggregate`. + + Example of the typical execution steps of this metric class follows :py:class:`monai.metrics.metric.Cumulative`. + + Args: + class_thresholds: List of class-specific thresholds. + The thresholds relate to the acceptable amount of deviation in the segmentation boundary in pixels. + Each threshold needs to be a finite, non-negative number. + include_background: Whether to include NSD computation on the first channel of the predicted output. + Defaults to ``False``. + distance_metric: The metric used to compute surface distances. + One of [``"euclidean"``, ``"chessboard"``, ``"taxicab"``]. + Defaults to ``"euclidean"``. + reduction: define mode of reduction to the metrics, will only apply reduction on `not-nan` values, + available reduction modes: {``"none"``, ``"mean"``, ``"sum"``, ``"mean_batch"``, ``"sum_batch"``, + ``"mean_channel"``, ``"sum_channel"``}, default to ``"mean"``. if "none", will not do reduction. + get_not_nans: whether to return the `not_nans` count. + Defaults to ``False``. + `not_nans` is the number of batch samples for which not all class-specific NSD values were nan values. + If set to ``True``, the function `aggregate` will return both the aggregated NSD and the `not_nans` count. + If set to ``False``, `aggregate` will only return the aggregated NSD. + use_subvoxels: Whether to use subvoxel distances. Defaults to ``False``. + """ + + def __init__( + self, + class_thresholds: list[float], + include_background: bool = False, + distance_metric: str = "euclidean", + reduction: MetricReduction | str = MetricReduction.MEAN, + get_not_nans: bool = False, + use_subvoxels: bool = False, + ) -> None: + super().__init__() + self.class_thresholds = class_thresholds + self.include_background = include_background + self.distance_metric = distance_metric + self.reduction = reduction + self.get_not_nans = get_not_nans + self.use_subvoxels = use_subvoxels + + def _compute_tensor(self, y_pred: torch.Tensor, y: torch.Tensor, **kwargs: Any) -> torch.Tensor: # type: ignore[override] + r""" + Args: + y_pred: Predicted segmentation, typically segmentation model output. + It must be a one-hot encoded, batch-first tensor [B,C,H,W] or [B,C,H,W,D]. + y: Reference segmentation. + It must be a one-hot encoded, batch-first tensor [B,C,H,W] or [B,C,H,W,D]. + kwargs: additional parameters: ``spacing`` should be passed to correctly compute the metric. + ``spacing``: spacing of pixel (or voxel). This parameter is relevant only + if ``distance_metric`` is set to ``"euclidean"``. + If a single number, isotropic spacing with that value is used for all images in the batch. If a sequence of numbers, + the length of the sequence must be equal to the image dimensions. + This spacing will be used for all images in the batch. + If a sequence of sequences, the length of the outer sequence must be equal to the batch size. + If inner sequence has length 1, isotropic spacing with that value is used for all images in the batch, + else the inner sequence length must be equal to the image dimensions. If ``None``, spacing of unity is used + for all images in batch. Defaults to ``None``. + use_subvoxels: Whether to use subvoxel distances. Defaults to ``False``. + + + Returns: + Pytorch Tensor of shape [B,C], containing the NSD values :math:`\operatorname {NSD}_{b,c}` for each batch + index :math:`b` and class :math:`c`. + """ + return compute_surface_dice( + y_pred=y_pred, + y=y, + class_thresholds=self.class_thresholds, + include_background=self.include_background, + distance_metric=self.distance_metric, + spacing=kwargs.get("spacing"), + use_subvoxels=self.use_subvoxels, + ) + + def aggregate( + self, reduction: MetricReduction | str | None = None + ) -> torch.Tensor | tuple[torch.Tensor, torch.Tensor]: + r""" + Aggregates the output of `_compute_tensor`. + + Args: + reduction: define mode of reduction to the metrics, will only apply reduction on `not-nan` values, + available reduction modes: {``"none"``, ``"mean"``, ``"sum"``, ``"mean_batch"``, ``"sum_batch"``, + ``"mean_channel"``, ``"sum_channel"``}, default to `self.reduction`. if "none", will not do reduction. + + Returns: + If `get_not_nans` is set to ``True``, this function returns the aggregated NSD and the `not_nans` count. + If `get_not_nans` is set to ``False``, this function returns only the aggregated NSD. + """ + data = self.get_buffer() + if not isinstance(data, torch.Tensor): + raise ValueError("the data to aggregate must be PyTorch Tensor.") + + # do metric reduction + f, not_nans = do_metric_reduction(data, reduction or self.reduction) + return (f, not_nans) if self.get_not_nans else f + + +def compute_surface_dice( + y_pred: torch.Tensor, + y: torch.Tensor, + class_thresholds: list[float], + include_background: bool = False, + distance_metric: str = "euclidean", + spacing: int | float | np.ndarray | Sequence[int | float | np.ndarray | Sequence[int | float]] | None = None, + use_subvoxels: bool = False, +) -> torch.Tensor: + r""" + This function computes the (Normalized) Surface Dice (NSD) between the two tensors `y_pred` (referred to as + :math:`\hat{Y}`) and `y` (referred to as :math:`Y`). This metric determines which fraction of a segmentation + boundary is correctly predicted. A boundary element is considered correctly predicted if the closest distance to the + reference boundary is smaller than or equal to the specified threshold related to the acceptable amount of deviation + in pixels. The NSD is bounded between 0 and 1. + + This implementation supports multi-class tasks with an individual threshold :math:`\tau_c` for each class :math:`c`. + The class-specific NSD for batch index :math:`b`, :math:`\operatorname {NSD}_{b,c}`, is computed using the function: + + .. math:: + \operatorname {NSD}_{b,c} \left(Y_{b,c}, \hat{Y}_{b,c}\right) = \frac{\left|\mathcal{D}_{Y_{b,c}}^{'}\right| + + \left| \mathcal{D}_{\hat{Y}_{b,c}}^{'} \right|}{\left|\mathcal{D}_{Y_{b,c}}\right| + + \left|\mathcal{D}_{\hat{Y}_{b,c}}\right|} + :label: nsd + + with :math:`\mathcal{D}_{Y_{b,c}}` and :math:`\mathcal{D}_{\hat{Y}_{b,c}}` being two sets of nearest-neighbor + distances. :math:`\mathcal{D}_{Y_{b,c}}` is computed from the predicted segmentation boundary towards the reference + segmentation boundary and vice-versa for :math:`\mathcal{D}_{\hat{Y}_{b,c}}`. :math:`\mathcal{D}_{Y_{b,c}}^{'}` and + :math:`\mathcal{D}_{\hat{Y}_{b,c}}^{'}` refer to the subsets of distances that are smaller or equal to the + acceptable distance :math:`\tau_c`: + + .. math:: + \mathcal{D}_{Y_{b,c}}^{'} = \{ d \in \mathcal{D}_{Y_{b,c}} \, | \, d \leq \tau_c \}. + + + In the case of a class neither being present in the predicted segmentation, nor in the reference segmentation, + a nan value will be returned for this class. In the case of a class being present in only one of predicted + segmentation or reference segmentation, the class NSD will be 0. + + This implementation is based on https://arxiv.org/abs/2111.05408 and supports 2D and 3D images. + The computation of boundaries follows DeepMind's implementation + https://github.com/deepmind/surface-distance when `use_subvoxels=True`; Otherwise the length of a segmentation + boundary is interpreted as the number of its edge pixels. + + Args: + y_pred: Predicted segmentation, typically segmentation model output. + It must be a one-hot encoded, batch-first tensor [B,C,H,W] or [B,C,H,W,D]. + y: Reference segmentation. + It must be a one-hot encoded, batch-first tensor [B,C,H,W] or [B,C,H,W,D]. + class_thresholds: List of class-specific thresholds. + The thresholds relate to the acceptable amount of deviation in the segmentation boundary in pixels. + Each threshold needs to be a finite, non-negative number. + include_background: Whether to include the surface dice computation on the first channel of + the predicted output. Defaults to ``False``. + distance_metric: The metric used to compute surface distances. + One of [``"euclidean"``, ``"chessboard"``, ``"taxicab"``]. + Defaults to ``"euclidean"``. + spacing: spacing of pixel (or voxel). This parameter is relevant only if ``distance_metric`` is set to ``"euclidean"``. + If a single number, isotropic spacing with that value is used for all images in the batch. If a sequence of numbers, + the length of the sequence must be equal to the image dimensions. This spacing will be used for all images in the batch. + If a sequence of sequences, the length of the outer sequence must be equal to the batch size. + If inner sequence has length 1, isotropic spacing with that value is used for all images in the batch, + else the inner sequence length must be equal to the image dimensions. If ``None``, spacing of unity is used + for all images in batch. Defaults to ``None``. + use_subvoxels: Whether to use subvoxel distances. Defaults to ``False``. + + Raises: + ValueError: If `y_pred` and/or `y` are not PyTorch tensors. + ValueError: If `y_pred` and/or `y` do not have four dimensions. + ValueError: If `y_pred` and/or `y` have different shapes. + ValueError: If `y_pred` and/or `y` are not one-hot encoded + ValueError: If the number of channels of `y_pred` and/or `y` is different from the number of class thresholds. + ValueError: If any class threshold is not finite. + ValueError: If any class threshold is negative. + + Returns: + Pytorch Tensor of shape [B,C], containing the NSD values :math:`\operatorname {NSD}_{b,c}` for each batch index + :math:`b` and class :math:`c`. + """ + + if not include_background: + y_pred, y = ignore_background(y_pred=y_pred, y=y) + + if not isinstance(y_pred, torch.Tensor) or not isinstance(y, torch.Tensor): + raise ValueError("y_pred and y must be PyTorch Tensor.") + + if y_pred.ndimension() not in (4, 5) or y.ndimension() not in (4, 5): + raise ValueError("y_pred and y should be one-hot encoded: [B,C,H,W] or [B,C,H,W,D].") + + if y_pred.shape != y.shape: + raise ValueError( + f"y_pred and y should have same shape, but instead, shapes are {y_pred.shape} (y_pred) and {y.shape} (y)." + ) + + batch_size, n_class = y_pred.shape[:2] + + if n_class != len(class_thresholds): + raise ValueError( + f"number of classes ({n_class}) does not match number of class thresholds ({len(class_thresholds)})." + ) + + if any(~np.isfinite(class_thresholds)): + raise ValueError("All class thresholds need to be finite.") + + if any(np.array(class_thresholds) < 0): + raise ValueError("All class thresholds need to be >= 0.") + + nsd = torch.empty((batch_size, n_class), device=y_pred.device, dtype=torch.float) + + img_dim = y_pred.ndim - 2 + spacing_list = prepare_spacing(spacing=spacing, batch_size=batch_size, img_dim=img_dim) + + for b, c in np.ndindex(batch_size, n_class): + (edges_pred, edges_gt), (distances_pred_gt, distances_gt_pred), areas = get_edge_surface_distance( # type: ignore + y_pred[b, c], + y[b, c], + distance_metric=distance_metric, + spacing=spacing_list[b], + use_subvoxels=use_subvoxels, + symmetric=True, + class_index=c, + ) + boundary_correct: int | torch.Tensor | float + boundary_complete: int | torch.Tensor | float + if not use_subvoxels: + boundary_complete = len(distances_pred_gt) + len(distances_gt_pred) + boundary_correct = torch.sum(distances_pred_gt <= class_thresholds[c]) + torch.sum( + distances_gt_pred <= class_thresholds[c] + ) + else: + areas_pred, areas_gt = areas # type: ignore + areas_gt, areas_pred = areas_gt[edges_gt], areas_pred[edges_pred] + boundary_complete = areas_gt.sum() + areas_pred.sum() + gt_true = areas_gt[distances_gt_pred <= class_thresholds[c]].sum() if len(areas_gt) > 0 else 0.0 + pred_true = areas_pred[distances_pred_gt <= class_thresholds[c]].sum() if len(areas_pred) > 0 else 0.0 + boundary_correct = gt_true + pred_true + if boundary_complete == 0: + # the class is neither present in the prediction, nor in the reference segmentation + nsd[b, c] = torch.tensor(np.nan) + else: + nsd[b, c] = boundary_correct / boundary_complete + + return nsd diff --git a/source_code/SegMamba/monai/metrics/surface_distance.py b/source_code/SegMamba/monai/metrics/surface_distance.py new file mode 100644 index 0000000000000000000000000000000000000000..3cb336d6a0696138b83759331516d266ea713a72 --- /dev/null +++ b/source_code/SegMamba/monai/metrics/surface_distance.py @@ -0,0 +1,186 @@ +# Copyright (c) MONAI Consortium +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from __future__ import annotations + +from collections.abc import Sequence +from typing import Any + +import numpy as np +import torch + +from monai.metrics.utils import do_metric_reduction, get_edge_surface_distance, ignore_background, prepare_spacing +from monai.utils import MetricReduction, convert_data_type + +from .metric import CumulativeIterationMetric + + +class SurfaceDistanceMetric(CumulativeIterationMetric): + """ + Compute Surface Distance between two tensors. It can support both multi-classes and multi-labels tasks. + It supports both symmetric and asymmetric surface distance calculation. + Input `y_pred` is compared with ground truth `y`. + `y_preds` is expected to have binarized predictions and `y` should be in one-hot format. + You can use suitable transforms in ``monai.transforms.post`` first to achieve binarized values. + `y_preds` and `y` can be a list of channel-first Tensor (CHW[D]) or a batch-first Tensor (BCHW[D]). + + Example of the typical execution steps of this metric class follows :py:class:`monai.metrics.metric.Cumulative`. + + Args: + include_background: whether to include distance computation on the first channel of + the predicted output. Defaults to ``False``. + symmetric: whether to calculate the symmetric average surface distance between + `seg_pred` and `seg_gt`. Defaults to ``False``. + distance_metric: : [``"euclidean"``, ``"chessboard"``, ``"taxicab"``] + the metric used to compute surface distance. Defaults to ``"euclidean"``. + reduction: define mode of reduction to the metrics, will only apply reduction on `not-nan` values, + available reduction modes: {``"none"``, ``"mean"``, ``"sum"``, ``"mean_batch"``, ``"sum_batch"``, + ``"mean_channel"``, ``"sum_channel"``}, default to ``"mean"``. if "none", will not do reduction. + get_not_nans: whether to return the `not_nans` count, if True, aggregate() returns (metric, not_nans). + Here `not_nans` count the number of not nans for the metric, thus its shape equals to the shape of the metric. + + """ + + def __init__( + self, + include_background: bool = False, + symmetric: bool = False, + distance_metric: str = "euclidean", + reduction: MetricReduction | str = MetricReduction.MEAN, + get_not_nans: bool = False, + ) -> None: + super().__init__() + self.include_background = include_background + self.distance_metric = distance_metric + self.symmetric = symmetric + self.reduction = reduction + self.get_not_nans = get_not_nans + + def _compute_tensor(self, y_pred: torch.Tensor, y: torch.Tensor, **kwargs: Any) -> torch.Tensor: # type: ignore[override] + """ + Args: + y_pred: input data to compute, typical segmentation model output. + It must be one-hot format and first dim is batch, example shape: [16, 3, 32, 32]. The values + should be binarized. + y: ground truth to compute the distance. It must be one-hot format and first dim is batch. + The values should be binarized. + kwargs: additional parameters, e.g. ``spacing`` should be passed to correctly compute the metric. + ``spacing``: spacing of pixel (or voxel). This parameter is relevant only + if ``distance_metric`` is set to ``"euclidean"``. + If a single number, isotropic spacing with that value is used for all images in the batch. If a sequence of numbers, + the length of the sequence must be equal to the image dimensions. + This spacing will be used for all images in the batch. + If a sequence of sequences, the length of the outer sequence must be equal to the batch size. + If inner sequence has length 1, isotropic spacing with that value is used for all images in the batch, + else the inner sequence length must be equal to the image dimensions. If ``None``, spacing of unity is used + for all images in batch. Defaults to ``None``. + + Raises: + ValueError: when `y_pred` has less than three dimensions. + """ + if y_pred.dim() < 3: + raise ValueError("y_pred should have at least three dimensions.") + + # compute (BxC) for each channel for each batch + return compute_average_surface_distance( + y_pred=y_pred, + y=y, + include_background=self.include_background, + symmetric=self.symmetric, + distance_metric=self.distance_metric, + spacing=kwargs.get("spacing"), + ) + + def aggregate( + self, reduction: MetricReduction | str | None = None + ) -> torch.Tensor | tuple[torch.Tensor, torch.Tensor]: + """ + Execute reduction logic for the output of `compute_average_surface_distance`. + + Args: + reduction: define mode of reduction to the metrics, will only apply reduction on `not-nan` values, + available reduction modes: {``"none"``, ``"mean"``, ``"sum"``, ``"mean_batch"``, ``"sum_batch"``, + ``"mean_channel"``, ``"sum_channel"``}, default to `self.reduction`. if "none", will not do reduction. + + """ + data = self.get_buffer() + if not isinstance(data, torch.Tensor): + raise ValueError("the data to aggregate must be PyTorch Tensor.") + + # do metric reduction + f, not_nans = do_metric_reduction(data, reduction or self.reduction) + return (f, not_nans) if self.get_not_nans else f + + +def compute_average_surface_distance( + y_pred: np.ndarray | torch.Tensor, + y: np.ndarray | torch.Tensor, + include_background: bool = False, + symmetric: bool = False, + distance_metric: str = "euclidean", + spacing: int | float | np.ndarray | Sequence[int | float | np.ndarray | Sequence[int | float]] | None = None, +) -> torch.Tensor: + """ + This function is used to compute the Average Surface Distance from `y_pred` to `y` + under the default setting. + In addition, if sets ``symmetric = True``, the average symmetric surface distance between + these two inputs will be returned. + The implementation refers to `DeepMind's implementation `_. + + Args: + y_pred: input data to compute, typical segmentation model output. + It must be one-hot format and first dim is batch, example shape: [16, 3, 32, 32]. The values + should be binarized. + y: ground truth to compute mean the distance. It must be one-hot format and first dim is batch. + The values should be binarized. + include_background: whether to include distance computation on the first channel of + the predicted output. Defaults to ``False``. + symmetric: whether to calculate the symmetric average surface distance between + `seg_pred` and `seg_gt`. Defaults to ``False``. + distance_metric: : [``"euclidean"``, ``"chessboard"``, ``"taxicab"``] + the metric used to compute surface distance. Defaults to ``"euclidean"``. + spacing: spacing of pixel (or voxel). This parameter is relevant only if ``distance_metric`` is set to ``"euclidean"``. + If a single number, isotropic spacing with that value is used for all images in the batch. If a sequence of numbers, + the length of the sequence must be equal to the image dimensions. This spacing will be used for all images in the batch. + If a sequence of sequences, the length of the outer sequence must be equal to the batch size. + If inner sequence has length 1, isotropic spacing with that value is used for all images in the batch, + else the inner sequence length must be equal to the image dimensions. If ``None``, spacing of unity is used + for all images in batch. Defaults to ``None``. + """ + + if not include_background: + y_pred, y = ignore_background(y_pred=y_pred, y=y) + + y_pred = convert_data_type(y_pred, output_type=torch.Tensor, dtype=torch.float)[0] + y = convert_data_type(y, output_type=torch.Tensor, dtype=torch.float)[0] + + if y.shape != y_pred.shape: + raise ValueError(f"y_pred and y should have same shapes, got {y_pred.shape} and {y.shape}.") + + batch_size, n_class = y_pred.shape[:2] + asd = torch.empty((batch_size, n_class), dtype=torch.float32, device=y_pred.device) + + img_dim = y_pred.ndim - 2 + spacing_list = prepare_spacing(spacing=spacing, batch_size=batch_size, img_dim=img_dim) + + for b, c in np.ndindex(batch_size, n_class): + _, distances, _ = get_edge_surface_distance( + y_pred[b, c], + y[b, c], + distance_metric=distance_metric, + spacing=spacing_list[b], + symmetric=symmetric, + class_index=c, + ) + surface_distance = torch.cat(distances) + asd[b, c] = torch.tensor(np.nan) if surface_distance.shape == (0,) else surface_distance.mean() + + return convert_data_type(asd, output_type=torch.Tensor, device=y_pred.device, dtype=torch.float)[0] diff --git a/source_code/SegMamba/monai/metrics/utils.py b/source_code/SegMamba/monai/metrics/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..e7057256fbc5d57a0d190e2ab3b4c2852f6b55f5 --- /dev/null +++ b/source_code/SegMamba/monai/metrics/utils.py @@ -0,0 +1,827 @@ +# Copyright (c) MONAI Consortium +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from __future__ import annotations + +import warnings +from functools import lru_cache, partial +from types import ModuleType +from typing import Any, Iterable, Sequence + +import numpy as np +import torch + +from monai.config import NdarrayOrTensor, NdarrayTensor +from monai.transforms.croppad.dictionary import CropForegroundD +from monai.transforms.utils import distance_transform_edt as monai_distance_transform_edt +from monai.utils import ( + MetricReduction, + convert_to_cupy, + convert_to_dst_type, + convert_to_numpy, + convert_to_tensor, + deprecated_arg, + deprecated_arg_default, + ensure_tuple_rep, + look_up_option, + optional_import, +) + +binary_erosion, _ = optional_import("scipy.ndimage.morphology", name="binary_erosion") +distance_transform_edt, _ = optional_import("scipy.ndimage.morphology", name="distance_transform_edt") +distance_transform_cdt, _ = optional_import("scipy.ndimage.morphology", name="distance_transform_cdt") + +__all__ = [ + "ignore_background", + "do_metric_reduction", + "get_mask_edges", + "get_surface_distance", + "is_binary_tensor", + "remap_instance_id", + "prepare_spacing", + "get_code_to_measure_table", +] + + +def ignore_background(y_pred: NdarrayTensor, y: NdarrayTensor) -> tuple[NdarrayTensor, NdarrayTensor]: + """ + This function is used to remove background (the first channel) for `y_pred` and `y`. + + Args: + y_pred: predictions. As for classification tasks, + `y_pred` should has the shape [BN] where N is larger than 1. As for segmentation tasks, + the shape should be [BNHW] or [BNHWD]. + y: ground truth, the first dim is batch. + + """ + + y = y[:, 1:] if y.shape[1] > 1 else y # type: ignore[assignment] + y_pred = y_pred[:, 1:] if y_pred.shape[1] > 1 else y_pred # type: ignore[assignment] + return y_pred, y + + +def do_metric_reduction( + f: torch.Tensor, reduction: MetricReduction | str = MetricReduction.MEAN +) -> tuple[torch.Tensor | Any, torch.Tensor]: + """ + This function is to do the metric reduction for calculated `not-nan` metrics of each sample's each class. + The function also returns `not_nans`, which counts the number of not nans for the metric. + + Args: + f: a tensor that contains the calculated metric scores per batch and + per class. The first two dims should be batch and class. + reduction: define the mode to reduce metrics, will only apply reduction on `not-nan` values, + available reduction modes: {``"none"``, ``"mean"``, ``"sum"``, ``"mean_batch"``, ``"sum_batch"``, + ``"mean_channel"``, ``"sum_channel"``}, default to ``"mean"``. + if "none", return the input f tensor and not_nans. + + Raises: + ValueError: When ``reduction`` is not one of + ["mean", "sum", "mean_batch", "sum_batch", "mean_channel", "sum_channel" "none"]. + """ + + # some elements might be Nan (if ground truth y was missing (zeros)) + # we need to account for it + nans = torch.isnan(f) + not_nans = ~nans + + t_zero = torch.zeros(1, device=f.device, dtype=torch.float) + reduction = look_up_option(reduction, MetricReduction) + if reduction == MetricReduction.NONE: + return f, not_nans.float() + + f[nans] = 0 + if reduction == MetricReduction.MEAN: + # 2 steps, first, mean by channel (accounting for nans), then by batch + not_nans = not_nans.sum(dim=1).float() + f = torch.where(not_nans > 0, f.sum(dim=1).float() / not_nans, t_zero) # channel average + + not_nans = (not_nans > 0).sum(dim=0).float() + f = torch.where(not_nans > 0, f.sum(dim=0).float() / not_nans, t_zero) # batch average + + elif reduction == MetricReduction.SUM: + not_nans = not_nans.sum(dim=[0, 1]).float() + f = torch.sum(f, dim=[0, 1]) # sum over the batch and channel dims + elif reduction == MetricReduction.MEAN_BATCH: + not_nans = not_nans.sum(dim=0).float() + f = torch.where(not_nans > 0, f.sum(dim=0).float() / not_nans, t_zero) # batch average + elif reduction == MetricReduction.SUM_BATCH: + not_nans = not_nans.sum(dim=0).float() + f = f.sum(dim=0).float() # the batch sum + elif reduction == MetricReduction.MEAN_CHANNEL: + not_nans = not_nans.sum(dim=1).float() + f = torch.where(not_nans > 0, f.sum(dim=1).float() / not_nans, t_zero) # channel average + elif reduction == MetricReduction.SUM_CHANNEL: + not_nans = not_nans.sum(dim=1).float() + f = f.sum(dim=1).float() # the channel sum + elif reduction != MetricReduction.NONE: + raise ValueError( + f"Unsupported reduction: {reduction}, available options are " + '["mean", "sum", "mean_batch", "sum_batch", "mean_channel", "sum_channel" "none"].' + ) + return f, not_nans + + +@deprecated_arg_default( + name="always_return_as_numpy", since="1.3.0", replaced="1.5.0", old_default=True, new_default=False +) +@deprecated_arg( + name="always_return_as_numpy", + since="1.5.0", + removed="1.7.0", + msg_suffix="The option is removed and the return type will always be equal to the input type.", +) +def get_mask_edges( + seg_pred: NdarrayOrTensor, + seg_gt: NdarrayOrTensor, + label_idx: int = 1, + crop: bool = True, + spacing: Sequence | None = None, + always_return_as_numpy: bool = True, +) -> tuple[NdarrayTensor, NdarrayTensor]: + """ + Compute edges from binary segmentation masks. This + function is helpful to further calculate metrics such as Average Surface + Distance and Hausdorff Distance. + The input images can be binary or labelfield images. If labelfield images + are supplied, they are converted to binary images using `label_idx`. + + In order to improve the computing efficiency, before getting the edges, + the images can be cropped and only keep the foreground if not specifies + ``crop = False``. + + We require that images are the same size, and assume that they occupy the + same space (spacing, orientation, etc.). + + Args: + seg_pred: the predicted binary or labelfield image. + seg_gt: the actual binary or labelfield image. + label_idx: for labelfield images, convert to binary with + `seg_pred = seg_pred == label_idx`. + crop: crop input images and only keep the foregrounds. In order to + maintain two inputs' shapes, here the bounding box is achieved + by ``(seg_pred | seg_gt)`` which represents the union set of two + images. Defaults to ``True``. + spacing: the input spacing. If not None, the subvoxel edges and areas will be computed. + otherwise `scipy`'s binary erosion is used to calculate the edges. + always_return_as_numpy: whether to a numpy array regardless of the input type. + If False, return the same type as inputs. + """ + # move in the funciton to avoid using all the GPUs + cucim_binary_erosion, has_cucim_binary_erosion = optional_import("cucim.skimage.morphology", name="binary_erosion") + if seg_pred.shape != seg_gt.shape: + raise ValueError(f"seg_pred and seg_gt should have same shapes, got {seg_pred.shape} and {seg_gt.shape}.") + converter: Any + lib: ModuleType + if isinstance(seg_pred, torch.Tensor) and not always_return_as_numpy: + converter = partial(convert_to_tensor, device=seg_pred.device) + lib = torch + else: + converter = convert_to_numpy + lib = np + use_cucim = ( + spacing is None + and has_cucim_binary_erosion + and isinstance(seg_pred, torch.Tensor) + and seg_pred.device.type == "cuda" + ) + + # If not binary images, convert them + if seg_pred.dtype not in (bool, torch.bool): + seg_pred = seg_pred == label_idx + if seg_gt.dtype not in (bool, torch.bool): + seg_gt = seg_gt == label_idx + if crop: + or_vol = seg_pred | seg_gt + if not or_vol.any(): + pred, gt = lib.zeros(seg_pred.shape, dtype=bool), lib.zeros(seg_gt.shape, dtype=bool) + return (pred, gt) if spacing is None else (pred, gt, pred, gt) + channel_first = [seg_pred[None], seg_gt[None], or_vol[None]] + if spacing is None and not use_cucim: # cpu only erosion + seg_pred, seg_gt, or_vol = convert_to_tensor(channel_first, device="cpu", dtype=bool) + else: # pytorch subvoxel, maybe on gpu, but croppad boolean values on GPU is not supported + seg_pred, seg_gt, or_vol = convert_to_tensor(channel_first, dtype=torch.float16) + cropper = CropForegroundD( + ["pred", "gt"], source_key="src", margin=1, allow_smaller=False, start_coord_key=None, end_coord_key=None + ) + cropped = cropper({"pred": seg_pred, "gt": seg_gt, "src": or_vol}) # type: ignore + seg_pred, seg_gt = cropped["pred"][0], cropped["gt"][0] + + if spacing is None: # Do binary erosion and use XOR to get edges + if not use_cucim: + seg_pred, seg_gt = convert_to_numpy([seg_pred, seg_gt], dtype=bool) + edges_pred = binary_erosion(seg_pred) ^ seg_pred + edges_gt = binary_erosion(seg_gt) ^ seg_gt + else: + seg_pred, seg_gt = convert_to_cupy([seg_pred, seg_gt], dtype=bool) # type: ignore[arg-type] + edges_pred = cucim_binary_erosion(seg_pred) ^ seg_pred + edges_gt = cucim_binary_erosion(seg_gt) ^ seg_gt + return converter((edges_pred, edges_gt), dtype=bool) # type: ignore + code_to_area_table, k = get_code_to_measure_table(spacing, device=seg_pred.device) # type: ignore + spatial_dims = len(spacing) + conv = torch.nn.functional.conv3d if spatial_dims == 3 else torch.nn.functional.conv2d + vol = torch.stack([seg_pred[None], seg_gt[None]], dim=0).float() # type: ignore + code_pred, code_gt = conv(vol, k.to(vol)) + # edges + all_ones = len(code_to_area_table) - 1 + edges_pred = (code_pred != 0) & (code_pred != all_ones) + edges_gt = (code_gt != 0) & (code_gt != all_ones) + # areas of edges + areas_pred = torch.index_select(code_to_area_table, 0, code_pred.view(-1).int()).reshape(code_pred.shape) + areas_gt = torch.index_select(code_to_area_table, 0, code_gt.view(-1).int()).reshape(code_gt.shape) + ret = (edges_pred[0], edges_gt[0], areas_pred[0], areas_gt[0]) + return converter(ret, wrap_sequence=False) # type: ignore + + +def get_surface_distance( + seg_pred: NdarrayOrTensor, + seg_gt: NdarrayOrTensor, + distance_metric: str = "euclidean", + spacing: int | float | np.ndarray | Sequence[int | float] | None = None, +) -> NdarrayOrTensor: + """ + This function is used to compute the surface distances from `seg_pred` to `seg_gt`. + + Args: + seg_pred: the edge of the predictions. + seg_gt: the edge of the ground truth. + distance_metric: : [``"euclidean"``, ``"chessboard"``, ``"taxicab"``] + the metric used to compute surface distance. Defaults to ``"euclidean"``. + + - ``"euclidean"``, uses Exact Euclidean distance transform. + - ``"chessboard"``, uses `chessboard` metric in chamfer type of transform. + - ``"taxicab"``, uses `taxicab` metric in chamfer type of transform. + spacing: spacing of pixel (or voxel). This parameter is relevant only if ``distance_metric`` is set to ``"euclidean"``. + Several input options are allowed: + (1) If a single number, isotropic spacing with that value is used. + (2) If a sequence of numbers, the length of the sequence must be equal to the image dimensions. + (3) If ``None``, spacing of unity is used. Defaults to ``None``. + + Note: + If seg_pred or seg_gt is all 0, may result in nan/inf distance. + + """ + lib: ModuleType = torch if isinstance(seg_pred, torch.Tensor) else np + if not seg_gt.any(): + dis = np.inf * lib.ones_like(seg_gt, dtype=lib.float32) + else: + if not lib.any(seg_pred): + dis = np.inf * lib.ones_like(seg_gt, dtype=lib.float32) + dis = dis[seg_gt] + return convert_to_dst_type(dis, seg_pred, dtype=dis.dtype)[0] + if distance_metric == "euclidean": + dis = monai_distance_transform_edt((~seg_gt)[None, ...], sampling=spacing)[0] # type: ignore + elif distance_metric in {"chessboard", "taxicab"}: + dis = distance_transform_cdt(convert_to_numpy(~seg_gt), metric=distance_metric) + else: + raise ValueError(f"distance_metric {distance_metric} is not implemented.") + dis = convert_to_dst_type(dis, seg_pred, dtype=lib.float32)[0] + return dis[seg_pred] # type: ignore + + +def get_edge_surface_distance( + y_pred: torch.Tensor, + y: torch.Tensor, + distance_metric: str = "euclidean", + spacing: int | float | np.ndarray | Sequence[int | float] | None = None, + use_subvoxels: bool = False, + symmetric: bool = False, + class_index: int = -1, +) -> tuple[ + tuple[torch.Tensor, torch.Tensor], + tuple[torch.Tensor, torch.Tensor] | tuple[torch.Tensor], + tuple[torch.Tensor, torch.Tensor] | tuple[()], +]: + """ + This function is used to compute the surface distance from `y_pred` to `y` using the edges of the masks. + + Args: + y_pred: the predicted binary or labelfield image. Expected to be in format (H, W[, D]). + y: the actual binary or labelfield image. Expected to be in format (H, W[, D]). + distance_metric: : [``"euclidean"``, ``"chessboard"``, ``"taxicab"``] + See :py:func:`monai.metrics.utils.get_surface_distance`. + spacing: spacing of pixel (or voxel). This parameter is relevant only if ``distance_metric`` is set to ``"euclidean"``. + See :py:func:`monai.metrics.utils.get_surface_distance`. + use_subvoxels: whether to use subvoxel resolution (using the spacing). + This will return the areas of the edges. + symmetric: whether to compute the surface distance from `y_pred` to `y` and from `y` to `y_pred`. + class_index: The class-index used for context when warning about empty ground truth or prediction. + + Returns: + (edges_pred, edges_gt), (distances_pred_to_gt, [distances_gt_to_pred]), (areas_pred, areas_gt) | tuple() + + """ + edges_spacing = None + if use_subvoxels: + edges_spacing = spacing if spacing is not None else ([1] * len(y_pred.shape)) + (edges_pred, edges_gt, *areas) = get_mask_edges( + y_pred, y, crop=True, spacing=edges_spacing, always_return_as_numpy=False + ) + if not edges_gt.any(): + warnings.warn( + f"the ground truth of class {class_index if class_index != -1 else 'Unknown'} is all 0," + " this may result in nan/inf distance." + ) + if not edges_pred.any(): + warnings.warn( + f"the prediction of class {class_index if class_index != -1 else 'Unknown'} is all 0," + " this may result in nan/inf distance." + ) + distances: tuple[torch.Tensor, torch.Tensor] | tuple[torch.Tensor] + if symmetric: + distances = ( + get_surface_distance(edges_pred, edges_gt, distance_metric, spacing), + get_surface_distance(edges_gt, edges_pred, distance_metric, spacing), + ) # type: ignore + else: + distances = (get_surface_distance(edges_pred, edges_gt, distance_metric, spacing),) # type: ignore + return convert_to_tensor(((edges_pred, edges_gt), distances, tuple(areas)), device=y_pred.device) # type: ignore[no-any-return] + + +def is_binary_tensor(input: torch.Tensor, name: str) -> None: + """Determines whether the input tensor is torch binary tensor or not. + + Args: + input (torch.Tensor): tensor to validate. + name (str): name of the tensor being checked. + + Raises: + ValueError: if `input` is not a PyTorch Tensor. + + Note: + A warning message is printed, if the tensor is not binary. + """ + if not isinstance(input, torch.Tensor): + raise ValueError(f"{name} must be of type PyTorch Tensor.") + if not torch.all(input.byte() == input) or input.max() > 1 or input.min() < 0: + warnings.warn(f"{name} should be a binarized tensor.") + + +def remap_instance_id(pred: torch.Tensor, by_size: bool = False) -> torch.Tensor: + """ + This function is used to rename all instance id of `pred`, so that the id is + contiguous. + For example: all ids of the input can be [0, 1, 2] rather than [0, 2, 5]. + This function is helpful for calculating metrics like Panoptic Quality (PQ). + The implementation refers to: + + https://github.com/vqdang/hover_net + + Args: + pred: segmentation predictions in the form of torch tensor. Each + value of the tensor should be an integer, and represents the prediction of its corresponding instance id. + by_size: if True, largest instance will be assigned a smaller id. + + """ + pred_id: Iterable[Any] = list(pred.unique()) + # the original implementation has the limitation that if there is no 0 in pred, error will happen + pred_id = [i for i in pred_id if i != 0] + + if not pred_id: + return pred + if by_size: + instance_size = [(pred == instance_id).sum() for instance_id in pred_id] + pair_data = zip(pred_id, instance_size) + pair_list = sorted(pair_data, key=lambda x: x[1], reverse=True) + pred_id, _ = zip(*pair_list) + + new_pred = torch.zeros_like(pred, dtype=torch.int) + for idx, instance_id in enumerate(pred_id): + new_pred[pred == instance_id] = idx + 1 + return new_pred + + +def prepare_spacing( + spacing: int | float | np.ndarray | Sequence[int | float | np.ndarray | Sequence[int | float]] | None, + batch_size: int, + img_dim: int, +) -> Sequence[None | int | float | np.ndarray | Sequence[int | float]]: + """ + This function is used to prepare the `spacing` parameter to include batch dimension for the computation of + surface distance, hausdorff distance or surface dice. + + An example with batch_size = 4 and img_dim = 3: + input spacing = None -> output spacing = [None, None, None, None] + input spacing = 0.8 -> output spacing = [0.8, 0.8, 0.8, 0.8] + input spacing = [0.8, 0.5, 0.9] -> output spacing = [[0.8, 0.5, 0.9], [0.8, 0.5, 0.9], [0.8, 0.5, 0.9], [0.8, 0.5, 0.9]] + input spacing = [0.8, 0.7, 1.2, 0.8] -> output spacing = [0.8, 0.7, 1.2, 0.8] (same as input) + + An example with batch_size = 3 and img_dim = 3: + input spacing = [0.8, 0.5, 0.9] -> + output spacing = [[0.8, 0.5, 0.9], [0.8, 0.5, 0.9], [0.8, 0.5, 0.9], [0.8, 0.5, 0.9]] + + Args: + spacing: can be a float, a sequence of length `img_dim`, or a sequence with length `batch_size` + that includes floats or sequences of length `img_dim`. + + Raises: + ValueError: when `spacing` is a sequence of sequence, where the outer sequence length does not + equal `batch_size` or inner sequence length does not equal `img_dim`. + + Returns: + spacing: a sequence with length `batch_size` that includes integers, floats or sequences of length `img_dim`. + """ + if spacing is None or isinstance(spacing, (int, float)): + return list([spacing] * batch_size) + if isinstance(spacing, (Sequence, np.ndarray)): + if any(not isinstance(s, type(spacing[0])) for s in list(spacing)): + raise ValueError(f"if `spacing` is a sequence, its elements should be of same type, got {spacing}.") + if isinstance(spacing[0], (Sequence, np.ndarray)): + if len(spacing) != batch_size: + raise ValueError( + "if `spacing` is a sequence of sequences, " + f"the outer sequence should have same length as batch size ({batch_size}), got {spacing}." + ) + if any(len(s) != img_dim for s in list(spacing)): + raise ValueError( + "each element of `spacing` list should either have same length as" + f"image dim ({img_dim}), got {spacing}." + ) + if not all(isinstance(i, (int, float)) for s in list(spacing) for i in list(s)): + raise ValueError( + f"if `spacing` is a sequence of sequences or 2D np.ndarray, " + f"the elements should be integers or floats, got {spacing}." + ) + return list(spacing) + if isinstance(spacing[0], (int, float)): + if len(spacing) != img_dim: + raise ValueError( + f"if `spacing` is a sequence of numbers, " + f"it should have same length as image dim ({img_dim}), got {spacing}." + ) + return [spacing for _ in range(batch_size)] # type: ignore + raise ValueError(f"`spacing` is a sequence of elements with unsupported type: {type(spacing[0])}") + raise ValueError( + f"`spacing` should either be a number, a sequence of numbers or a sequence of sequences, got {spacing}." + ) + + +ENCODING_KERNEL = {2: [[8, 4], [2, 1]], 3: [[[128, 64], [32, 16]], [[8, 4], [2, 1]]]} + + +@lru_cache(maxsize=None) +def _get_neighbour_code_to_normals_table(device=None): + """ + returns a lookup table. For every binary neighbour code (2x2x2 neighbourhood = 8 neighbours = 8 bits = 256 codes) + it contains the surface normals of the triangles. The length of the normal vector encodes the surfel area. + Adapted from https://github.com/deepmind/surface-distance + + created using the marching_cube algorithm see e.g. https://en.wikipedia.org/wiki/Marching_cubes + + Args: + device: torch device to use for the table. + """ + zeros = [0.0, 0.0, 0.0] + ret = [ + [zeros, zeros, zeros, zeros], + [[0.125, 0.125, 0.125], zeros, zeros, zeros], + [[-0.125, -0.125, 0.125], zeros, zeros, zeros], + [[-0.25, -0.25, 0.0], [0.25, 0.25, -0.0], zeros, zeros], + [[0.125, -0.125, 0.125], zeros, zeros, zeros], + [[-0.25, -0.0, -0.25], [0.25, 0.0, 0.25], zeros, zeros], + [[0.125, -0.125, 0.125], [-0.125, -0.125, 0.125], zeros, zeros], + [[0.5, 0.0, -0.0], [0.25, 0.25, 0.25], [0.125, 0.125, 0.125], zeros], + [[-0.125, 0.125, 0.125], zeros, zeros, zeros], + [[0.125, 0.125, 0.125], [-0.125, 0.125, 0.125], zeros, zeros], + [[-0.25, 0.0, 0.25], [-0.25, 0.0, 0.25], zeros, zeros], + [[0.5, 0.0, 0.0], [-0.25, -0.25, 0.25], [-0.125, -0.125, 0.125], zeros], + [[0.25, -0.25, 0.0], [0.25, -0.25, 0.0], zeros, zeros], + [[0.5, 0.0, 0.0], [0.25, -0.25, 0.25], [-0.125, 0.125, -0.125], zeros], + [[-0.5, 0.0, 0.0], [-0.25, 0.25, 0.25], [-0.125, 0.125, 0.125], zeros], + [[0.5, 0.0, 0.0], [0.5, 0.0, 0.0], zeros, zeros], + [[0.125, -0.125, -0.125], zeros, zeros, zeros], + [[0.0, -0.25, -0.25], [0.0, 0.25, 0.25], zeros, zeros], + [[-0.125, -0.125, 0.125], [0.125, -0.125, -0.125], zeros, zeros], + [[0.0, -0.5, 0.0], [0.25, 0.25, 0.25], [0.125, 0.125, 0.125], zeros], + [[0.125, -0.125, 0.125], [0.125, -0.125, -0.125], zeros, zeros], + [[0.0, 0.0, -0.5], [0.25, 0.25, 0.25], [-0.125, -0.125, -0.125], zeros], + [[-0.125, -0.125, 0.125], [0.125, -0.125, 0.125], [0.125, -0.125, -0.125], zeros], + [[-0.125, -0.125, -0.125], [-0.25, -0.25, -0.25], [0.25, 0.25, 0.25], [0.125, 0.125, 0.125]], + [[-0.125, 0.125, 0.125], [0.125, -0.125, -0.125], zeros, zeros], + [[0.0, -0.25, -0.25], [0.0, 0.25, 0.25], [-0.125, 0.125, 0.125], zeros], + [[-0.25, 0.0, 0.25], [-0.25, 0.0, 0.25], [0.125, -0.125, -0.125], zeros], + [[0.125, 0.125, 0.125], [0.375, 0.375, 0.375], [0.0, -0.25, 0.25], [-0.25, 0.0, 0.25]], + [[0.125, -0.125, -0.125], [0.25, -0.25, 0.0], [0.25, -0.25, 0.0], zeros], + [[0.375, 0.375, 0.375], [0.0, 0.25, -0.25], [-0.125, -0.125, -0.125], [-0.25, 0.25, 0.0]], + [[-0.5, 0.0, 0.0], [-0.125, -0.125, -0.125], [-0.25, -0.25, -0.25], [0.125, 0.125, 0.125]], + [[-0.5, 0.0, 0.0], [-0.125, -0.125, -0.125], [-0.25, -0.25, -0.25], zeros], + [[0.125, -0.125, 0.125], zeros, zeros, zeros], + [[0.125, 0.125, 0.125], [0.125, -0.125, 0.125], zeros, zeros], + [[0.0, -0.25, 0.25], [0.0, 0.25, -0.25], zeros, zeros], + [[0.0, -0.5, 0.0], [0.125, 0.125, -0.125], [0.25, 0.25, -0.25], zeros], + [[0.125, -0.125, 0.125], [0.125, -0.125, 0.125], zeros, zeros], + [[0.125, -0.125, 0.125], [-0.25, -0.0, -0.25], [0.25, 0.0, 0.25], zeros], + [[0.0, -0.25, 0.25], [0.0, 0.25, -0.25], [0.125, -0.125, 0.125], zeros], + [[-0.375, -0.375, 0.375], [-0.0, 0.25, 0.25], [0.125, 0.125, -0.125], [-0.25, -0.0, -0.25]], + [[-0.125, 0.125, 0.125], [0.125, -0.125, 0.125], zeros, zeros], + [[0.125, 0.125, 0.125], [0.125, -0.125, 0.125], [-0.125, 0.125, 0.125], zeros], + [[-0.0, 0.0, 0.5], [-0.25, -0.25, 0.25], [-0.125, -0.125, 0.125], zeros], + [[0.25, 0.25, -0.25], [0.25, 0.25, -0.25], [0.125, 0.125, -0.125], [-0.125, -0.125, 0.125]], + [[0.125, -0.125, 0.125], [0.25, -0.25, 0.0], [0.25, -0.25, 0.0], zeros], + [[0.5, 0.0, 0.0], [0.25, -0.25, 0.25], [-0.125, 0.125, -0.125], [0.125, -0.125, 0.125]], + [[0.0, 0.25, -0.25], [0.375, -0.375, -0.375], [-0.125, 0.125, 0.125], [0.25, 0.25, 0.0]], + [[-0.5, 0.0, 0.0], [-0.25, -0.25, 0.25], [-0.125, -0.125, 0.125], zeros], + [[0.25, -0.25, 0.0], [-0.25, 0.25, 0.0], zeros, zeros], + [[0.0, 0.5, 0.0], [-0.25, 0.25, 0.25], [0.125, -0.125, -0.125], zeros], + [[0.0, 0.5, 0.0], [0.125, -0.125, 0.125], [-0.25, 0.25, -0.25], zeros], + [[0.0, 0.5, 0.0], [0.0, -0.5, 0.0], zeros, zeros], + [[0.25, -0.25, 0.0], [-0.25, 0.25, 0.0], [0.125, -0.125, 0.125], zeros], + [[-0.375, -0.375, -0.375], [-0.25, 0.0, 0.25], [-0.125, -0.125, -0.125], [-0.25, 0.25, 0.0]], + [[0.125, 0.125, 0.125], [0.0, -0.5, 0.0], [-0.25, -0.25, -0.25], [-0.125, -0.125, -0.125]], + [[0.0, -0.5, 0.0], [-0.25, -0.25, -0.25], [-0.125, -0.125, -0.125], zeros], + [[-0.125, 0.125, 0.125], [0.25, -0.25, 0.0], [-0.25, 0.25, 0.0], zeros], + [[0.0, 0.5, 0.0], [0.25, 0.25, -0.25], [-0.125, -0.125, 0.125], [-0.125, -0.125, 0.125]], + [[-0.375, 0.375, -0.375], [-0.25, -0.25, 0.0], [-0.125, 0.125, -0.125], [-0.25, 0.0, 0.25]], + [[0.0, 0.5, 0.0], [0.25, 0.25, -0.25], [-0.125, -0.125, 0.125], zeros], + [[0.25, -0.25, 0.0], [-0.25, 0.25, 0.0], [0.25, -0.25, 0.0], [0.25, -0.25, 0.0]], + [[-0.25, -0.25, 0.0], [-0.25, -0.25, 0.0], [-0.125, -0.125, 0.125], zeros], + [[0.125, 0.125, 0.125], [-0.25, -0.25, 0.0], [-0.25, -0.25, 0.0], zeros], + [[-0.25, -0.25, 0.0], [-0.25, -0.25, 0.0], zeros, zeros], + [[-0.125, -0.125, 0.125], zeros, zeros, zeros], + [[0.125, 0.125, 0.125], [-0.125, -0.125, 0.125], zeros, zeros], + [[-0.125, -0.125, 0.125], [-0.125, -0.125, 0.125], zeros, zeros], + [[-0.125, -0.125, 0.125], [-0.25, -0.25, 0.0], [0.25, 0.25, -0.0], zeros], + [[0.0, -0.25, 0.25], [0.0, -0.25, 0.25], zeros, zeros], + [[0.0, 0.0, 0.5], [0.25, -0.25, 0.25], [0.125, -0.125, 0.125], zeros], + [[0.0, -0.25, 0.25], [0.0, -0.25, 0.25], [-0.125, -0.125, 0.125], zeros], + [[0.375, -0.375, 0.375], [0.0, -0.25, -0.25], [-0.125, 0.125, -0.125], [0.25, 0.25, 0.0]], + [[-0.125, -0.125, 0.125], [-0.125, 0.125, 0.125], zeros, zeros], + [[0.125, 0.125, 0.125], [-0.125, -0.125, 0.125], [-0.125, 0.125, 0.125], zeros], + [[-0.125, -0.125, 0.125], [-0.25, 0.0, 0.25], [-0.25, 0.0, 0.25], zeros], + [[0.5, 0.0, 0.0], [-0.25, -0.25, 0.25], [-0.125, -0.125, 0.125], [-0.125, -0.125, 0.125]], + [[-0.0, 0.5, 0.0], [-0.25, 0.25, -0.25], [0.125, -0.125, 0.125], zeros], + [[-0.25, 0.25, -0.25], [-0.25, 0.25, -0.25], [-0.125, 0.125, -0.125], [-0.125, 0.125, -0.125]], + [[-0.25, 0.0, -0.25], [0.375, -0.375, -0.375], [0.0, 0.25, -0.25], [-0.125, 0.125, 0.125]], + [[0.5, 0.0, 0.0], [-0.25, 0.25, -0.25], [0.125, -0.125, 0.125], zeros], + [[-0.25, 0.0, 0.25], [0.25, 0.0, -0.25], zeros, zeros], + [[-0.0, 0.0, 0.5], [-0.25, 0.25, 0.25], [-0.125, 0.125, 0.125], zeros], + [[-0.125, -0.125, 0.125], [-0.25, 0.0, 0.25], [0.25, 0.0, -0.25], zeros], + [[-0.25, -0.0, -0.25], [-0.375, 0.375, 0.375], [-0.25, -0.25, 0.0], [-0.125, 0.125, 0.125]], + [[0.0, 0.0, -0.5], [0.25, 0.25, -0.25], [-0.125, -0.125, 0.125], zeros], + [[-0.0, 0.0, 0.5], [0.0, 0.0, 0.5], zeros, zeros], + [[0.125, 0.125, 0.125], [0.125, 0.125, 0.125], [0.25, 0.25, 0.25], [0.0, 0.0, 0.5]], + [[0.125, 0.125, 0.125], [0.25, 0.25, 0.25], [0.0, 0.0, 0.5], zeros], + [[-0.25, 0.0, 0.25], [0.25, 0.0, -0.25], [-0.125, 0.125, 0.125], zeros], + [[-0.0, 0.0, 0.5], [0.25, -0.25, 0.25], [0.125, -0.125, 0.125], [0.125, -0.125, 0.125]], + [[-0.25, 0.0, 0.25], [-0.25, 0.0, 0.25], [-0.25, 0.0, 0.25], [0.25, 0.0, -0.25]], + [[0.125, -0.125, 0.125], [0.25, 0.0, 0.25], [0.25, 0.0, 0.25], zeros], + [[0.25, 0.0, 0.25], [-0.375, -0.375, 0.375], [-0.25, 0.25, 0.0], [-0.125, -0.125, 0.125]], + [[-0.0, 0.0, 0.5], [0.25, -0.25, 0.25], [0.125, -0.125, 0.125], zeros], + [[0.125, 0.125, 0.125], [0.25, 0.0, 0.25], [0.25, 0.0, 0.25], zeros], + [[0.25, 0.0, 0.25], [0.25, 0.0, 0.25], zeros, zeros], + [[-0.125, -0.125, 0.125], [0.125, -0.125, 0.125], zeros, zeros], + [[0.125, 0.125, 0.125], [-0.125, -0.125, 0.125], [0.125, -0.125, 0.125], zeros], + [[-0.125, -0.125, 0.125], [0.0, -0.25, 0.25], [0.0, 0.25, -0.25], zeros], + [[0.0, -0.5, 0.0], [0.125, 0.125, -0.125], [0.25, 0.25, -0.25], [-0.125, -0.125, 0.125]], + [[0.0, -0.25, 0.25], [0.0, -0.25, 0.25], [0.125, -0.125, 0.125], zeros], + [[0.0, 0.0, 0.5], [0.25, -0.25, 0.25], [0.125, -0.125, 0.125], [0.125, -0.125, 0.125]], + [[0.0, -0.25, 0.25], [0.0, -0.25, 0.25], [0.0, -0.25, 0.25], [0.0, 0.25, -0.25]], + [[0.0, 0.25, 0.25], [0.0, 0.25, 0.25], [0.125, -0.125, -0.125], zeros], + [[-0.125, 0.125, 0.125], [0.125, -0.125, 0.125], [-0.125, -0.125, 0.125], zeros], + [[-0.125, 0.125, 0.125], [0.125, -0.125, 0.125], [-0.125, -0.125, 0.125], [0.125, 0.125, 0.125]], + [[-0.0, 0.0, 0.5], [-0.25, -0.25, 0.25], [-0.125, -0.125, 0.125], [-0.125, -0.125, 0.125]], + [[0.125, 0.125, 0.125], [0.125, -0.125, 0.125], [0.125, -0.125, -0.125], zeros], + [[-0.0, 0.5, 0.0], [-0.25, 0.25, -0.25], [0.125, -0.125, 0.125], [0.125, -0.125, 0.125]], + [[0.125, 0.125, 0.125], [-0.125, -0.125, 0.125], [0.125, -0.125, -0.125], zeros], + [[0.0, -0.25, -0.25], [0.0, 0.25, 0.25], [0.125, 0.125, 0.125], zeros], + [[0.125, 0.125, 0.125], [0.125, -0.125, -0.125], zeros, zeros], + [[0.5, 0.0, -0.0], [0.25, -0.25, -0.25], [0.125, -0.125, -0.125], zeros], + [[-0.25, 0.25, 0.25], [-0.125, 0.125, 0.125], [-0.25, 0.25, 0.25], [0.125, -0.125, -0.125]], + [[0.375, -0.375, 0.375], [0.0, 0.25, 0.25], [-0.125, 0.125, -0.125], [-0.25, 0.0, 0.25]], + [[0.0, -0.5, 0.0], [-0.25, 0.25, 0.25], [-0.125, 0.125, 0.125], zeros], + [[-0.375, -0.375, 0.375], [0.25, -0.25, 0.0], [0.0, 0.25, 0.25], [-0.125, -0.125, 0.125]], + [[-0.125, 0.125, 0.125], [-0.25, 0.25, 0.25], [0.0, 0.0, 0.5], zeros], + [[0.125, 0.125, 0.125], [0.0, 0.25, 0.25], [0.0, 0.25, 0.25], zeros], + [[0.0, 0.25, 0.25], [0.0, 0.25, 0.25], zeros, zeros], + [[0.5, 0.0, -0.0], [0.25, 0.25, 0.25], [0.125, 0.125, 0.125], [0.125, 0.125, 0.125]], + [[0.125, -0.125, 0.125], [-0.125, -0.125, 0.125], [0.125, 0.125, 0.125], zeros], + [[-0.25, -0.0, -0.25], [0.25, 0.0, 0.25], [0.125, 0.125, 0.125], zeros], + [[0.125, 0.125, 0.125], [0.125, -0.125, 0.125], zeros, zeros], + [[-0.25, -0.25, 0.0], [0.25, 0.25, -0.0], [0.125, 0.125, 0.125], zeros], + [[0.125, 0.125, 0.125], [-0.125, -0.125, 0.125], zeros, zeros], + [[0.125, 0.125, 0.125], [0.125, 0.125, 0.125], zeros, zeros], + [[0.125, 0.125, 0.125], zeros, zeros, zeros], + [[0.125, 0.125, 0.125], zeros, zeros, zeros], + [[0.125, 0.125, 0.125], [0.125, 0.125, 0.125], zeros, zeros], + [[0.125, 0.125, 0.125], [-0.125, -0.125, 0.125], zeros, zeros], + [[-0.25, -0.25, 0.0], [0.25, 0.25, -0.0], [0.125, 0.125, 0.125], zeros], + [[0.125, 0.125, 0.125], [0.125, -0.125, 0.125], zeros, zeros], + [[-0.25, -0.0, -0.25], [0.25, 0.0, 0.25], [0.125, 0.125, 0.125], zeros], + [[0.125, -0.125, 0.125], [-0.125, -0.125, 0.125], [0.125, 0.125, 0.125], zeros], + [[0.5, 0.0, -0.0], [0.25, 0.25, 0.25], [0.125, 0.125, 0.125], [0.125, 0.125, 0.125]], + [[0.0, 0.25, 0.25], [0.0, 0.25, 0.25], zeros, zeros], + [[0.125, 0.125, 0.125], [0.0, 0.25, 0.25], [0.0, 0.25, 0.25], zeros], + [[-0.125, 0.125, 0.125], [-0.25, 0.25, 0.25], [0.0, 0.0, 0.5], zeros], + [[-0.375, -0.375, 0.375], [0.25, -0.25, 0.0], [0.0, 0.25, 0.25], [-0.125, -0.125, 0.125]], + [[0.0, -0.5, 0.0], [-0.25, 0.25, 0.25], [-0.125, 0.125, 0.125], zeros], + [[0.375, -0.375, 0.375], [0.0, 0.25, 0.25], [-0.125, 0.125, -0.125], [-0.25, 0.0, 0.25]], + [[-0.25, 0.25, 0.25], [-0.125, 0.125, 0.125], [-0.25, 0.25, 0.25], [0.125, -0.125, -0.125]], + [[0.5, 0.0, -0.0], [0.25, -0.25, -0.25], [0.125, -0.125, -0.125], zeros], + [[0.125, 0.125, 0.125], [0.125, -0.125, -0.125], zeros, zeros], + [[0.0, -0.25, -0.25], [0.0, 0.25, 0.25], [0.125, 0.125, 0.125], zeros], + [[0.125, 0.125, 0.125], [-0.125, -0.125, 0.125], [0.125, -0.125, -0.125], zeros], + [[-0.0, 0.5, 0.0], [-0.25, 0.25, -0.25], [0.125, -0.125, 0.125], [0.125, -0.125, 0.125]], + [[0.125, 0.125, 0.125], [0.125, -0.125, 0.125], [0.125, -0.125, -0.125], zeros], + [[-0.0, 0.0, 0.5], [-0.25, -0.25, 0.25], [-0.125, -0.125, 0.125], [-0.125, -0.125, 0.125]], + [[-0.125, 0.125, 0.125], [0.125, -0.125, 0.125], [-0.125, -0.125, 0.125], [0.125, 0.125, 0.125]], + [[-0.125, 0.125, 0.125], [0.125, -0.125, 0.125], [-0.125, -0.125, 0.125], zeros], + [[0.0, 0.25, 0.25], [0.0, 0.25, 0.25], [0.125, -0.125, -0.125], zeros], + [[0.0, -0.25, -0.25], [0.0, 0.25, 0.25], [0.0, 0.25, 0.25], [0.0, 0.25, 0.25]], + [[0.0, 0.0, 0.5], [0.25, -0.25, 0.25], [0.125, -0.125, 0.125], [0.125, -0.125, 0.125]], + [[0.0, -0.25, 0.25], [0.0, -0.25, 0.25], [0.125, -0.125, 0.125], zeros], + [[0.0, -0.5, 0.0], [0.125, 0.125, -0.125], [0.25, 0.25, -0.25], [-0.125, -0.125, 0.125]], + [[-0.125, -0.125, 0.125], [0.0, -0.25, 0.25], [0.0, 0.25, -0.25], zeros], + [[0.125, 0.125, 0.125], [-0.125, -0.125, 0.125], [0.125, -0.125, 0.125], zeros], + [[-0.125, -0.125, 0.125], [0.125, -0.125, 0.125], zeros, zeros], + [[0.25, 0.0, 0.25], [0.25, 0.0, 0.25], zeros, zeros], + [[0.125, 0.125, 0.125], [0.25, 0.0, 0.25], [0.25, 0.0, 0.25], zeros], + [[-0.0, 0.0, 0.5], [0.25, -0.25, 0.25], [0.125, -0.125, 0.125], zeros], + [[0.25, 0.0, 0.25], [-0.375, -0.375, 0.375], [-0.25, 0.25, 0.0], [-0.125, -0.125, 0.125]], + [[0.125, -0.125, 0.125], [0.25, 0.0, 0.25], [0.25, 0.0, 0.25], zeros], + [[-0.25, -0.0, -0.25], [0.25, 0.0, 0.25], [0.25, 0.0, 0.25], [0.25, 0.0, 0.25]], + [[-0.0, 0.0, 0.5], [0.25, -0.25, 0.25], [0.125, -0.125, 0.125], [0.125, -0.125, 0.125]], + [[-0.25, 0.0, 0.25], [0.25, 0.0, -0.25], [-0.125, 0.125, 0.125], zeros], + [[0.125, 0.125, 0.125], [0.25, 0.25, 0.25], [0.0, 0.0, 0.5], zeros], + [[0.125, 0.125, 0.125], [0.125, 0.125, 0.125], [0.25, 0.25, 0.25], [0.0, 0.0, 0.5]], + [[-0.0, 0.0, 0.5], [0.0, 0.0, 0.5], zeros, zeros], + [[0.0, 0.0, -0.5], [0.25, 0.25, -0.25], [-0.125, -0.125, 0.125], zeros], + [[-0.25, -0.0, -0.25], [-0.375, 0.375, 0.375], [-0.25, -0.25, 0.0], [-0.125, 0.125, 0.125]], + [[-0.125, -0.125, 0.125], [-0.25, 0.0, 0.25], [0.25, 0.0, -0.25], zeros], + [[-0.0, 0.0, 0.5], [-0.25, 0.25, 0.25], [-0.125, 0.125, 0.125], zeros], + [[-0.25, 0.0, 0.25], [0.25, 0.0, -0.25], zeros, zeros], + [[0.5, 0.0, 0.0], [-0.25, 0.25, -0.25], [0.125, -0.125, 0.125], zeros], + [[-0.25, 0.0, -0.25], [0.375, -0.375, -0.375], [0.0, 0.25, -0.25], [-0.125, 0.125, 0.125]], + [[-0.25, 0.25, -0.25], [-0.25, 0.25, -0.25], [-0.125, 0.125, -0.125], [-0.125, 0.125, -0.125]], + [[-0.0, 0.5, 0.0], [-0.25, 0.25, -0.25], [0.125, -0.125, 0.125], zeros], + [[0.5, 0.0, 0.0], [-0.25, -0.25, 0.25], [-0.125, -0.125, 0.125], [-0.125, -0.125, 0.125]], + [[-0.125, -0.125, 0.125], [-0.25, 0.0, 0.25], [-0.25, 0.0, 0.25], zeros], + [[0.125, 0.125, 0.125], [-0.125, -0.125, 0.125], [-0.125, 0.125, 0.125], zeros], + [[-0.125, -0.125, 0.125], [-0.125, 0.125, 0.125], zeros, zeros], + [[0.375, -0.375, 0.375], [0.0, -0.25, -0.25], [-0.125, 0.125, -0.125], [0.25, 0.25, 0.0]], + [[0.0, -0.25, 0.25], [0.0, -0.25, 0.25], [-0.125, -0.125, 0.125], zeros], + [[0.0, 0.0, 0.5], [0.25, -0.25, 0.25], [0.125, -0.125, 0.125], zeros], + [[0.0, -0.25, 0.25], [0.0, -0.25, 0.25], zeros, zeros], + [[-0.125, -0.125, 0.125], [-0.25, -0.25, 0.0], [0.25, 0.25, -0.0], zeros], + [[-0.125, -0.125, 0.125], [-0.125, -0.125, 0.125], zeros, zeros], + [[0.125, 0.125, 0.125], [-0.125, -0.125, 0.125], zeros, zeros], + [[-0.125, -0.125, 0.125], zeros, zeros, zeros], + [[-0.25, -0.25, 0.0], [-0.25, -0.25, 0.0], zeros, zeros], + [[0.125, 0.125, 0.125], [-0.25, -0.25, 0.0], [-0.25, -0.25, 0.0], zeros], + [[-0.25, -0.25, 0.0], [-0.25, -0.25, 0.0], [-0.125, -0.125, 0.125], zeros], + [[-0.25, -0.25, 0.0], [-0.25, -0.25, 0.0], [-0.25, -0.25, 0.0], [0.25, 0.25, -0.0]], + [[0.0, 0.5, 0.0], [0.25, 0.25, -0.25], [-0.125, -0.125, 0.125], zeros], + [[-0.375, 0.375, -0.375], [-0.25, -0.25, 0.0], [-0.125, 0.125, -0.125], [-0.25, 0.0, 0.25]], + [[0.0, 0.5, 0.0], [0.25, 0.25, -0.25], [-0.125, -0.125, 0.125], [-0.125, -0.125, 0.125]], + [[-0.125, 0.125, 0.125], [0.25, -0.25, 0.0], [-0.25, 0.25, 0.0], zeros], + [[0.0, -0.5, 0.0], [-0.25, -0.25, -0.25], [-0.125, -0.125, -0.125], zeros], + [[0.125, 0.125, 0.125], [0.0, -0.5, 0.0], [-0.25, -0.25, -0.25], [-0.125, -0.125, -0.125]], + [[-0.375, -0.375, -0.375], [-0.25, 0.0, 0.25], [-0.125, -0.125, -0.125], [-0.25, 0.25, 0.0]], + [[0.25, -0.25, 0.0], [-0.25, 0.25, 0.0], [0.125, -0.125, 0.125], zeros], + [[0.0, 0.5, 0.0], [0.0, -0.5, 0.0], zeros, zeros], + [[0.0, 0.5, 0.0], [0.125, -0.125, 0.125], [-0.25, 0.25, -0.25], zeros], + [[0.0, 0.5, 0.0], [-0.25, 0.25, 0.25], [0.125, -0.125, -0.125], zeros], + [[0.25, -0.25, 0.0], [-0.25, 0.25, 0.0], zeros, zeros], + [[-0.5, 0.0, 0.0], [-0.25, -0.25, 0.25], [-0.125, -0.125, 0.125], zeros], + [[0.0, 0.25, -0.25], [0.375, -0.375, -0.375], [-0.125, 0.125, 0.125], [0.25, 0.25, 0.0]], + [[0.5, 0.0, 0.0], [0.25, -0.25, 0.25], [-0.125, 0.125, -0.125], [0.125, -0.125, 0.125]], + [[0.125, -0.125, 0.125], [0.25, -0.25, 0.0], [0.25, -0.25, 0.0], zeros], + [[0.25, 0.25, -0.25], [0.25, 0.25, -0.25], [0.125, 0.125, -0.125], [-0.125, -0.125, 0.125]], + [[-0.0, 0.0, 0.5], [-0.25, -0.25, 0.25], [-0.125, -0.125, 0.125], zeros], + [[0.125, 0.125, 0.125], [0.125, -0.125, 0.125], [-0.125, 0.125, 0.125], zeros], + [[-0.125, 0.125, 0.125], [0.125, -0.125, 0.125], zeros, zeros], + [[-0.375, -0.375, 0.375], [-0.0, 0.25, 0.25], [0.125, 0.125, -0.125], [-0.25, -0.0, -0.25]], + [[0.0, -0.25, 0.25], [0.0, 0.25, -0.25], [0.125, -0.125, 0.125], zeros], + [[0.125, -0.125, 0.125], [-0.25, -0.0, -0.25], [0.25, 0.0, 0.25], zeros], + [[0.125, -0.125, 0.125], [0.125, -0.125, 0.125], zeros, zeros], + [[0.0, -0.5, 0.0], [0.125, 0.125, -0.125], [0.25, 0.25, -0.25], zeros], + [[0.0, -0.25, 0.25], [0.0, 0.25, -0.25], zeros, zeros], + [[0.125, 0.125, 0.125], [0.125, -0.125, 0.125], zeros, zeros], + [[0.125, -0.125, 0.125], zeros, zeros, zeros], + [[-0.5, 0.0, 0.0], [-0.125, -0.125, -0.125], [-0.25, -0.25, -0.25], zeros], + [[-0.5, 0.0, 0.0], [-0.125, -0.125, -0.125], [-0.25, -0.25, -0.25], [0.125, 0.125, 0.125]], + [[0.375, 0.375, 0.375], [0.0, 0.25, -0.25], [-0.125, -0.125, -0.125], [-0.25, 0.25, 0.0]], + [[0.125, -0.125, -0.125], [0.25, -0.25, 0.0], [0.25, -0.25, 0.0], zeros], + [[0.125, 0.125, 0.125], [0.375, 0.375, 0.375], [0.0, -0.25, 0.25], [-0.25, 0.0, 0.25]], + [[-0.25, 0.0, 0.25], [-0.25, 0.0, 0.25], [0.125, -0.125, -0.125], zeros], + [[0.0, -0.25, -0.25], [0.0, 0.25, 0.25], [-0.125, 0.125, 0.125], zeros], + [[-0.125, 0.125, 0.125], [0.125, -0.125, -0.125], zeros, zeros], + [[-0.125, -0.125, -0.125], [-0.25, -0.25, -0.25], [0.25, 0.25, 0.25], [0.125, 0.125, 0.125]], + [[-0.125, -0.125, 0.125], [0.125, -0.125, 0.125], [0.125, -0.125, -0.125], zeros], + [[0.0, 0.0, -0.5], [0.25, 0.25, 0.25], [-0.125, -0.125, -0.125], zeros], + [[0.125, -0.125, 0.125], [0.125, -0.125, -0.125], zeros, zeros], + [[0.0, -0.5, 0.0], [0.25, 0.25, 0.25], [0.125, 0.125, 0.125], zeros], + [[-0.125, -0.125, 0.125], [0.125, -0.125, -0.125], zeros, zeros], + [[0.0, -0.25, -0.25], [0.0, 0.25, 0.25], zeros, zeros], + [[0.125, -0.125, -0.125], zeros, zeros, zeros], + [[0.5, 0.0, 0.0], [0.5, 0.0, 0.0], zeros, zeros], + [[-0.5, 0.0, 0.0], [-0.25, 0.25, 0.25], [-0.125, 0.125, 0.125], zeros], + [[0.5, 0.0, 0.0], [0.25, -0.25, 0.25], [-0.125, 0.125, -0.125], zeros], + [[0.25, -0.25, 0.0], [0.25, -0.25, 0.0], zeros, zeros], + [[0.5, 0.0, 0.0], [-0.25, -0.25, 0.25], [-0.125, -0.125, 0.125], zeros], + [[-0.25, 0.0, 0.25], [-0.25, 0.0, 0.25], zeros, zeros], + [[0.125, 0.125, 0.125], [-0.125, 0.125, 0.125], zeros, zeros], + [[-0.125, 0.125, 0.125], zeros, zeros, zeros], + [[0.5, 0.0, -0.0], [0.25, 0.25, 0.25], [0.125, 0.125, 0.125], zeros], + [[0.125, -0.125, 0.125], [-0.125, -0.125, 0.125], zeros, zeros], + [[-0.25, -0.0, -0.25], [0.25, 0.0, 0.25], zeros, zeros], + [[0.125, 0.125, 0.125], zeros, zeros, zeros], + [[-0.25, -0.25, 0.0], [0.25, 0.25, -0.0], zeros, zeros], + [[0.125, 0.125, 0.125], zeros, zeros, zeros], + [[0.125, 0.125, 0.125], zeros, zeros, zeros], + [zeros, zeros, zeros, zeros], + ] + return torch.as_tensor(ret, device=device) + + +def create_table_neighbour_code_to_surface_area(spacing_mm, device=None): + """ + Returns an array mapping neighbourhood code to the surface elements area. + Adapted from https://github.com/deepmind/surface-distance + + Note that the normals encode the initial surface area. This function computes + the area corresponding to the given `spacing`. + + Args: + spacing_mm: a sequence of 3 numbers. Voxel spacing along the first 3 spatial axes. + device: device to put the table on. + + Returns: + An array of size 256, mapping neighbourhood code to the surface area. + ENCODING_KERNEL[3] which is the kernel used to compute the neighbourhood code. + """ + spacing_mm = ensure_tuple_rep(spacing_mm, 3) + # compute the area for all 256 possible surface elements given a 2x2x2 neighbourhood according to the spacing_mm + c = _get_neighbour_code_to_normals_table(device) + s = torch.as_tensor( + [[[spacing_mm[1] * spacing_mm[2], spacing_mm[0] * spacing_mm[2], spacing_mm[0] * spacing_mm[1]]]], + device=device, + dtype=c.dtype, + ) + norm = torch.linalg.norm(c * s, dim=-1) + neighbour_code_to_surface_area = norm.sum(-1) + return neighbour_code_to_surface_area, torch.as_tensor([[ENCODING_KERNEL[3]]], device=device) + + +def create_table_neighbour_code_to_contour_length(spacing_mm, device=None): + """ + Returns an array mapping neighbourhood code to the contour length. + Adapted from https://github.com/deepmind/surface-distance + + In 2D, each point has 4 neighbors. Thus, are 16 configurations. A + configuration is encoded with '1' meaning "inside the object" and '0' "outside + the object". For example, + "0101" and "1010" both encode an edge along the first spatial axis with length spacing[0] mm; + "0011" and "1100" both encode an edge along the second spatial axis with length spacing[1] mm. + + Args: + spacing_mm: 2-element list-like structure. Pixel spacing along the 1st and 2nd spatial axes. + device: device to put the table on. + + Returns: + A 16-element array mapping neighbourhood code to the contour length. + ENCODING_KERNEL[2] which is the kernel used to compute the neighbourhood code. + """ + spacing_mm = ensure_tuple_rep(spacing_mm, 2) + first, second = spacing_mm # spacing along the first and second spatial dimension respectively + diag = 0.5 * np.linalg.norm(spacing_mm) + + neighbour_code_to_contour_length = np.zeros([16], dtype=diag.dtype) + neighbour_code_to_contour_length[int("0001", 2)] = diag + neighbour_code_to_contour_length[int("0010", 2)] = diag + neighbour_code_to_contour_length[int("0011", 2)] = second + neighbour_code_to_contour_length[int("0100", 2)] = diag + neighbour_code_to_contour_length[int("0101", 2)] = first + neighbour_code_to_contour_length[int("0110", 2)] = 2 * diag + neighbour_code_to_contour_length[int("0111", 2)] = diag + neighbour_code_to_contour_length[int("1000", 2)] = diag + neighbour_code_to_contour_length[int("1001", 2)] = 2 * diag + neighbour_code_to_contour_length[int("1010", 2)] = first + neighbour_code_to_contour_length[int("1011", 2)] = diag + neighbour_code_to_contour_length[int("1100", 2)] = second + neighbour_code_to_contour_length[int("1101", 2)] = diag + neighbour_code_to_contour_length[int("1110", 2)] = diag + neighbour_code_to_contour_length = convert_to_tensor(neighbour_code_to_contour_length, device=device) + return neighbour_code_to_contour_length, torch.as_tensor([[ENCODING_KERNEL[2]]], device=device) + + +def get_code_to_measure_table(spacing, device=None): + """ + returns a table mapping neighbourhood code to the surface area or contour length. + + Args: + spacing: a sequence of 2 or 3 numbers, indicating the spacing in the spatial dimensions. + device: device to put the table on. + """ + spatial_dims = len(spacing) + spacing = ensure_tuple_rep(spacing, look_up_option(spatial_dims, (2, 3))) + if spatial_dims == 2: + return create_table_neighbour_code_to_contour_length(spacing, device) + return create_table_neighbour_code_to_surface_area(spacing, device) diff --git a/source_code/SegMamba/monai/metrics/wrapper.py b/source_code/SegMamba/monai/metrics/wrapper.py new file mode 100644 index 0000000000000000000000000000000000000000..80b22e82e914c80fcfc8e3293888811f166be95a --- /dev/null +++ b/source_code/SegMamba/monai/metrics/wrapper.py @@ -0,0 +1,302 @@ +# Copyright (c) MONAI Consortium +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from __future__ import annotations + +from typing import cast + +import torch + +from monai.metrics.utils import do_metric_reduction, ignore_background +from monai.utils import MetricReduction, convert_to_numpy, convert_to_tensor, optional_import + +from .metric import CumulativeIterationMetric + +BinaryPairwiseMeasures, _ = optional_import("MetricsReloaded.metrics.pairwise_measures", name="BinaryPairwiseMeasures") +MultiClassPairwiseMeasures, _ = optional_import( + "MetricsReloaded.metrics.pairwise_measures", name="MultiClassPairwiseMeasures" +) + +__all__ = ["MetricsReloadedBinary", "MetricsReloadedCategorical"] + + +class MetricsReloadedWrapper(CumulativeIterationMetric): + """Base class for defining MetricsReloaded metrics as a CumulativeIterationMetric. + + Args: + metric_name: Name of a metric from the MetricsReloaded package. + include_background: whether to include computation on the first channel of + the predicted output. Defaults to ``True``. + reduction: define mode of reduction to the metrics, will only apply reduction on `not-nan` values, + available reduction modes: {``"none"``, ``"mean"``, ``"sum"``, ``"mean_batch"``, ``"sum_batch"``, + ``"mean_channel"``, ``"sum_channel"``}, default to ``"mean"``. if "none", will not do reduction. + get_not_nans: whether to return the `not_nans` count, if True, aggregate() returns (metric, not_nans). + Here `not_nans` count the number of not nans for the metric, + thus its shape equals to the shape of the metric. + + """ + + def __init__( + self, + metric_name: str, + include_background: bool = True, + reduction: MetricReduction | str = MetricReduction.MEAN, + get_not_nans: bool = False, + ) -> None: + super().__init__() + self.metric_name = metric_name + self.include_background = include_background + self.reduction = reduction + self.get_not_nans = get_not_nans + + def aggregate( + self, reduction: MetricReduction | str | None = None + ) -> torch.Tensor | tuple[torch.Tensor, torch.Tensor]: + data = self.get_buffer() + if not isinstance(data, torch.Tensor): + raise ValueError("the data to aggregate must be PyTorch Tensor.") + # do metric reduction + f, not_nans = do_metric_reduction(data, reduction or self.reduction) + return (f, not_nans) if self.get_not_nans else f + + def prepare_onehot(self, y_pred, y): + """Prepares onehot encoded input for metric call.""" + y = y.float() + y_pred = y_pred.float() + if not self.include_background: + y_pred, y = ignore_background(y_pred=y_pred, y=y) + return y_pred, y, y_pred.device + + +class MetricsReloadedBinary(MetricsReloadedWrapper): + """ + Wraps the binary pairwise metrics of MetricsReloaded. + + Args: + metric_name: Name of a binary metric from the MetricsReloaded package. + include_background: whether to include computation on the first channel of + the predicted output. Defaults to ``True``. + reduction: define mode of reduction to the metrics, will only apply reduction on `not-nan` values, + available reduction modes: {``"none"``, ``"mean"``, ``"sum"``, ``"mean_batch"``, ``"sum_batch"``, + ``"mean_channel"``, ``"sum_channel"``}, default to ``"mean"``. if "none", will not do reduction. + get_not_nans: whether to return the `not_nans` count, if True, aggregate() returns (metric, not_nans). + Here `not_nans` count the number of not nans for the metric, + thus its shape equals to the shape of the metric. + + Example: + + .. code-block:: python + + import torch + from monai.metrics import MetricsReloadedBinary + + metric_name = "Cohens Kappa" + metric = MetricsReloadedBinary(metric_name=metric_name) + + # first iteration + # shape [batch=1, channel=1, 2, 2] + y_pred = torch.tensor([[[[1.0, 0.0], [0.0, 1.0]]]]) + y = torch.tensor([[[[1.0, 0.0], [1.0, 1.0]]]]) + print(metric(y_pred, y)) + + # second iteration + # shape [batch=1, channel=1, 2, 2] + y_pred = torch.tensor([[[[1.0, 0.0], [0.0, 0.0]]]]) + y = torch.tensor([[[[1.0, 0.0], [1.0, 1.0]]]]) + print(metric(y_pred, y)) + + # aggregate + # shape ([batch=2, channel=1]) + print(metric.aggregate(reduction="none")) # tensor([[0.5], [0.2]]) + + # reset + metric.reset() + + """ + + def __init__( + self, + metric_name: str, + include_background: bool = True, + reduction: MetricReduction | str = MetricReduction.MEAN, + get_not_nans: bool = False, + ) -> None: + super().__init__( + metric_name=metric_name, + include_background=include_background, + reduction=reduction, + get_not_nans=get_not_nans, + ) + + def _compute_tensor(self, y_pred: torch.Tensor, y: torch.Tensor) -> torch.Tensor: # type: ignore[override] + """Computes a binary (single-class) MetricsReloaded metric from a batch of + predictions and references. + + Args: + y_pred: Prediction with dimensions (batch, channel, *spatial), where channel=1. + The values should be binarized. + y: Ground-truth with dimensions (batch, channel, *spatial), where channel=1. + The values should be binarized. + + Raises: + ValueError: when `y_pred` has less than three dimensions. + ValueError: when second dimension ~= 1 + + """ + # Preprocess + y_pred, y, device = self.prepare_onehot(y_pred, y) + + # Sanity check + dims = y_pred.ndimension() + if dims < 3: + raise ValueError(f"y_pred should have at least 3 dimensions (batch, channel, spatial), got {dims}.") + if y_pred.shape[1] != 1 or y.shape[1] != 1: + raise ValueError(f"y_pred.shape[1]={y_pred.shape[1]} and y.shape[1]={y.shape[1]} should be one.") + + # To numpy array + y_pred = convert_to_numpy(y_pred) + y = convert_to_numpy(y) + + # Create binary pairwise metric object + bpm = BinaryPairwiseMeasures(y_pred, y, axis=tuple(range(2, dims)), smooth_dr=1e-5) + + # Is requested metric available? + if self.metric_name not in bpm.metrics: + raise ValueError(f"Unsupported metric: {self.metric_name}") + + # Compute metric + metric = bpm.metrics[self.metric_name]() + + # Return metric as tensor + return convert_to_tensor(metric, device=device) # type: ignore[no-any-return] + + +class MetricsReloadedCategorical(MetricsReloadedWrapper): + """ + Wraps the categorical pairwise metrics of MetricsReloaded. + + + Args: + metric_name: Name of a categorical metric from the MetricsReloaded package. + include_background: whether to include computation on the first channel of + the predicted output. Defaults to ``True``. + reduction: define mode of reduction to the metrics, will only apply reduction on `not-nan` values, + available reduction modes: {``"none"``, ``"mean"``, ``"sum"``, ``"mean_batch"``, ``"sum_batch"``, + ``"mean_channel"``, ``"sum_channel"``}, default to ``"mean"``. if "none", will not do reduction. + get_not_nans: whether to return the `not_nans` count, if True, aggregate() returns (metric, not_nans). + Here `not_nans` count the number of not nans for the metric, + thus its shape equals to the shape of the metric. + smooth_dr: a small constant added to the denominator to avoid nan. OBS: should be greater than zero. + + Example: + + .. code-block:: python + + import torch + from monai.metrics import MetricsReloadedCategorical + + metric_name = "Weighted Cohens Kappa" + metric = MetricsReloadedCategorical(metric_name=metric_name) + + # first iteration + # shape [bach=1, channel=3, 2, 2] + y_pred = torch.tensor([[[[0, 0], [0, 1]], [[0, 0], [0, 0]], [[1, 1], [1, 0]]]]) + y = torch.tensor([[[[1, 0], [0, 1]], [[0, 1], [0, 0]], [[0, 0], [1, 0]]]]) + print(metric(y_pred, y)) + + # second iteration + # shape [batch=1, channel=3, 2, 2] + y_pred = torch.tensor([[[[1, 0], [0, 1]], [[0, 1], [1, 0]], [[0, 0], [0, 0]]]]) + y = torch.tensor([[[[1, 0], [0, 1]], [[0, 1], [0, 0]], [[0, 0], [1, 0]]]]) + print(metric(y_pred, y)) + + # aggregate + # shape ([batch=2, channel=1]) + print(metric.aggregate(reduction="none")) # tensor([[0.2727], [0.6000]]) + + # reset + metric.reset() + + """ + + def __init__( + self, + metric_name: str, + include_background: bool = True, + reduction: MetricReduction | str = MetricReduction.MEAN, + get_not_nans: bool = False, + smooth_dr: float = 1e-5, + ) -> None: + super().__init__( + metric_name=metric_name, + include_background=include_background, + reduction=reduction, + get_not_nans=get_not_nans, + ) + self.smooth_dr = smooth_dr + + def _compute_tensor(self, y_pred: torch.Tensor, y: torch.Tensor) -> torch.Tensor: # type: ignore[override] + """Computes a categorical (multi-class) MetricsReloaded metric from a batch of + predictions and references. + + Args: + y_pred: Prediction with dimensions (batch, channel, *spatial). The values should be + one-hot encoded and binarized. + y: Ground-truth with dimensions (batch, channel, *spatial). The values should be 1 + one-hot encoded and binarized. + + Raises: + ValueError: when `y_pred` has less than three dimensions. + + """ + # Preprocess + y_pred, y, device = self.prepare_onehot(y_pred, y) + + # Sanity check + dims = y_pred.ndimension() + if dims < 3: + raise ValueError(f"y_pred should have at least 3 dimensions (batch, channel, spatial), got {dims}.") + + num_classes = y_pred.shape[1] + + # Reshape and permute for compatible dimension with MetricsReloaded + y_pred = y_pred.reshape(y_pred.shape[0], y_pred.shape[1], -1) + y_pred = y_pred.permute((0, 2, 1)) + y = y.reshape(y.shape[0], y.shape[1], -1) + y = y.permute((0, 2, 1)) + dims = y_pred.ndimension() + + # To numpy array + y_pred = convert_to_numpy(y_pred) + y = convert_to_numpy(y) + + # Create categorical pairwise metric object + bpm = MultiClassPairwiseMeasures( + y_pred, + y, + axis=tuple(range(1, dims)), + smooth_dr=self.smooth_dr, + list_values=list(range(num_classes)), + is_onehot=True, + ) + + # Is requested metric available? + if self.metric_name not in bpm.metrics: + raise ValueError(f"Unsupported metric: {self.metric_name}") + + # Compute metric + metric = bpm.metrics[self.metric_name]() + + # Put back singleton channel dimension + metric = metric[..., None] + + # Return metric as tensor + return cast(torch.Tensor, convert_to_tensor(metric, device=device)) diff --git a/source_code/SegMamba/monai/networks/blocks/activation.py b/source_code/SegMamba/monai/networks/blocks/activation.py new file mode 100644 index 0000000000000000000000000000000000000000..1e5e979dffe568e4fd16e457bc46fff14c603bbf --- /dev/null +++ b/source_code/SegMamba/monai/networks/blocks/activation.py @@ -0,0 +1,184 @@ +# Copyright (c) MONAI Consortium +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from __future__ import annotations + +import torch +from torch import nn + +from monai.utils import optional_import + +if optional_import("torch.nn.functional", name="mish")[1]: + + def monai_mish(x, inplace: bool = False): + return torch.nn.functional.mish(x, inplace=inplace) + +else: + + def monai_mish(x, inplace: bool = False): + return x * torch.tanh(torch.nn.functional.softplus(x)) + + +if optional_import("torch.nn.functional", name="silu")[1]: + + def monai_swish(x, inplace: bool = False): + return torch.nn.functional.silu(x, inplace=inplace) + +else: + + def monai_swish(x, inplace: bool = False): + return SwishImplementation.apply(x) + + +class Swish(nn.Module): + r"""Applies the element-wise function: + + .. math:: + \text{Swish}(x) = x * \text{Sigmoid}(\alpha * x) ~~~~\text{for constant value}~ \alpha. + + Citation: Searching for Activation Functions, Ramachandran et al., 2017, https://arxiv.org/abs/1710.05941. + + + Shape: + - Input: :math:`(N, *)` where `*` means, any number of additional dimensions + - Output: :math:`(N, *)`, same shape as the input + + + Examples:: + + >>> import torch + >>> from monai.networks.layers.factories import Act + >>> m = Act['swish']() + >>> input = torch.randn(2) + >>> output = m(input) + """ + + def __init__(self, alpha=1.0): + super().__init__() + self.alpha = alpha + + def forward(self, input: torch.Tensor) -> torch.Tensor: + return input * torch.sigmoid(self.alpha * input) + + +class SwishImplementation(torch.autograd.Function): + r"""Memory efficient implementation for training + Follows recommendation from: + https://github.com/lukemelas/EfficientNet-PyTorch/issues/18#issuecomment-511677853 + + Results in ~ 30% memory saving during training as compared to Swish() + """ + + @staticmethod + def forward(ctx, input): + result = input * torch.sigmoid(input) + ctx.save_for_backward(input) + return result + + @staticmethod + def backward(ctx, grad_output): + input = ctx.saved_tensors[0] + sigmoid_input = torch.sigmoid(input) + return grad_output * (sigmoid_input * (1 + input * (1 - sigmoid_input))) + + +class MemoryEfficientSwish(nn.Module): + r"""Applies the element-wise function: + + .. math:: + \text{Swish}(x) = x * \text{Sigmoid}(\alpha * x) ~~~~\text{for constant value}~ \alpha=1. + + Memory efficient implementation for training following recommendation from: + https://github.com/lukemelas/EfficientNet-PyTorch/issues/18#issuecomment-511677853 + + Results in ~ 30% memory saving during training as compared to Swish() + + Citation: Searching for Activation Functions, Ramachandran et al., 2017, https://arxiv.org/abs/1710.05941. + + From Pytorch 1.7.0+, the optimized version of `Swish` named `SiLU` is implemented, + this class will utilize `torch.nn.functional.silu` to do the calculation if meets the version. + + Shape: + - Input: :math:`(N, *)` where `*` means, any number of additional + dimensions + - Output: :math:`(N, *)`, same shape as the input + + + Examples:: + + >>> import torch + >>> from monai.networks.layers.factories import Act + >>> m = Act['memswish']() + >>> input = torch.randn(2) + >>> output = m(input) + """ + + def __init__(self, inplace: bool = False): + super().__init__() + # inplace only works when using torch.nn.functional.silu + self.inplace = inplace + + def forward(self, input: torch.Tensor): + return monai_swish(input, self.inplace) + + +class Mish(nn.Module): + r"""Applies the element-wise function: + + .. math:: + \text{Mish}(x) = x * tanh(\text{softplus}(x)). + + Citation: Mish: A Self Regularized Non-Monotonic Activation Function, Diganta Misra, 2019, https://arxiv.org/abs/1908.08681. + + From Pytorch 1.9.0+, the optimized version of `Mish` is implemented, + this class will utilize `torch.nn.functional.mish` to do the calculation if meets the version. + + Shape: + - Input: :math:`(N, *)` where `*` means, any number of additional dimensions + - Output: :math:`(N, *)`, same shape as the input + + + Examples:: + + >>> import torch + >>> from monai.networks.layers.factories import Act + >>> m = Act['mish']() + >>> input = torch.randn(2) + >>> output = m(input) + """ + + def __init__(self, inplace: bool = False): + super().__init__() + # inplace only works when using torch.nn.functional.mish + self.inplace = inplace + + def forward(self, input: torch.Tensor): + return monai_mish(input, self.inplace) + + +class GEGLU(nn.Module): + r"""Applies the element-wise function: + + .. math:: + \text{GEGLU}(x) = x_1 * \text{Sigmoid}(x_2) + + where :math:`x_1` and :math:`x_2` are split from the input tensor along the last dimension. + + Citation: GLU Variants Improve Transformer, Noam Shazeer, 2020, https://arxiv.org/abs/2002.05202. + + Shape: + - Input: :math:`(N, *, 2 * D)` + - Output: :math:`(N, *, D)`, where `*` means, any number of additional dimensions + """ + + def forward(self, input: torch.Tensor): + x, gate = input.chunk(2, dim=-1) + return x * nn.functional.gelu(gate) diff --git a/source_code/SegMamba/monai/networks/blocks/aspp.py b/source_code/SegMamba/monai/networks/blocks/aspp.py new file mode 100644 index 0000000000000000000000000000000000000000..1f6c76c3af299e0ff07c902636d510c4a879611a --- /dev/null +++ b/source_code/SegMamba/monai/networks/blocks/aspp.py @@ -0,0 +1,107 @@ +# Copyright (c) MONAI Consortium +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from __future__ import annotations + +from collections.abc import Sequence + +import torch +import torch.nn as nn + +from monai.networks.blocks.convolutions import Convolution +from monai.networks.layers import same_padding +from monai.networks.layers.factories import Conv + + +class SimpleASPP(nn.Module): + """ + A simplified version of the atrous spatial pyramid pooling (ASPP) module. + + Chen et al., Encoder-Decoder with Atrous Separable Convolution for Semantic Image Segmentation. + https://arxiv.org/abs/1802.02611 + + Wang et al., A Noise-robust Framework for Automatic Segmentation of COVID-19 Pneumonia Lesions + from CT Images. https://ieeexplore.ieee.org/document/9109297 + """ + + def __init__( + self, + spatial_dims: int, + in_channels: int, + conv_out_channels: int, + kernel_sizes: Sequence[int] = (1, 3, 3, 3), + dilations: Sequence[int] = (1, 2, 4, 6), + norm_type: tuple | str | None = "BATCH", + acti_type: tuple | str | None = "LEAKYRELU", + bias: bool = False, + ) -> None: + """ + Args: + spatial_dims: number of spatial dimensions, could be 1, 2, or 3. + in_channels: number of input channels. + conv_out_channels: number of output channels of each atrous conv. + The final number of output channels is conv_out_channels * len(kernel_sizes). + kernel_sizes: a sequence of four convolutional kernel sizes. + Defaults to (1, 3, 3, 3) for four (dilated) convolutions. + dilations: a sequence of four convolutional dilation parameters. + Defaults to (1, 2, 4, 6) for four (dilated) convolutions. + norm_type: final kernel-size-one convolution normalization type. + Defaults to batch norm. + acti_type: final kernel-size-one convolution activation type. + Defaults to leaky ReLU. + bias: whether to have a bias term in convolution blocks. Defaults to False. + According to `Performance Tuning Guide `_, + if a conv layer is directly followed by a batch norm layer, bias should be False. + + Raises: + ValueError: When ``kernel_sizes`` length differs from ``dilations``. + + See also: + + :py:class:`monai.networks.layers.Act` + :py:class:`monai.networks.layers.Conv` + :py:class:`monai.networks.layers.Norm` + + """ + super().__init__() + if len(kernel_sizes) != len(dilations): + raise ValueError( + "kernel_sizes and dilations length must match, " + f"got kernel_sizes={len(kernel_sizes)} dilations={len(dilations)}." + ) + pads = tuple(same_padding(k, d) for k, d in zip(kernel_sizes, dilations)) + + self.convs = nn.ModuleList() + for k, d, p in zip(kernel_sizes, dilations, pads): + _conv = Conv[Conv.CONV, spatial_dims]( + in_channels=in_channels, out_channels=conv_out_channels, kernel_size=k, dilation=d, padding=p + ) + self.convs.append(_conv) + + out_channels = conv_out_channels * len(pads) # final conv. output channels + self.conv_k1 = Convolution( + spatial_dims=spatial_dims, + in_channels=out_channels, + out_channels=out_channels, + kernel_size=1, + act=acti_type, + norm=norm_type, + bias=bias, + ) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + """ + Args: + x: in shape (batch, channel, spatial_1[, spatial_2, ...]). + """ + x_out = torch.cat([conv(x) for conv in self.convs], dim=1) + x_out = self.conv_k1(x_out) + return x_out diff --git a/source_code/SegMamba/monai/networks/blocks/backbone_fpn_utils.py b/source_code/SegMamba/monai/networks/blocks/backbone_fpn_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..c1453b31833138a64bcb2146d125ce1c081ffbaa --- /dev/null +++ b/source_code/SegMamba/monai/networks/blocks/backbone_fpn_utils.py @@ -0,0 +1,175 @@ +# Copyright (c) MONAI Consortium +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# ========================================================================= +# Adapted from https://github.com/pytorch/vision/blob/release/0.12/torchvision/models/detection/backbone_utils.py +# which has the following license... +# https://github.com/pytorch/vision/blob/main/LICENSE +# +# BSD 3-Clause License + +# Copyright (c) Soumith Chintala 2016, +# All rights reserved. + +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are met: + +# * Redistributions of source code must retain the above copyright notice, this +# list of conditions and the following disclaimer. + +# * Redistributions in binary form must reproduce the above copyright notice, +# this list of conditions and the following disclaimer in the documentation +# and/or other materials provided with the distribution. + +# * Neither the name of the copyright holder nor the names of its +# contributors may be used to endorse or promote products derived from +# this software without specific prior written permission. + +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +""" +This script is modified from from torchvision to support N-D images, +by overriding the definition of convolutional layers and pooling layers. + +https://github.com/pytorch/vision/blob/release/0.12/torchvision/models/detection/backbone_utils.py +""" + +from __future__ import annotations + +from torch import Tensor, nn + +from monai.networks.nets import resnet +from monai.utils import optional_import + +from .feature_pyramid_network import ExtraFPNBlock, FeaturePyramidNetwork, LastLevelMaxPool + +torchvision_models, _ = optional_import("torchvision.models") + +__all__ = ["BackboneWithFPN"] + + +class BackboneWithFPN(nn.Module): + """ + Adds an FPN on top of a model. + Internally, it uses torchvision.models._utils.IntermediateLayerGetter to + extract a submodel that returns the feature maps specified in return_layers. + The same limitations of IntermediateLayerGetter apply here. + + Same code as https://github.com/pytorch/vision/blob/release/0.12/torchvision/models/detection/backbone_utils.py + Except that this class uses spatial_dims + + Args: + backbone: backbone network + return_layers: a dict containing the names + of the modules for which the activations will be returned as + the key of the dict, and the value of the dict is the name + of the returned activation (which the user can specify). + in_channels_list: number of channels for each feature map + that is returned, in the order they are present in the OrderedDict + out_channels: number of channels in the FPN. + spatial_dims: 2D or 3D images + """ + + def __init__( + self, + backbone: nn.Module, + return_layers: dict[str, str], + in_channels_list: list[int], + out_channels: int, + spatial_dims: int | None = None, + extra_blocks: ExtraFPNBlock | None = None, + ) -> None: + super().__init__() + + # if spatial_dims is not specified, try to find it from backbone. + if spatial_dims is None: + if hasattr(backbone, "spatial_dims") and isinstance(backbone.spatial_dims, int): + spatial_dims = backbone.spatial_dims + elif isinstance(backbone.conv1, nn.Conv2d): + spatial_dims = 2 + elif isinstance(backbone.conv1, nn.Conv3d): + spatial_dims = 3 + else: + raise ValueError("Could not find spatial_dims of backbone, please specify it.") + + if extra_blocks is None: + extra_blocks = LastLevelMaxPool(spatial_dims) + + self.body = torchvision_models._utils.IntermediateLayerGetter(backbone, return_layers=return_layers) + self.fpn = FeaturePyramidNetwork( + spatial_dims=spatial_dims, + in_channels_list=in_channels_list, + out_channels=out_channels, + extra_blocks=extra_blocks, + ) + self.out_channels = out_channels + + def forward(self, x: Tensor) -> dict[str, Tensor]: + """ + Computes the resulted feature maps of the network. + + Args: + x: input images + + Returns: + feature maps after FPN layers. They are ordered from highest resolution first. + """ + x = self.body(x) # backbone + y: dict[str, Tensor] = self.fpn(x) # FPN + return y + + +def _resnet_fpn_extractor( + backbone: resnet.ResNet, + spatial_dims: int, + trainable_layers: int = 5, + returned_layers: list[int] | None = None, + extra_blocks: ExtraFPNBlock | None = None, +) -> BackboneWithFPN: + """ + Same code as https://github.com/pytorch/vision/blob/release/0.12/torchvision/models/detection/backbone_utils.py + Except that ``in_channels_stage2 = backbone.in_planes // 8`` instead of ``in_channels_stage2 = backbone.inplanes // 8``, + and it requires spatial_dims: 2D or 3D images. + """ + + # select layers that wont be frozen + if trainable_layers < 0 or trainable_layers > 5: + raise ValueError(f"Trainable layers should be in the range [0,5], got {trainable_layers}") + layers_to_train = ["layer4", "layer3", "layer2", "layer1", "conv1"][:trainable_layers] + if trainable_layers == 5: + layers_to_train.append("bn1") + for name, parameter in backbone.named_parameters(): + if all(not name.startswith(layer) for layer in layers_to_train): + parameter.requires_grad_(False) + + if extra_blocks is None: + extra_blocks = LastLevelMaxPool(spatial_dims) + + if returned_layers is None: + returned_layers = [1, 2, 3, 4] + if min(returned_layers) <= 0 or max(returned_layers) >= 5: + raise ValueError(f"Each returned layer should be in the range [1,4]. Got {returned_layers}") + return_layers = {f"layer{k}": str(v) for v, k in enumerate(returned_layers)} + + in_channels_stage2 = backbone.in_planes // 8 + in_channels_list = [in_channels_stage2 * 2 ** (i - 1) for i in returned_layers] + out_channels = 256 + return BackboneWithFPN( + backbone, return_layers, in_channels_list, out_channels, extra_blocks=extra_blocks, spatial_dims=spatial_dims + ) diff --git a/source_code/SegMamba/monai/networks/blocks/convolutions.py b/source_code/SegMamba/monai/networks/blocks/convolutions.py new file mode 100644 index 0000000000000000000000000000000000000000..8b186143648f5f10755cc57fd3f3380fc8547f6a --- /dev/null +++ b/source_code/SegMamba/monai/networks/blocks/convolutions.py @@ -0,0 +1,318 @@ +# Copyright (c) MONAI Consortium +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from __future__ import annotations + +from collections.abc import Sequence + +import numpy as np +import torch +import torch.nn as nn + +from monai.networks.blocks import ADN +from monai.networks.layers.convutils import same_padding, stride_minus_kernel_padding +from monai.networks.layers.factories import Conv + + +class Convolution(nn.Sequential): + """ + Constructs a convolution with normalization, optional dropout, and optional activation layers:: + + -- (Conv|ConvTrans) -- (Norm -- Dropout -- Acti) -- + + if ``conv_only`` set to ``True``:: + + -- (Conv|ConvTrans) -- + + For example: + + .. code-block:: python + + from monai.networks.blocks import Convolution + + conv = Convolution( + spatial_dims=3, + in_channels=1, + out_channels=1, + adn_ordering="ADN", + act=("prelu", {"init": 0.2}), + dropout=0.1, + norm=("layer", {"normalized_shape": (10, 10, 10)}), + ) + print(conv) + + output:: + + Convolution( + (conv): Conv3d(1, 1, kernel_size=(3, 3, 3), stride=(1, 1, 1), padding=(1, 1, 1)) + (adn): ADN( + (A): PReLU(num_parameters=1) + (D): Dropout(p=0.1, inplace=False) + (N): LayerNorm((10, 10, 10), eps=1e-05, elementwise_affine=True) + ) + ) + + Args: + spatial_dims: number of spatial dimensions. + in_channels: number of input channels. + out_channels: number of output channels. + strides: convolution stride. Defaults to 1. + kernel_size: convolution kernel size. Defaults to 3. + adn_ordering: a string representing the ordering of activation, normalization, and dropout. + Defaults to "NDA". + act: activation type and arguments. Defaults to PReLU. + norm: feature normalization type and arguments. Defaults to instance norm. + dropout: dropout ratio. Defaults to no dropout. + dropout_dim: determine the spatial dimensions of dropout. Defaults to 1. + + - When dropout_dim = 1, randomly zeroes some of the elements for each channel. + - When dropout_dim = 2, Randomly zeroes out entire channels (a channel is a 2D feature map). + - When dropout_dim = 3, Randomly zeroes out entire channels (a channel is a 3D feature map). + + The value of dropout_dim should be no larger than the value of `spatial_dims`. + dilation: dilation rate. Defaults to 1. + groups: controls the connections between inputs and outputs. Defaults to 1. + bias: whether to have a bias term. Defaults to True. + conv_only: whether to use the convolutional layer only. Defaults to False. + is_transposed: if True uses ConvTrans instead of Conv. Defaults to False. + padding: controls the amount of implicit zero-paddings on both sides for padding number of points + for each dimension. Defaults to None. + output_padding: controls the additional size added to one side of the output shape. + Defaults to None. + + See also: + + :py:class:`monai.networks.layers.Conv` + :py:class:`monai.networks.blocks.ADN` + + """ + + def __init__( + self, + spatial_dims: int, + in_channels: int, + out_channels: int, + strides: Sequence[int] | int = 1, + kernel_size: Sequence[int] | int = 3, + adn_ordering: str = "NDA", + act: tuple | str | None = "PRELU", + norm: tuple | str | None = "INSTANCE", + dropout: tuple | str | float | None = None, + dropout_dim: int | None = 1, + dilation: Sequence[int] | int = 1, + groups: int = 1, + bias: bool = True, + conv_only: bool = False, + is_transposed: bool = False, + padding: Sequence[int] | int | None = None, + output_padding: Sequence[int] | int | None = None, + ) -> None: + super().__init__() + self.spatial_dims = spatial_dims + self.in_channels = in_channels + self.out_channels = out_channels + self.is_transposed = is_transposed + if padding is None: + padding = same_padding(kernel_size, dilation) + conv_type = Conv[Conv.CONVTRANS if is_transposed else Conv.CONV, self.spatial_dims] + + conv: nn.Module + if is_transposed: + if output_padding is None: + output_padding = stride_minus_kernel_padding(1, strides) + conv = conv_type( + in_channels, + out_channels, + kernel_size=kernel_size, + stride=strides, + padding=padding, + output_padding=output_padding, + groups=groups, + bias=bias, + dilation=dilation, + ) + else: + conv = conv_type( + in_channels, + out_channels, + kernel_size=kernel_size, + stride=strides, + padding=padding, + dilation=dilation, + groups=groups, + bias=bias, + ) + + self.add_module("conv", conv) + + if conv_only: + return + if act is None and norm is None and dropout is None: + return + self.add_module( + "adn", + ADN( + ordering=adn_ordering, + in_channels=out_channels, + act=act, + norm=norm, + norm_dim=self.spatial_dims, + dropout=dropout, + dropout_dim=dropout_dim, + ), + ) + + +class ResidualUnit(nn.Module): + """ + Residual module with multiple convolutions and a residual connection. + + For example: + + .. code-block:: python + + from monai.networks.blocks import ResidualUnit + + convs = ResidualUnit( + spatial_dims=3, + in_channels=1, + out_channels=1, + adn_ordering="AN", + act=("prelu", {"init": 0.2}), + norm=("layer", {"normalized_shape": (10, 10, 10)}), + ) + print(convs) + + output:: + + ResidualUnit( + (conv): Sequential( + (unit0): Convolution( + (conv): Conv3d(1, 1, kernel_size=(3, 3, 3), stride=(1, 1, 1), padding=(1, 1, 1)) + (adn): ADN( + (A): PReLU(num_parameters=1) + (N): LayerNorm((10, 10, 10), eps=1e-05, elementwise_affine=True) + ) + ) + (unit1): Convolution( + (conv): Conv3d(1, 1, kernel_size=(3, 3, 3), stride=(1, 1, 1), padding=(1, 1, 1)) + (adn): ADN( + (A): PReLU(num_parameters=1) + (N): LayerNorm((10, 10, 10), eps=1e-05, elementwise_affine=True) + ) + ) + ) + (residual): Identity() + ) + + Args: + spatial_dims: number of spatial dimensions. + in_channels: number of input channels. + out_channels: number of output channels. + strides: convolution stride. Defaults to 1. + kernel_size: convolution kernel size. Defaults to 3. + subunits: number of convolutions. Defaults to 2. + adn_ordering: a string representing the ordering of activation, normalization, and dropout. + Defaults to "NDA". + act: activation type and arguments. Defaults to PReLU. + norm: feature normalization type and arguments. Defaults to instance norm. + dropout: dropout ratio. Defaults to no dropout. + dropout_dim: determine the dimensions of dropout. Defaults to 1. + + - When dropout_dim = 1, randomly zeroes some of the elements for each channel. + - When dropout_dim = 2, Randomly zero out entire channels (a channel is a 2D feature map). + - When dropout_dim = 3, Randomly zero out entire channels (a channel is a 3D feature map). + + The value of dropout_dim should be no larger than the value of `dimensions`. + dilation: dilation rate. Defaults to 1. + bias: whether to have a bias term. Defaults to True. + last_conv_only: for the last subunit, whether to use the convolutional layer only. + Defaults to False. + padding: controls the amount of implicit zero-paddings on both sides for padding number of points + for each dimension. Defaults to None. + + See also: + + :py:class:`monai.networks.blocks.Convolution` + + """ + + def __init__( + self, + spatial_dims: int, + in_channels: int, + out_channels: int, + strides: Sequence[int] | int = 1, + kernel_size: Sequence[int] | int = 3, + subunits: int = 2, + adn_ordering: str = "NDA", + act: tuple | str | None = "PRELU", + norm: tuple | str | None = "INSTANCE", + dropout: tuple | str | float | None = None, + dropout_dim: int | None = 1, + dilation: Sequence[int] | int = 1, + bias: bool = True, + last_conv_only: bool = False, + padding: Sequence[int] | int | None = None, + ) -> None: + super().__init__() + self.spatial_dims = spatial_dims + self.in_channels = in_channels + self.out_channels = out_channels + self.conv = nn.Sequential() + self.residual = nn.Identity() + if not padding: + padding = same_padding(kernel_size, dilation) + schannels = in_channels + sstrides = strides + subunits = max(1, subunits) + + for su in range(subunits): + conv_only = last_conv_only and su == (subunits - 1) + unit = Convolution( + self.spatial_dims, + schannels, + out_channels, + strides=sstrides, + kernel_size=kernel_size, + adn_ordering=adn_ordering, + act=act, + norm=norm, + dropout=dropout, + dropout_dim=dropout_dim, + dilation=dilation, + bias=bias, + conv_only=conv_only, + padding=padding, + ) + + self.conv.add_module(f"unit{su:d}", unit) + + # after first loop set channels and strides to what they should be for subsequent units + schannels = out_channels + sstrides = 1 + + # apply convolution to input to change number of output channels and size to match that coming from self.conv + if np.prod(strides) != 1 or in_channels != out_channels: + rkernel_size = kernel_size + rpadding = padding + + if np.prod(strides) == 1: # if only adapting number of channels a 1x1 kernel is used with no padding + rkernel_size = 1 + rpadding = 0 + + conv_type = Conv[Conv.CONV, self.spatial_dims] + self.residual = conv_type(in_channels, out_channels, rkernel_size, strides, rpadding, bias=bias) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + res: torch.Tensor = self.residual(x) # create the additive residual from x + cx: torch.Tensor = self.conv(x) # apply x to sequence of operations + return cx + res # add the residual to the output diff --git a/source_code/SegMamba/monai/networks/blocks/denseblock.py b/source_code/SegMamba/monai/networks/blocks/denseblock.py new file mode 100644 index 0000000000000000000000000000000000000000..8c67584f5f32ccdadcc5559d1cb36172aa633f7b --- /dev/null +++ b/source_code/SegMamba/monai/networks/blocks/denseblock.py @@ -0,0 +1,131 @@ +# Copyright (c) MONAI Consortium +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from __future__ import annotations + +from typing import Sequence + +import torch +import torch.nn as nn + +from monai.networks.blocks import Convolution, ResidualUnit +from monai.networks.layers.factories import Act, Norm + +__ALL__ = ["DenseBlock", "ConvDenseBlock"] + + +class DenseBlock(nn.Sequential): + """ + A DenseBlock is a sequence of layers where each layer's outputs are concatenated with their inputs. This has the + effect of accumulating outputs from previous layers as inputs to later ones and as the final output of the block. + + Args: + layers: sequence of nn.Module objects to define the individual layers of the dense block + """ + + def __init__(self, layers: Sequence[nn.Module]): + super().__init__() + for i, l in enumerate(layers): + self.add_module(f"layers{i}", l) + + def forward(self, x): + for l in self.children(): + result = l(x) + x = torch.cat([x, result], 1) + + return x + + +class ConvDenseBlock(DenseBlock): + """ + This dense block is defined as a sequence of `Convolution` or `ResidualUnit` blocks. The `_get_layer` method returns + an object for each layer and can be overridden to change the composition of the block. + + Args: + spatial_dims: number of spatial dimensions. + in_channels: number of input channels. + channels: output channels for each layer. + dilations: dilation value for each layer. + kernel_size: convolution kernel size. Defaults to 3. + num_res_units: number of convolutions. Defaults to 2. + adn_ordering: a string representing the ordering of activation, normalization, and dropout. Defaults to "NDA". + act: activation type and arguments. Defaults to PReLU. + norm: feature normalization type and arguments. Defaults to instance norm. + dropout: dropout ratio. Defaults to no dropout. + bias: whether to have a bias term. Defaults to True. + """ + + def __init__( + self, + spatial_dims: int, + in_channels: int, + channels: Sequence[int], + dilations: Sequence[int] | None = None, + kernel_size: Sequence[int] | int = 3, + num_res_units: int = 0, + adn_ordering: str = "NDA", + act: tuple | str | None = Act.PRELU, + norm: tuple | str | None = Norm.INSTANCE, + dropout: tuple | str | float | None = None, + bias: bool = True, + ): + self.spatial_dims = spatial_dims + self.kernel_size = kernel_size + self.num_res_units = num_res_units + self.adn_ordering = adn_ordering + self.act = act + self.norm = norm + self.dropout = dropout + self.bias = bias + + l_channels = in_channels + dilations = dilations if dilations is not None else ([1] * len(channels)) + layers = [] + + if len(channels) != len(dilations): + raise ValueError("Length of `channels` and `dilations` must match") + + for c, d in zip(channels, dilations): + layer = self._get_layer(l_channels, c, d) + layers.append(layer) + l_channels += c + + super().__init__(layers) + + def _get_layer(self, in_channels, out_channels, dilation): + if self.num_res_units > 0: + return ResidualUnit( + spatial_dims=self.spatial_dims, + in_channels=in_channels, + out_channels=out_channels, + strides=1, + kernel_size=self.kernel_size, + subunits=self.num_res_units, + adn_ordering=self.adn_ordering, + act=self.act, + norm=self.norm, + dropout=self.dropout, + dilation=dilation, + bias=self.bias, + ) + else: + return Convolution( + spatial_dims=self.spatial_dims, + in_channels=in_channels, + out_channels=out_channels, + strides=1, + kernel_size=self.kernel_size, + act=self.act, + norm=self.norm, + dropout=self.dropout, + dilation=dilation, + bias=self.bias, + ) diff --git a/source_code/SegMamba/monai/networks/blocks/dints_block.py b/source_code/SegMamba/monai/networks/blocks/dints_block.py new file mode 100644 index 0000000000000000000000000000000000000000..d3ac7cf04b3a60890c6b8b81439c99ef894a6493 --- /dev/null +++ b/source_code/SegMamba/monai/networks/blocks/dints_block.py @@ -0,0 +1,271 @@ +# Copyright (c) MONAI Consortium +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from __future__ import annotations + +import torch + +from monai.networks.layers.factories import Conv +from monai.networks.layers.utils import get_act_layer, get_norm_layer + +__all__ = ["FactorizedIncreaseBlock", "FactorizedReduceBlock", "P3DActiConvNormBlock", "ActiConvNormBlock"] + + +class FactorizedIncreaseBlock(torch.nn.Sequential): + """ + Up-sampling the features by two using linear interpolation and convolutions. + """ + + def __init__( + self, + in_channel: int, + out_channel: int, + spatial_dims: int = 3, + act_name: tuple | str = "RELU", + norm_name: tuple | str = ("INSTANCE", {"affine": True}), + ): + """ + Args: + in_channel: number of input channels + out_channel: number of output channels + spatial_dims: number of spatial dimensions + act_name: activation layer type and arguments. + norm_name: feature normalization type and arguments. + """ + super().__init__() + self._in_channel = in_channel + self._out_channel = out_channel + self._spatial_dims = spatial_dims + if self._spatial_dims not in (2, 3): + raise ValueError("spatial_dims must be 2 or 3.") + + conv_type = Conv[Conv.CONV, self._spatial_dims] + mode = "trilinear" if self._spatial_dims == 3 else "bilinear" + self.add_module("up", torch.nn.Upsample(scale_factor=2, mode=mode, align_corners=True)) + self.add_module("acti", get_act_layer(name=act_name)) + self.add_module( + "conv", + conv_type( + in_channels=self._in_channel, + out_channels=self._out_channel, + kernel_size=1, + stride=1, + padding=0, + groups=1, + bias=False, + dilation=1, + ), + ) + self.add_module( + "norm", get_norm_layer(name=norm_name, spatial_dims=self._spatial_dims, channels=self._out_channel) + ) + + +class FactorizedReduceBlock(torch.nn.Module): + """ + Down-sampling the feature by 2 using stride. + The length along each spatial dimension must be a multiple of 2. + """ + + def __init__( + self, + in_channel: int, + out_channel: int, + spatial_dims: int = 3, + act_name: tuple | str = "RELU", + norm_name: tuple | str = ("INSTANCE", {"affine": True}), + ): + """ + Args: + in_channel: number of input channels + out_channel: number of output channels. + spatial_dims: number of spatial dimensions. + act_name: activation layer type and arguments. + norm_name: feature normalization type and arguments. + """ + super().__init__() + self._in_channel = in_channel + self._out_channel = out_channel + self._spatial_dims = spatial_dims + if self._spatial_dims not in (2, 3): + raise ValueError("spatial_dims must be 2 or 3.") + + conv_type = Conv[Conv.CONV, self._spatial_dims] + + self.act = get_act_layer(name=act_name) + self.conv_1 = conv_type( + in_channels=self._in_channel, + out_channels=self._out_channel // 2, + kernel_size=1, + stride=2, + padding=0, + groups=1, + bias=False, + dilation=1, + ) + self.conv_2 = conv_type( + in_channels=self._in_channel, + out_channels=self._out_channel - self._out_channel // 2, + kernel_size=1, + stride=2, + padding=0, + groups=1, + bias=False, + dilation=1, + ) + self.norm = get_norm_layer(name=norm_name, spatial_dims=self._spatial_dims, channels=self._out_channel) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + """ + The length along each spatial dimension must be a multiple of 2. + """ + x = self.act(x) + if self._spatial_dims == 3: + out = torch.cat([self.conv_1(x), self.conv_2(x[:, :, 1:, 1:, 1:])], dim=1) + else: + out = torch.cat([self.conv_1(x), self.conv_2(x[:, :, 1:, 1:])], dim=1) + out = self.norm(out) + return out + + +class P3DActiConvNormBlock(torch.nn.Sequential): + """ + -- (act) -- (conv) -- (norm) -- + """ + + def __init__( + self, + in_channel: int, + out_channel: int, + kernel_size: int, + padding: int, + mode: int = 0, + act_name: tuple | str = "RELU", + norm_name: tuple | str = ("INSTANCE", {"affine": True}), + ): + """ + Args: + in_channel: number of input channels. + out_channel: number of output channels. + kernel_size: kernel size to be expanded to 3D. + padding: padding size to be expanded to 3D. + mode: mode for the anisotropic kernels: + + - 0: ``(k, k, 1)``, ``(1, 1, k)``, + - 1: ``(k, 1, k)``, ``(1, k, 1)``, + - 2: ``(1, k, k)``. ``(k, 1, 1)``. + + act_name: activation layer type and arguments. + norm_name: feature normalization type and arguments. + """ + super().__init__() + self._in_channel = in_channel + self._out_channel = out_channel + self._p3dmode = int(mode) + + conv_type = Conv[Conv.CONV, 3] + + if self._p3dmode == 0: # (k, k, 1), (1, 1, k) + kernel_size0 = (kernel_size, kernel_size, 1) + kernel_size1 = (1, 1, kernel_size) + padding0 = (padding, padding, 0) + padding1 = (0, 0, padding) + elif self._p3dmode == 1: # (k, 1, k), (1, k, 1) + kernel_size0 = (kernel_size, 1, kernel_size) + kernel_size1 = (1, kernel_size, 1) + padding0 = (padding, 0, padding) + padding1 = (0, padding, 0) + elif self._p3dmode == 2: # (1, k, k), (k, 1, 1) + kernel_size0 = (1, kernel_size, kernel_size) + kernel_size1 = (kernel_size, 1, 1) + padding0 = (0, padding, padding) + padding1 = (padding, 0, 0) + else: + raise ValueError("`mode` must be 0, 1, or 2.") + + self.add_module("acti", get_act_layer(name=act_name)) + self.add_module( + "conv", + conv_type( + in_channels=self._in_channel, + out_channels=self._in_channel, + kernel_size=kernel_size0, + stride=1, + padding=padding0, + groups=1, + bias=False, + dilation=1, + ), + ) + self.add_module( + "conv_1", + conv_type( + in_channels=self._in_channel, + out_channels=self._out_channel, + kernel_size=kernel_size1, + stride=1, + padding=padding1, + groups=1, + bias=False, + dilation=1, + ), + ) + self.add_module("norm", get_norm_layer(name=norm_name, spatial_dims=3, channels=self._out_channel)) + + +class ActiConvNormBlock(torch.nn.Sequential): + """ + -- (Acti) -- (Conv) -- (Norm) -- + """ + + def __init__( + self, + in_channel: int, + out_channel: int, + kernel_size: int = 3, + padding: int = 1, + spatial_dims: int = 3, + act_name: tuple | str = "RELU", + norm_name: tuple | str = ("INSTANCE", {"affine": True}), + ): + """ + Args: + in_channel: number of input channels. + out_channel: number of output channels. + kernel_size: kernel size of the convolution. + padding: padding size of the convolution. + spatial_dims: number of spatial dimensions. + act_name: activation layer type and arguments. + norm_name: feature normalization type and arguments. + """ + super().__init__() + self._in_channel = in_channel + self._out_channel = out_channel + self._spatial_dims = spatial_dims + + conv_type = Conv[Conv.CONV, self._spatial_dims] + self.add_module("acti", get_act_layer(name=act_name)) + self.add_module( + "conv", + conv_type( + in_channels=self._in_channel, + out_channels=self._out_channel, + kernel_size=kernel_size, + stride=1, + padding=padding, + groups=1, + bias=False, + dilation=1, + ), + ) + self.add_module( + "norm", get_norm_layer(name=norm_name, spatial_dims=self._spatial_dims, channels=self._out_channel) + ) diff --git a/source_code/SegMamba/monai/networks/blocks/dynunet_block.py b/source_code/SegMamba/monai/networks/blocks/dynunet_block.py new file mode 100644 index 0000000000000000000000000000000000000000..801b49de8bd2e889adf6ec4bdeffc50b18775d98 --- /dev/null +++ b/source_code/SegMamba/monai/networks/blocks/dynunet_block.py @@ -0,0 +1,327 @@ +# Copyright (c) MONAI Consortium +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from __future__ import annotations + +from collections.abc import Sequence + +import numpy as np +import torch +import torch.nn as nn + +from monai.networks.blocks.convolutions import Convolution +from monai.networks.layers.factories import Act, Norm +from monai.networks.layers.utils import get_act_layer, get_norm_layer + + +class UnetResBlock(nn.Module): + """ + A skip-connection based module that can be used for DynUNet, based on: + `Automated Design of Deep Learning Methods for Biomedical Image Segmentation `_. + `nnU-Net: Self-adapting Framework for U-Net-Based Medical Image Segmentation `_. + + Args: + spatial_dims: number of spatial dimensions. + in_channels: number of input channels. + out_channels: number of output channels. + kernel_size: convolution kernel size. + stride: convolution stride. + norm_name: feature normalization type and arguments. + act_name: activation layer type and arguments. + dropout: dropout probability. + + """ + + def __init__( + self, + spatial_dims: int, + in_channels: int, + out_channels: int, + kernel_size: Sequence[int] | int, + stride: Sequence[int] | int, + norm_name: tuple | str, + act_name: tuple | str = ("leakyrelu", {"inplace": True, "negative_slope": 0.01}), + dropout: tuple | str | float | None = None, + ): + super().__init__() + self.conv1 = get_conv_layer( + spatial_dims, + in_channels, + out_channels, + kernel_size=kernel_size, + stride=stride, + dropout=dropout, + act=None, + norm=None, + conv_only=False, + ) + self.conv2 = get_conv_layer( + spatial_dims, + out_channels, + out_channels, + kernel_size=kernel_size, + stride=1, + dropout=dropout, + act=None, + norm=None, + conv_only=False, + ) + self.lrelu = get_act_layer(name=act_name) + self.norm1 = get_norm_layer(name=norm_name, spatial_dims=spatial_dims, channels=out_channels) + self.norm2 = get_norm_layer(name=norm_name, spatial_dims=spatial_dims, channels=out_channels) + self.downsample = in_channels != out_channels + stride_np = np.atleast_1d(stride) + if not np.all(stride_np == 1): + self.downsample = True + if self.downsample: + self.conv3 = get_conv_layer( + spatial_dims, + in_channels, + out_channels, + kernel_size=1, + stride=stride, + dropout=dropout, + act=None, + norm=None, + conv_only=False, + ) + self.norm3 = get_norm_layer(name=norm_name, spatial_dims=spatial_dims, channels=out_channels) + + def forward(self, inp): + residual = inp + out = self.conv1(inp) + out = self.norm1(out) + out = self.lrelu(out) + out = self.conv2(out) + out = self.norm2(out) + if hasattr(self, "conv3"): + residual = self.conv3(residual) + if hasattr(self, "norm3"): + residual = self.norm3(residual) + out += residual + out = self.lrelu(out) + return out + + +class UnetBasicBlock(nn.Module): + """ + A CNN module that can be used for DynUNet, based on: + `Automated Design of Deep Learning Methods for Biomedical Image Segmentation `_. + `nnU-Net: Self-adapting Framework for U-Net-Based Medical Image Segmentation `_. + + Args: + spatial_dims: number of spatial dimensions. + in_channels: number of input channels. + out_channels: number of output channels. + kernel_size: convolution kernel size. + stride: convolution stride. + norm_name: feature normalization type and arguments. + act_name: activation layer type and arguments. + dropout: dropout probability. + + """ + + def __init__( + self, + spatial_dims: int, + in_channels: int, + out_channels: int, + kernel_size: Sequence[int] | int, + stride: Sequence[int] | int, + norm_name: tuple | str, + act_name: tuple | str = ("leakyrelu", {"inplace": True, "negative_slope": 0.01}), + dropout: tuple | str | float | None = None, + ): + super().__init__() + self.conv1 = get_conv_layer( + spatial_dims, + in_channels, + out_channels, + kernel_size=kernel_size, + stride=stride, + dropout=dropout, + act=None, + norm=None, + conv_only=False, + ) + self.conv2 = get_conv_layer( + spatial_dims, + out_channels, + out_channels, + kernel_size=kernel_size, + stride=1, + dropout=dropout, + act=None, + norm=None, + conv_only=False, + ) + self.lrelu = get_act_layer(name=act_name) + self.norm1 = get_norm_layer(name=norm_name, spatial_dims=spatial_dims, channels=out_channels) + self.norm2 = get_norm_layer(name=norm_name, spatial_dims=spatial_dims, channels=out_channels) + + def forward(self, inp): + out = self.conv1(inp) + out = self.norm1(out) + out = self.lrelu(out) + out = self.conv2(out) + out = self.norm2(out) + out = self.lrelu(out) + return out + + +class UnetUpBlock(nn.Module): + """ + An upsampling module that can be used for DynUNet, based on: + `Automated Design of Deep Learning Methods for Biomedical Image Segmentation `_. + `nnU-Net: Self-adapting Framework for U-Net-Based Medical Image Segmentation `_. + + Args: + spatial_dims: number of spatial dimensions. + in_channels: number of input channels. + out_channels: number of output channels. + kernel_size: convolution kernel size. + stride: convolution stride. + upsample_kernel_size: convolution kernel size for transposed convolution layers. + norm_name: feature normalization type and arguments. + act_name: activation layer type and arguments. + dropout: dropout probability. + trans_bias: transposed convolution bias. + + """ + + def __init__( + self, + spatial_dims: int, + in_channels: int, + out_channels: int, + kernel_size: Sequence[int] | int, + stride: Sequence[int] | int, + upsample_kernel_size: Sequence[int] | int, + norm_name: tuple | str, + act_name: tuple | str = ("leakyrelu", {"inplace": True, "negative_slope": 0.01}), + dropout: tuple | str | float | None = None, + trans_bias: bool = False, + ): + super().__init__() + upsample_stride = upsample_kernel_size + self.transp_conv = get_conv_layer( + spatial_dims, + in_channels, + out_channels, + kernel_size=upsample_kernel_size, + stride=upsample_stride, + dropout=dropout, + bias=trans_bias, + act=None, + norm=None, + conv_only=False, + is_transposed=True, + ) + self.conv_block = UnetBasicBlock( + spatial_dims, + out_channels + out_channels, + out_channels, + kernel_size=kernel_size, + stride=1, + dropout=dropout, + norm_name=norm_name, + act_name=act_name, + ) + + def forward(self, inp, skip): + # number of channels for skip should equals to out_channels + out = self.transp_conv(inp) + out = torch.cat((out, skip), dim=1) + out = self.conv_block(out) + return out + + +class UnetOutBlock(nn.Module): + + def __init__( + self, spatial_dims: int, in_channels: int, out_channels: int, dropout: tuple | str | float | None = None + ): + super().__init__() + self.conv = get_conv_layer( + spatial_dims, + in_channels, + out_channels, + kernel_size=1, + stride=1, + dropout=dropout, + bias=True, + act=None, + norm=None, + conv_only=False, + ) + + def forward(self, inp): + return self.conv(inp) + + +def get_conv_layer( + spatial_dims: int, + in_channels: int, + out_channels: int, + kernel_size: Sequence[int] | int = 3, + stride: Sequence[int] | int = 1, + act: tuple | str | None = Act.PRELU, + norm: tuple | str | None = Norm.INSTANCE, + dropout: tuple | str | float | None = None, + bias: bool = False, + conv_only: bool = True, + is_transposed: bool = False, +): + padding = get_padding(kernel_size, stride) + output_padding = None + if is_transposed: + output_padding = get_output_padding(kernel_size, stride, padding) + return Convolution( + spatial_dims, + in_channels, + out_channels, + strides=stride, + kernel_size=kernel_size, + act=act, + norm=norm, + dropout=dropout, + bias=bias, + conv_only=conv_only, + is_transposed=is_transposed, + padding=padding, + output_padding=output_padding, + ) + + +def get_padding(kernel_size: Sequence[int] | int, stride: Sequence[int] | int) -> tuple[int, ...] | int: + kernel_size_np = np.atleast_1d(kernel_size) + stride_np = np.atleast_1d(stride) + padding_np = (kernel_size_np - stride_np + 1) / 2 + if np.min(padding_np) < 0: + raise AssertionError("padding value should not be negative, please change the kernel size and/or stride.") + padding = tuple(int(p) for p in padding_np) + + return padding if len(padding) > 1 else padding[0] + + +def get_output_padding( + kernel_size: Sequence[int] | int, stride: Sequence[int] | int, padding: Sequence[int] | int +) -> tuple[int, ...] | int: + kernel_size_np = np.atleast_1d(kernel_size) + stride_np = np.atleast_1d(stride) + padding_np = np.atleast_1d(padding) + + out_padding_np = 2 * padding_np + stride_np - kernel_size_np + if np.min(out_padding_np) < 0: + raise AssertionError("out_padding value should not be negative, please change the kernel size and/or stride.") + out_padding = tuple(int(p) for p in out_padding_np) + + return out_padding if len(out_padding) > 1 else out_padding[0] diff --git a/source_code/SegMamba/monai/networks/blocks/encoder.py b/source_code/SegMamba/monai/networks/blocks/encoder.py new file mode 100644 index 0000000000000000000000000000000000000000..419afec8389a8a8745b4066949f05d81f1f25d84 --- /dev/null +++ b/source_code/SegMamba/monai/networks/blocks/encoder.py @@ -0,0 +1,85 @@ +# Copyright (c) MONAI Consortium +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from __future__ import annotations + +from abc import ABCMeta, abstractmethod + +__all__ = ["BaseEncoder"] + + +class BaseEncoder(metaclass=ABCMeta): + """ + Abstract class defines interface of encoders in flexible unet. + Encoders in flexible unet must derive from this class. Each interface method + should return a list containing relative information about a series of networks + defined by encoder. For example, the efficient-net encoder implement 10 basic + network structures in one encoder. When calling `get_encoder_name_string_list` + function, a string list like ["efficientnet-b0", "efficientnet-b1" ... "efficientnet-l2"] + should be returned. + """ + + @classmethod + @abstractmethod + def get_encoder_parameters(cls) -> list[dict]: + """ + Get parameter list to initialize encoder networks. + Each parameter dict must have `spatial_dims`, `in_channels` + and `pretrained` parameters. + The reason that this function should return a list is that a + series of encoders can be implemented by one encoder class + given different initialization parameters. Each parameter dict + in return list should be able to initialize a unique encoder. + """ + raise NotImplementedError + + @classmethod + @abstractmethod + def num_channels_per_output(cls) -> list[tuple[int, ...]]: + """ + Get number of output features' channels. + The reason that this function should return a list is that a + series of encoders can be implemented by one encoder class + given different initialization parameters. And it is possible + that different encoders have different output feature map + channels. Therefore a list of output feature map channel tuples + corresponding to each encoder should be returned by this method. + """ + raise NotImplementedError + + @classmethod + @abstractmethod + def num_outputs(cls) -> list[int]: + """ + Get number of outputs of encoder. + The reason that this function should return a list is that a + series of encoders can be implemented by one encoder class + given different initialization parameters. And it is possible + that different encoders have different output feature numbers. + Therefore a list of output feature numbers corresponding to + each encoder should be returned by this method. + """ + raise NotImplementedError + + @classmethod + @abstractmethod + def get_encoder_names(cls) -> list[str]: + """ + Get the name string of encoders which will be used to initialize + flexible unet. + The reason that this function should return a list is that a + series of encoders can be implemented by one encoder class + given different initialization parameters. And a name string is + the key to each encoder in flexible unet backbone registry. + Therefore this method should return every encoder name that needs + to be registered in flexible unet. + """ + raise NotImplementedError diff --git a/source_code/SegMamba/monai/networks/blocks/fcn.py b/source_code/SegMamba/monai/networks/blocks/fcn.py new file mode 100644 index 0000000000000000000000000000000000000000..b44ea5f99ac255069e8d383a6d23bf62058c3fcc --- /dev/null +++ b/source_code/SegMamba/monai/networks/blocks/fcn.py @@ -0,0 +1,242 @@ +# Copyright (c) MONAI Consortium +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from __future__ import annotations + +import torch +import torch.nn as nn +import torch.nn.functional as F + +from monai.networks.blocks.convolutions import Convolution +from monai.networks.blocks.upsample import UpSample +from monai.networks.layers.factories import Act, Conv, Norm +from monai.utils import optional_import + +models, _ = optional_import("torchvision", name="models") + + +class GCN(nn.Module): + """ + The Global Convolutional Network module using large 1D + Kx1 and 1xK kernels to represent 2D kernels. + """ + + def __init__(self, inplanes: int, planes: int, ks: int = 7): + """ + Args: + inplanes: number of input channels. + planes: number of output channels. + ks: kernel size for one dimension. Defaults to 7. + """ + 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)) + self.conv_l2 = conv2d_type(in_channels=planes, out_channels=planes, kernel_size=(1, ks), padding=(0, ks // 2)) + self.conv_r1 = conv2d_type(in_channels=inplanes, out_channels=planes, kernel_size=(1, ks), padding=(0, ks // 2)) + self.conv_r2 = conv2d_type(in_channels=planes, out_channels=planes, kernel_size=(ks, 1), padding=(ks // 2, 0)) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + """ + Args: + x: in shape (batch, inplanes, spatial_1, spatial_2). + """ + x_l = self.conv_l1(x) + x_l = self.conv_l2(x_l) + x_r = self.conv_r1(x) + x_r = self.conv_r2(x_r) + x = x_l + x_r + return x + + +class Refine(nn.Module): + """ + Simple residual block to refine the details of the activation maps. + """ + + def __init__(self, planes: int): + """ + Args: + planes: number of input channels. + """ + super().__init__() + + relu_type: type[nn.ReLU] = Act[Act.RELU] + conv2d_type: type[nn.Conv2d] = Conv[Conv.CONV, 2] + norm2d_type: type[nn.BatchNorm2d] = Norm[Norm.BATCH, 2] + + self.bn = norm2d_type(num_features=planes) + self.relu = relu_type(inplace=True) + self.conv1 = conv2d_type(in_channels=planes, out_channels=planes, kernel_size=3, padding=1) + self.conv2 = conv2d_type(in_channels=planes, out_channels=planes, kernel_size=3, padding=1) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + """ + Args: + x: in shape (batch, planes, spatial_1, spatial_2). + """ + residual = x + x = self.bn(x) + x = self.relu(x) + x = self.conv1(x) + x = self.bn(x) + x = self.relu(x) + x = self.conv2(x) + + return residual + x + + +class FCN(nn.Module): + """ + 2D FCN network with 3 input channels. The small decoder is built + with the GCN and Refine modules. + The code is adapted from `lsqshr's official 2D code `_. + + Args: + out_channels: number of output channels. Defaults to 1. + upsample_mode: [``"transpose"``, ``"bilinear"``] + The mode of upsampling manipulations. + Using the second mode cannot guarantee the model's reproducibility. Defaults to ``bilinear``. + + - ``transpose``, uses transposed convolution layers. + - ``bilinear``, uses bilinear interpolation. + + pretrained: If True, returns a model pre-trained on ImageNet + progress: If True, displays a progress bar of the download to stderr. + """ + + def __init__( + self, out_channels: int = 1, upsample_mode: str = "bilinear", pretrained: bool = True, progress: bool = True + ): + super().__init__() + + conv2d_type: type[nn.Conv2d] = Conv[Conv.CONV, 2] + + self.upsample_mode = upsample_mode + self.conv2d_type = conv2d_type + self.out_channels = out_channels + resnet = models.resnet50(pretrained=pretrained, progress=progress) + + self.conv1 = resnet.conv1 + self.bn0 = resnet.bn1 + self.relu = resnet.relu + self.maxpool = resnet.maxpool + + self.layer1 = resnet.layer1 + self.layer2 = resnet.layer2 + self.layer3 = resnet.layer3 + self.layer4 = resnet.layer4 + + self.gcn1 = GCN(2048, self.out_channels) + self.gcn2 = GCN(1024, self.out_channels) + self.gcn3 = GCN(512, self.out_channels) + self.gcn4 = GCN(64, self.out_channels) + self.gcn5 = GCN(64, self.out_channels) + + self.refine1 = Refine(self.out_channels) + self.refine2 = Refine(self.out_channels) + self.refine3 = Refine(self.out_channels) + self.refine4 = Refine(self.out_channels) + self.refine5 = Refine(self.out_channels) + self.refine6 = Refine(self.out_channels) + self.refine7 = Refine(self.out_channels) + self.refine8 = Refine(self.out_channels) + self.refine9 = Refine(self.out_channels) + self.refine10 = Refine(self.out_channels) + 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") + + def forward(self, x: torch.Tensor): + """ + Args: + x: in shape (batch, 3, spatial_1, spatial_2). + """ + org_input = x + x = self.conv1(x) + x = self.bn0(x) + x = self.relu(x) + conv_x = x + x = self.maxpool(x) + pool_x = x + + fm1 = self.layer1(x) + fm2 = self.layer2(fm1) + fm3 = self.layer3(fm2) + fm4 = self.layer4(fm3) + + gcfm1 = self.refine1(self.gcn1(fm4)) + gcfm2 = self.refine2(self.gcn2(fm3)) + gcfm3 = self.refine3(self.gcn3(fm2)) + gcfm4 = self.refine4(self.gcn4(pool_x)) + gcfm5 = self.refine5(self.gcn5(conv_x)) + + if self.upsample_mode == "transpose": + fs1 = self.refine6(self.up_conv(gcfm1) + gcfm2) + fs2 = self.refine7(self.up_conv(fs1) + gcfm3) + fs3 = self.refine8(self.up_conv(fs2) + gcfm4) + fs4 = self.refine9(self.up_conv(fs3) + gcfm5) + return self.refine10(self.up_conv(fs4)) + fs1 = self.refine6(F.interpolate(gcfm1, fm3.size()[2:], mode=self.upsample_mode, align_corners=True) + gcfm2) + 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)) + + +class MCFCN(FCN): + """ + The multi-channel version of the 2D FCN module. + Adds a projection layer to take arbitrary number of inputs. + + Args: + in_channels: number of input channels. Defaults to 3. + out_channels: number of output channels. Defaults to 1. + upsample_mode: [``"transpose"``, ``"bilinear"``] + The mode of upsampling manipulations. + Using the second mode cannot guarantee the model's reproducibility. Defaults to ``bilinear``. + + - ``transpose``, uses transposed convolution layers. + - ``bilinear``, uses bilinear interpolate. + pretrained: If True, returns a model pre-trained on ImageNet + progress: If True, displays a progress bar of the download to stderr. + """ + + def __init__( + self, + in_channels: int = 3, + out_channels: int = 1, + upsample_mode: str = "bilinear", + pretrained: bool = True, + progress: bool = True, + ): + super().__init__( + out_channels=out_channels, upsample_mode=upsample_mode, pretrained=pretrained, progress=progress + ) + + self.init_proj = Convolution( + spatial_dims=2, + in_channels=in_channels, + out_channels=3, + kernel_size=1, + act=("relu", {"inplace": True}), + norm=Norm.BATCH, + bias=False, + ) + + def forward(self, x: torch.Tensor): + """ + Args: + x: in shape (batch, in_channels, spatial_1, spatial_2). + """ + x = self.init_proj(x) + return super().forward(x) diff --git a/source_code/SegMamba/monai/networks/blocks/feature_pyramid_network.py b/source_code/SegMamba/monai/networks/blocks/feature_pyramid_network.py new file mode 100644 index 0000000000000000000000000000000000000000..7de899803c5ef4ef84153fe899527c16445d66d4 --- /dev/null +++ b/source_code/SegMamba/monai/networks/blocks/feature_pyramid_network.py @@ -0,0 +1,264 @@ +# Copyright (c) MONAI Consortium +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# ========================================================================= +# Adapted from https://github.com/pytorch/vision/blob/release/0.12/torchvision/ops/feature_pyramid_network.py +# which has the following license... +# https://github.com/pytorch/vision/blob/main/LICENSE +# +# BSD 3-Clause License + +# Copyright (c) Soumith Chintala 2016, +# All rights reserved. + +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are met: + +# * Redistributions of source code must retain the above copyright notice, this +# list of conditions and the following disclaimer. + +# * Redistributions in binary form must reproduce the above copyright notice, +# this list of conditions and the following disclaimer in the documentation +# and/or other materials provided with the distribution. + +# * Neither the name of the copyright holder nor the names of its +# contributors may be used to endorse or promote products derived from +# this software without specific prior written permission. + +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +""" +This script is modified from from torchvision to support N-D images, +by overriding the definition of convolutional layers and pooling layers. + +https://github.com/pytorch/vision/blob/release/0.12/torchvision/ops/feature_pyramid_network.py +""" + +from __future__ import annotations + +from collections import OrderedDict +from collections.abc import Callable + +import torch.nn.functional as F +from torch import Tensor, nn + +from monai.networks.layers.factories import Conv, Pool + +__all__ = ["ExtraFPNBlock", "LastLevelMaxPool", "LastLevelP6P7", "FeaturePyramidNetwork"] + + +class ExtraFPNBlock(nn.Module): + """ + Base class for the extra block in the FPN. + + Same code as https://github.com/pytorch/vision/blob/release/0.12/torchvision/ops/feature_pyramid_network.py + """ + + def forward(self, results: list[Tensor], x: list[Tensor], names: list[str]): + """ + Compute extended set of results of the FPN and their names. + + Args: + results: the result of the FPN + x: the original feature maps + names: the names for each one of the original feature maps + + Returns: + - the extended set of results of the FPN + - the extended set of names for the results + """ + pass + + +class LastLevelMaxPool(ExtraFPNBlock): + """ + Applies a max_pool2d or max_pool3d on top of the last feature map. Serves as an ``extra_blocks`` + in :class:`~monai.networks.blocks.feature_pyramid_network.FeaturePyramidNetwork` . + """ + + def __init__(self, spatial_dims: int): + super().__init__() + pool_type: type[nn.MaxPool1d | nn.MaxPool2d | nn.MaxPool3d] = Pool[Pool.MAX, spatial_dims] + self.maxpool = pool_type(kernel_size=1, stride=2, padding=0) + + def forward(self, results: list[Tensor], x: list[Tensor], names: list[str]) -> tuple[list[Tensor], list[str]]: + names.append("pool") + results.append(self.maxpool(results[-1])) + return results, names + + +class LastLevelP6P7(ExtraFPNBlock): + """ + This module is used in RetinaNet to generate extra layers, P6 and P7. + Serves as an ``extra_blocks`` + in :class:`~monai.networks.blocks.feature_pyramid_network.FeaturePyramidNetwork` . + """ + + def __init__(self, spatial_dims: int, in_channels: int, out_channels: int): + super().__init__() + conv_type: Callable = Conv[Conv.CONV, spatial_dims] + self.p6 = conv_type(in_channels, out_channels, kernel_size=3, stride=2, padding=1) + self.p7 = conv_type(out_channels, out_channels, kernel_size=3, stride=2, padding=1) + for module in [self.p6, self.p7]: + nn.init.kaiming_uniform_(module.weight, a=1) + nn.init.constant_(module.bias, 0) + self.use_P5 = in_channels == out_channels + + def forward(self, results: list[Tensor], x: list[Tensor], names: list[str]) -> tuple[list[Tensor], list[str]]: + p5, c5 = results[-1], x[-1] + x5 = p5 if self.use_P5 else c5 + p6 = self.p6(x5) + p7 = self.p7(F.relu(p6)) + results.extend([p6, p7]) + names.extend(["p6", "p7"]) + return results, names + + +class FeaturePyramidNetwork(nn.Module): + """ + Module that adds a FPN from on top of a set of feature maps. This is based on + `"Feature Pyramid Network for Object Detection" `_. + + The feature maps are currently supposed to be in increasing depth + order. + + The input to the model is expected to be an OrderedDict[Tensor], containing + the feature maps on top of which the FPN will be added. + + Args: + spatial_dims: 2D or 3D images + in_channels_list: number of channels for each feature map that + is passed to the module + out_channels: number of channels of the FPN representation + extra_blocks: if provided, extra operations will + be performed. It is expected to take the fpn features, the original + features and the names of the original features as input, and returns + a new list of feature maps and their corresponding names + + Examples:: + + >>> m = FeaturePyramidNetwork(2, [10, 20, 30], 5) + >>> # get some dummy data + >>> x = OrderedDict() + >>> x['feat0'] = torch.rand(1, 10, 64, 64) + >>> x['feat2'] = torch.rand(1, 20, 16, 16) + >>> x['feat3'] = torch.rand(1, 30, 8, 8) + >>> # compute the FPN on top of x + >>> output = m(x) + >>> print([(k, v.shape) for k, v in output.items()]) + >>> # returns + >>> [('feat0', torch.Size([1, 5, 64, 64])), + >>> ('feat2', torch.Size([1, 5, 16, 16])), + >>> ('feat3', torch.Size([1, 5, 8, 8]))] + + """ + + def __init__( + self, + spatial_dims: int, + in_channels_list: list[int], + out_channels: int, + extra_blocks: ExtraFPNBlock | None = None, + ): + super().__init__() + + conv_type: Callable = Conv[Conv.CONV, spatial_dims] + + self.inner_blocks = nn.ModuleList() + self.layer_blocks = nn.ModuleList() + for in_channels in in_channels_list: + if in_channels == 0: + raise ValueError("in_channels=0 is currently not supported") + inner_block_module = conv_type(in_channels, out_channels, 1) + layer_block_module = conv_type(out_channels, out_channels, 3, padding=1) + self.inner_blocks.append(inner_block_module) + self.layer_blocks.append(layer_block_module) + + # initialize parameters now to avoid modifying the initialization of top_blocks + conv_type_: type[nn.Module] = Conv[Conv.CONV, spatial_dims] + for m in self.modules(): + if isinstance(m, conv_type_): + nn.init.kaiming_uniform_(m.weight, a=1) + nn.init.constant_(m.bias, 0.0) + + if extra_blocks is not None: + if not isinstance(extra_blocks, ExtraFPNBlock): + raise AssertionError + self.extra_blocks = extra_blocks + + def get_result_from_inner_blocks(self, x: Tensor, idx: int) -> Tensor: + """ + This is equivalent to self.inner_blocks[idx](x), + but torchscript doesn't support this yet + """ + num_blocks = len(self.inner_blocks) + if idx < 0: + idx += num_blocks + out = x + for i, module in enumerate(self.inner_blocks): + if i == idx: + out = module(x) + return out + + def get_result_from_layer_blocks(self, x: Tensor, idx: int) -> Tensor: + """ + This is equivalent to self.layer_blocks[idx](x), + but torchscript doesn't support this yet + """ + num_blocks = len(self.layer_blocks) + if idx < 0: + idx += num_blocks + out = x + for i, module in enumerate(self.layer_blocks): + if i == idx: + out = module(x) + return out + + def forward(self, x: dict[str, Tensor]) -> dict[str, Tensor]: + """ + Computes the FPN for a set of feature maps. + + Args: + x: feature maps for each feature level. + + Returns: + feature maps after FPN layers. They are ordered from highest resolution first. + """ + # unpack OrderedDict into two lists for easier handling + names = list(x.keys()) + x_values: list[Tensor] = list(x.values()) + + last_inner = self.get_result_from_inner_blocks(x_values[-1], -1) + results = [] + results.append(self.get_result_from_layer_blocks(last_inner, -1)) + + for idx in range(len(x_values) - 2, -1, -1): + inner_lateral = self.get_result_from_inner_blocks(x_values[idx], idx) + feat_shape = inner_lateral.shape[2:] + inner_top_down = F.interpolate(last_inner, size=feat_shape, mode="nearest") + last_inner = inner_lateral + inner_top_down + results.insert(0, self.get_result_from_layer_blocks(last_inner, idx)) + + if self.extra_blocks is not None: + results, names = self.extra_blocks(results, x_values, names) + + # make it back an OrderedDict + out = OrderedDict(list(zip(names, results))) + + return out diff --git a/source_code/SegMamba/monai/networks/blocks/localnet_block.py b/source_code/SegMamba/monai/networks/blocks/localnet_block.py new file mode 100644 index 0000000000000000000000000000000000000000..6e0efc85886e84655640f0ad93d2d180216393b5 --- /dev/null +++ b/source_code/SegMamba/monai/networks/blocks/localnet_block.py @@ -0,0 +1,301 @@ +# Copyright (c) MONAI Consortium +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from __future__ import annotations + +from collections.abc import Sequence + +import torch +from torch import nn +from torch.nn import functional as F + +from monai.networks.blocks import Convolution +from monai.networks.layers import same_padding +from monai.networks.layers.factories import Conv, Norm, Pool + + +def get_conv_block( + spatial_dims: int, + in_channels: int, + out_channels: int, + kernel_size: Sequence[int] | int = 3, + act: tuple | str | None = "RELU", + norm: tuple | str | None = "BATCH", +) -> nn.Module: + padding = same_padding(kernel_size) + mod: nn.Module = Convolution( + spatial_dims, + in_channels, + out_channels, + kernel_size=kernel_size, + act=act, + norm=norm, + bias=False, + conv_only=False, + padding=padding, + ) + return mod + + +def get_conv_layer( + spatial_dims: int, in_channels: int, out_channels: int, kernel_size: 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 + ) + return mod + + +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, + out_channels=out_channels, + strides=2, + act="RELU", + norm="BATCH", + bias=False, + is_transposed=True, + padding=1, + output_padding=1, + ) + return mod + + +class ResidualBlock(nn.Module): + + def __init__( + self, spatial_dims: int, in_channels: int, out_channels: int, kernel_size: Sequence[int] | 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_block = get_conv_block( + 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 + ) + self.norm = Norm[Norm.BATCH, spatial_dims](out_channels) + self.relu = nn.ReLU() + + def forward(self, x) -> torch.Tensor: + out: torch.Tensor = self.relu(self.norm(self.conv(self.conv_block(x))) + x) + return out + + +class LocalNetResidualBlock(nn.Module): + + 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.norm = Norm[Norm.BATCH, spatial_dims](out_channels) + self.relu = nn.ReLU() + + def forward(self, x, mid) -> torch.Tensor: + out: torch.Tensor = self.relu(self.norm(self.conv_layer(x)) + mid) + return out + + +class LocalNetDownSampleBlock(nn.Module): + """ + A down-sample module that can be used for LocalNet, based on: + `Weakly-supervised convolutional neural networks for multimodal image registration + `_. + `Label-driven weakly-supervised learning for multimodal deformable image registration + `_. + + Adapted from: + DeepReg (https://github.com/DeepRegNet/DeepReg) + """ + + def __init__( + self, spatial_dims: int, in_channels: int, out_channels: int, kernel_size: Sequence[int] | int + ) -> None: + """ + Args: + spatial_dims: number of spatial dimensions. + in_channels: number of input channels. + out_channels: number of output channels. + kernel_size: convolution kernel size. + Raises: + NotImplementedError: when ``kernel_size`` is even + """ + super().__init__() + self.conv_block = get_conv_block( + spatial_dims=spatial_dims, in_channels=in_channels, out_channels=out_channels, kernel_size=kernel_size + ) + 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) + + def forward(self, x) -> tuple[torch.Tensor, torch.Tensor]: + """ + Halves the spatial dimensions. + A tuple of (x, mid) is returned: + + - x is the downsample result, in shape (batch, ``out_channels``, insize_1 / 2, insize_2 / 2, [insize_3 / 2]), + - mid is the mid-level feature, in shape (batch, ``out_channels``, insize_1, insize_2, [insize_3]) + + Args: + x: Tensor in shape (batch, ``in_channels``, insize_1, insize_2, [insize_3]) + + Raises: + ValueError: when input spatial dimensions are not even. + """ + for i in x.shape[2:]: + if i % 2 != 0: + raise ValueError("expecting x spatial dimensions be even, " f"got x of shape {x.shape}") + x = self.conv_block(x) + mid = self.residual_block(x) + x = self.max_pool(mid) + return x, mid + + +class LocalNetUpSampleBlock(nn.Module): + """ + An up-sample module that can be used for LocalNet, based on: + `Weakly-supervised convolutional neural networks for multimodal image registration + `_. + `Label-driven weakly-supervised learning for multimodal deformable image registration + `_. + + Adapted from: + DeepReg (https://github.com/DeepRegNet/DeepReg) + """ + + def __init__( + self, + spatial_dims: int, + in_channels: int, + out_channels: int, + mode: str = "nearest", + align_corners: bool | None = None, + ) -> None: + """ + Args: + spatial_dims: number of spatial dimensions. + in_channels: number of input channels. + out_channels: number of output channels. + mode: interpolation mode of the additive upsampling, default to 'nearest'. + align_corners: whether to align corners for the additive upsampling, default to None. + Raises: + ValueError: when ``in_channels != 2 * out_channels`` + """ + 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) + self.residual_block = LocalNetResidualBlock( + spatial_dims=spatial_dims, in_channels=out_channels, out_channels=out_channels + ) + if in_channels / out_channels != 2: + raise ValueError( + f"expecting in_channels == 2 * out_channels, " + f"got in_channels={in_channels}, out_channels={out_channels}" + ) + self.out_channels = out_channels + self.mode = mode + self.align_corners = align_corners + + def additive_upsampling(self, x, mid) -> torch.Tensor: + x = F.interpolate(x, mid.shape[2:], mode=self.mode, align_corners=self.align_corners) + # [(batch, out_channels, ...), (batch, out_channels, ...)] + x = x.split(split_size=int(self.out_channels), dim=1) + # (batch, out_channels, ...) + out: torch.Tensor = torch.sum(torch.stack(x, dim=-1), dim=-1) + return out + + def forward(self, x, mid) -> torch.Tensor: + """ + Halves the channel and doubles the spatial dimensions. + + Args: + x: feature to be up-sampled, in shape (batch, ``in_channels``, insize_1, insize_2, [insize_3]) + mid: mid-level feature saved during down-sampling, + in shape (batch, ``out_channels``, midsize_1, midsize_2, [midsize_3]) + + Raises: + ValueError: when ``midsize != insize * 2`` + """ + for i, j in zip(x.shape[2:], mid.shape[2:]): + if j != 2 * i: + raise ValueError( + "expecting mid spatial dimensions be exactly the double of x spatial dimensions, " + f"got x of shape {x.shape}, mid of shape {mid.shape}" + ) + h0 = self.deconv_block(x) + self.additive_upsampling(x, mid) + r1 = h0 + mid + r2 = self.conv_block(h0) + out: torch.Tensor = self.residual_block(r2, r1) + return out + + +class LocalNetFeatureExtractorBlock(nn.Module): + """ + A feature-extraction module that can be used for LocalNet, based on: + `Weakly-supervised convolutional neural networks for multimodal image registration + `_. + `Label-driven weakly-supervised learning for multimodal deformable image registration + `_. + + Adapted from: + DeepReg (https://github.com/DeepRegNet/DeepReg) + """ + + def __init__( + self, + spatial_dims: int, + in_channels: int, + out_channels: int, + act: tuple | str | None = "RELU", + initializer: str = "kaiming_uniform", + ) -> None: + """ + Args: + spatial_dims: number of spatial dimensions. + in_channels: number of input channels. + out_channels: number of output channels. + act: activation type and arguments. Defaults to ReLU. + kernel_initializer: kernel initializer. Defaults to None. + """ + super().__init__() + self.conv_block = get_conv_block( + spatial_dims=spatial_dims, in_channels=in_channels, out_channels=out_channels, act=act, norm=None + ) + conv_type: type[nn.Conv1d | nn.Conv2d | nn.Conv3d] = Conv[Conv.CONV, spatial_dims] + for m in self.conv_block.modules(): + if isinstance(m, conv_type): + if initializer == "kaiming_uniform": + nn.init.kaiming_normal_(torch.as_tensor(m.weight)) + elif initializer == "zeros": + nn.init.zeros_(torch.as_tensor(m.weight)) + else: + raise ValueError( + f"initializer {initializer} is not supported, " "currently supporting kaiming_uniform and zeros" + ) + + def forward(self, x) -> torch.Tensor: + """ + Args: + x: Tensor in shape (batch, ``in_channels``, insize_1, insize_2, [insize_3]) + """ + out: torch.Tensor = self.conv_block(x) + return out diff --git a/source_code/SegMamba/monai/networks/blocks/mlp.py b/source_code/SegMamba/monai/networks/blocks/mlp.py new file mode 100644 index 0000000000000000000000000000000000000000..d3510b64d3853b4b7c21c049563181c3ec9cc65c --- /dev/null +++ b/source_code/SegMamba/monai/networks/blocks/mlp.py @@ -0,0 +1,68 @@ +# Copyright (c) MONAI Consortium +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from __future__ import annotations + +import torch.nn as nn + +from monai.networks.layers import get_act_layer +from monai.utils import look_up_option + +SUPPORTED_DROPOUT_MODE = {"vit", "swin"} + + +class MLPBlock(nn.Module): + """ + A multi-layer perceptron block, based on: "Dosovitskiy et al., + 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, act: tuple | str = "GELU", dropout_mode="vit" + ) -> None: + """ + Args: + hidden_size: dimension of hidden layer. + mlp_dim: dimension of feedforward layer. If 0, `hidden_size` will be used. + dropout_rate: fraction of the input units to drop. + act: activation type and arguments. Defaults to GELU. Also supports "GEGLU" and others. + dropout_mode: dropout mode, can be "vit" or "swin". + "vit" mode uses two dropout instances as implemented in + https://github.com/google-research/vision_transformer/blob/main/vit_jax/models.py#L87 + "swin" corresponds to one instance as implemented in + https://github.com/microsoft/Swin-Transformer/blob/main/models/swin_mlp.py#L23 + + + """ + + super().__init__() + + if not (0 <= dropout_rate <= 1): + raise ValueError("dropout_rate should be between 0 and 1.") + mlp_dim = mlp_dim or hidden_size + self.linear1 = nn.Linear(hidden_size, mlp_dim) if act != "GEGLU" else nn.Linear(hidden_size, mlp_dim * 2) + self.linear2 = nn.Linear(mlp_dim, hidden_size) + self.fn = get_act_layer(act) + self.drop1 = nn.Dropout(dropout_rate) + dropout_opt = look_up_option(dropout_mode, SUPPORTED_DROPOUT_MODE) + if dropout_opt == "vit": + self.drop2 = nn.Dropout(dropout_rate) + elif dropout_opt == "swin": + self.drop2 = self.drop1 + else: + raise ValueError(f"dropout_mode should be one of {SUPPORTED_DROPOUT_MODE}") + + def forward(self, x): + x = self.fn(self.linear1(x)) + x = self.drop1(x) + x = self.linear2(x) + x = self.drop2(x) + return x diff --git a/source_code/SegMamba/monai/networks/blocks/patchembedding.py b/source_code/SegMamba/monai/networks/blocks/patchembedding.py new file mode 100644 index 0000000000000000000000000000000000000000..91bd73ebbbf43529af5ed60a9f046edb5531f8da --- /dev/null +++ b/source_code/SegMamba/monai/networks/blocks/patchembedding.py @@ -0,0 +1,225 @@ +# Copyright (c) MONAI Consortium +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from __future__ import annotations + +from collections.abc import Sequence + +import numpy as np +import torch +import torch.nn as nn +import torch.nn.functional as F +from torch.nn import LayerNorm + +from monai.networks.blocks.pos_embed_utils import build_sincos_position_embedding +from monai.networks.layers import Conv, trunc_normal_ +from monai.utils import deprecated_arg, ensure_tuple_rep, optional_import +from monai.utils.module import look_up_option + +Rearrange, _ = optional_import("einops.layers.torch", name="Rearrange") +SUPPORTED_PATCH_EMBEDDING_TYPES = {"conv", "perceptron"} +SUPPORTED_POS_EMBEDDING_TYPES = {"none", "learnable", "sincos"} + + +class PatchEmbeddingBlock(nn.Module): + """ + A patch embedding block, based on: "Dosovitskiy et al., + An Image is Worth 16x16 Words: Transformers for Image Recognition at Scale " + + Example:: + + >>> from monai.networks.blocks import PatchEmbeddingBlock + >>> PatchEmbeddingBlock(in_channels=4, img_size=32, patch_size=8, hidden_size=32, num_heads=4, + >>> proj_type="conv", pos_embed_type="sincos") + + """ + + @deprecated_arg( + name="pos_embed", since="1.2", removed="1.4", new_name="proj_type", msg_suffix="please use `proj_type` instead." + ) + def __init__( + self, + in_channels: int, + img_size: Sequence[int] | int, + patch_size: Sequence[int] | int, + hidden_size: int, + num_heads: int, + pos_embed: str = "conv", + proj_type: str = "conv", + pos_embed_type: str = "learnable", + dropout_rate: float = 0.0, + spatial_dims: int = 3, + ) -> None: + """ + Args: + in_channels: dimension of input channels. + img_size: dimension of input image. + patch_size: dimension of patch size. + hidden_size: dimension of hidden layer. + num_heads: number of attention heads. + proj_type: patch embedding layer type. + pos_embed_type: position embedding layer type. + dropout_rate: fraction of the input units to drop. + spatial_dims: number of spatial dimensions. + .. deprecated:: 1.4 + ``pos_embed`` is deprecated in favor of ``proj_type``. + """ + + super().__init__() + + if not (0 <= dropout_rate <= 1): + raise ValueError(f"dropout_rate {dropout_rate} should be between 0 and 1.") + + if hidden_size % num_heads != 0: + raise ValueError(f"hidden size {hidden_size} should be divisible by num_heads {num_heads}.") + + self.proj_type = look_up_option(proj_type, SUPPORTED_PATCH_EMBEDDING_TYPES) + self.pos_embed_type = look_up_option(pos_embed_type, SUPPORTED_POS_EMBEDDING_TYPES) + + img_size = ensure_tuple_rep(img_size, spatial_dims) + patch_size = ensure_tuple_rep(patch_size, spatial_dims) + for m, p in zip(img_size, patch_size): + if m < p: + raise ValueError("patch_size should be smaller than img_size.") + if self.proj_type == "perceptron" and m % p != 0: + raise ValueError("patch_size should be divisible by img_size for perceptron.") + self.n_patches = np.prod([im_d // p_d for im_d, p_d in zip(img_size, patch_size)]) + self.patch_dim = int(in_channels * np.prod(patch_size)) + + self.patch_embeddings: nn.Module + if self.proj_type == "conv": + self.patch_embeddings = Conv[Conv.CONV, spatial_dims]( + in_channels=in_channels, out_channels=hidden_size, kernel_size=patch_size, stride=patch_size + ) + elif self.proj_type == "perceptron": + # for 3d: "b c (h p1) (w p2) (d p3)-> b (h w d) (p1 p2 p3 c)" + chars = (("h", "p1"), ("w", "p2"), ("d", "p3"))[:spatial_dims] + from_chars = "b c " + " ".join(f"({k} {v})" for k, v in chars) + 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) + ) + self.position_embeddings = nn.Parameter(torch.zeros(1, self.n_patches, hidden_size)) + self.dropout = nn.Dropout(dropout_rate) + + if self.pos_embed_type == "none": + pass + elif self.pos_embed_type == "learnable": + trunc_normal_(self.position_embeddings, mean=0.0, std=0.02, a=-2.0, b=2.0) + elif self.pos_embed_type == "sincos": + grid_size = [] + for in_size, pa_size in zip(img_size, patch_size): + grid_size.append(in_size // pa_size) + + self.position_embeddings = build_sincos_position_embedding(grid_size, hidden_size, spatial_dims) + else: + raise ValueError(f"pos_embed_type {self.pos_embed_type} not supported.") + + self.apply(self._init_weights) + + def _init_weights(self, m): + if isinstance(m, nn.Linear): + trunc_normal_(m.weight, mean=0.0, std=0.02, a=-2.0, b=2.0) + if isinstance(m, nn.Linear) and m.bias is not None: + nn.init.constant_(m.bias, 0) + elif isinstance(m, nn.LayerNorm): + nn.init.constant_(m.bias, 0) + nn.init.constant_(m.weight, 1.0) + + def forward(self, x): + x = self.patch_embeddings(x) + if self.proj_type == "conv": + x = x.flatten(2).transpose(-1, -2) + embeddings = x + self.position_embeddings + embeddings = self.dropout(embeddings) + return embeddings + + +class PatchEmbed(nn.Module): + """ + Patch embedding block based on: "Liu et al., + Swin Transformer: Hierarchical Vision Transformer using Shifted Windows + " + https://github.com/microsoft/Swin-Transformer + + Unlike ViT patch embedding block: (1) input is padded to satisfy window size requirements (2) normalized if + specified (3) position embedding is not used. + + Example:: + + >>> from monai.networks.blocks import PatchEmbed + >>> PatchEmbed(patch_size=2, in_chans=1, embed_dim=48, norm_layer=nn.LayerNorm, spatial_dims=3) + """ + + def __init__( + self, + patch_size: Sequence[int] | int = 2, + in_chans: int = 1, + embed_dim: int = 48, + norm_layer: type[LayerNorm] = nn.LayerNorm, + spatial_dims: int = 3, + ) -> None: + """ + Args: + patch_size: dimension of patch size. + in_chans: dimension of input channels. + embed_dim: number of linear projection output channels. + norm_layer: normalization layer. + spatial_dims: spatial dimension. + """ + + super().__init__() + + if spatial_dims not in (2, 3): + raise ValueError("spatial dimension should be 2 or 3.") + + patch_size = ensure_tuple_rep(patch_size, spatial_dims) + self.patch_size = patch_size + self.embed_dim = embed_dim + self.proj = Conv[Conv.CONV, spatial_dims]( + in_channels=in_chans, out_channels=embed_dim, kernel_size=patch_size, stride=patch_size + ) + if norm_layer is not None: + self.norm = norm_layer(embed_dim) + else: + self.norm = None + + def forward(self, x): + x_shape = x.size() + if len(x_shape) == 5: + _, _, d, h, w = x_shape + if w % self.patch_size[2] != 0: + x = F.pad(x, (0, self.patch_size[2] - w % self.patch_size[2])) + if h % self.patch_size[1] != 0: + x = F.pad(x, (0, 0, 0, self.patch_size[1] - h % self.patch_size[1])) + if d % self.patch_size[0] != 0: + x = F.pad(x, (0, 0, 0, 0, 0, self.patch_size[0] - d % self.patch_size[0])) + + elif len(x_shape) == 4: + _, _, h, w = x_shape + if w % self.patch_size[1] != 0: + x = F.pad(x, (0, self.patch_size[1] - w % self.patch_size[1])) + if h % self.patch_size[0] != 0: + x = F.pad(x, (0, 0, 0, self.patch_size[0] - h % self.patch_size[0])) + + x = self.proj(x) + if self.norm is not None: + x_shape = x.size() + x = x.flatten(2).transpose(1, 2) + x = self.norm(x) + if len(x_shape) == 5: + d, wh, ww = x_shape[2], x_shape[3], x_shape[4] + x = x.transpose(1, 2).view(-1, self.embed_dim, d, wh, ww) + elif len(x_shape) == 4: + wh, ww = x_shape[2], x_shape[3] + x = x.transpose(1, 2).view(-1, self.embed_dim, wh, ww) + return x diff --git a/source_code/SegMamba/monai/networks/blocks/segresnet_block.py b/source_code/SegMamba/monai/networks/blocks/segresnet_block.py new file mode 100644 index 0000000000000000000000000000000000000000..370abffe89b7279c44919041c0dc0180c7852c60 --- /dev/null +++ b/source_code/SegMamba/monai/networks/blocks/segresnet_block.py @@ -0,0 +1,96 @@ +# Copyright (c) MONAI Consortium +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from __future__ import annotations + +import torch.nn as nn + +from monai.networks.blocks.convolutions import Convolution +from monai.networks.blocks.upsample import UpSample +from monai.networks.layers.utils import get_act_layer, get_norm_layer +from monai.utils import InterpolateMode, UpsampleMode + + +def get_conv_layer( + spatial_dims: int, in_channels: int, out_channels: int, kernel_size: int = 3, stride: int = 1, bias: bool = False +): + return Convolution( + spatial_dims, in_channels, out_channels, strides=stride, kernel_size=kernel_size, bias=bias, conv_only=True + ) + + +def get_upsample_layer( + spatial_dims: int, in_channels: int, upsample_mode: UpsampleMode | str = "nontrainable", scale_factor: int = 2 +): + return UpSample( + spatial_dims=spatial_dims, + in_channels=in_channels, + out_channels=in_channels, + scale_factor=scale_factor, + mode=upsample_mode, + interp_mode=InterpolateMode.LINEAR, + align_corners=False, + ) + + +class ResBlock(nn.Module): + """ + ResBlock employs skip connection and two convolution blocks and is used + in SegResNet based on `3D MRI brain tumor segmentation using autoencoder regularization + `_. + """ + + def __init__( + self, + spatial_dims: int, + in_channels: int, + norm: tuple | str, + kernel_size: int = 3, + act: tuple | str = ("RELU", {"inplace": True}), + ) -> None: + """ + Args: + spatial_dims: number of spatial dimensions, could be 1, 2 or 3. + in_channels: number of input channels. + norm: feature normalization type and arguments. + kernel_size: convolution kernel size, the value should be an odd number. Defaults to 3. + act: activation type and arguments. Defaults to ``RELU``. + """ + + super().__init__() + + if kernel_size % 2 != 1: + raise AssertionError("kernel_size should be an odd number.") + + self.norm1 = get_norm_layer(name=norm, spatial_dims=spatial_dims, channels=in_channels) + self.norm2 = get_norm_layer(name=norm, spatial_dims=spatial_dims, channels=in_channels) + self.act = get_act_layer(act) + self.conv1 = get_conv_layer( + spatial_dims, in_channels=in_channels, out_channels=in_channels, kernel_size=kernel_size + ) + self.conv2 = get_conv_layer( + spatial_dims, in_channels=in_channels, out_channels=in_channels, kernel_size=kernel_size + ) + + def forward(self, x): + identity = x + + x = self.norm1(x) + x = self.act(x) + x = self.conv1(x) + + x = self.norm2(x) + x = self.act(x) + x = self.conv2(x) + + x += identity + + return x diff --git a/source_code/SegMamba/monai/networks/blocks/squeeze_and_excitation.py b/source_code/SegMamba/monai/networks/blocks/squeeze_and_excitation.py new file mode 100644 index 0000000000000000000000000000000000000000..665e9020fff8178e351189a190b155f4fe551983 --- /dev/null +++ b/source_code/SegMamba/monai/networks/blocks/squeeze_and_excitation.py @@ -0,0 +1,378 @@ +# Copyright (c) MONAI Consortium +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from __future__ import annotations + +import math + +import torch +import torch.nn as nn + +from monai.networks.blocks import Convolution +from monai.networks.layers.factories import Act, Conv, Norm, Pool, split_args + + +class ChannelSELayer(nn.Module): + """ + Re-implementation of the Squeeze-and-Excitation block based on: + "Hu et al., Squeeze-and-Excitation Networks, https://arxiv.org/abs/1709.01507". + """ + + def __init__( + self, + spatial_dims: int, + in_channels: int, + r: int = 2, + acti_type_1: tuple[str, dict] | str = ("relu", {"inplace": True}), + acti_type_2: tuple[str, dict] | str = "sigmoid", + add_residual: bool = False, + ) -> None: + """ + Args: + spatial_dims: number of spatial dimensions, could be 1, 2, or 3. + in_channels: number of input channels. + r: the reduction ratio r in the paper. Defaults to 2. + acti_type_1: activation type of the hidden squeeze layer. Defaults to ``("relu", {"inplace": True})``. + acti_type_2: activation type of the output squeeze layer. Defaults to "sigmoid". + + Raises: + ValueError: When ``r`` is nonpositive or larger than ``in_channels``. + + See also: + + :py:class:`monai.networks.layers.Act` + + """ + super().__init__() + + self.add_residual = add_residual + + pool_type = Pool[Pool.ADAPTIVEAVG, spatial_dims] + self.avg_pool = pool_type(1) # spatial size (1, 1, ...) + + channels = int(in_channels // r) + if channels <= 0: + raise ValueError(f"r must be positive and smaller than in_channels, got r={r} in_channels={in_channels}.") + + act_1, act_1_args = split_args(acti_type_1) + act_2, act_2_args = split_args(acti_type_2) + self.fc = nn.Sequential( + nn.Linear(in_channels, channels, bias=True), + Act[act_1](**act_1_args), + nn.Linear(channels, in_channels, bias=True), + Act[act_2](**act_2_args), + ) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + """ + Args: + x: in shape (batch, in_channels, spatial_1[, spatial_2, ...]). + """ + b, c = x.shape[:2] + y: torch.Tensor = self.avg_pool(x).view(b, c) + y = self.fc(y).view([b, c] + [1] * (x.ndim - 2)) + result = x * y + + # Residual connection is moved here instead of providing an override of forward in ResidualSELayer since + # Torchscript has an issue with using super(). + if self.add_residual: + result += x + + return result + + +class ResidualSELayer(ChannelSELayer): + """ + A "squeeze-and-excitation"-like layer with a residual connection:: + + --+-- SE --o-- + | | + +--------+ + """ + + def __init__( + self, + spatial_dims: int, + in_channels: int, + r: int = 2, + acti_type_1: tuple[str, dict] | str = "leakyrelu", + acti_type_2: tuple[str, dict] | str = "relu", + ) -> None: + """ + Args: + spatial_dims: number of spatial dimensions, could be 1, 2, or 3. + in_channels: number of input channels. + r: the reduction ratio r in the paper. Defaults to 2. + acti_type_1: defaults to "leakyrelu". + acti_type_2: defaults to "relu". + + See also: + :py:class:`monai.networks.blocks.ChannelSELayer` + """ + super().__init__( + spatial_dims=spatial_dims, + in_channels=in_channels, + r=r, + acti_type_1=acti_type_1, + acti_type_2=acti_type_2, + add_residual=True, + ) + + +class SEBlock(nn.Module): + """ + Residual module enhanced with Squeeze-and-Excitation:: + + ----+- conv1 -- conv2 -- conv3 -- SE -o--- + | | + +---(channel project if needed)----+ + + Re-implementation of the SE-Resnet block based on: + "Hu et al., Squeeze-and-Excitation Networks, https://arxiv.org/abs/1709.01507". + """ + + def __init__( + self, + spatial_dims: int, + in_channels: int, + n_chns_1: int, + n_chns_2: int, + n_chns_3: int, + conv_param_1: dict | None = None, + conv_param_2: dict | None = None, + conv_param_3: dict | None = None, + project: Convolution | None = None, + r: int = 2, + acti_type_1: tuple[str, dict] | str = ("relu", {"inplace": True}), + acti_type_2: tuple[str, dict] | str = "sigmoid", + acti_type_final: tuple[str, dict] | str | None = ("relu", {"inplace": True}), + ): + """ + Args: + spatial_dims: number of spatial dimensions, could be 1, 2, or 3. + in_channels: number of input channels. + n_chns_1: number of output channels in the 1st convolution. + n_chns_2: number of output channels in the 2nd convolution. + n_chns_3: number of output channels in the 3rd convolution. + conv_param_1: additional parameters to the 1st convolution. + Defaults to ``{"kernel_size": 1, "norm": Norm.BATCH, "act": ("relu", {"inplace": True})}`` + conv_param_2: additional parameters to the 2nd convolution. + Defaults to ``{"kernel_size": 3, "norm": Norm.BATCH, "act": ("relu", {"inplace": True})}`` + conv_param_3: additional parameters to the 3rd convolution. + Defaults to ``{"kernel_size": 1, "norm": Norm.BATCH, "act": None}`` + project: in the case of residual chns and output chns doesn't match, a project + (Conv) layer/block is used to adjust the number of chns. In SENET, it is + consisted with a Conv layer as well as a Norm layer. + Defaults to None (chns are matchable) or a Conv layer with kernel size 1. + r: the reduction ratio r in the paper. Defaults to 2. + acti_type_1: activation type of the hidden squeeze layer. Defaults to "relu". + acti_type_2: activation type of the output squeeze layer. Defaults to "sigmoid". + acti_type_final: activation type of the end of the block. Defaults to "relu". + + See also: + + :py:class:`monai.networks.blocks.ChannelSELayer` + + """ + super().__init__() + + if not conv_param_1: + conv_param_1 = {"kernel_size": 1, "norm": Norm.BATCH, "act": ("relu", {"inplace": True})} + self.conv1 = Convolution( + spatial_dims=spatial_dims, in_channels=in_channels, out_channels=n_chns_1, **conv_param_1 + ) + + if not conv_param_2: + conv_param_2 = {"kernel_size": 3, "norm": Norm.BATCH, "act": ("relu", {"inplace": True})} + self.conv2 = Convolution(spatial_dims=spatial_dims, in_channels=n_chns_1, out_channels=n_chns_2, **conv_param_2) + + if not conv_param_3: + conv_param_3 = {"kernel_size": 1, "norm": Norm.BATCH, "act": None} + self.conv3 = Convolution(spatial_dims=spatial_dims, in_channels=n_chns_2, out_channels=n_chns_3, **conv_param_3) + + self.se_layer = ChannelSELayer( + spatial_dims=spatial_dims, in_channels=n_chns_3, r=r, acti_type_1=acti_type_1, acti_type_2=acti_type_2 + ) + + if project is None and in_channels != n_chns_3: + self.project = Conv[Conv.CONV, spatial_dims](in_channels, n_chns_3, kernel_size=1) + elif project is None: + self.project = nn.Identity() + else: + self.project = project + + if acti_type_final is not None: + act_final, act_final_args = split_args(acti_type_final) + self.act = Act[act_final](**act_final_args) + else: + self.act = nn.Identity() + + def forward(self, x: torch.Tensor) -> torch.Tensor: + """ + Args: + x: in shape (batch, in_channels, spatial_1[, spatial_2, ...]). + """ + residual = self.project(x) + x = self.conv1(x) + x = self.conv2(x) + x = self.conv3(x) + x = self.se_layer(x) + x += residual + x = self.act(x) + return x + + +class SEBottleneck(SEBlock): + """ + Bottleneck for SENet154. + """ + + expansion = 4 + + def __init__( + self, + spatial_dims: int, + inplanes: int, + planes: int, + groups: int, + reduction: int, + stride: int = 1, + downsample: Convolution | None = None, + ) -> None: + conv_param_1 = { + "strides": 1, + "kernel_size": 1, + "act": ("relu", {"inplace": True}), + "norm": Norm.BATCH, + "bias": False, + } + conv_param_2 = { + "strides": stride, + "kernel_size": 3, + "act": ("relu", {"inplace": True}), + "norm": Norm.BATCH, + "groups": groups, + "bias": False, + } + conv_param_3 = {"strides": 1, "kernel_size": 1, "act": None, "norm": Norm.BATCH, "bias": False} + + super().__init__( + spatial_dims=spatial_dims, + in_channels=inplanes, + n_chns_1=planes * 2, + n_chns_2=planes * 4, + n_chns_3=planes * 4, + conv_param_1=conv_param_1, + conv_param_2=conv_param_2, + conv_param_3=conv_param_3, + project=downsample, + r=reduction, + ) + + +class SEResNetBottleneck(SEBlock): + """ + ResNet bottleneck with a Squeeze-and-Excitation module. It follows Caffe + implementation and uses `strides=stride` in `conv1` and not in `conv2` + (the latter is used in the torchvision implementation of ResNet). + """ + + expansion = 4 + + def __init__( + self, + spatial_dims: int, + inplanes: int, + planes: int, + groups: int, + reduction: int, + stride: int = 1, + downsample: Convolution | None = None, + ) -> None: + conv_param_1 = { + "strides": stride, + "kernel_size": 1, + "act": ("relu", {"inplace": True}), + "norm": Norm.BATCH, + "bias": False, + } + conv_param_2 = { + "strides": 1, + "kernel_size": 3, + "act": ("relu", {"inplace": True}), + "norm": Norm.BATCH, + "groups": groups, + "bias": False, + } + conv_param_3 = {"strides": 1, "kernel_size": 1, "act": None, "norm": Norm.BATCH, "bias": False} + + super().__init__( + spatial_dims=spatial_dims, + in_channels=inplanes, + n_chns_1=planes, + n_chns_2=planes, + n_chns_3=planes * 4, + conv_param_1=conv_param_1, + conv_param_2=conv_param_2, + conv_param_3=conv_param_3, + project=downsample, + r=reduction, + ) + + +class SEResNeXtBottleneck(SEBlock): + """ + ResNeXt bottleneck type C with a Squeeze-and-Excitation module. + """ + + expansion = 4 + + def __init__( + self, + spatial_dims: int, + inplanes: int, + planes: int, + groups: int, + reduction: int, + stride: int = 1, + downsample: Convolution | None = None, + base_width: int = 4, + ) -> None: + conv_param_1 = { + "strides": 1, + "kernel_size": 1, + "act": ("relu", {"inplace": True}), + "norm": Norm.BATCH, + "bias": False, + } + conv_param_2 = { + "strides": stride, + "kernel_size": 3, + "act": ("relu", {"inplace": True}), + "norm": Norm.BATCH, + "groups": groups, + "bias": False, + } + conv_param_3 = {"strides": 1, "kernel_size": 1, "act": None, "norm": Norm.BATCH, "bias": False} + width = math.floor(planes * (base_width / 64)) * groups + + super().__init__( + spatial_dims=spatial_dims, + in_channels=inplanes, + n_chns_1=width, + n_chns_2=width, + n_chns_3=planes * 4, + conv_param_1=conv_param_1, + conv_param_2=conv_param_2, + conv_param_3=conv_param_3, + project=downsample, + r=reduction, + ) diff --git a/source_code/SegMamba/monai/networks/blocks/text_embedding.py b/source_code/SegMamba/monai/networks/blocks/text_embedding.py new file mode 100644 index 0000000000000000000000000000000000000000..6f2990e35c1dbb0e1a4e7a08460ee370e62635af --- /dev/null +++ b/source_code/SegMamba/monai/networks/blocks/text_embedding.py @@ -0,0 +1,90 @@ +# Copyright (c) MONAI Consortium +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from __future__ import annotations + +import torch +from torch import nn +from torch.utils import model_zoo + +url_map = { + "clip_encoding_universal_model_32": ( + "https://github.com/Project-MONAI/MONAI-extra-test-data/" + "releases/download/0.8.1/clip_encoding_universal_model.pth" + ) +} + + +class TextEncoder(nn.Module): + """ + Text to vision encoding by Contrastive Language-Image Pre-training (CLIP) or random embedding. + The text to vision encoder loads the pre-trained or random initialized weights with connection to 2D/3D vision models. + + Contrastive Language-Image Pre-training (CLIP), based on: "Radford et al., + Learning Transferable Visual Models From Natural Language Supervision " + + Connecting text and medical 3D image, based on: "Liu et al., + CLIP-Driven Universal Model for Organ Segmentation and Tumor Detection " + """ + + def __init__( + self, + out_channels: int, + spatial_dims: int = 3, + text_dim: int = 512, + hidden_size: int = 256, + encoding: str = "clip_encoding_universal_model_32", + pretrained: bool = True, + ) -> None: + """ + Args: + out_channels: number of output channels, to control text-based embedding for classes. + spatial_dims: number of spatial dims. + text_dim: dimension of text embeddings. + hidden_size: dimension of hidden features, compatible to different vision feature dimensions. + encoding: the text embedding type, default to use clip text pretrained weights. + pretrained: whether to load pretrained weights from e.g., (CLIP) to initialize text embeddings, default to False. + """ + super().__init__() + self.encoding = encoding + + self.spatial_dims = spatial_dims + if spatial_dims not in (2, 3): + raise ValueError("spatial dimension should be 2 or 3.") + + if self.encoding == "rand_embedding": + self.text_embedding = nn.Embedding(out_channels, hidden_size) + else: + self.register_buffer("text_embedding", torch.randn(out_channels, text_dim)) + + if pretrained: + model_url = url_map[self.encoding] + pretrain_state_dict = model_zoo.load_url(model_url, map_location="cpu") + self.text_embedding.data = pretrain_state_dict.float() # type: ignore + else: + print(f"{self.encoding} is not implemented, and can not be downloaded, please load your own") + + self.text_to_vision = nn.Linear(text_dim, hidden_size) + + def forward(self): + if self.encoding == "rand_embedding": + # text embedding as random initialized 'rand_embedding' + text_embedding = self.text_embedding.weight + else: + print(self.text_embedding) + text_embedding = nn.functional.relu(self.text_to_vision(self.text_embedding)) + + if self.spatial_dims == 3: + text_embedding = text_embedding.unsqueeze(2).unsqueeze(2).unsqueeze(2) + elif self.spatial_dims == 2: + text_embedding = text_embedding.unsqueeze(2).unsqueeze(2) + + return text_embedding diff --git a/source_code/SegMamba/monai/networks/blocks/transformerblock.py b/source_code/SegMamba/monai/networks/blocks/transformerblock.py new file mode 100644 index 0000000000000000000000000000000000000000..ddf959dad2347bf5a18681d6248eacb3f3c93348 --- /dev/null +++ b/source_code/SegMamba/monai/networks/blocks/transformerblock.py @@ -0,0 +1,62 @@ +# Copyright (c) MONAI Consortium +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from __future__ import annotations + +import torch.nn as nn + +from monai.networks.blocks.mlp import MLPBlock +from monai.networks.blocks.selfattention import SABlock + + +class TransformerBlock(nn.Module): + """ + A transformer block, based on: "Dosovitskiy et al., + 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, + qkv_bias: bool = False, + save_attn: bool = False, + ) -> None: + """ + Args: + hidden_size (int): dimension of hidden layer. + mlp_dim (int): dimension of feedforward layer. + num_heads (int): number of attention heads. + dropout_rate (float, optional): fraction of the input units to drop. Defaults to 0.0. + qkv_bias (bool, optional): apply bias term for the qkv linear layer. Defaults to False. + save_attn (bool, optional): to make accessible the attention matrix. Defaults to False. + + """ + + super().__init__() + + if not (0 <= dropout_rate <= 1): + raise ValueError("dropout_rate should be between 0 and 1.") + + if hidden_size % num_heads != 0: + raise ValueError("hidden_size should be divisible by num_heads.") + + self.mlp = MLPBlock(hidden_size, mlp_dim, dropout_rate) + self.norm1 = nn.LayerNorm(hidden_size) + self.attn = SABlock(hidden_size, num_heads, dropout_rate, qkv_bias, save_attn) + self.norm2 = nn.LayerNorm(hidden_size) + + def forward(self, x): + x = x + self.attn(self.norm1(x)) + x = x + self.mlp(self.norm2(x)) + return x diff --git a/source_code/SegMamba/monai/networks/blocks/upsample.py b/source_code/SegMamba/monai/networks/blocks/upsample.py new file mode 100644 index 0000000000000000000000000000000000000000..dee996691974cb769d9834e09a1bd9ce6547a10d --- /dev/null +++ b/source_code/SegMamba/monai/networks/blocks/upsample.py @@ -0,0 +1,288 @@ +# Copyright (c) MONAI Consortium +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from __future__ import annotations + +from collections.abc import Sequence + +import torch +import torch.nn as nn + +from monai.networks.layers.factories import Conv, Pad, Pool +from monai.networks.utils import icnr_init, pixelshuffle +from monai.utils import InterpolateMode, UpsampleMode, ensure_tuple_rep, look_up_option + +__all__ = ["Upsample", "UpSample", "SubpixelUpsample", "Subpixelupsample", "SubpixelUpSample"] + + +class UpSample(nn.Sequential): + """ + Upsamples data by `scale_factor`. + Supported modes are: + + - "deconv": uses a transposed convolution. + - "deconvgroup": uses a transposed group convolution. + - "nontrainable": uses :py:class:`torch.nn.Upsample`. + - "pixelshuffle": uses :py:class:`monai.networks.blocks.SubpixelUpsample`. + + This operation will cause non-deterministic when ``mode`` is ``UpsampleMode.NONTRAINABLE``. + Please check the link below for more details: + https://pytorch.org/docs/stable/generated/torch.use_deterministic_algorithms.html#torch.use_deterministic_algorithms + This module can optionally take a pre-convolution + (often used to map the number of features from `in_channels` to `out_channels`). + """ + + def __init__( + self, + spatial_dims: int, + in_channels: int | None = None, + out_channels: int | None = None, + scale_factor: Sequence[float] | float = 2, + kernel_size: Sequence[float] | float | None = None, + size: tuple[int] | int | None = None, + mode: UpsampleMode | str = UpsampleMode.DECONV, + pre_conv: nn.Module | str | None = "default", + interp_mode: str = InterpolateMode.LINEAR, + align_corners: bool | None = True, + bias: bool = True, + apply_pad_pool: bool = True, + ) -> None: + """ + Args: + spatial_dims: number of spatial dimensions of the input image. + in_channels: number of channels of the input image. + out_channels: number of channels of the output image. Defaults to `in_channels`. + scale_factor: multiplier for spatial size. Has to match input size if it is a tuple. Defaults to 2. + kernel_size: kernel size used during transposed convolutions. Defaults to `scale_factor`. + size: spatial size of the output image. + Only used when ``mode`` is ``UpsampleMode.NONTRAINABLE``. + In torch.nn.functional.interpolate, only one of `size` or `scale_factor` should be defined, + thus if size is defined, `scale_factor` will not be used. + Defaults to None. + mode: {``"deconv"``, ``"deconvgroup"``, ``"nontrainable"``, ``"pixelshuffle"``}. Defaults to ``"deconv"``. + pre_conv: a conv block applied before upsampling. Defaults to "default". + When ``conv_block`` is ``"default"``, one reserved conv layer will be utilized when + Only used in the "nontrainable" or "pixelshuffle" mode. + interp_mode: {``"nearest"``, ``"linear"``, ``"bilinear"``, ``"bicubic"``, ``"trilinear"``} + Only used in the "nontrainable" mode. + If ends with ``"linear"`` will use ``spatial dims`` to determine the correct interpolation. + This corresponds to linear, bilinear, trilinear for 1D, 2D, and 3D respectively. + The interpolation mode. Defaults to ``"linear"``. + See also: https://pytorch.org/docs/stable/generated/torch.nn.Upsample.html + align_corners: set the align_corners parameter of `torch.nn.Upsample`. Defaults to True. + Only used in the "nontrainable" mode. + bias: whether to have a bias term in the default preconv and deconv layers. Defaults to True. + apply_pad_pool: if True the upsampled tensor is padded then average pooling is applied with a kernel the + size of `scale_factor` with a stride of 1. See also: :py:class:`monai.networks.blocks.SubpixelUpsample`. + Only used in the "pixelshuffle" mode. + + """ + super().__init__() + scale_factor_ = ensure_tuple_rep(scale_factor, spatial_dims) + up_mode = look_up_option(mode, UpsampleMode) + + if not kernel_size: + kernel_size_ = scale_factor_ + output_padding = padding = 0 + else: + kernel_size_ = ensure_tuple_rep(kernel_size, spatial_dims) + padding = tuple((k - 1) // 2 for k in kernel_size_) # type: ignore + output_padding = tuple(s - 1 - (k - 1) % 2 for k, s in zip(kernel_size_, scale_factor_)) # type: ignore + + if up_mode == UpsampleMode.DECONV: + if not in_channels: + raise ValueError(f"in_channels needs to be specified in the '{mode}' mode.") + self.add_module( + "deconv", + Conv[Conv.CONVTRANS, spatial_dims]( + in_channels=in_channels, + out_channels=out_channels or in_channels, + kernel_size=kernel_size_, + stride=scale_factor_, + padding=padding, + output_padding=output_padding, + bias=bias, + ), + ) + elif up_mode == UpsampleMode.DECONVGROUP: + if not in_channels: + raise ValueError(f"in_channels needs to be specified in the '{mode}' mode.") + + if out_channels is None: + out_channels = in_channels + groups = out_channels if in_channels % out_channels == 0 else 1 + + self.add_module( + "deconvgroup", + Conv[Conv.CONVTRANS, spatial_dims]( + in_channels=in_channels, + out_channels=out_channels, + kernel_size=kernel_size_, + stride=scale_factor_, + padding=padding, + output_padding=output_padding, + groups=groups, + bias=bias, + ), + ) + elif up_mode == UpsampleMode.NONTRAINABLE: + if pre_conv == "default" and (out_channels != in_channels): # defaults to no conv if out_chns==in_chns + if not in_channels: + raise ValueError(f"in_channels needs to be specified in the '{mode}' mode.") + self.add_module( + "preconv", + Conv[Conv.CONV, spatial_dims]( + in_channels=in_channels, out_channels=out_channels or in_channels, kernel_size=1, bias=bias + ), + ) + elif pre_conv is not None and pre_conv != "default": + self.add_module("preconv", pre_conv) # type: ignore + elif pre_conv is None and (out_channels != in_channels): + raise ValueError( + "in the nontrainable mode, if not setting pre_conv, out_channels should equal to in_channels." + ) + + interp_mode = InterpolateMode(interp_mode) + linear_mode = [InterpolateMode.LINEAR, InterpolateMode.BILINEAR, InterpolateMode.TRILINEAR] + if interp_mode in linear_mode: # choose mode based on dimensions + interp_mode = linear_mode[spatial_dims - 1] + self.add_module( + "upsample_non_trainable", + nn.Upsample( + size=size, + scale_factor=None if size else scale_factor_, + mode=interp_mode.value, + align_corners=align_corners, + ), + ) + elif up_mode == UpsampleMode.PIXELSHUFFLE: + self.add_module( + "pixelshuffle", + SubpixelUpsample( + spatial_dims=spatial_dims, + in_channels=in_channels, + out_channels=out_channels, + scale_factor=scale_factor_[0], # isotropic + conv_block=pre_conv, + apply_pad_pool=apply_pad_pool, + bias=bias, + ), + ) + else: + raise NotImplementedError(f"Unsupported upsampling mode {mode}.") + + +class SubpixelUpsample(nn.Module): + """ + Upsample via using a subpixel CNN. This module supports 1D, 2D and 3D input images. + The module is consisted with two parts. First of all, a convolutional layer is employed + to increase the number of channels into: ``in_channels * (scale_factor ** dimensions)``. + Secondly, a pixel shuffle manipulation is utilized to aggregates the feature maps from + low resolution space and build the super resolution space. + The first part of the module is not fixed, a sequential layers can be used to replace the + default single layer. + + See: Shi et al., 2016, "Real-Time Single Image and Video Super-Resolution + Using a nEfficient Sub-Pixel Convolutional Neural Network." + + See: Aitken et al., 2017, "Checkerboard artifact free sub-pixel convolution". + + The idea comes from: + https://arxiv.org/abs/1609.05158 + + The pixel shuffle mechanism refers to: + https://pytorch.org/docs/stable/generated/torch.nn.PixelShuffle.html#torch.nn.PixelShuffle. + and: + https://github.com/pytorch/pytorch/pull/6340. + + """ + + def __init__( + self, + spatial_dims: int, + in_channels: int | None, + out_channels: int | None = None, + scale_factor: int = 2, + conv_block: nn.Module | str | None = "default", + apply_pad_pool: bool = True, + bias: bool = True, + ) -> None: + """ + Args: + spatial_dims: number of spatial dimensions of the input image. + in_channels: number of channels of the input image. + out_channels: optional number of channels of the output image. + scale_factor: multiplier for spatial size. Defaults to 2. + conv_block: a conv block to extract feature maps before upsampling. Defaults to None. + + - When ``conv_block`` is ``"default"``, one reserved conv layer will be utilized. + - When ``conv_block`` is an ``nn.module``, + please ensure the output number of channels is divisible ``(scale_factor ** dimensions)``. + + apply_pad_pool: if True the upsampled tensor is padded then average pooling is applied with a kernel the + size of `scale_factor` with a stride of 1. This implements the nearest neighbour resize convolution + component of subpixel convolutions described in Aitken et al. + bias: whether to have a bias term in the default conv_block. Defaults to True. + + """ + super().__init__() + + if scale_factor <= 0: + raise ValueError(f"The `scale_factor` multiplier must be an integer greater than 0, got {scale_factor}.") + + self.dimensions = spatial_dims + self.scale_factor = scale_factor + + if conv_block == "default": + out_channels = out_channels or in_channels + if not out_channels: + raise ValueError("in_channels need to be specified.") + conv_out_channels = out_channels * (scale_factor**self.dimensions) + self.conv_block = Conv[Conv.CONV, self.dimensions]( + in_channels=in_channels, out_channels=conv_out_channels, kernel_size=3, stride=1, padding=1, bias=bias + ) + + icnr_init(self.conv_block, self.scale_factor) + elif conv_block is None: + self.conv_block = nn.Identity() + else: + self.conv_block = conv_block + + self.pad_pool: nn.Module = nn.Identity() + + if apply_pad_pool: + pool_type = Pool[Pool.AVG, self.dimensions] + pad_type = Pad[Pad.CONSTANTPAD, self.dimensions] + + self.pad_pool = nn.Sequential( + pad_type(padding=(self.scale_factor - 1, 0) * self.dimensions, value=0.0), + pool_type(kernel_size=self.scale_factor, stride=1), + ) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + """ + Args: + x: Tensor in shape (batch, channel, spatial_1[, spatial_2, ...). + """ + x = self.conv_block(x) + if x.shape[1] % (self.scale_factor**self.dimensions) != 0: + raise ValueError( + f"Number of channels after `conv_block` ({x.shape[1]}) must be evenly " + "divisible by scale_factor ** dimensions " + f"({self.scale_factor}^{self.dimensions}={self.scale_factor**self.dimensions})." + ) + x = pixelshuffle(x, self.dimensions, self.scale_factor) + x = self.pad_pool(x) + return x + + +Upsample = UpSample +Subpixelupsample = SubpixelUpSample = SubpixelUpsample diff --git a/source_code/SegMamba/monai/networks/layers/__init__.py b/source_code/SegMamba/monai/networks/layers/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..3a6e4aa5545afd0e09430512ce155863386c941a --- /dev/null +++ b/source_code/SegMamba/monai/networks/layers/__init__.py @@ -0,0 +1,41 @@ +# Copyright (c) MONAI Consortium +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from __future__ import annotations + +from .conjugate_gradient import ConjugateGradient +from .convutils import calculate_out_shape, gaussian_1d, polyval, same_padding, stride_minus_kernel_padding +from .drop_path import DropPath +from .factories import Act, Conv, Dropout, LayerFactory, Norm, Pad, Pool, split_args +from .filtering import BilateralFilter, PHLFilter, TrainableBilateralFilter, TrainableJointBilateralFilter +from .gmm import GaussianMixtureModel +from .simplelayers import ( + LLTM, + ApplyFilter, + ChannelPad, + EllipticalFilter, + Flatten, + GaussianFilter, + HilbertTransform, + LaplaceFilter, + MeanFilter, + MedianFilter, + Reshape, + SavitzkyGolayFilter, + SharpenFilter, + SkipConnection, + apply_filter, + median_filter, + separable_filtering, +) +from .spatial_transforms import AffineTransform, grid_count, grid_grad, grid_pull, grid_push +from .utils import get_act_layer, get_dropout_layer, get_norm_layer, get_pool_layer +from .weight_init import _no_grad_trunc_normal_, trunc_normal_ diff --git a/source_code/SegMamba/monai/networks/layers/conjugate_gradient.py b/source_code/SegMamba/monai/networks/layers/conjugate_gradient.py new file mode 100644 index 0000000000000000000000000000000000000000..93a45930d767213cece090fdac1385082a52522c --- /dev/null +++ b/source_code/SegMamba/monai/networks/layers/conjugate_gradient.py @@ -0,0 +1,112 @@ +# Copyright (c) MONAI Consortium +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from __future__ import annotations + +from typing import Callable + +import torch +from torch import nn + + +def _zdot(x1: torch.Tensor, x2: torch.Tensor) -> torch.Tensor: + """ + Complex dot product between tensors x1 and x2: sum(x1.*x2) + """ + if torch.is_complex(x1): + assert torch.is_complex(x2), "x1 and x2 must both be complex" + return torch.sum(x1.conj() * x2) + else: + return torch.sum(x1 * x2) + + +def _zdot_single(x: torch.Tensor) -> torch.Tensor: + """ + Complex dot product between tensor x and itself + """ + res = _zdot(x, x) + if torch.is_complex(res): + return res.real + else: + return res + + +class ConjugateGradient(nn.Module): + """ + Congugate Gradient (CG) solver for linear systems Ax = y. + + For linear_op that is positive definite and self-adjoint, CG is + guaranteed to converge CG is often used to solve linear systems of the form + Ax = y, where A is too large to store explicitly, but can be computed via a + linear operator. + + As a result, here we won't set A explicitly as a matrix, but rather as a + linear operator. For example, A could be a FFT/IFFT operation + """ + + def __init__(self, linear_op: Callable, num_iter: int): + """ + Args: + linear_op: Linear operator + num_iter: Number of iterations to run CG + """ + super().__init__() + + self.linear_op = linear_op + self.num_iter = num_iter + + def update( + self, x: torch.Tensor, p: torch.Tensor, r: torch.Tensor, rsold: torch.Tensor + ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]: + """ + perform one iteration of the CG method. It takes the current solution x, + the current search direction p, the current residual r, and the old + residual norm rsold as inputs. Then it computes the new solution, search + direction, residual, and residual norm, and returns them. + """ + + dy = self.linear_op(p) + p_dot_dy = _zdot(p, dy) + alpha = rsold / p_dot_dy + x = x + alpha * p + r = r - alpha * dy + rsnew = _zdot_single(r) + beta = rsnew / rsold + rsold = rsnew + p = beta * p + r + return x, p, r, rsold + + def forward(self, x: torch.Tensor, y: torch.Tensor) -> torch.Tensor: + """ + run conjugate gradient for num_iter iterations to solve Ax = y + + Args: + x: tensor (real or complex); Initial guess for linear system Ax = y. + The size of x should be applicable to the linear operator. For + example, if the linear operator is FFT, then x is HCHW; if the + linear operator is a matrix multiplication, then x is a vector + + y: tensor (real or complex); Measurement. Same size as x + + Returns: + x: Solution to Ax = y + """ + # Compute residual + r = y - self.linear_op(x) + rsold = _zdot_single(r) + p = r + + # Update + for _i in range(self.num_iter): + x, p, r, rsold = self.update(x, p, r, rsold) + if rsold < 1e-10: + break + return x diff --git a/source_code/SegMamba/monai/networks/layers/convutils.py b/source_code/SegMamba/monai/networks/layers/convutils.py new file mode 100644 index 0000000000000000000000000000000000000000..fc8ea0380932818b793c544838b09a5b21e97f9d --- /dev/null +++ b/source_code/SegMamba/monai/networks/layers/convutils.py @@ -0,0 +1,225 @@ +# Copyright (c) MONAI Consortium +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from __future__ import annotations + +from collections.abc import Sequence + +import numpy as np +import torch + +__all__ = ["same_padding", "stride_minus_kernel_padding", "calculate_out_shape", "gaussian_1d", "polyval"] + + +def same_padding(kernel_size: Sequence[int] | int, dilation: Sequence[int] | int = 1) -> tuple[int, ...] | int: + """ + Return the padding value needed to ensure a convolution using the given kernel size produces an output of the same + shape as the input for a stride of 1, otherwise ensure a shape of the input divided by the stride rounded down. + + Raises: + NotImplementedError: When ``np.any((kernel_size - 1) * dilation % 2 == 1)``. + + """ + + kernel_size_np = np.atleast_1d(kernel_size) + dilation_np = np.atleast_1d(dilation) + + if np.any((kernel_size_np - 1) * dilation % 2 == 1): + raise NotImplementedError( + f"Same padding not available for kernel_size={kernel_size_np} and dilation={dilation_np}." + ) + + padding_np = (kernel_size_np - 1) / 2 * dilation_np + padding = tuple(int(p) for p in padding_np) + + return padding if len(padding) > 1 else padding[0] + + +def stride_minus_kernel_padding(kernel_size: Sequence[int] | int, stride: Sequence[int] | int) -> tuple[int, ...] | int: + kernel_size_np = np.atleast_1d(kernel_size) + stride_np = np.atleast_1d(stride) + + out_padding_np = stride_np - kernel_size_np + out_padding = tuple(int(p) for p in out_padding_np) + + return out_padding if len(out_padding) > 1 else out_padding[0] + + +def calculate_out_shape( + in_shape: Sequence[int] | int | np.ndarray, + kernel_size: Sequence[int] | int, + stride: Sequence[int] | int, + padding: Sequence[int] | int, +) -> tuple[int, ...] | int: + """ + Calculate the output tensor shape when applying a convolution to a tensor of shape `inShape` with kernel size + `kernel_size`, stride value `stride`, and input padding value `padding`. All arguments can be scalars or multiple + values, return value is a scalar if all inputs are scalars. + """ + in_shape_np = np.atleast_1d(in_shape) + kernel_size_np = np.atleast_1d(kernel_size) + stride_np = np.atleast_1d(stride) + padding_np = np.atleast_1d(padding) + + out_shape_np = ((in_shape_np - kernel_size_np + padding_np + padding_np) // stride_np) + 1 + out_shape = tuple(int(s) for s in out_shape_np) + + return out_shape + + +def gaussian_1d( + sigma: torch.Tensor, truncated: float = 4.0, approx: str = "erf", normalize: bool = False +) -> torch.Tensor: + """ + one dimensional Gaussian kernel. + + Args: + sigma: std of the kernel + truncated: tail length + approx: discrete Gaussian kernel type, available options are "erf", "sampled", and "scalespace". + + - ``erf`` approximation interpolates the error function; + - ``sampled`` uses a sampled Gaussian kernel; + - ``scalespace`` corresponds to + https://en.wikipedia.org/wiki/Scale_space_implementation#The_discrete_Gaussian_kernel + based on the modified Bessel functions. + + normalize: whether to normalize the kernel with `kernel.sum()`. + + Raises: + ValueError: When ``truncated`` is non-positive. + + Returns: + 1D torch tensor + + """ + sigma = torch.as_tensor(sigma, dtype=torch.float, device=sigma.device if isinstance(sigma, torch.Tensor) else None) + device = sigma.device + if truncated <= 0.0: + raise ValueError(f"truncated must be positive, got {truncated}.") + tail = int(max(float(sigma) * truncated, 0.5) + 0.5) + if approx.lower() == "erf": + x = torch.arange(-tail, tail + 1, dtype=torch.float, device=device) + t = 0.70710678 / torch.abs(sigma) + out = 0.5 * ((t * (x + 0.5)).erf() - (t * (x - 0.5)).erf()) + out = out.clamp(min=0) + elif approx.lower() == "sampled": + x = torch.arange(-tail, tail + 1, dtype=torch.float, device=sigma.device) + out = torch.exp(-0.5 / (sigma * sigma) * x**2) + if not normalize: # compute the normalizer + out = out / (2.5066282 * sigma) + elif approx.lower() == "scalespace": + sigma2 = sigma * sigma + out_pos: list[torch.Tensor | None] = [None] * (tail + 1) + out_pos[0] = _modified_bessel_0(sigma2) + out_pos[1] = _modified_bessel_1(sigma2) + for k in range(2, len(out_pos)): + out_pos[k] = _modified_bessel_i(k, sigma2) + out = out_pos[:0:-1] + out.extend(out_pos) + out = torch.stack(out) * torch.exp(-sigma2) + else: + raise NotImplementedError(f"Unsupported option: approx='{approx}'.") + return out / out.sum() if normalize else out # type: ignore + + +def polyval(coef, x) -> torch.Tensor: + """ + Evaluates the polynomial defined by `coef` at `x`. + + For a 1D sequence of coef (length n), evaluate:: + + y = coef[n-1] + x * (coef[n-2] + ... + x * (coef[1] + x * coef[0])) + + Args: + coef: a sequence of floats representing the coefficients of the polynomial + x: float or a sequence of floats representing the variable of the polynomial + + Returns: + 1D torch tensor + """ + device = x.device if isinstance(x, torch.Tensor) else None + coef = torch.as_tensor(coef, dtype=torch.float, device=device) + if coef.ndim == 0 or (len(coef) < 1): + return torch.zeros(x.shape) + x = torch.as_tensor(x, dtype=torch.float, device=device) + ans = coef[0] + for c in coef[1:]: + ans = ans * x + c + return ans # type: ignore + + +def _modified_bessel_0(x: torch.Tensor) -> torch.Tensor: + x = torch.as_tensor(x, dtype=torch.float, device=x.device if isinstance(x, torch.Tensor) else None) + if torch.abs(x) < 3.75: + y = x * x / 14.0625 + return polyval([0.45813e-2, 0.360768e-1, 0.2659732, 1.2067492, 3.0899424, 3.5156229, 1.0], y) + ax = torch.abs(x) + y = 3.75 / ax + _coef = [ + 0.392377e-2, + -0.1647633e-1, + 0.2635537e-1, + -0.2057706e-1, + 0.916281e-2, + -0.157565e-2, + 0.225319e-2, + 0.1328592e-1, + 0.39894228, + ] + return polyval(_coef, y) * torch.exp(ax) / torch.sqrt(ax) + + +def _modified_bessel_1(x: torch.Tensor) -> torch.Tensor: + x = torch.as_tensor(x, dtype=torch.float, device=x.device if isinstance(x, torch.Tensor) else None) + if torch.abs(x) < 3.75: + y = x * x / 14.0625 + _coef = [0.32411e-3, 0.301532e-2, 0.2658733e-1, 0.15084934, 0.51498869, 0.87890594, 0.5] + return torch.abs(x) * polyval(_coef, y) + ax = torch.abs(x) + y = 3.75 / ax + _coef = [ + -0.420059e-2, + 0.1787654e-1, + -0.2895312e-1, + 0.2282967e-1, + -0.1031555e-1, + 0.163801e-2, + -0.362018e-2, + -0.3988024e-1, + 0.39894228, + ] + ans = polyval(_coef, y) * torch.exp(ax) / torch.sqrt(ax) + return -ans if x < 0.0 else ans + + +def _modified_bessel_i(n: int, x: torch.Tensor) -> torch.Tensor: + if n < 2: + raise ValueError(f"n must be greater than 1, got n={n}.") + x = torch.as_tensor(x, dtype=torch.float, device=x.device if isinstance(x, torch.Tensor) else None) + if x == 0.0: + return x + device = x.device + tox = 2.0 / torch.abs(x) + ans, bip, bi = torch.tensor(0.0, device=device), torch.tensor(0.0, device=device), torch.tensor(1.0, device=device) + m = int(2 * (n + np.floor(np.sqrt(40.0 * n)))) + for j in range(m, 0, -1): + bim = bip + float(j) * tox * bi + bip = bi + bi = bim + if abs(bi) > 1.0e10: + ans = ans * 1.0e-10 + bi = bi * 1.0e-10 + bip = bip * 1.0e-10 + if j == n: + ans = bip + ans = ans * _modified_bessel_0(x) / bi + return -ans if x < 0.0 and (n % 2) == 1 else ans diff --git a/source_code/SegMamba/monai/networks/layers/drop_path.py b/source_code/SegMamba/monai/networks/layers/drop_path.py new file mode 100644 index 0000000000000000000000000000000000000000..6073ca4402766e04687ab5726b6967ad2d783ecf --- /dev/null +++ b/source_code/SegMamba/monai/networks/layers/drop_path.py @@ -0,0 +1,47 @@ +# Copyright (c) MONAI Consortium +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from __future__ import annotations + +import torch.nn as nn + + +class DropPath(nn.Module): + """Stochastic drop paths per sample for residual blocks. + Based on: + https://github.com/rwightman/pytorch-image-models + """ + + def __init__(self, drop_prob: float = 0.0, scale_by_keep: bool = True) -> None: + """ + Args: + drop_prob: drop path probability. + scale_by_keep: scaling by non-dropped probability. + """ + super().__init__() + self.drop_prob = drop_prob + self.scale_by_keep = scale_by_keep + + if not (0 <= drop_prob <= 1): + raise ValueError("Drop path prob should be between 0 and 1.") + + def drop_path(self, x, drop_prob: float = 0.0, training: bool = False, scale_by_keep: bool = True): + if drop_prob == 0.0 or not training: + return x + keep_prob = 1 - drop_prob + shape = (x.shape[0],) + (1,) * (x.ndim - 1) + random_tensor = x.new_empty(shape).bernoulli_(keep_prob) + if keep_prob > 0.0 and scale_by_keep: + random_tensor.div_(keep_prob) + return x * random_tensor + + def forward(self, x): + return self.drop_path(x, self.drop_prob, self.training, self.scale_by_keep) diff --git a/source_code/SegMamba/monai/networks/layers/factories.py b/source_code/SegMamba/monai/networks/layers/factories.py new file mode 100644 index 0000000000000000000000000000000000000000..4fc2c16f73bc84ca2efcf7af6e0c80130e0740d8 --- /dev/null +++ b/source_code/SegMamba/monai/networks/layers/factories.py @@ -0,0 +1,470 @@ +# Copyright (c) MONAI Consortium +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +""" +Defines factories for creating layers in generic, extensible, and dimensionally independent ways. A separate factory +object is created for each type of layer, and factory functions keyed to names are added to these objects. Whenever +a layer is requested the factory name and any necessary arguments are passed to the factory object. The return value +is typically a type but can be any callable producing a layer object. + +The factory objects contain functions keyed to names converted to upper case, these names can be referred to as members +of the factory so that they can function as constant identifiers. eg. instance normalization is named `Norm.INSTANCE`. + +For example, to get a transpose convolution layer the name is needed and then a dimension argument is provided which is +passed to the factory function: + +.. code-block:: python + + dimension = 3 + name = Conv.CONVTRANS + conv = Conv[name, dimension] + +This allows the `dimension` value to be set in the constructor, for example so that the dimensionality of a network is +parameterizable. Not all factories require arguments after the name, the caller must be aware which are required. + +Defining new factories involves creating the object then associating it with factory functions: + +.. code-block:: python + + fact = LayerFactory() + + @fact.factory_function('test') + def make_something(x, y): + # do something with x and y to choose which layer type to return + return SomeLayerType + ... + + # request object from factory TEST with 1 and 2 as values for x and y + layer = fact[fact.TEST, 1, 2] + +Typically the caller of a factory would know what arguments to pass (ie. the dimensionality of the requested type) but +can be parameterized with the factory name and the arguments to pass to the created type at instantiation time: + +.. code-block:: python + + def use_factory(fact_args): + fact_name, type_args = split_args + layer_type = fact[fact_name, 1, 2] + return layer_type(**type_args) + ... + + kw_args = {'arg0':0, 'arg1':True} + layer = use_factory( (fact.TEST, kwargs) ) +""" + +from __future__ import annotations + +import warnings +from collections.abc import Callable +from typing import Any + +import torch.nn as nn + +from monai.networks.utils import has_nvfuser_instance_norm +from monai.utils import ComponentStore, look_up_option, optional_import + +__all__ = ["LayerFactory", "Dropout", "Norm", "Act", "Conv", "Pool", "Pad", "split_args"] + + +class LayerFactory(ComponentStore): + """ + Factory object for creating layers, this uses given factory functions to actually produce the types or constructing + callables. These functions are referred to by name and can be added at any time. + """ + + def __init__(self, name: str, description: str) -> None: + super().__init__(name, description) + self.__doc__ = ( + f"Layer Factory '{name}': {description}\n".strip() + + "\nPlease see :py:class:`monai.networks.layers.split_args` for additional args parsing." + + "\n\nThe supported members are:" + ) + + def add_factory_callable(self, name: str, func: Callable, desc: str | None = None) -> None: + """ + Add the factory function to this object under the given name, with optional description. + """ + description: str = desc or func.__doc__ or "" + self.add(name.upper(), description, func) + # append name to the docstring + assert self.__doc__ is not None + self.__doc__ += f"{', ' if len(self.names)>1 else ' '}``{name}``" + + def add_factory_class(self, name: str, cls: type, desc: str | None = None) -> None: + """ + Adds a factory function which returns the supplied class under the given name, with optional description. + """ + self.add_factory_callable(name, lambda x=None: cls, desc) + + def factory_function(self, name: str) -> Callable: + """ + Decorator for adding a factory function with the given name. + """ + + def _add(func: Callable) -> Callable: + self.add_factory_callable(name, func) + return func + + return _add + + def get_constructor(self, factory_name: str, *args) -> Any: + """ + Get the constructor for the given factory name and arguments. + + Raises: + TypeError: When ``factory_name`` is not a ``str``. + + """ + + if not isinstance(factory_name, str): + raise TypeError(f"factory_name must a str but is {type(factory_name).__name__}.") + + component = look_up_option(factory_name.upper(), self.components) + + return component.value(*args) + + def __getitem__(self, args) -> Any: + """ + Get the given name or name/arguments pair. If `args` is a callable it is assumed to be the constructor + itself and is returned, otherwise it should be the factory name or a pair containing the name and arguments. + """ + + # `args[0]` is actually a type or constructor + if callable(args): + return args + + # `args` is a factory name or a name with arguments + if isinstance(args, str): + name_obj, args = args, () + else: + name_obj, *args = args + + return self.get_constructor(name_obj, *args) + + def __getattr__(self, key): + """ + If `key` is a factory name, return it, otherwise behave as inherited. This allows referring to factory names + as if they were constants, eg. `Fact.FOO` for a factory Fact with factory function foo. + """ + + if key in self.components: + return key + + return super().__getattribute__(key) + + +def split_args(args): + """ + Split arguments in a way to be suitable for using with the factory types. If `args` is a string it's interpreted as + the type name. + + Args: + args (str or a tuple of object name and kwarg dict): input arguments to be parsed. + + Raises: + TypeError: When ``args`` type is not in ``Union[str, Tuple[Union[str, Callable], dict]]``. + + Examples:: + + >>> act_type, args = split_args("PRELU") + >>> monai.networks.layers.Act[act_type] + + + >>> act_type, args = split_args(("PRELU", {"num_parameters": 1, "init": 0.25})) + >>> monai.networks.layers.Act[act_type](**args) + PReLU(num_parameters=1) + + """ + + if isinstance(args, str): + return args, {} + name_obj, name_args = args + + if not (isinstance(name_obj, str) or callable(name_obj)) or not isinstance(name_args, dict): + msg = "Layer specifiers must be single strings or pairs of the form (name/object-types, argument dict)" + raise TypeError(msg) + + return name_obj, name_args + + +# Define factories for these layer types +Dropout = LayerFactory(name="Dropout layers", description="Factory for creating dropout layers.") +Norm = LayerFactory(name="Normalization layers", description="Factory for creating normalization layers.") +Act = LayerFactory(name="Activation layers", description="Factory for creating activation layers.") +Conv = LayerFactory(name="Convolution layers", description="Factory for creating convolution layers.") +Pool = LayerFactory(name="Pooling layers", description="Factory for creating pooling layers.") +Pad = LayerFactory(name="Padding layers", description="Factory for creating padding layers.") + + +@Dropout.factory_function("dropout") +def dropout_factory(dim: int) -> type[nn.Dropout | nn.Dropout2d | nn.Dropout3d]: + """ + Dropout layers in 1,2,3 dimensions. + + Args: + dim: desired dimension of the dropout layer + + Returns: + Dropout[dim]d + """ + types = (nn.Dropout, nn.Dropout2d, nn.Dropout3d) + return types[dim - 1] + + +Dropout.add_factory_class("alphadropout", nn.AlphaDropout) + + +@Norm.factory_function("instance") +def instance_factory(dim: int) -> type[nn.InstanceNorm1d | nn.InstanceNorm2d | nn.InstanceNorm3d]: + """ + Instance normalization layers in 1,2,3 dimensions. + + Args: + dim: desired dimension of the instance normalization layer + + Returns: + InstanceNorm[dim]d + """ + types = (nn.InstanceNorm1d, nn.InstanceNorm2d, nn.InstanceNorm3d) + return types[dim - 1] + + +@Norm.factory_function("batch") +def batch_factory(dim: int) -> type[nn.BatchNorm1d | nn.BatchNorm2d | nn.BatchNorm3d]: + """ + Batch normalization layers in 1,2,3 dimensions. + + Args: + dim: desired dimension of the batch normalization layer + + Returns: + BatchNorm[dim]d + """ + types = (nn.BatchNorm1d, nn.BatchNorm2d, nn.BatchNorm3d) + return types[dim - 1] + + +@Norm.factory_function("instance_nvfuser") +def instance_nvfuser_factory(dim): + """ + `InstanceNorm3dNVFuser` is a faster version of InstanceNorm layer and implemented in `apex`. + It only supports 3d tensors as the input. It also requires to use with CUDA and non-Windows OS. + In this function, if the required library `apex.normalization.InstanceNorm3dNVFuser` does not exist, + `nn.InstanceNorm3d` will be returned instead. + This layer is based on a customized autograd function, which is not supported in TorchScript currently. + Please switch to use `nn.InstanceNorm3d` if TorchScript is necessary. + + Please check the following link for more details about how to install `apex`: + https://github.com/NVIDIA/apex#installation + + """ + + if dim != 3: + types = (nn.InstanceNorm1d, nn.InstanceNorm2d) + warnings.warn(f"`InstanceNorm3dNVFuser` only supports 3d cases, use {types[dim - 1]} instead.") + return types[dim - 1] + + if not has_nvfuser_instance_norm(): + warnings.warn( + "`apex.normalization.InstanceNorm3dNVFuser` is not installed properly, use nn.InstanceNorm3d instead." + ) + return nn.InstanceNorm3d + return optional_import("apex.normalization", name="InstanceNorm3dNVFuser")[0] + + +Norm.add_factory_class("group", nn.GroupNorm) +Norm.add_factory_class("layer", nn.LayerNorm) +Norm.add_factory_class("localresponse", nn.LocalResponseNorm) +Norm.add_factory_class("syncbatch", nn.SyncBatchNorm) + +Act.add_factory_class("elu", nn.modules.ELU) +Act.add_factory_class("relu", nn.modules.ReLU) +Act.add_factory_class("leakyrelu", nn.modules.LeakyReLU) +Act.add_factory_class("prelu", nn.modules.PReLU) +Act.add_factory_class("relu6", nn.modules.ReLU6) +Act.add_factory_class("selu", nn.modules.SELU) +Act.add_factory_class("celu", nn.modules.CELU) +Act.add_factory_class("gelu", nn.modules.GELU) +Act.add_factory_class("sigmoid", nn.modules.Sigmoid) +Act.add_factory_class("tanh", nn.modules.Tanh) +Act.add_factory_class("softmax", nn.modules.Softmax) +Act.add_factory_class("logsoftmax", nn.modules.LogSoftmax) + + +@Act.factory_function("swish") +def swish_factory(): + """ + Swish activation layer. + + Returns: + Swish + """ + from monai.networks.blocks.activation import Swish + + return Swish + + +@Act.factory_function("memswish") +def memswish_factory(): + """ + Memory efficient swish activation layer. + + Returns: + MemoryEfficientSwish + """ + from monai.networks.blocks.activation import MemoryEfficientSwish + + return MemoryEfficientSwish + + +@Act.factory_function("mish") +def mish_factory(): + """ + Mish activation layer. + + Returns: + Mish + """ + from monai.networks.blocks.activation import Mish + + return Mish + + +@Act.factory_function("geglu") +def geglu_factory(): + """ + GEGLU activation layer. + + Returns: + GEGLU + """ + from monai.networks.blocks.activation import GEGLU + + return GEGLU + + +@Conv.factory_function("conv") +def conv_factory(dim: int) -> type[nn.Conv1d | nn.Conv2d | nn.Conv3d]: + """ + Convolutional layers in 1,2,3 dimensions. + + Args: + dim: desired dimension of the convolutional layer + + Returns: + Conv[dim]d + """ + types = (nn.Conv1d, nn.Conv2d, nn.Conv3d) + return types[dim - 1] + + +@Conv.factory_function("convtrans") +def convtrans_factory(dim: int) -> type[nn.ConvTranspose1d | nn.ConvTranspose2d | nn.ConvTranspose3d]: + """ + Transposed convolutional layers in 1,2,3 dimensions. + + Args: + dim: desired dimension of the transposed convolutional layer + + Returns: + ConvTranspose[dim]d + """ + types = (nn.ConvTranspose1d, nn.ConvTranspose2d, nn.ConvTranspose3d) + return types[dim - 1] + + +@Pool.factory_function("max") +def maxpooling_factory(dim: int) -> type[nn.MaxPool1d | nn.MaxPool2d | nn.MaxPool3d]: + """ + Max pooling layers in 1,2,3 dimensions. + + Args: + dim: desired dimension of the max pooling layer + + Returns: + MaxPool[dim]d + """ + types = (nn.MaxPool1d, nn.MaxPool2d, nn.MaxPool3d) + return types[dim - 1] + + +@Pool.factory_function("adaptivemax") +def adaptive_maxpooling_factory(dim: int) -> type[nn.AdaptiveMaxPool1d | nn.AdaptiveMaxPool2d | nn.AdaptiveMaxPool3d]: + """ + Adaptive max pooling layers in 1,2,3 dimensions. + + Args: + dim: desired dimension of the adaptive max pooling layer + + Returns: + AdaptiveMaxPool[dim]d + """ + types = (nn.AdaptiveMaxPool1d, nn.AdaptiveMaxPool2d, nn.AdaptiveMaxPool3d) + return types[dim - 1] + + +@Pool.factory_function("avg") +def avgpooling_factory(dim: int) -> type[nn.AvgPool1d | nn.AvgPool2d | nn.AvgPool3d]: + """ + Average pooling layers in 1,2,3 dimensions. + + Args: + dim: desired dimension of the average pooling layer + + Returns: + AvgPool[dim]d + """ + types = (nn.AvgPool1d, nn.AvgPool2d, nn.AvgPool3d) + return types[dim - 1] + + +@Pool.factory_function("adaptiveavg") +def adaptive_avgpooling_factory(dim: int) -> type[nn.AdaptiveAvgPool1d | nn.AdaptiveAvgPool2d | nn.AdaptiveAvgPool3d]: + """ + Adaptive average pooling layers in 1,2,3 dimensions. + + Args: + dim: desired dimension of the adaptive average pooling layer + + Returns: + AdaptiveAvgPool[dim]d + """ + types = (nn.AdaptiveAvgPool1d, nn.AdaptiveAvgPool2d, nn.AdaptiveAvgPool3d) + return types[dim - 1] + + +@Pad.factory_function("replicationpad") +def replication_pad_factory(dim: int) -> type[nn.ReplicationPad1d | nn.ReplicationPad2d | nn.ReplicationPad3d]: + """ + Replication padding layers in 1,2,3 dimensions. + + Args: + dim: desired dimension of the replication padding layer + + Returns: + ReplicationPad[dim]d + """ + types = (nn.ReplicationPad1d, nn.ReplicationPad2d, nn.ReplicationPad3d) + return types[dim - 1] + + +@Pad.factory_function("constantpad") +def constant_pad_factory(dim: int) -> type[nn.ConstantPad1d | nn.ConstantPad2d | nn.ConstantPad3d]: + """ + Constant padding layers in 1,2,3 dimensions. + + Args: + dim: desired dimension of the constant padding layer + + Returns: + ConstantPad[dim]d + """ + types = (nn.ConstantPad1d, nn.ConstantPad2d, nn.ConstantPad3d) + return types[dim - 1] diff --git a/source_code/SegMamba/monai/networks/layers/gmm.py b/source_code/SegMamba/monai/networks/layers/gmm.py new file mode 100644 index 0000000000000000000000000000000000000000..6ebe66832fea411f6ed3355c28e5da6aac2b7f4e --- /dev/null +++ b/source_code/SegMamba/monai/networks/layers/gmm.py @@ -0,0 +1,88 @@ +# Copyright (c) MONAI Consortium +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from __future__ import annotations + +import torch + +from monai._extensions.loader import load_module + +__all__ = ["GaussianMixtureModel"] + + +class GaussianMixtureModel: + """ + Takes an initial labeling and uses a mixture of Gaussians to approximate each classes + distribution in the feature space. Each unlabeled element is then assigned a probability + of belonging to each class based on it's fit to each classes approximated distribution. + + See: + https://en.wikipedia.org/wiki/Mixture_model + """ + + def __init__(self, channel_count: int, mixture_count: int, mixture_size: int, verbose_build: bool = False): + """ + Args: + channel_count: The number of features per element. + mixture_count: The number of class distributions. + mixture_size: The number Gaussian components per class distribution. + verbose_build: If ``True``, turns on verbose logging of load steps. + """ + if not torch.cuda.is_available(): + raise NotImplementedError("GaussianMixtureModel is currently implemented for CUDA.") + self.channel_count = channel_count + self.mixture_count = mixture_count + self.mixture_size = mixture_size + self.compiled_extension = load_module( + "gmm", + {"CHANNEL_COUNT": channel_count, "MIXTURE_COUNT": mixture_count, "MIXTURE_SIZE": mixture_size}, + verbose_build=verbose_build, + ) + self.params, self.scratch = self.compiled_extension.init() + + def reset(self): + """ + Resets the parameters of the model. + """ + self.params, self.scratch = self.compiled_extension.init() + + def learn(self, features, labels): + """ + Learns, from scratch, the distribution of each class from the provided labels. + + Args: + features (torch.Tensor): features for each element. + labels (torch.Tensor): initial labeling for each element. + """ + self.compiled_extension.learn(self.params, self.scratch, features, labels) + + def apply(self, features): + """ + Applies the current model to a set of feature vectors. + + Args: + features (torch.Tensor): feature vectors for each element. + + Returns: + output (torch.Tensor): class assignment probabilities for each element. + """ + return _ApplyFunc.apply(self.params, features, self.compiled_extension) + + +class _ApplyFunc(torch.autograd.Function): + + @staticmethod + def forward(ctx, params, features, compiled_extension): + return compiled_extension.apply(params, features) + + @staticmethod + def backward(ctx, grad_output): + raise NotImplementedError("GMM does not support backpropagation") diff --git a/source_code/SegMamba/monai/networks/layers/simplelayers.py b/source_code/SegMamba/monai/networks/layers/simplelayers.py new file mode 100644 index 0000000000000000000000000000000000000000..4ac621967f2f4a5f37b450331fcacc13550a9aec --- /dev/null +++ b/source_code/SegMamba/monai/networks/layers/simplelayers.py @@ -0,0 +1,745 @@ +# Copyright (c) MONAI Consortium +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from __future__ import annotations + +import math +from copy import deepcopy +from typing import Sequence + +import torch +import torch.nn.functional as F +from torch import nn +from torch.autograd import Function + +from monai.config.type_definitions import NdarrayOrTensor +from monai.networks.layers.convutils import gaussian_1d +from monai.networks.layers.factories import Conv +from monai.utils import ( + ChannelMatching, + SkipMode, + convert_to_tensor, + ensure_tuple_rep, + issequenceiterable, + look_up_option, + optional_import, + pytorch_after, +) + +_C, _ = optional_import("monai._C") +fft, _ = optional_import("torch.fft") + +__all__ = [ + "ChannelPad", + "Flatten", + "GaussianFilter", + "HilbertTransform", + "LLTM", + "MedianFilter", + "Reshape", + "SavitzkyGolayFilter", + "SkipConnection", + "apply_filter", + "median_filter", + "separable_filtering", +] + + +class ChannelPad(nn.Module): + """ + Expand the input tensor's channel dimension from length `in_channels` to `out_channels`, + by padding or a projection. + """ + + def __init__( + self, spatial_dims: int, in_channels: int, out_channels: int, mode: ChannelMatching | str = ChannelMatching.PAD + ): + """ + + Args: + spatial_dims: number of spatial dimensions of the input image. + in_channels: number of input channels. + out_channels: number of output channels. + mode: {``"pad"``, ``"project"``} + Specifies handling residual branch and conv branch channel mismatches. Defaults to ``"pad"``. + + - ``"pad"``: with zero padding. + - ``"project"``: with a trainable conv with kernel size one. + """ + super().__init__() + self.project = None + self.pad = None + if in_channels == out_channels: + return + mode = look_up_option(mode, ChannelMatching) + if mode == ChannelMatching.PROJECT: + conv_type = Conv[Conv.CONV, spatial_dims] + self.project = conv_type(in_channels, out_channels, kernel_size=1) + return + if mode == ChannelMatching.PAD: + if in_channels > out_channels: + raise ValueError('Incompatible values: channel_matching="pad" and in_channels > out_channels.') + pad_1 = (out_channels - in_channels) // 2 + pad_2 = out_channels - in_channels - pad_1 + pad = [0, 0] * spatial_dims + [pad_1, pad_2] + [0, 0] + self.pad = tuple(pad) + return + + def forward(self, x: torch.Tensor) -> torch.Tensor: + if self.project is not None: + return torch.as_tensor(self.project(x)) # as_tensor used to get around mypy typing bug + if self.pad is not None: + return F.pad(x, self.pad) + return x + + +class SkipConnection(nn.Module): + """ + Combine the forward pass input with the result from the given submodule:: + + --+--submodule--o-- + |_____________| + + The available modes are ``"cat"``, ``"add"``, ``"mul"``. + """ + + def __init__(self, submodule, dim: int = 1, mode: str | SkipMode = "cat") -> None: + """ + + Args: + submodule: the module defines the trainable branch. + dim: the dimension over which the tensors are concatenated. + Used when mode is ``"cat"``. + mode: ``"cat"``, ``"add"``, ``"mul"``. defaults to ``"cat"``. + """ + super().__init__() + self.submodule = submodule + self.dim = dim + self.mode = look_up_option(mode, SkipMode).value + + def forward(self, x: torch.Tensor) -> torch.Tensor: + y = self.submodule(x) + + if self.mode == "cat": + return torch.cat([x, y], dim=self.dim) + if self.mode == "add": + return torch.add(x, y) + if self.mode == "mul": + return torch.mul(x, y) + raise NotImplementedError(f"Unsupported mode {self.mode}.") + + +class Flatten(nn.Module): + """ + Flattens the given input in the forward pass to be [B,-1] in shape. + """ + + def forward(self, x: torch.Tensor) -> torch.Tensor: + return x.view(x.size(0), -1) + + +class Reshape(nn.Module): + """ + Reshapes input tensors to the given shape (minus batch dimension), retaining original batch size. + """ + + def __init__(self, *shape: int) -> None: + """ + Given a shape list/tuple `shape` of integers (s0, s1, ... , sn), this layer will reshape input tensors of + shape (batch, s0 * s1 * ... * sn) to shape (batch, s0, s1, ... , sn). + + Args: + shape: list/tuple of integer shape dimensions + """ + super().__init__() + self.shape = (1,) + tuple(shape) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + shape = list(self.shape) + shape[0] = x.shape[0] # done this way for Torchscript + return x.reshape(shape) + + +def _separable_filtering_conv( + input_: torch.Tensor, + kernels: list[torch.Tensor], + pad_mode: str, + d: int, + spatial_dims: int, + paddings: list[int], + num_channels: int, +) -> torch.Tensor: + if d < 0: + return input_ + + s = [1] * len(input_.shape) + s[d + 2] = -1 + _kernel = kernels[d].reshape(s) + + # if filter kernel is unity, don't convolve + if _kernel.numel() == 1 and _kernel[0] == 1: + return _separable_filtering_conv(input_, kernels, pad_mode, d - 1, spatial_dims, paddings, num_channels) + + _kernel = _kernel.repeat([num_channels, 1] + [1] * spatial_dims) + _padding = [0] * spatial_dims + _padding[d] = paddings[d] + conv_type = [F.conv1d, F.conv2d, F.conv3d][spatial_dims - 1] + + # translate padding for input to torch.nn.functional.pad + _reversed_padding_repeated_twice: list[list[int]] = [[p, p] for p in reversed(_padding)] + _sum_reversed_padding_repeated_twice: list[int] = sum(_reversed_padding_repeated_twice, []) + padded_input = F.pad(input_, _sum_reversed_padding_repeated_twice, mode=pad_mode) + + return conv_type( + input=_separable_filtering_conv(padded_input, kernels, pad_mode, d - 1, spatial_dims, paddings, num_channels), + weight=_kernel, + groups=num_channels, + ) + + +def separable_filtering(x: torch.Tensor, kernels: list[torch.Tensor], mode: str = "zeros") -> torch.Tensor: + """ + Apply 1-D convolutions along each spatial dimension of `x`. + + Args: + x: the input image. must have shape (batch, channels, H[, W, ...]). + kernels: kernel along each spatial dimension. + could be a single kernel (duplicated for all spatial dimensions), or + a list of `spatial_dims` number of kernels. + mode (string, optional): padding mode passed to convolution class. ``'zeros'``, ``'reflect'``, ``'replicate'`` + or ``'circular'``. Default: ``'zeros'``. See ``torch.nn.Conv1d()`` for more information. + + Raises: + TypeError: When ``x`` is not a ``torch.Tensor``. + + Examples: + + .. code-block:: python + + >>> import torch + >>> from monai.networks.layers import separable_filtering + >>> img = torch.randn(2, 4, 32, 32) # batch_size 2, channels 4, 32x32 2D images + # applying a [-1, 0, 1] filter along each of the spatial dimensions. + # the output shape is the same as the input shape. + >>> out = separable_filtering(img, torch.tensor((-1., 0., 1.))) + # applying `[-1, 0, 1]`, `[1, 0, -1]` filters along two spatial dimensions respectively. + # the output shape is the same as the input shape. + >>> out = separable_filtering(img, [torch.tensor((-1., 0., 1.)), torch.tensor((1., 0., -1.))]) + + """ + + if not isinstance(x, torch.Tensor): + raise TypeError(f"x must be a torch.Tensor but is {type(x).__name__}.") + + spatial_dims = len(x.shape) - 2 + if isinstance(kernels, torch.Tensor): + kernels = [kernels] * spatial_dims + _kernels = [s.to(x) for s in kernels] + _paddings = [(k.shape[0] - 1) // 2 for k in _kernels] + n_chs = x.shape[1] + pad_mode = "constant" if mode == "zeros" else mode + + return _separable_filtering_conv(x, _kernels, pad_mode, spatial_dims - 1, spatial_dims, _paddings, n_chs) + + +def apply_filter(x: torch.Tensor, kernel: torch.Tensor, **kwargs) -> torch.Tensor: + """ + Filtering `x` with `kernel` independently for each batch and channel respectively. + + Args: + x: the input image, must have shape (batch, channels, H[, W, D]). + kernel: `kernel` must at least have the spatial shape (H_k[, W_k, D_k]). + `kernel` shape must be broadcastable to the `batch` and `channels` dimensions of `x`. + kwargs: keyword arguments passed to `conv*d()` functions. + + Returns: + The filtered `x`. + + Examples: + + .. code-block:: python + + >>> import torch + >>> from monai.networks.layers import apply_filter + >>> img = torch.rand(2, 5, 10, 10) # batch_size 2, channels 5, 10x10 2D images + >>> out = apply_filter(img, torch.rand(3, 3)) # spatial kernel + >>> out = apply_filter(img, torch.rand(5, 3, 3)) # channel-wise kernels + >>> out = apply_filter(img, torch.rand(2, 5, 3, 3)) # batch-, channel-wise kernels + + """ + if not isinstance(x, torch.Tensor): + raise TypeError(f"x must be a torch.Tensor but is {type(x).__name__}.") + batch, chns, *spatials = x.shape + n_spatial = len(spatials) + if n_spatial > 3: + raise NotImplementedError(f"Only spatial dimensions up to 3 are supported but got {n_spatial}.") + k_size = len(kernel.shape) + if k_size < n_spatial or k_size > n_spatial + 2: + raise ValueError( + f"kernel must have {n_spatial} ~ {n_spatial + 2} dimensions to match the input shape {x.shape}." + ) + kernel = kernel.to(x) + # broadcast kernel size to (batch chns, spatial_kernel_size) + kernel = kernel.expand(batch, chns, *kernel.shape[(k_size - n_spatial) :]) + kernel = kernel.reshape(-1, 1, *kernel.shape[2:]) # group=1 + x = x.view(1, kernel.shape[0], *spatials) + conv = [F.conv1d, F.conv2d, F.conv3d][n_spatial - 1] + if "padding" not in kwargs: + if pytorch_after(1, 10): + kwargs["padding"] = "same" + else: + # even-sized kernels are not supported + kwargs["padding"] = [(k - 1) // 2 for k in kernel.shape[2:]] + elif kwargs["padding"] == "same" and not pytorch_after(1, 10): + # even-sized kernels are not supported + kwargs["padding"] = [(k - 1) // 2 for k in kernel.shape[2:]] + + if "stride" not in kwargs: + kwargs["stride"] = 1 + output = conv(x, kernel, groups=kernel.shape[0], bias=None, **kwargs) + return output.view(batch, chns, *output.shape[2:]) + + +class SavitzkyGolayFilter(nn.Module): + """ + Convolve a Tensor along a particular axis with a Savitzky-Golay kernel. + + Args: + window_length: Length of the filter window, must be a positive odd integer. + order: Order of the polynomial to fit to each window, must be less than ``window_length``. + axis (optional): Axis along which to apply the filter kernel. Default 2 (first spatial dimension). + mode (string, optional): padding mode passed to convolution class. ``'zeros'``, ``'reflect'``, ``'replicate'`` or + ``'circular'``. Default: ``'zeros'``. See torch.nn.Conv1d() for more information. + """ + + def __init__(self, window_length: int, order: int, axis: int = 2, mode: str = "zeros"): + super().__init__() + if order >= window_length: + raise ValueError("order must be less than window_length.") + + self.axis = axis + self.mode = mode + self.coeffs = self._make_coeffs(window_length, order) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + """ + Args: + x: Tensor or array-like to filter. Must be real, in shape ``[Batch, chns, spatial1, spatial2, ...]`` and + have a device type of ``'cpu'``. + Returns: + torch.Tensor: ``x`` filtered by Savitzky-Golay kernel with window length ``self.window_length`` using + polynomials of order ``self.order``, along axis specified in ``self.axis``. + """ + + # Make input a real tensor on the CPU + x = torch.as_tensor(x, device=x.device if isinstance(x, torch.Tensor) else None) + if torch.is_complex(x): + raise ValueError("x must be real.") + x = x.to(dtype=torch.float) + + if (self.axis < 0) or (self.axis > len(x.shape) - 1): + raise ValueError(f"Invalid axis for shape of x, got axis {self.axis} and shape {x.shape}.") + + # Create list of filter kernels (1 per spatial dimension). The kernel for self.axis will be the savgol coeffs, + # while the other kernels will be set to [1]. + n_spatial_dims = len(x.shape) - 2 + spatial_processing_axis = self.axis - 2 + new_dims_before = spatial_processing_axis + new_dims_after = n_spatial_dims - spatial_processing_axis - 1 + kernel_list = [self.coeffs.to(device=x.device, dtype=x.dtype)] + for _ in range(new_dims_before): + kernel_list.insert(0, torch.ones(1, device=x.device, dtype=x.dtype)) + for _ in range(new_dims_after): + kernel_list.append(torch.ones(1, device=x.device, dtype=x.dtype)) + + return separable_filtering(x, kernel_list, mode=self.mode) + + @staticmethod + def _make_coeffs(window_length, order): + half_length, rem = divmod(window_length, 2) + if rem == 0: + raise ValueError("window_length must be odd.") + + idx = torch.arange(window_length - half_length - 1, -half_length - 1, -1, dtype=torch.float, device="cpu") + a = idx ** torch.arange(order + 1, dtype=torch.float, device="cpu").reshape(-1, 1) + y = torch.zeros(order + 1, dtype=torch.float, device="cpu") + y[0] = 1.0 + return ( + torch.lstsq(y, a).solution.squeeze() # type: ignore + if not pytorch_after(1, 11) + else torch.linalg.lstsq(a, y).solution.squeeze() + ) + + +class HilbertTransform(nn.Module): + """ + Determine the analytical signal of a Tensor along a particular axis. + + Args: + axis: Axis along which to apply Hilbert transform. Default 2 (first spatial dimension). + n: Number of Fourier components (i.e. FFT size). Default: ``x.shape[axis]``. + """ + + def __init__(self, axis: int = 2, n: int | None = None) -> None: + super().__init__() + self.axis = axis + self.n = n + + def forward(self, x: torch.Tensor) -> torch.Tensor: + """ + Args: + x: Tensor or array-like to transform. Must be real and in shape ``[Batch, chns, spatial1, spatial2, ...]``. + Returns: + torch.Tensor: Analytical signal of ``x``, transformed along axis specified in ``self.axis`` using + FFT of size ``self.N``. The absolute value of ``x_ht`` relates to the envelope of ``x`` along axis ``self.axis``. + """ + + # Make input a real tensor + x = torch.as_tensor(x, device=x.device if isinstance(x, torch.Tensor) else None) + if torch.is_complex(x): + raise ValueError("x must be real.") + x = x.to(dtype=torch.float) + + if (self.axis < 0) or (self.axis > len(x.shape) - 1): + raise ValueError(f"Invalid axis for shape of x, got axis {self.axis} and shape {x.shape}.") + + n = x.shape[self.axis] if self.n is None else self.n + if n <= 0: + raise ValueError("N must be positive.") + x = torch.as_tensor(x, dtype=torch.complex64) + # Create frequency axis + f = torch.cat( + [ + torch.true_divide(torch.arange(0, (n - 1) // 2 + 1, device=x.device), float(n)), + torch.true_divide(torch.arange(-(n // 2), 0, device=x.device), float(n)), + ] + ) + xf = fft.fft(x, n=n, dim=self.axis) + # Create step function + u = torch.heaviside(f, torch.tensor([0.5], device=f.device)) + u = torch.as_tensor(u, dtype=x.dtype, device=u.device) + new_dims_before = self.axis + new_dims_after = len(xf.shape) - self.axis - 1 + for _ in range(new_dims_before): + u.unsqueeze_(0) + for _ in range(new_dims_after): + u.unsqueeze_(-1) + + ht = fft.ifft(xf * 2 * u, dim=self.axis) + + # Apply transform + return torch.as_tensor(ht, device=ht.device, dtype=ht.dtype) + + +def get_binary_kernel(window_size: Sequence[int], dtype=torch.float, device=None) -> torch.Tensor: + """ + Create a binary kernel to extract the patches. + The window size HxWxD will create a (H*W*D)xHxWxD kernel. + """ + win_size = convert_to_tensor(window_size, int, wrap_sequence=True) + prod = torch.prod(win_size) + s = [prod, 1, *win_size] + return torch.diag(torch.ones(prod, dtype=dtype, device=device)).view(s) # type: ignore + + +def median_filter( + in_tensor: torch.Tensor, + kernel_size: Sequence[int] = (3, 3, 3), + spatial_dims: int = 3, + kernel: torch.Tensor | None = None, + **kwargs, +) -> torch.Tensor: + """ + Apply median filter to an image. + + Args: + in_tensor: input tensor; median filtering will be applied to the last `spatial_dims` dimensions. + kernel_size: the convolution kernel size. + spatial_dims: number of spatial dimensions to apply median filtering. + kernel: an optional customized kernel. + kwargs: additional parameters to the `conv`. + + Returns: + the filtered input tensor, shape remains the same as ``in_tensor`` + + Example:: + + >>> from monai.networks.layers import median_filter + >>> import torch + >>> x = torch.rand(4, 5, 7, 6) + >>> output = median_filter(x, (3, 3, 3)) + >>> output.shape + torch.Size([4, 5, 7, 6]) + + """ + if not isinstance(in_tensor, torch.Tensor): + raise TypeError(f"Input type is not a torch.Tensor. Got {type(in_tensor)}") + + original_shape = in_tensor.shape + oshape, sshape = original_shape[: len(original_shape) - spatial_dims], original_shape[-spatial_dims:] + oprod = torch.prod(convert_to_tensor(oshape, int, wrap_sequence=True)) + # prepare kernel + if kernel is None: + kernel_size = ensure_tuple_rep(kernel_size, spatial_dims) + kernel = get_binary_kernel(kernel_size, in_tensor.dtype, in_tensor.device) + else: + kernel = kernel.to(in_tensor) + # map the local window to single vector + conv = [F.conv1d, F.conv2d, F.conv3d][spatial_dims - 1] + reshaped_input: torch.Tensor = in_tensor.reshape(oprod, 1, *sshape) # type: ignore + + # even-sized kernels are not supported + padding = [(k - 1) // 2 for k in reversed(kernel.shape[2:]) for _ in range(2)] + padded_input: torch.Tensor = F.pad(reshaped_input, pad=padding, mode="replicate") + features: torch.Tensor = conv(padded_input, kernel, padding=0, stride=1, **kwargs) + + features = features.view(oprod, -1, *sshape) # type: ignore + + # compute the median along the feature axis + median: torch.Tensor = torch.median(features, dim=1)[0] + median = median.reshape(original_shape) + + return median + + +class MedianFilter(nn.Module): + """ + Apply median filter to an image. + + Args: + radius: the blurring kernel radius (radius of 1 corresponds to 3x3x3 kernel when spatial_dims=3). + + Returns: + filtered input tensor. + + Example:: + + >>> from monai.networks.layers import MedianFilter + >>> import torch + >>> in_tensor = torch.rand(4, 5, 7, 6) + >>> blur = MedianFilter([1, 1, 1]) # 3x3x3 kernel + >>> output = blur(in_tensor) + >>> output.shape + torch.Size([4, 5, 7, 6]) + + """ + + def __init__(self, radius: Sequence[int] | int, spatial_dims: int = 3, device="cpu") -> None: + super().__init__() + self.spatial_dims = spatial_dims + self.radius: Sequence[int] = ensure_tuple_rep(radius, spatial_dims) + self.window: Sequence[int] = [1 + 2 * deepcopy(r) for r in self.radius] + self.kernel = get_binary_kernel(self.window, device=device) + + def forward(self, in_tensor: torch.Tensor, number_of_passes=1) -> torch.Tensor: + """ + Args: + in_tensor: input tensor, median filtering will be applied to the last `spatial_dims` dimensions. + number_of_passes: median filtering will be repeated this many times + """ + x = in_tensor + for _ in range(number_of_passes): + x = median_filter(x, kernel=self.kernel, spatial_dims=self.spatial_dims) + return x + + +class GaussianFilter(nn.Module): + + def __init__( + self, + spatial_dims: int, + sigma: Sequence[float] | float | Sequence[torch.Tensor] | torch.Tensor, + truncated: float = 4.0, + approx: str = "erf", + requires_grad: bool = False, + ) -> None: + """ + Args: + spatial_dims: number of spatial dimensions of the input image. + must have shape (Batch, channels, H[, W, ...]). + sigma: std. could be a single value, or `spatial_dims` number of values. + truncated: spreads how many stds. + approx: discrete Gaussian kernel type, available options are "erf", "sampled", and "scalespace". + + - ``erf`` approximation interpolates the error function; + - ``sampled`` uses a sampled Gaussian kernel; + - ``scalespace`` corresponds to + https://en.wikipedia.org/wiki/Scale_space_implementation#The_discrete_Gaussian_kernel + based on the modified Bessel functions. + + requires_grad: whether to store the gradients for sigma. + if True, `sigma` will be the initial value of the parameters of this module + (for example `parameters()` iterator could be used to get the parameters); + otherwise this module will fix the kernels using `sigma` as the std. + """ + if issequenceiterable(sigma): + if len(sigma) != spatial_dims: # type: ignore + raise ValueError + else: + sigma = [deepcopy(sigma) for _ in range(spatial_dims)] # type: ignore + super().__init__() + self.sigma = [ + torch.nn.Parameter( + torch.as_tensor(s, dtype=torch.float, device=s.device if isinstance(s, torch.Tensor) else None), + requires_grad=requires_grad, + ) + for s in sigma # type: ignore + ] + self.truncated = truncated + self.approx = approx + for idx, param in enumerate(self.sigma): + self.register_parameter(f"kernel_sigma_{idx}", param) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + """ + Args: + x: in shape [Batch, chns, H, W, D]. + """ + _kernel = [gaussian_1d(s, truncated=self.truncated, approx=self.approx) for s in self.sigma] + return separable_filtering(x=x, kernels=_kernel) + + +class LLTMFunction(Function): + + @staticmethod + def forward(ctx, input, weights, bias, old_h, old_cell): + outputs = _C.lltm_forward(input, weights, bias, old_h, old_cell) + new_h, new_cell = outputs[:2] + variables = outputs[1:] + [weights] + ctx.save_for_backward(*variables) + + return new_h, new_cell + + @staticmethod + def backward(ctx, grad_h, grad_cell): + outputs = _C.lltm_backward(grad_h.contiguous(), grad_cell.contiguous(), *ctx.saved_tensors) + d_old_h, d_input, d_weights, d_bias, d_old_cell = outputs[:5] + + return d_input, d_weights, d_bias, d_old_h, d_old_cell + + +class LLTM(nn.Module): + """ + This recurrent unit is similar to an LSTM, but differs in that it lacks a forget + gate and uses an Exponential Linear Unit (ELU) as its internal activation function. + Because this unit never forgets, call it LLTM, or Long-Long-Term-Memory unit. + It has both C++ and CUDA implementation, automatically switch according to the + target device where put this module to. + + Args: + input_features: size of input feature data + state_size: size of the state of recurrent unit + + Referring to: https://pytorch.org/tutorials/advanced/cpp_extension.html + """ + + def __init__(self, input_features: int, state_size: int): + super().__init__() + self.input_features = input_features + self.state_size = state_size + self.weights = nn.Parameter(torch.empty(3 * state_size, input_features + state_size)) + self.bias = nn.Parameter(torch.empty(1, 3 * state_size)) + self.reset_parameters() + + def reset_parameters(self): + stdv = 1.0 / math.sqrt(self.state_size) + for weight in self.parameters(): + weight.data.uniform_(-stdv, +stdv) + + def forward(self, input, state): + return LLTMFunction.apply(input, self.weights, self.bias, *state) + + +class ApplyFilter(nn.Module): + "Wrapper class to apply a filter to an image." + + def __init__(self, filter: NdarrayOrTensor) -> None: + super().__init__() + + self.filter = convert_to_tensor(filter, dtype=torch.float32) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + return apply_filter(x, self.filter) + + +class MeanFilter(ApplyFilter): + """ + Mean filtering can smooth edges and remove aliasing artifacts in an segmentation image. + The mean filter used, is a `torch.Tensor` of all ones. + """ + + def __init__(self, spatial_dims: int, size: int) -> None: + """ + Args: + spatial_dims: `int` of either 2 for 2D images and 3 for 3D images + size: edge length of the filter + """ + filter = torch.ones([size] * spatial_dims) + filter = filter + super().__init__(filter=filter) + + +class LaplaceFilter(ApplyFilter): + """ + Laplacian filtering for outline detection in images. Can be used to transform labels to contours. + The laplace filter used, is a `torch.Tensor` where all values are -1, except the center value + which is `size` ** `spatial_dims` + """ + + def __init__(self, spatial_dims: int, size: int) -> None: + """ + Args: + spatial_dims: `int` of either 2 for 2D images and 3 for 3D images + size: edge length of the filter + """ + filter = torch.zeros([size] * spatial_dims).float() - 1 # make all -1 + center_point = tuple([size // 2] * spatial_dims) + filter[center_point] = (size**spatial_dims) - 1 + super().__init__(filter=filter) + + +class EllipticalFilter(ApplyFilter): + """ + Elliptical filter, can be used to dilate labels or label-contours. + The elliptical filter used here, is a `torch.Tensor` with shape (size, ) * ndim containing a circle/sphere of `1` + """ + + def __init__(self, spatial_dims: int, size: int) -> None: + """ + Args: + spatial_dims: `int` of either 2 for 2D images and 3 for 3D images + size: edge length of the filter + """ + radius = size // 2 + grid = torch.meshgrid(*[torch.arange(0, size) for _ in range(spatial_dims)]) + squared_distances = torch.stack([(axis - radius) ** 2 for axis in grid], 0).sum(0) + filter = squared_distances <= radius**2 + super().__init__(filter=filter) + + +class SharpenFilter(EllipticalFilter): + """ + Convolutional filter to sharpen a 2D or 3D image. + The filter used contains a circle/sphere of `-1`, with the center value being + the absolute sum of all non-zero elements in the kernel + """ + + def __init__(self, spatial_dims: int, size: int) -> None: + """ + Args: + spatial_dims: `int` of either 2 for 2D images and 3 for 3D images + size: edge length of the filter + """ + super().__init__(spatial_dims=spatial_dims, size=size) + center_point = tuple([size // 2] * spatial_dims) + center_value = self.filter.sum() + self.filter *= -1 + self.filter[center_point] = center_value diff --git a/source_code/SegMamba/monai/networks/layers/utils.py b/source_code/SegMamba/monai/networks/layers/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..ace1af27b6230ee4afc51f010c3ec826ae437f68 --- /dev/null +++ b/source_code/SegMamba/monai/networks/layers/utils.py @@ -0,0 +1,126 @@ +# Copyright (c) MONAI Consortium +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from __future__ import annotations + +import torch.nn + +from monai.networks.layers.factories import Act, Dropout, Norm, Pool, split_args +from monai.utils import has_option + +__all__ = ["get_norm_layer", "get_act_layer", "get_dropout_layer", "get_pool_layer"] + + +def get_norm_layer(name: tuple | str, spatial_dims: int | None = 1, channels: int | None = 1): + """ + Create a normalization layer instance. + + For example, to create normalization layers: + + .. code-block:: python + + from monai.networks.layers import get_norm_layer + + g_layer = get_norm_layer(name=("group", {"num_groups": 1})) + n_layer = get_norm_layer(name="instance", spatial_dims=2) + + Args: + name: a normalization type string or a tuple of type string and parameters. + spatial_dims: number of spatial dimensions of the input. + channels: number of features/channels when the normalization layer requires this parameter + but it is not specified in the norm parameters. + """ + if name == "": + return torch.nn.Identity() + norm_name, norm_args = split_args(name) + norm_type = Norm[norm_name, spatial_dims] + kw_args = dict(norm_args) + if has_option(norm_type, "num_features") and "num_features" not in kw_args: + kw_args["num_features"] = channels + if has_option(norm_type, "num_channels") and "num_channels" not in kw_args: + kw_args["num_channels"] = channels + return norm_type(**kw_args) + + +def get_act_layer(name: tuple | str): + """ + Create an activation layer instance. + + For example, to create activation layers: + + .. code-block:: python + + from monai.networks.layers import get_act_layer + + s_layer = get_act_layer(name="swish") + p_layer = get_act_layer(name=("prelu", {"num_parameters": 1, "init": 0.25})) + + Args: + name: an activation type string or a tuple of type string and parameters. + """ + if name == "": + return torch.nn.Identity() + act_name, act_args = split_args(name) + act_type = Act[act_name] + return act_type(**act_args) + + +def get_dropout_layer(name: tuple | str | float | int, dropout_dim: int | None = 1): + """ + Create a dropout layer instance. + + For example, to create dropout layers: + + .. code-block:: python + + from monai.networks.layers import get_dropout_layer + + d_layer = get_dropout_layer(name="dropout") + a_layer = get_dropout_layer(name=("alphadropout", {"p": 0.25})) + + Args: + name: a dropout ratio or a tuple of dropout type and parameters. + dropout_dim: the spatial dimension of the dropout operation. + """ + if name == "": + return torch.nn.Identity() + if isinstance(name, (int, float)): + # if dropout was specified simply as a p value, use default name and make a keyword map with the value + drop_name = Dropout.DROPOUT + drop_args = {"p": float(name)} + else: + drop_name, drop_args = split_args(name) + drop_type = Dropout[drop_name, dropout_dim] + return drop_type(**drop_args) + + +def get_pool_layer(name: tuple | str, spatial_dims: int | None = 1): + """ + Create a pooling layer instance. + + For example, to create adaptiveavg layer: + + .. code-block:: python + + from monai.networks.layers import get_pool_layer + + pool_layer = get_pool_layer(("adaptiveavg", {"output_size": (1, 1, 1)}), spatial_dims=3) + + Args: + name: a pooling type string or a tuple of type string and parameters. + spatial_dims: number of spatial dimensions of the input. + + """ + if name == "": + return torch.nn.Identity() + pool_name, pool_args = split_args(name) + pool_type = Pool[pool_name, spatial_dims] + return pool_type(**pool_args) diff --git a/source_code/SegMamba/monai/networks/nets/ahnet.py b/source_code/SegMamba/monai/networks/nets/ahnet.py new file mode 100644 index 0000000000000000000000000000000000000000..5e280d7f249064c1c3c979f0d533523f63e104ca --- /dev/null +++ b/source_code/SegMamba/monai/networks/nets/ahnet.py @@ -0,0 +1,547 @@ +# Copyright (c) MONAI Consortium +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from __future__ import annotations + +import math +from collections.abc import Sequence +from typing import Union + +import torch +import torch.nn as nn +import torch.nn.functional as F + +from monai.networks.blocks.fcn import FCN +from monai.networks.layers.factories import Act, Conv, Norm, Pool + +__all__ = ["AHnet", "Ahnet", "AHNet"] + + +class Bottleneck3x3x1(nn.Module): + expansion = 4 + + def __init__( + self, + spatial_dims: int, + inplanes: int, + planes: int, + stride: Sequence[int] | int = 1, + downsample: nn.Sequential | None = None, + ) -> None: + super().__init__() + + conv_type = Conv[Conv.CONV, spatial_dims] + norm_type: type[nn.BatchNorm2d | nn.BatchNorm3d] = Norm[Norm.BATCH, spatial_dims] + pool_type: type[nn.MaxPool2d | nn.MaxPool3d] = Pool[Pool.MAX, spatial_dims] + relu_type: type[nn.ReLU] = Act[Act.RELU] + + self.conv1 = conv_type(inplanes, planes, kernel_size=1, bias=False) + self.bn1 = norm_type(planes) + self.conv2 = conv_type( + planes, + planes, + kernel_size=(3, 3, 1)[-spatial_dims:], + stride=stride, + padding=(1, 1, 0)[-spatial_dims:], + bias=False, + ) + self.bn2 = norm_type(planes) + self.conv3 = conv_type(planes, planes * 4, kernel_size=1, bias=False) + self.bn3 = norm_type(planes * 4) + self.relu = relu_type(inplace=True) + self.downsample = downsample + self.stride = stride + self.pool = pool_type(kernel_size=(1, 1, 2)[-spatial_dims:], stride=(1, 1, 2)[-spatial_dims:]) + + def forward(self, x): + residual = x + + out = self.conv1(x) + out = self.bn1(out) + out = self.relu(out) + + out = self.conv2(out) + out = self.bn2(out) + out = self.relu(out) + + out = self.conv3(out) + out = self.bn3(out) + + if self.downsample is not None: + residual = self.downsample(x) + if out.size() != residual.size(): + out = self.pool(out) + + out += residual + out = self.relu(out) + + return out + + +class Projection(nn.Sequential): + + def __init__(self, spatial_dims: int, num_input_features: int, num_output_features: int): + super().__init__() + + conv_type = Conv[Conv.CONV, spatial_dims] + norm_type: type[nn.BatchNorm2d | nn.BatchNorm3d] = Norm[Norm.BATCH, spatial_dims] + relu_type: type[nn.ReLU] = Act[Act.RELU] + + self.add_module("norm", norm_type(num_input_features)) + self.add_module("relu", relu_type(inplace=True)) + self.add_module("conv", conv_type(num_input_features, num_output_features, kernel_size=1, stride=1, bias=False)) + + +class DenseBlock(nn.Sequential): + + def __init__( + self, + spatial_dims: int, + num_layers: int, + num_input_features: int, + bn_size: int, + growth_rate: int, + dropout_prob: float, + ): + super().__init__() + for i in range(num_layers): + layer = Pseudo3DLayer( + spatial_dims, num_input_features + i * growth_rate, growth_rate, bn_size, dropout_prob + ) + self.add_module("denselayer%d" % (i + 1), layer) + + +class UpTransition(nn.Sequential): + + def __init__( + self, spatial_dims: int, num_input_features: int, num_output_features: int, upsample_mode: str = "transpose" + ): + super().__init__() + + conv_type = Conv[Conv.CONV, spatial_dims] + norm_type: type[nn.BatchNorm2d | nn.BatchNorm3d] = Norm[Norm.BATCH, spatial_dims] + relu_type: type[nn.ReLU] = Act[Act.RELU] + + self.add_module("norm", norm_type(num_input_features)) + self.add_module("relu", relu_type(inplace=True)) + self.add_module("conv", conv_type(num_input_features, num_output_features, kernel_size=1, stride=1, bias=False)) + if upsample_mode == "transpose": + conv_trans_type = Conv[Conv.CONVTRANS, spatial_dims] + self.add_module( + "up", conv_trans_type(num_output_features, num_output_features, kernel_size=2, stride=2, bias=False) + ) + else: + align_corners: bool | None = None + if upsample_mode in ["trilinear", "bilinear"]: + align_corners = True + self.add_module("up", nn.Upsample(scale_factor=2, mode=upsample_mode, align_corners=align_corners)) + + +class Final(nn.Sequential): + + def __init__( + self, spatial_dims: int, num_input_features: int, num_output_features: int, upsample_mode: str = "transpose" + ): + super().__init__() + + conv_type = Conv[Conv.CONV, spatial_dims] + norm_type: type[nn.BatchNorm2d | nn.BatchNorm3d] = Norm[Norm.BATCH, spatial_dims] + relu_type: type[nn.ReLU] = Act[Act.RELU] + + self.add_module("norm", norm_type(num_input_features)) + self.add_module("relu", relu_type(inplace=True)) + self.add_module( + "conv", + conv_type( + num_input_features, + num_output_features, + kernel_size=(3, 3, 1)[-spatial_dims:], + stride=1, + padding=(1, 1, 0)[-spatial_dims:], + bias=False, + ), + ) + if upsample_mode == "transpose": + conv_trans_type = Conv[Conv.CONVTRANS, spatial_dims] + self.add_module( + "up", conv_trans_type(num_output_features, num_output_features, kernel_size=2, stride=2, bias=False) + ) + else: + align_corners: bool | None = None + if upsample_mode in ["trilinear", "bilinear"]: + align_corners = True + self.add_module("up", nn.Upsample(scale_factor=2, mode=upsample_mode, align_corners=align_corners)) + + +class Pseudo3DLayer(nn.Module): + + def __init__(self, spatial_dims: int, num_input_features: int, growth_rate: int, bn_size: int, dropout_prob: float): + super().__init__() + # 1x1x1 + + conv_type = Conv[Conv.CONV, spatial_dims] + norm_type: type[nn.BatchNorm2d | nn.BatchNorm3d] = Norm[Norm.BATCH, spatial_dims] + relu_type: type[nn.ReLU] = Act[Act.RELU] + + self.bn1 = norm_type(num_input_features) + self.relu1 = relu_type(inplace=True) + self.conv1 = conv_type(num_input_features, bn_size * growth_rate, kernel_size=1, stride=1, bias=False) + # 3x3x1 + self.bn2 = norm_type(bn_size * growth_rate) + self.relu2 = relu_type(inplace=True) + self.conv2 = conv_type( + bn_size * growth_rate, + growth_rate, + kernel_size=(3, 3, 1)[-spatial_dims:], + stride=1, + padding=(1, 1, 0)[-spatial_dims:], + bias=False, + ) + # 1x1x3 + self.bn3 = norm_type(growth_rate) + self.relu3 = relu_type(inplace=True) + self.conv3 = conv_type( + growth_rate, + growth_rate, + kernel_size=(1, 1, 3)[-spatial_dims:], + stride=1, + padding=(0, 0, 1)[-spatial_dims:], + bias=False, + ) + # 1x1x1 + self.bn4 = norm_type(growth_rate) + self.relu4 = relu_type(inplace=True) + self.conv4 = conv_type(growth_rate, growth_rate, kernel_size=1, stride=1, bias=False) + self.dropout_prob = dropout_prob + + def forward(self, x): + inx = x + x = self.bn1(x) + x = self.relu1(x) + x = self.conv1(x) + + x = self.bn2(x) + x = self.relu2(x) + x3x3x1 = self.conv2(x) + + x = self.bn3(x3x3x1) + x = self.relu3(x) + x1x1x3 = self.conv3(x) + + x = x3x3x1 + x1x1x3 + x = self.bn4(x) + x = self.relu4(x) + new_features = self.conv4(x) + + self.dropout_prob = 0.0 # Dropout will make trouble! + # since we use the train mode for inference + if self.dropout_prob > 0.0: + new_features = F.dropout(new_features, p=self.dropout_prob, training=self.training) + return torch.cat([inx, new_features], 1) + + +class PSP(nn.Module): + + def __init__(self, spatial_dims: int, psp_block_num: int, in_ch: int, upsample_mode: str = "transpose"): + super().__init__() + self.up_modules = nn.ModuleList() + conv_type = Conv[Conv.CONV, spatial_dims] + pool_type: type[nn.MaxPool2d | nn.MaxPool3d] = Pool[Pool.MAX, spatial_dims] + + self.pool_modules = nn.ModuleList() + self.project_modules = nn.ModuleList() + + for i in range(psp_block_num): + 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:]) + ) + + self.spatial_dims = spatial_dims + self.psp_block_num = psp_block_num + self.upsample_mode = upsample_mode + + if self.upsample_mode == "transpose": + conv_trans_type = Conv[Conv.CONVTRANS, spatial_dims] + 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)) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + outputs = [] + if self.upsample_mode == "transpose": + for project_module, pool_module, up_module in zip(self.project_modules, self.pool_modules, self.up_modules): + output = up_module(project_module(pool_module(x))) + outputs.append(output) + else: + for project_module, pool_module in zip(self.project_modules, self.pool_modules): + interpolate_size = x.shape[2:] + align_corners: Union[bool, None] = None + if self.upsample_mode in ["trilinear", "bilinear"]: + align_corners = True + output = F.interpolate( + project_module(pool_module(x)), + size=interpolate_size, + mode=self.upsample_mode, + align_corners=align_corners, + ) + outputs.append(output) + x = torch.cat(outputs, dim=1) + return x + + +class AHNet(nn.Module): + """ + AHNet based on `Anisotropic Hybrid Network `_. + Adapted from `lsqshr's official code `_. + Except from the original network that supports 3D inputs, this implementation also supports 2D inputs. + According to the `tests for deconvolutions `_, using + ``"transpose"`` rather than linear interpolations is faster. Therefore, this implementation sets ``"transpose"`` + as the default upsampling method. + + To meet the requirements of the structure, the input size for each spatial dimension + (except the last one) should be: divisible by 2 ** (psp_block_num + 3) and no less than 32 in ``transpose`` mode, + and should be divisible by 32 and no less than 2 ** (psp_block_num + 3) in other upsample modes. + In addition, the input size for the last spatial dimension should be divisible by 32, and at least one spatial size + should be no less than 64. + + Args: + layers: number of residual blocks for 4 layers of the network (layer1...layer4). Defaults to ``(3, 4, 6, 3)``. + spatial_dims: spatial dimension of the input data. Defaults to 3. + in_channels: number of input channels for the network. Default to 1. + out_channels: number of output channels for the network. Defaults to 1. + psp_block_num: the number of pyramid volumetric pooling modules used at the end of the network before the final + output layer for extracting multiscale features. The number should be an integer that belongs to [0,4]. Defaults + to 4. + upsample_mode: [``"transpose"``, ``"bilinear"``, ``"trilinear"``, ``nearest``] + The mode of upsampling manipulations. + Using the last two modes cannot guarantee the model's reproducibility. Defaults to ``transpose``. + + - ``"transpose"``, uses transposed convolution layers. + - ``"bilinear"``, uses bilinear interpolate. + - ``"trilinear"``, uses trilinear interpolate. + - ``"nearest"``, uses nearest interpolate. + pretrained: whether to load pretrained weights from ResNet50 to initialize convolution layers, default to False. + progress: If True, displays a progress bar of the download of pretrained weights to stderr. + """ + + def __init__( + self, + layers: tuple = (3, 4, 6, 3), + spatial_dims: int = 3, + in_channels: int = 1, + out_channels: int = 1, + psp_block_num: int = 4, + upsample_mode: str = "transpose", + pretrained: bool = False, + progress: bool = True, + ): + self.inplanes = 64 + super().__init__() + + conv_type = Conv[Conv.CONV, spatial_dims] + conv_trans_type = Conv[Conv.CONVTRANS, spatial_dims] + norm_type = Norm[Norm.BATCH, spatial_dims] + pool_type: type[nn.MaxPool2d | nn.MaxPool3d] = Pool[Pool.MAX, spatial_dims] + relu_type: type[nn.ReLU] = Act[Act.RELU] + conv2d_type: type[nn.Conv2d] = Conv[Conv.CONV, 2] + norm2d_type: type[nn.BatchNorm2d] = Norm[Norm.BATCH, 2] + + self.conv2d_type = conv2d_type + self.norm2d_type = norm2d_type + self.conv_type = conv_type + self.norm_type = norm_type + self.relu_type = relu_type + self.pool_type = pool_type + self.spatial_dims = spatial_dims + self.psp_block_num = psp_block_num + self.psp: PSP + + if spatial_dims not in [2, 3]: + raise AssertionError("spatial_dims can only be 2 or 3.") + if psp_block_num not in [0, 1, 2, 3, 4]: + raise AssertionError("psp_block_num should be an integer that belongs to [0, 4].") + + self.conv1 = conv_type( + in_channels, + 64, + kernel_size=(7, 7, 3)[-spatial_dims:], + stride=(2, 2, 1)[-spatial_dims:], + padding=(3, 3, 1)[-spatial_dims:], + bias=False, + ) + self.pool1 = pool_type(kernel_size=(1, 1, 2)[-spatial_dims:], stride=(1, 1, 2)[-spatial_dims:]) + self.bn0 = norm_type(64) + self.relu = relu_type(inplace=True) + if upsample_mode in ["transpose", "nearest"]: + # To maintain the determinism, the value of kernel_size and stride should be the same. + # (you can check this link for reference: https://github.com/Project-MONAI/MONAI/pull/815 ) + self.maxpool = pool_type(kernel_size=(2, 2, 2)[-spatial_dims:], stride=2) + else: + self.maxpool = pool_type(kernel_size=(3, 3, 3)[-spatial_dims:], stride=2, padding=1) + + self.layer1 = self._make_layer(Bottleneck3x3x1, 64, layers[0], stride=1) + self.layer2 = self._make_layer(Bottleneck3x3x1, 128, layers[1], stride=2) + self.layer3 = self._make_layer(Bottleneck3x3x1, 256, layers[2], stride=2) + self.layer4 = self._make_layer(Bottleneck3x3x1, 512, layers[3], stride=2) + + # Make the 3D dense decoder layers + densegrowth = 20 + densebn = 4 + ndenselayer = 3 + + num_init_features = 64 + noutres1 = 256 + noutres2 = 512 + noutres3 = 1024 + noutres4 = 2048 + + self.up0 = UpTransition(spatial_dims, noutres4, noutres3, upsample_mode) + self.dense0 = DenseBlock(spatial_dims, ndenselayer, noutres3, densebn, densegrowth, 0.0) + noutdense = noutres3 + ndenselayer * densegrowth + + self.up1 = UpTransition(spatial_dims, noutdense, noutres2, upsample_mode) + self.dense1 = DenseBlock(spatial_dims, ndenselayer, noutres2, densebn, densegrowth, 0.0) + noutdense1 = noutres2 + ndenselayer * densegrowth + + self.up2 = UpTransition(spatial_dims, noutdense1, noutres1, upsample_mode) + self.dense2 = DenseBlock(spatial_dims, ndenselayer, noutres1, densebn, densegrowth, 0.0) + noutdense2 = noutres1 + ndenselayer * densegrowth + + self.trans1 = Projection(spatial_dims, noutdense2, num_init_features) + self.dense3 = DenseBlock(spatial_dims, ndenselayer, num_init_features, densebn, densegrowth, 0.0) + noutdense3 = num_init_features + densegrowth * ndenselayer + + self.up3 = UpTransition(spatial_dims, noutdense3, num_init_features, upsample_mode) + self.dense4 = DenseBlock(spatial_dims, ndenselayer, num_init_features, densebn, densegrowth, 0.0) + noutdense4 = num_init_features + densegrowth * ndenselayer + + self.psp = PSP(spatial_dims, psp_block_num, noutdense4, upsample_mode) + self.final = Final(spatial_dims, psp_block_num + noutdense4, out_channels, upsample_mode) + + # Initialise parameters + for m in self.modules(): + if isinstance(m, (conv_type, conv_trans_type)): + n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels + m.weight.data.normal_(0, math.sqrt(2.0 / n)) + elif isinstance(m, norm_type): + m.weight.data.fill_(1) + m.bias.data.zero_() + + if pretrained: + 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: + downsample = None + if stride != 1 or self.inplanes != planes * block.expansion: + downsample = nn.Sequential( + self.conv_type( + self.inplanes, + planes * block.expansion, + kernel_size=1, + stride=(stride, stride, 1)[: self.spatial_dims], + bias=False, + ), + self.pool_type( + kernel_size=(1, 1, stride)[: self.spatial_dims], stride=(1, 1, stride)[: self.spatial_dims] + ), + self.norm_type(planes * block.expansion), + ) + + layers = [] + layers.append( + block(self.spatial_dims, self.inplanes, planes, (stride, stride, 1)[: self.spatial_dims], downsample) + ) + self.inplanes = planes * block.expansion + for _ in range(1, blocks): + layers.append(block(self.spatial_dims, self.inplanes, planes)) + return nn.Sequential(*layers) + + def forward(self, x): + x = self.conv1(x) + x = self.pool1(x) + x = self.bn0(x) + x = self.relu(x) + conv_x = x + x = self.maxpool(x) + pool_x = x + + fm1 = self.layer1(x) + fm2 = self.layer2(fm1) + fm3 = self.layer3(fm2) + fm4 = self.layer4(fm3) + + sum0 = self.up0(fm4) + fm3 + d0 = self.dense0(sum0) + + sum1 = self.up1(d0) + fm2 + d1 = self.dense1(sum1) + + sum2 = self.up2(d1) + fm1 + d2 = self.dense2(sum2) + + sum3 = self.trans1(d2) + pool_x + d3 = self.dense3(sum3) + + sum4 = self.up3(d3) + conv_x + d4 = self.dense4(sum4) + if self.psp_block_num > 0: + psp = self.psp(d4) + x = torch.cat((psp, d4), dim=1) + else: + x = d4 + return self.final(x) + + def copy_from(self, net): + # This method only supports for 3D AHNet, the input channel should be 1. + p2d, p3d = next(net.conv1.parameters()), next(self.conv1.parameters()) + + # From 64x3x7x7 -> 64x3x7x7x1 -> 64x1x7x7x3 + weights = p2d.data.unsqueeze(dim=4).permute(0, 4, 2, 3, 1).clone() + p3d.data = weights.repeat([1, p3d.shape[1], 1, 1, 1]) + + # Copy the initial module BN0 + copy_bn_param(net.bn0, self.bn0) + + # Copy layer1 to layer4 + for i in range(1, 5): + layer_num = "layer" + str(i) + + layer_2d = [] + layer_3d = [] + for m1 in vars(net)["_modules"][layer_num].modules(): + if isinstance(m1, (self.norm2d_type, self.conv2d_type)): + layer_2d.append(m1) + for m2 in vars(self)["_modules"][layer_num].modules(): + if isinstance(m2, (self.norm_type, self.conv_type)): + layer_3d.append(m2) + + for m1, m2 in zip(layer_2d, layer_3d): + if isinstance(m1, self.conv2d_type): + copy_conv_param(m1, m2) + if isinstance(m1, self.norm2d_type): + copy_bn_param(m1, m2) + + +def copy_conv_param(module2d, module3d): + for p2d, p3d in zip(module2d.parameters(), module3d.parameters()): + p3d.data[:] = p2d.data.unsqueeze(dim=4).clone()[:] + + +def copy_bn_param(module2d, module3d): + for p2d, p3d in zip(module2d.parameters(), module3d.parameters()): + p3d.data[:] = p2d.data[:] # Two parameter gamma and beta + + +AHnet = Ahnet = AHNet diff --git a/source_code/SegMamba/monai/networks/nets/attentionunet.py b/source_code/SegMamba/monai/networks/nets/attentionunet.py new file mode 100644 index 0000000000000000000000000000000000000000..fdf31d9701da443d25a8d1ce6dfff5fb0f69f6a5 --- /dev/null +++ b/source_code/SegMamba/monai/networks/nets/attentionunet.py @@ -0,0 +1,290 @@ +# Copyright (c) MONAI Consortium +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from __future__ import annotations + +from collections.abc import Sequence + +import torch +import torch.nn as nn + +from monai.networks.blocks.convolutions import Convolution +from monai.networks.layers.factories import Norm + +__all__ = ["AttentionUnet"] + + +class ConvBlock(nn.Module): + + def __init__( + self, + spatial_dims: int, + in_channels: int, + out_channels: int, + kernel_size: Sequence[int] | int = 3, + strides: int = 1, + dropout=0.0, + ): + super().__init__() + layers = [ + Convolution( + spatial_dims=spatial_dims, + in_channels=in_channels, + out_channels=out_channels, + kernel_size=kernel_size, + strides=strides, + padding=None, + adn_ordering="NDA", + act="relu", + norm=Norm.BATCH, + dropout=dropout, + ), + Convolution( + spatial_dims=spatial_dims, + in_channels=out_channels, + out_channels=out_channels, + kernel_size=kernel_size, + strides=1, + padding=None, + adn_ordering="NDA", + act="relu", + norm=Norm.BATCH, + dropout=dropout, + ), + ] + self.conv = nn.Sequential(*layers) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + x_c: torch.Tensor = self.conv(x) + return x_c + + +class UpConv(nn.Module): + + def __init__(self, spatial_dims: int, in_channels: int, out_channels: int, kernel_size=3, strides=2, dropout=0.0): + super().__init__() + self.up = Convolution( + spatial_dims, + in_channels, + out_channels, + strides=strides, + kernel_size=kernel_size, + act="relu", + adn_ordering="NDA", + norm=Norm.BATCH, + dropout=dropout, + is_transposed=True, + ) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + x_u: torch.Tensor = self.up(x) + return x_u + + +class AttentionBlock(nn.Module): + + def __init__(self, spatial_dims: int, f_int: int, f_g: int, f_l: int, dropout=0.0): + super().__init__() + self.W_g = nn.Sequential( + Convolution( + spatial_dims=spatial_dims, + in_channels=f_g, + out_channels=f_int, + kernel_size=1, + strides=1, + padding=0, + dropout=dropout, + conv_only=True, + ), + Norm[Norm.BATCH, spatial_dims](f_int), + ) + + self.W_x = nn.Sequential( + Convolution( + spatial_dims=spatial_dims, + in_channels=f_l, + out_channels=f_int, + kernel_size=1, + strides=1, + padding=0, + dropout=dropout, + conv_only=True, + ), + Norm[Norm.BATCH, spatial_dims](f_int), + ) + + self.psi = nn.Sequential( + Convolution( + spatial_dims=spatial_dims, + in_channels=f_int, + out_channels=1, + kernel_size=1, + strides=1, + padding=0, + dropout=dropout, + conv_only=True, + ), + Norm[Norm.BATCH, spatial_dims](1), + nn.Sigmoid(), + ) + + self.relu = nn.ReLU() + + def forward(self, g: torch.Tensor, x: torch.Tensor) -> torch.Tensor: + g1 = self.W_g(g) + x1 = self.W_x(x) + psi: torch.Tensor = self.relu(g1 + x1) + psi = self.psi(psi) + + return x * psi + + +class AttentionLayer(nn.Module): + + def __init__( + self, + spatial_dims: int, + in_channels: int, + out_channels: int, + submodule: nn.Module, + up_kernel_size=3, + strides=2, + dropout=0.0, + ): + super().__init__() + self.attention = AttentionBlock( + spatial_dims=spatial_dims, f_g=in_channels, f_l=in_channels, f_int=in_channels // 2 + ) + self.upconv = UpConv( + spatial_dims=spatial_dims, + in_channels=out_channels, + out_channels=in_channels, + strides=strides, + kernel_size=up_kernel_size, + ) + self.merge = Convolution( + spatial_dims=spatial_dims, in_channels=2 * in_channels, out_channels=in_channels, dropout=dropout + ) + self.submodule = submodule + + def forward(self, x: torch.Tensor) -> torch.Tensor: + fromlower = self.upconv(self.submodule(x)) + att = self.attention(g=fromlower, x=x) + att_m: torch.Tensor = self.merge(torch.cat((att, fromlower), dim=1)) + return att_m + + +class AttentionUnet(nn.Module): + """ + Attention Unet based on + Otkay et al. "Attention U-Net: Learning Where to Look for the Pancreas" + https://arxiv.org/abs/1804.03999 + + Args: + spatial_dims: number of spatial dimensions of the input image. + in_channels: number of the input channel. + out_channels: number of the output classes. + channels (Sequence[int]): sequence of channels. Top block first. The length of `channels` should be no less than 2. + strides (Sequence[int]): stride to use for convolutions. + kernel_size: convolution kernel size. + up_kernel_size: convolution kernel size for transposed convolution layers. + dropout: dropout ratio. Defaults to no dropout. + """ + + def __init__( + self, + spatial_dims: int, + in_channels: int, + out_channels: int, + channels: Sequence[int], + strides: Sequence[int], + kernel_size: Sequence[int] | int = 3, + up_kernel_size: Sequence[int] | int = 3, + dropout: float = 0.0, + ): + super().__init__() + self.dimensions = spatial_dims + self.in_channels = in_channels + self.out_channels = out_channels + self.channels = channels + self.strides = strides + self.kernel_size = kernel_size + self.dropout = dropout + + head = ConvBlock( + spatial_dims=spatial_dims, + in_channels=in_channels, + out_channels=channels[0], + dropout=dropout, + kernel_size=self.kernel_size, + ) + reduce_channels = Convolution( + spatial_dims=spatial_dims, + in_channels=channels[0], + out_channels=out_channels, + kernel_size=1, + strides=1, + padding=0, + conv_only=True, + ) + self.up_kernel_size = up_kernel_size + + def _create_block(channels: Sequence[int], strides: Sequence[int]) -> nn.Module: + if len(channels) > 2: + subblock = _create_block(channels[1:], strides[1:]) + return AttentionLayer( + spatial_dims=spatial_dims, + in_channels=channels[0], + out_channels=channels[1], + submodule=nn.Sequential( + ConvBlock( + spatial_dims=spatial_dims, + in_channels=channels[0], + out_channels=channels[1], + strides=strides[0], + dropout=self.dropout, + kernel_size=self.kernel_size, + ), + subblock, + ), + up_kernel_size=self.up_kernel_size, + strides=strides[0], + dropout=dropout, + ) + else: + # the next layer is the bottom so stop recursion, + # create the bottom layer as the subblock for this layer + return self._get_bottom_layer(channels[0], channels[1], strides[0]) + + encdec = _create_block(self.channels, self.strides) + self.model = nn.Sequential(head, encdec, reduce_channels) + + def _get_bottom_layer(self, in_channels: int, out_channels: int, strides: int) -> nn.Module: + return AttentionLayer( + spatial_dims=self.dimensions, + in_channels=in_channels, + out_channels=out_channels, + submodule=ConvBlock( + spatial_dims=self.dimensions, + in_channels=in_channels, + out_channels=out_channels, + strides=strides, + dropout=self.dropout, + kernel_size=self.kernel_size, + ), + up_kernel_size=self.up_kernel_size, + strides=strides, + dropout=self.dropout, + ) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + x_m: torch.Tensor = self.model(x) + return x_m diff --git a/source_code/SegMamba/monai/networks/nets/dints.py b/source_code/SegMamba/monai/networks/nets/dints.py new file mode 100644 index 0000000000000000000000000000000000000000..129e0925d3ec774740a9881d733d9c66101c4864 --- /dev/null +++ b/source_code/SegMamba/monai/networks/nets/dints.py @@ -0,0 +1,1047 @@ +# Copyright (c) MONAI Consortium +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from __future__ import annotations + +import datetime +import warnings +from typing import Optional + +import numpy as np +import torch +import torch.nn as nn +import torch.nn.functional as F + +from monai.networks.blocks.dints_block import ( + ActiConvNormBlock, + FactorizedIncreaseBlock, + FactorizedReduceBlock, + P3DActiConvNormBlock, +) +from monai.networks.layers.factories import Conv +from monai.networks.layers.utils import get_act_layer, get_norm_layer +from monai.utils import optional_import + +# solving shortest path problem +csr_matrix, _ = optional_import("scipy.sparse", name="csr_matrix") +dijkstra, _ = optional_import("scipy.sparse.csgraph", name="dijkstra") + +__all__ = ["DiNTS", "TopologyConstruction", "TopologyInstance", "TopologySearch"] + + +@torch.jit.interface +class CellInterface(torch.nn.Module): + """interface for torchscriptable Cell""" + + def forward(self, x: torch.Tensor, weight: Optional[torch.Tensor]) -> torch.Tensor: # type: ignore + pass + + +@torch.jit.interface +class StemInterface(torch.nn.Module): + """interface for torchscriptable Stem""" + + def forward(self, x: torch.Tensor) -> torch.Tensor: # type: ignore + pass + + +class StemTS(StemInterface): + """wrapper for torchscriptable Stem""" + + def __init__(self, *mod): + super().__init__() + self.mod = torch.nn.Sequential(*mod) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + return self.mod(x) # type: ignore + + +def _dfs(node, paths): + """use depth first search to find all path activation combination""" + if node == paths: + return [[0], [1]] + child = _dfs(node + 1, paths) + return [[0] + _ for _ in child] + [[1] + _ for _ in child] + + +class _IdentityWithRAMCost(nn.Identity): + + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + self.ram_cost = 0 + + +class _ActiConvNormBlockWithRAMCost(ActiConvNormBlock): + """The class wraps monai layers with ram estimation. The ram_cost = total_ram/output_size is estimated. + Here is the estimation: + feature_size = output_size/out_channel + total_ram = ram_cost * output_size + total_ram = in_channel * feature_size (activation map) + + in_channel * feature_size (convolution map) + + out_channel * feature_size (normalization) + = (2*in_channel + out_channel) * output_size/out_channel + ram_cost = total_ram/output_size = 2 * in_channel/out_channel + 1 + """ + + def __init__( + self, + in_channel: int, + out_channel: int, + kernel_size: int, + padding: int, + spatial_dims: int = 3, + act_name: tuple | str = "RELU", + norm_name: tuple | str = ("INSTANCE", {"affine": True}), + ): + super().__init__(in_channel, out_channel, kernel_size, padding, spatial_dims, act_name, norm_name) + self.ram_cost = 1 + in_channel / out_channel * 2 + + +class _P3DActiConvNormBlockWithRAMCost(P3DActiConvNormBlock): + + def __init__( + self, + in_channel: int, + out_channel: int, + kernel_size: int, + padding: int, + p3dmode: int = 0, + act_name: tuple | str = "RELU", + norm_name: tuple | str = ("INSTANCE", {"affine": True}), + ): + super().__init__(in_channel, out_channel, kernel_size, padding, p3dmode, act_name, norm_name) + # 1 in_channel (activation) + 1 in_channel (convolution) + + # 1 out_channel (convolution) + 1 out_channel (normalization) + self.ram_cost = 2 + 2 * in_channel / out_channel + + +class _FactorizedIncreaseBlockWithRAMCost(FactorizedIncreaseBlock): + + def __init__( + self, + in_channel: int, + out_channel: int, + spatial_dims: int = 3, + act_name: tuple | str = "RELU", + norm_name: tuple | str = ("INSTANCE", {"affine": True}), + ): + super().__init__(in_channel, out_channel, spatial_dims, act_name, norm_name) + # s0 is upsampled 2x from s1, representing feature sizes at two resolutions. + # 2 * in_channel * s0 (upsample + activation) + 2 * out_channel * s0 (conv + normalization) + # s0 = output_size/out_channel + self.ram_cost = 2 * in_channel / out_channel + 2 + + +class _FactorizedReduceBlockWithRAMCost(FactorizedReduceBlock): + + def __init__( + self, + in_channel: int, + out_channel: int, + spatial_dims: int = 3, + act_name: tuple | str = "RELU", + norm_name: tuple | str = ("INSTANCE", {"affine": True}), + ): + super().__init__(in_channel, out_channel, spatial_dims, act_name, norm_name) + # s0 is upsampled 2x from s1, representing feature sizes at two resolutions. + # in_channel * s0 (activation) + 3 * out_channel * s1 (convolution, concatenation, normalization) + # s0 = s1 * 2^(spatial_dims) = output_size / out_channel * 2^(spatial_dims) + self.ram_cost = in_channel / out_channel * 2**self._spatial_dims + 3 + + +class MixedOp(nn.Module): + """ + The weighted averaging of cell operations. + Args: + c: number of output channels. + ops: a dictionary of operations. See also: ``Cell.OPS2D`` or ``Cell.OPS3D``. + arch_code_c: binary cell operation code. It represents the operation results added to the output. + """ + + def __init__(self, c: int, ops: dict, arch_code_c=None): + super().__init__() + if arch_code_c is None: + arch_code_c = np.ones(len(ops)) + self.ops = nn.ModuleList() + for arch_c, op_name in zip(arch_code_c, ops): + if arch_c > 0: + self.ops.append(ops[op_name](c)) + + def forward(self, x: torch.Tensor, weight: Optional[torch.Tensor] = None): + """ + Args: + x: input tensor. + weight: learnable architecture weights for cell operations. arch_code_c are derived from it. + Return: + out: weighted average of the operation results. + """ + out = 0.0 + if weight is not None: + weight = weight.to(x) + for idx, _op in enumerate(self.ops): + out = (out + _op(x)) if weight is None else out + _op(x) * weight[idx] + return out + + +class Cell(CellInterface): + """ + The basic class for cell operation search, which contains a preprocessing operation and a mixed cell operation. + Each cell is defined on a `path` in the topology search space. + Args: + c_prev: number of input channels + c: number of output channels + rate: resolution change rate. It represents the preprocessing operation before the mixed cell operation. + ``-1`` for 2x downsample, ``1`` for 2x upsample, ``0`` for no change of resolution. + arch_code_c: cell operation code + """ + + DIRECTIONS = 3 + # Possible output paths for `Cell`. + # + # - UpSample + # / + # +--+/ + # | |--- Identity or AlignChannels + # +--+\ + # \ + # - Downsample + + # Define 2D operation set, parameterized by the number of channels + OPS2D = { + "skip_connect": lambda _c: _IdentityWithRAMCost(), + "conv_3x3": lambda c: _ActiConvNormBlockWithRAMCost(c, c, 3, padding=1, spatial_dims=2), + } + + # Define 3D operation set, parameterized by the number of channels + OPS3D = { + "skip_connect": lambda _c: _IdentityWithRAMCost(), + "conv_3x3x3": lambda c: _ActiConvNormBlockWithRAMCost(c, c, 3, padding=1, spatial_dims=3), + "conv_3x3x1": lambda c: _P3DActiConvNormBlockWithRAMCost(c, c, 3, padding=1, p3dmode=0), + "conv_3x1x3": lambda c: _P3DActiConvNormBlockWithRAMCost(c, c, 3, padding=1, p3dmode=1), + "conv_1x3x3": lambda c: _P3DActiConvNormBlockWithRAMCost(c, c, 3, padding=1, p3dmode=2), + } + + # Define connection operation set, parameterized by the number of channels + ConnOPS = { + "up": _FactorizedIncreaseBlockWithRAMCost, + "down": _FactorizedReduceBlockWithRAMCost, + "identity": _IdentityWithRAMCost, + "align_channels": _ActiConvNormBlockWithRAMCost, + } + + def __init__( + self, + c_prev: int, + c: int, + rate: int, + arch_code_c=None, + spatial_dims: int = 3, + act_name: tuple | str = "RELU", + norm_name: tuple | str = ("INSTANCE", {"affine": True}), + ): + super().__init__() + self._spatial_dims = spatial_dims + self._act_name = act_name + self._norm_name = norm_name + + if rate == -1: # downsample + self.preprocess = self.ConnOPS["down"]( + c_prev, c, spatial_dims=self._spatial_dims, act_name=self._act_name, norm_name=self._norm_name + ) + elif rate == 1: # upsample + self.preprocess = self.ConnOPS["up"]( + c_prev, c, spatial_dims=self._spatial_dims, act_name=self._act_name, norm_name=self._norm_name + ) + else: + if c_prev == c: + self.preprocess = self.ConnOPS["identity"]() + else: + self.preprocess = self.ConnOPS["align_channels"]( + c_prev, c, 1, 0, spatial_dims=self._spatial_dims, act_name=self._act_name, norm_name=self._norm_name + ) + + # Define 2D operation set, parameterized by the number of channels + self.OPS2D = { + "skip_connect": lambda _c: _IdentityWithRAMCost(), + "conv_3x3": lambda c: _ActiConvNormBlockWithRAMCost( + c, c, 3, padding=1, spatial_dims=2, act_name=self._act_name, norm_name=self._norm_name + ), + } + + # Define 3D operation set, parameterized by the number of channels + self.OPS3D = { + "skip_connect": lambda _c: _IdentityWithRAMCost(), + "conv_3x3x3": lambda c: _ActiConvNormBlockWithRAMCost( + c, c, 3, padding=1, spatial_dims=3, act_name=self._act_name, norm_name=self._norm_name + ), + "conv_3x3x1": lambda c: _P3DActiConvNormBlockWithRAMCost( + c, c, 3, padding=1, p3dmode=0, act_name=self._act_name, norm_name=self._norm_name + ), + "conv_3x1x3": lambda c: _P3DActiConvNormBlockWithRAMCost( + c, c, 3, padding=1, p3dmode=1, act_name=self._act_name, norm_name=self._norm_name + ), + "conv_1x3x3": lambda c: _P3DActiConvNormBlockWithRAMCost( + c, c, 3, padding=1, p3dmode=2, act_name=self._act_name, norm_name=self._norm_name + ), + } + + self.OPS = {} + if self._spatial_dims == 2: + self.OPS = self.OPS2D + elif self._spatial_dims == 3: + self.OPS = self.OPS3D + else: + raise NotImplementedError(f"Spatial dimensions {self._spatial_dims} is not supported.") + + self.op = MixedOp(c, self.OPS, arch_code_c) + + def forward(self, x: torch.Tensor, weight: Optional[torch.Tensor]) -> torch.Tensor: + """ + Args: + x: input tensor + weight: weights for different operations. + """ + x = self.preprocess(x) + x = self.op(x, weight) + return x + + +class DiNTS(nn.Module): + """ + Reimplementation of DiNTS based on + "DiNTS: Differentiable Neural Network Topology Search for 3D Medical Image Segmentation + ". + + The model contains a pre-defined multi-resolution stem block (defined in this class) and a + DiNTS space (defined in :py:class:`monai.networks.nets.TopologyInstance` and + :py:class:`monai.networks.nets.TopologySearch`). + + The stem block is for: 1) input downsample and 2) output upsample to original size. + The model downsamples the input image by 2 (if ``use_downsample=True``). + The downsampled image is downsampled by [1, 2, 4, 8] times (``num_depths=4``) and used as input to the + DiNTS search space (``TopologySearch``) or the DiNTS instance (``TopologyInstance``). + + - ``TopologyInstance`` is the final searched model. The initialization requires the searched architecture codes. + - ``TopologySearch`` is a multi-path topology and cell operation search space. + The architecture codes will be initialized as one. + - ``TopologyConstruction`` is the parent class which constructs the instance and search space. + + To meet the requirements of the structure, the input size for each spatial dimension should be: + divisible by 2 ** (num_depths + 1). + + Args: + dints_space: DiNTS search space. The value should be instance of `TopologyInstance` or `TopologySearch`. + in_channels: number of input image channels. + num_classes: number of output segmentation classes. + act_name: activation name, default to 'RELU'. + norm_name: normalization used in convolution blocks. Default to `InstanceNorm`. + spatial_dims: spatial 2D or 3D inputs. + use_downsample: use downsample in the stem. + If ``False``, the search space will be in resolution [1, 1/2, 1/4, 1/8], + if ``True``, the search space will be in resolution [1/2, 1/4, 1/8, 1/16]. + node_a: node activation numpy matrix. Its shape is `(num_depths, num_blocks + 1)`. + +1 for multi-resolution inputs. + In model searching stage, ``node_a`` can be None. In deployment stage, ``node_a`` cannot be None. + """ + + def __init__( + self, + dints_space, + in_channels: int, + num_classes: int, + act_name: tuple | str = "RELU", + norm_name: tuple | str = ("INSTANCE", {"affine": True}), + spatial_dims: int = 3, + use_downsample: bool = True, + node_a=None, + ): + super().__init__() + + self.dints_space = dints_space + self.filter_nums = dints_space.filter_nums + self.num_blocks = dints_space.num_blocks + self.num_depths = dints_space.num_depths + if spatial_dims not in (2, 3): + raise NotImplementedError(f"Spatial dimensions {spatial_dims} is not supported.") + self._spatial_dims = spatial_dims + if node_a is None: + self.node_a = torch.ones((self.num_blocks + 1, self.num_depths)) + else: + self.node_a = node_a + + # define stem operations for every block + conv_type = Conv[Conv.CONV, spatial_dims] + self.stem_down = nn.ModuleDict() + self.stem_up = nn.ModuleDict() + self.stem_finals = nn.Sequential( + ActiConvNormBlock( + self.filter_nums[0], + self.filter_nums[0], + act_name=act_name, + norm_name=norm_name, + spatial_dims=spatial_dims, + ), + conv_type( + in_channels=self.filter_nums[0], + out_channels=num_classes, + kernel_size=1, + stride=1, + padding=0, + groups=1, + bias=True, + dilation=1, + ), + ) + mode = "trilinear" if self._spatial_dims == 3 else "bilinear" + for res_idx in range(self.num_depths): + # define downsample stems before DiNTS search + if use_downsample: + self.stem_down[str(res_idx)] = StemTS( + nn.Upsample(scale_factor=1 / (2**res_idx), mode=mode, align_corners=True), + conv_type( + in_channels=in_channels, + out_channels=self.filter_nums[res_idx], + kernel_size=3, + stride=1, + padding=1, + groups=1, + bias=False, + dilation=1, + ), + get_norm_layer(name=norm_name, spatial_dims=spatial_dims, channels=self.filter_nums[res_idx]), + get_act_layer(name=act_name), + conv_type( + in_channels=self.filter_nums[res_idx], + out_channels=self.filter_nums[res_idx + 1], + kernel_size=3, + stride=2, + padding=1, + groups=1, + bias=False, + dilation=1, + ), + get_norm_layer(name=norm_name, spatial_dims=spatial_dims, channels=self.filter_nums[res_idx + 1]), + ) + self.stem_up[str(res_idx)] = StemTS( + get_act_layer(name=act_name), + conv_type( + in_channels=self.filter_nums[res_idx + 1], + out_channels=self.filter_nums[res_idx], + kernel_size=3, + stride=1, + padding=1, + groups=1, + bias=False, + dilation=1, + ), + get_norm_layer(name=norm_name, spatial_dims=spatial_dims, channels=self.filter_nums[res_idx]), + nn.Upsample(scale_factor=2, mode=mode, align_corners=True), + ) + + else: + self.stem_down[str(res_idx)] = StemTS( + nn.Upsample(scale_factor=1 / (2**res_idx), mode=mode, align_corners=True), + conv_type( + in_channels=in_channels, + out_channels=self.filter_nums[res_idx], + kernel_size=3, + stride=1, + padding=1, + groups=1, + bias=False, + dilation=1, + ), + get_norm_layer(name=norm_name, spatial_dims=spatial_dims, channels=self.filter_nums[res_idx]), + ) + self.stem_up[str(res_idx)] = StemTS( + get_act_layer(name=act_name), + conv_type( + in_channels=self.filter_nums[res_idx], + out_channels=self.filter_nums[max(res_idx - 1, 0)], + kernel_size=3, + stride=1, + padding=1, + groups=1, + bias=False, + dilation=1, + ), + get_norm_layer( + name=norm_name, spatial_dims=spatial_dims, channels=self.filter_nums[max(res_idx - 1, 0)] + ), + nn.Upsample(scale_factor=2 ** (res_idx != 0), mode=mode, align_corners=True), + ) + + def weight_parameters(self): + return [param for name, param in self.named_parameters()] + + def forward(self, x: torch.Tensor): + """ + Prediction based on dynamic arch_code. + + Args: + x: input tensor. + """ + inputs = [] + for d in range(self.num_depths): + # allow multi-resolution input + _mod_w: StemInterface = self.stem_down[str(d)] + x_out = _mod_w.forward(x) + if self.node_a[0][d]: + inputs.append(x_out) + else: + inputs.append(torch.zeros_like(x_out)) + + outputs = self.dints_space(inputs) + + blk_idx = self.num_blocks - 1 + start = False + _temp: torch.Tensor = torch.empty(0) + for res_idx in range(self.num_depths - 1, -1, -1): + _mod_up: StemInterface = self.stem_up[str(res_idx)] + if start: + _temp = _mod_up.forward(outputs[res_idx] + _temp) + elif self.node_a[blk_idx + 1][res_idx]: + start = True + _temp = _mod_up.forward(outputs[res_idx]) + prediction = self.stem_finals(_temp) + return prediction + + +class TopologyConstruction(nn.Module): + """ + The base class for `TopologyInstance` and `TopologySearch`. + + Args: + arch_code: `[arch_code_a, arch_code_c]`, numpy arrays. The architecture codes defining the model. + For example, for a ``num_depths=4, num_blocks=12`` search space: + + - `arch_code_a` is a 12x10 (10 paths) binary matrix representing if a path is activated. + - `arch_code_c` is a 12x10x5 (5 operations) binary matrix representing if a cell operation is used. + - `arch_code` in ``__init__()`` is used for creating the network and remove unused network blocks. If None, + + all paths and cells operations will be used, and must be in the searching stage (is_search=True). + channel_mul: adjust intermediate channel number, default is 1. + cell: operation of each node. + num_blocks: number of blocks (depth in the horizontal direction) of the DiNTS search space. + num_depths: number of image resolutions of the DiNTS search space: 1, 1/2, 1/4 ... in each dimension. + use_downsample: use downsample in the stem. If False, the search space will be in resolution [1, 1/2, 1/4, 1/8], + if True, the search space will be in resolution [1/2, 1/4, 1/8, 1/16]. + device: `'cpu'`, `'cuda'`, or device ID. + + + Predefined variables: + `filter_nums`: default to 32. Double the number of channels after downsample. + topology related variables: + + - `arch_code2in`: path activation to its incoming node index (resolution). For depth = 4, + arch_code2in = [0, 1, 0, 1, 2, 1, 2, 3, 2, 3]. The first path outputs from node 0 (top resolution), + the second path outputs from node 1 (second resolution in the search space), + the third path outputs from node 0, etc. + - `arch_code2ops`: path activation to operations of upsample 1, keep 0, downsample -1. For depth = 4, + arch_code2ops = [0, 1, -1, 0, 1, -1, 0, 1, -1, 0]. The first path does not change + resolution, the second path perform upsample, the third perform downsample, etc. + - `arch_code2out`: path activation to its output node index. + For depth = 4, arch_code2out = [0, 0, 1, 1, 1, 2, 2, 2, 3, 3], + the first and second paths connects to node 0 (top resolution), the 3,4,5 paths connects to node 1, etc. + """ + + def __init__( + self, + arch_code: list | None = None, + channel_mul: float = 1.0, + cell=Cell, + num_blocks: int = 6, + num_depths: int = 3, + spatial_dims: int = 3, + act_name: tuple | str = "RELU", + norm_name: tuple | str = ("INSTANCE", {"affine": True}), + use_downsample: bool = True, + device: str = "cpu", + ): + super().__init__() + + n_feats = tuple([32 * (2**_i) for _i in range(num_depths + 1)]) + self.filter_nums = [int(n_feat * channel_mul) for n_feat in n_feats] + + self.num_blocks = num_blocks + self.num_depths = num_depths + print( + "{} - Length of input patch is recommended to be a multiple of {:d}.".format( + datetime.datetime.now(), 2 ** (num_depths + int(use_downsample)) + ) + ) + + self._spatial_dims = spatial_dims + self._act_name = act_name + self._norm_name = norm_name + self.use_downsample = use_downsample + self.device = device + self.num_cell_ops = 0 + if self._spatial_dims == 2: + self.num_cell_ops = len(cell.OPS2D) + elif self._spatial_dims == 3: + self.num_cell_ops = len(cell.OPS3D) + + # Calculate predefined parameters for topology search and decoding + arch_code2in, arch_code2out = [], [] + for i in range(Cell.DIRECTIONS * self.num_depths - 2): + arch_code2in.append((i + 1) // Cell.DIRECTIONS - 1 + (i + 1) % Cell.DIRECTIONS) + arch_code2ops = ([-1, 0, 1] * self.num_depths)[1:-1] + for m in range(self.num_depths): + arch_code2out.extend([m, m, m]) + arch_code2out = arch_code2out[1:-1] + self.arch_code2in = arch_code2in + self.arch_code2ops = arch_code2ops + self.arch_code2out = arch_code2out + + # define NAS search space + if arch_code is None: + arch_code_a = torch.ones((self.num_blocks, len(self.arch_code2out))).to(self.device) + arch_code_c = torch.ones((self.num_blocks, len(self.arch_code2out), self.num_cell_ops)).to(self.device) + else: + arch_code_a = torch.from_numpy(arch_code[0]).to(self.device) + arch_code_c = F.one_hot(torch.from_numpy(arch_code[1]).to(torch.int64), self.num_cell_ops).to(self.device) + + self.arch_code_a = arch_code_a + self.arch_code_c = arch_code_c + # define cell operation on each path + self.cell_tree = nn.ModuleDict() + for blk_idx in range(self.num_blocks): + for res_idx in range(len(self.arch_code2out)): + if self.arch_code_a[blk_idx, res_idx] == 1: + self.cell_tree[str((blk_idx, res_idx))] = cell( + self.filter_nums[self.arch_code2in[res_idx] + int(use_downsample)], + self.filter_nums[self.arch_code2out[res_idx] + int(use_downsample)], + self.arch_code2ops[res_idx], + self.arch_code_c[blk_idx, res_idx], + self._spatial_dims, + self._act_name, + self._norm_name, + ) + + def forward(self, x): + """This function to be implemented by the architecture instances or search spaces.""" + pass + + +class TopologyInstance(TopologyConstruction): + """ + Instance of the final searched architecture. Only used in re-training/inference stage. + """ + + def __init__( + self, + arch_code=None, + channel_mul: float = 1.0, + cell=Cell, + num_blocks: int = 6, + num_depths: int = 3, + spatial_dims: int = 3, + act_name: tuple | str = "RELU", + norm_name: tuple | str = ("INSTANCE", {"affine": True}), + use_downsample: bool = True, + device: str = "cpu", + ): + """ + Initialize DiNTS topology search space of neural architectures. + """ + if arch_code is None: + warnings.warn("arch_code not provided when not searching.") + + super().__init__( + arch_code=arch_code, + channel_mul=channel_mul, + cell=cell, + num_blocks=num_blocks, + num_depths=num_depths, + spatial_dims=spatial_dims, + act_name=act_name, + norm_name=norm_name, + use_downsample=use_downsample, + device=device, + ) + + def forward(self, x: list[torch.Tensor]) -> list[torch.Tensor]: + """ + Args: + x: input tensor. + """ + # generate path activation probability + inputs = x + for blk_idx in range(self.num_blocks): + outputs = [torch.tensor(0.0, dtype=x[0].dtype, device=x[0].device)] * self.num_depths + for res_idx, activation in enumerate(self.arch_code_a[blk_idx].data): + if activation: + mod: CellInterface = self.cell_tree[str((blk_idx, res_idx))] + _out = mod.forward(x=inputs[self.arch_code2in[res_idx]], weight=None) + outputs[self.arch_code2out[res_idx]] = outputs[self.arch_code2out[res_idx]] + _out + inputs = outputs + + return inputs + + +class TopologySearch(TopologyConstruction): + """ + DiNTS topology search space of neural architectures. + + Examples: + + .. code-block:: python + + from monai.networks.nets.dints import TopologySearch + + topology_search_space = TopologySearch( + channel_mul=0.5, num_blocks=8, num_depths=4, use_downsample=True, spatial_dims=3) + topology_search_space.get_ram_cost_usage(in_size=(2, 16, 80, 80, 80), full=True) + multi_res_images = [ + torch.randn(2, 16, 80, 80, 80), + torch.randn(2, 32, 40, 40, 40), + torch.randn(2, 64, 20, 20, 20), + torch.randn(2, 128, 10, 10, 10)] + prediction = topology_search_space(image) + for x in prediction: print(x.shape) + # torch.Size([2, 16, 80, 80, 80]) + # torch.Size([2, 32, 40, 40, 40]) + # torch.Size([2, 64, 20, 20, 20]) + # torch.Size([2, 128, 10, 10, 10]) + + Class method overview: + + - ``get_prob_a()``: convert learnable architecture weights to path activation probabilities. + - ``get_ram_cost_usage()``: get estimated ram cost. + - ``get_topology_entropy()``: get topology entropy loss in searching stage. + - ``decode()``: get final binarized architecture code. + - ``gen_mtx()``: generate variables needed for topology search. + + Predefined variables: + - `tidx`: index used to convert path activation matrix T = (depth,depth) in transfer_mtx to + path activation arch_code (1,3*depth-2), for depth = 4, tidx = [0, 1, 4, 5, 6, 9, 10, 11, 14, 15], + A tidx (10 binary values) represents the path activation. + - `transfer_mtx`: feasible path activation matrix (denoted as T) given a node activation pattern. + It is used to convert path activation pattern (1, paths) to node activation (1, nodes) + - `node_act_list`: all node activation [2^num_depths-1, depth]. For depth = 4, there are 15 node activation + patterns, each of length 4. For example, [1,1,0,0] means nodes 0, 1 are activated (with input paths). + - `all_connect`: All possible path activations. For depth = 4, + all_connection has 1024 vectors of length 10 (10 paths). + The return value will exclude path activation of all 0. + """ + + node2out: list[list] + node2in: list[list] + + def __init__( + self, + channel_mul: float = 1.0, + cell=Cell, + arch_code: list | None = None, + num_blocks: int = 6, + num_depths: int = 3, + spatial_dims: int = 3, + act_name: tuple | str = "RELU", + norm_name: tuple | str = ("INSTANCE", {"affine": True}), + use_downsample: bool = True, + device: str = "cpu", + ): + """ + Initialize DiNTS topology search space of neural architectures. + """ + super().__init__( + arch_code=arch_code, + channel_mul=channel_mul, + cell=cell, + num_blocks=num_blocks, + num_depths=num_depths, + spatial_dims=spatial_dims, + act_name=act_name, + norm_name=norm_name, + use_downsample=use_downsample, + device=device, + ) + + tidx = [] + _d = Cell.DIRECTIONS + for i in range(_d * self.num_depths - 2): + tidx.append((i + 1) // _d * self.num_depths + (i + 1) // _d - 1 + (i + 1) % _d) + self.tidx = tidx + transfer_mtx, node_act_list, child_list = self.gen_mtx(num_depths) + + self.node_act_list = np.asarray(node_act_list) + self.node_act_dict = {str(self.node_act_list[i]): i for i in range(len(self.node_act_list))} + self.transfer_mtx = transfer_mtx + self.child_list = np.asarray(child_list) + + self.ram_cost = np.zeros((self.num_blocks, len(self.arch_code2out), self.num_cell_ops)) + for blk_idx in range(self.num_blocks): + for res_idx in range(len(self.arch_code2out)): + if self.arch_code_a[blk_idx, res_idx] == 1: + self.ram_cost[blk_idx, res_idx] = np.array( + [ + op.ram_cost + self.cell_tree[str((blk_idx, res_idx))].preprocess.ram_cost + for op in self.cell_tree[str((blk_idx, res_idx))].op.ops[: self.num_cell_ops] + ] + ) + + # define cell and macro architecture probabilities + self.log_alpha_c = nn.Parameter( + torch.zeros(self.num_blocks, len(self.arch_code2out), self.num_cell_ops) + .normal_(1, 0.01) + .to(self.device) + .requires_grad_() + ) + self.log_alpha_a = nn.Parameter( + torch.zeros(self.num_blocks, len(self.arch_code2out)).normal_(0, 0.01).to(self.device).requires_grad_() + ) + self._arch_param_names = ["log_alpha_a", "log_alpha_c"] + + def gen_mtx(self, depth: int): + """ + Generate elements needed in decoding and topology. + + - `transfer_mtx`: feasible path activation matrix (denoted as T) given a node activation pattern. + It is used to convert path activation pattern (1, paths) to node activation (1, nodes) + - `node_act_list`: all node activation [2^num_depths-1, depth]. For depth = 4, there are 15 node activation + patterns, each of length 4. For example, [1,1,0,0] means nodes 0, 1 are activated (with input paths). + - `all_connect`: All possible path activations. For depth = 4, + all_connection has 1024 vectors of length 10 (10 paths). + The return value will exclude path activation of all 0. + """ + # total paths in a block, each node has three output paths, + # except the two nodes at the top and the bottom scales + paths = Cell.DIRECTIONS * depth - 2 + + # for 10 paths, all_connect has 1024 possible path activations. [1 0 0 0 0 0 0 0 0 0] means the top + # path is activated. + all_connect = _dfs(0, paths - 1) + + # Save all possible connections in mtx (might be redundant and infeasible) + mtx = [] + for m in all_connect: + # convert path activation [1,paths] to path activation matrix [depth, depth] + ma = np.zeros((depth, depth)) + for i in range(paths): + ma[(i + 1) // Cell.DIRECTIONS, (i + 1) // Cell.DIRECTIONS - 1 + (i + 1) % Cell.DIRECTIONS] = m[i] + mtx.append(ma) + + # define all possible node activation + node_act_list = _dfs(0, depth - 1)[1:] + transfer_mtx = {} + for arch_code in node_act_list: + # make sure each activated node has an active connection, inactivated node has no connection + arch_code_mtx = [_ for _ in mtx if ((np.sum(_, 0) > 0).astype(int) == np.array(arch_code)).all()] + transfer_mtx[str(np.array(arch_code))] = arch_code_mtx + + return transfer_mtx, node_act_list, all_connect[1:] + + def weight_parameters(self): + return [param for name, param in self.named_parameters() if name not in self._arch_param_names] + + def get_prob_a(self, child: bool = False): + """ + Get final path and child model probabilities from architecture weights `log_alpha_a`. + This is used in forward pass, getting training loss, and final decoding. + + Args: + child: return child probability (used in decoding) + Return: + arch_code_prob_a: the path activation probability of size: + `[number of blocks, number of paths in each block]`. + For 12 blocks, 4 depths search space, the size is [12,10] + probs_a: The probability of all child models (size 1023x10). Each child model is a path activation pattern + (1D vector of length 10 for 10 paths). In total 1023 child models (2^10 -1) + """ + _arch_code_prob_a = torch.sigmoid(self.log_alpha_a) + # remove the case where all path are zero, and re-normalize. + norm = 1 - (1 - _arch_code_prob_a).prod(-1) + arch_code_prob_a = _arch_code_prob_a / norm.unsqueeze(1) + if child: + path_activation = torch.from_numpy(self.child_list).to(self.device) + probs_a = [ + ( + path_activation * _arch_code_prob_a[blk_idx] + + (1 - path_activation) * (1 - _arch_code_prob_a[blk_idx]) + ).prod(-1) + / norm[blk_idx] + for blk_idx in range(self.num_blocks) + ] + probs_a = torch.stack(probs_a) # type: ignore + return probs_a, arch_code_prob_a + return None, arch_code_prob_a + + def get_ram_cost_usage(self, in_size, full: bool = False): + """ + Get estimated output tensor size to approximate RAM consumption. + + Args: + in_size: input image shape (4D/5D, ``[BCHW[D]]``) at the highest resolution level. + full: full ram cost usage with all probability of 1. + """ + # convert input image size to feature map size at each level + batch_size = in_size[0] + image_size = np.array(in_size[-self._spatial_dims :]) + sizes = [] + for res_idx in range(self.num_depths): + sizes.append(batch_size * self.filter_nums[res_idx] * (image_size // (2**res_idx)).prod()) + sizes = torch.tensor(sizes, dtype=torch.float32, device=self.device) / (2 ** (int(self.use_downsample))) + probs_a, arch_code_prob_a = self.get_prob_a(child=False) + cell_prob = F.softmax(self.log_alpha_c, dim=-1) + if full: + arch_code_prob_a = arch_code_prob_a.detach() + arch_code_prob_a.fill_(1) + ram_cost = torch.from_numpy(self.ram_cost).to(dtype=torch.float32, device=self.device) + usage = 0.0 + for blk_idx in range(self.num_blocks): + # node activation for input + # cell operation + for path_idx in range(len(self.arch_code2out)): + usage += ( + arch_code_prob_a[blk_idx, path_idx] + * (1 + (ram_cost[blk_idx, path_idx] * cell_prob[blk_idx, path_idx]).sum()) + * sizes[self.arch_code2out[path_idx]] + ) + return usage * 32 / 8 / 1024**2 + + def get_topology_entropy(self, probs): + """ + Get topology entropy loss at searching stage. + + Args: + probs: path activation probabilities + """ + if hasattr(self, "node2in"): + node2in = self.node2in # pylint: disable=E0203 + node2out = self.node2out # pylint: disable=E0203 + else: + # node activation index to feasible input child_idx + node2in = [[] for _ in range(len(self.node_act_list))] + # node activation index to feasible output child_idx + node2out = [[] for _ in range(len(self.node_act_list))] + for child_idx in range(len(self.child_list)): + _node_in, _node_out = np.zeros(self.num_depths), np.zeros(self.num_depths) + for res_idx in range(len(self.arch_code2out)): + _node_out[self.arch_code2out[res_idx]] += self.child_list[child_idx][res_idx] + _node_in[self.arch_code2in[res_idx]] += self.child_list[child_idx][res_idx] + _node_in = (_node_in >= 1).astype(int) + _node_out = (_node_out >= 1).astype(int) + node2in[self.node_act_dict[str(_node_out)]].append(child_idx) + node2out[self.node_act_dict[str(_node_in)]].append(child_idx) + self.node2in = node2in + self.node2out = node2out + # calculate entropy + ent = 0 + for blk_idx in range(self.num_blocks - 1): + blk_ent = 0 + # node activation probability + for node_idx in range(len(self.node_act_list)): + _node_p = probs[blk_idx, node2in[node_idx]].sum() + _out_probs = probs[blk_idx + 1, node2out[node_idx]].sum() + blk_ent += -(_node_p * torch.log(_out_probs + 1e-5) + (1 - _node_p) * torch.log(1 - _out_probs + 1e-5)) + ent += blk_ent + return ent + + def decode(self): + """ + Decode network log_alpha_a/log_alpha_c using dijkstra shortest path algorithm. + + `[node_a, arch_code_a, arch_code_c, arch_code_a_max]` is decoded when using ``self.decode()``. + + For example, for a ``num_depths=4``, ``num_blocks=12`` search space: + + - ``node_a`` is a 4x13 binary matrix representing if a feature node is activated + (13 because of multi-resolution inputs). + - ``arch_code_a`` is a 12x10 (10 paths) binary matrix representing if a path is activated. + - ``arch_code_c`` is a 12x10x5 (5 operations) binary matrix representing if a cell operation is used. + + Return: + arch_code with maximum probability + """ + probs, arch_code_prob_a = self.get_prob_a(child=True) + arch_code_a_max = self.child_list[torch.argmax(probs, -1).data.cpu().numpy()] + arch_code_c = torch.argmax(F.softmax(self.log_alpha_c, -1), -1).data.cpu().numpy() + probs = probs.data.cpu().numpy() + + # define adjacency matrix + amtx = np.zeros( + (1 + len(self.child_list) * self.num_blocks + 1, 1 + len(self.child_list) * self.num_blocks + 1) + ) + + # build a path activation to child index searching dictionary + path2child = {str(self.child_list[i]): i for i in range(len(self.child_list))} + + # build a submodel to submodel index + sub_amtx = np.zeros((len(self.child_list), len(self.child_list))) + for child_idx in range(len(self.child_list)): + _node_act = np.zeros(self.num_depths).astype(int) + for path_idx in range(len(self.child_list[child_idx])): + _node_act[self.arch_code2out[path_idx]] += self.child_list[child_idx][path_idx] + _node_act = (_node_act >= 1).astype(int) + for mtx in self.transfer_mtx[str(_node_act)]: + connect_child_idx = path2child[str(mtx.flatten()[self.tidx].astype(int))] + sub_amtx[child_idx, connect_child_idx] = 1 + + # fill in source to first block, add 1e-5/1e-3 to avoid log0 and negative edge weights + amtx[0, 1 : 1 + len(self.child_list)] = -np.log(probs[0] + 1e-5) + 0.001 + + # fill in the rest blocks + for blk_idx in range(1, self.num_blocks): + amtx[ + 1 + (blk_idx - 1) * len(self.child_list) : 1 + blk_idx * len(self.child_list), + 1 + blk_idx * len(self.child_list) : 1 + (blk_idx + 1) * len(self.child_list), + ] = sub_amtx * np.tile(-np.log(probs[blk_idx] + 1e-5) + 0.001, (len(self.child_list), 1)) + + # fill in the last to the sink + amtx[1 + (self.num_blocks - 1) * len(self.child_list) : 1 + self.num_blocks * len(self.child_list), -1] = 0.001 + + graph = csr_matrix(amtx) + dist_matrix, predecessors, sources = dijkstra( + csgraph=graph, directed=True, indices=0, min_only=True, return_predecessors=True + ) + index, a_idx = -1, -1 + arch_code_a = np.zeros((self.num_blocks, len(self.arch_code2out))) + node_a = np.zeros((self.num_blocks + 1, self.num_depths)) + + # decoding to paths + while True: + index = predecessors[index] + if index == 0: + break + child_idx = (index - 1) % len(self.child_list) + arch_code_a[a_idx, :] = self.child_list[child_idx] + for res_idx in range(len(self.arch_code2out)): + node_a[a_idx, self.arch_code2out[res_idx]] += arch_code_a[a_idx, res_idx] + a_idx -= 1 + for res_idx in range(len(self.arch_code2out)): + node_a[a_idx, self.arch_code2in[res_idx]] += arch_code_a[0, res_idx] + node_a = (node_a >= 1).astype(int) + return node_a, arch_code_a, arch_code_c, arch_code_a_max + + def forward(self, x): + """ + Prediction based on dynamic arch_code. + + Args: + x: a list of `num_depths` input tensors as a multi-resolution input. + tensor is of shape `BCHW[D]` where `C` must match `self.filter_nums`. + """ + # generate path activation probability + probs_a, arch_code_prob_a = self.get_prob_a(child=False) + inputs = x + for blk_idx in range(self.num_blocks): + outputs = [0.0] * self.num_depths + for res_idx, activation in enumerate(self.arch_code_a[blk_idx].data.cpu().numpy()): + if activation: + _w = F.softmax(self.log_alpha_c[blk_idx, res_idx], dim=-1) + outputs[self.arch_code2out[res_idx]] += ( + self.cell_tree[str((blk_idx, res_idx))](inputs[self.arch_code2in[res_idx]], weight=_w) + * arch_code_prob_a[blk_idx, res_idx] + ) + inputs = outputs + + return inputs diff --git a/source_code/SegMamba/monai/networks/nets/efficientnet.py b/source_code/SegMamba/monai/networks/nets/efficientnet.py new file mode 100644 index 0000000000000000000000000000000000000000..4e6c327b23ce2a8265492d6b0c8e67a167883621 --- /dev/null +++ b/source_code/SegMamba/monai/networks/nets/efficientnet.py @@ -0,0 +1,1013 @@ +# Copyright (c) MONAI Consortium +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from __future__ import annotations + +import math +import operator +import re +from functools import reduce +from typing import NamedTuple + +import torch +from torch import nn +from torch.utils import model_zoo + +from monai.networks.blocks import BaseEncoder +from monai.networks.layers.factories import Act, Conv, Pad, Pool +from monai.networks.layers.utils import get_norm_layer +from monai.utils.module import look_up_option + +__all__ = [ + "EfficientNet", + "EfficientNetBN", + "get_efficientnet_image_size", + "drop_connect", + "EfficientNetBNFeatures", + "BlockArgs", + "EfficientNetEncoder", +] + +efficientnet_params = { + # model_name: (width_mult, depth_mult, image_size, dropout_rate, dropconnect_rate) + "efficientnet-b0": (1.0, 1.0, 224, 0.2, 0.2), + "efficientnet-b1": (1.0, 1.1, 240, 0.2, 0.2), + "efficientnet-b2": (1.1, 1.2, 260, 0.3, 0.2), + "efficientnet-b3": (1.2, 1.4, 300, 0.3, 0.2), + "efficientnet-b4": (1.4, 1.8, 380, 0.4, 0.2), + "efficientnet-b5": (1.6, 2.2, 456, 0.4, 0.2), + "efficientnet-b6": (1.8, 2.6, 528, 0.5, 0.2), + "efficientnet-b7": (2.0, 3.1, 600, 0.5, 0.2), + "efficientnet-b8": (2.2, 3.6, 672, 0.5, 0.2), + "efficientnet-l2": (4.3, 5.3, 800, 0.5, 0.2), +} + +url_map = { + "efficientnet-b0": "https://github.com/lukemelas/EfficientNet-PyTorch/releases/download/1.0/efficientnet-b0-355c32eb.pth", + "efficientnet-b1": "https://github.com/lukemelas/EfficientNet-PyTorch/releases/download/1.0/efficientnet-b1-f1951068.pth", + "efficientnet-b2": "https://github.com/lukemelas/EfficientNet-PyTorch/releases/download/1.0/efficientnet-b2-8bb594d6.pth", + "efficientnet-b3": "https://github.com/lukemelas/EfficientNet-PyTorch/releases/download/1.0/efficientnet-b3-5fb5a3c3.pth", + "efficientnet-b4": "https://github.com/lukemelas/EfficientNet-PyTorch/releases/download/1.0/efficientnet-b4-6ed6700e.pth", + "efficientnet-b5": "https://github.com/lukemelas/EfficientNet-PyTorch/releases/download/1.0/efficientnet-b5-b6417697.pth", + "efficientnet-b6": "https://github.com/lukemelas/EfficientNet-PyTorch/releases/download/1.0/efficientnet-b6-c76e70fd.pth", + "efficientnet-b7": "https://github.com/lukemelas/EfficientNet-PyTorch/releases/download/1.0/efficientnet-b7-dcc49843.pth", + # trained with adversarial examples, simplify the name to decrease string length + "b0-ap": "https://github.com/lukemelas/EfficientNet-PyTorch/releases/download/1.0/adv-efficientnet-b0-b64d5a18.pth", + "b1-ap": "https://github.com/lukemelas/EfficientNet-PyTorch/releases/download/1.0/adv-efficientnet-b1-0f3ce85a.pth", + "b2-ap": "https://github.com/lukemelas/EfficientNet-PyTorch/releases/download/1.0/adv-efficientnet-b2-6e9d97e5.pth", + "b3-ap": "https://github.com/lukemelas/EfficientNet-PyTorch/releases/download/1.0/adv-efficientnet-b3-cdd7c0f4.pth", + "b4-ap": "https://github.com/lukemelas/EfficientNet-PyTorch/releases/download/1.0/adv-efficientnet-b4-44fb3a87.pth", + "b5-ap": "https://github.com/lukemelas/EfficientNet-PyTorch/releases/download/1.0/adv-efficientnet-b5-86493f6b.pth", + "b6-ap": "https://github.com/lukemelas/EfficientNet-PyTorch/releases/download/1.0/adv-efficientnet-b6-ac80338e.pth", + "b7-ap": "https://github.com/lukemelas/EfficientNet-PyTorch/releases/download/1.0/adv-efficientnet-b7-4652b6dd.pth", + "b8-ap": "https://github.com/lukemelas/EfficientNet-PyTorch/releases/download/1.0/adv-efficientnet-b8-22a8fe65.pth", +} + + +class MBConvBlock(nn.Module): + + def __init__( + self, + spatial_dims: int, + in_channels: int, + out_channels: int, + kernel_size: int, + stride: int, + image_size: list[int], + expand_ratio: int, + se_ratio: float | None, + id_skip: bool | None = True, + norm: str | tuple = ("batch", {"eps": 1e-3, "momentum": 0.01}), + drop_connect_rate: float | None = 0.2, + ) -> None: + """ + Mobile Inverted Residual Bottleneck Block. + + Args: + spatial_dims: number of spatial dimensions. + in_channels: number of input channels. + out_channels: number of output channels. + kernel_size: size of the kernel for conv ops. + stride: stride to use for conv ops. + image_size: input image resolution. + expand_ratio: expansion ratio for inverted bottleneck. + se_ratio: squeeze-excitation ratio for se layers. + id_skip: whether to use skip connection. + norm: feature normalization type and arguments. Defaults to batch norm. + drop_connect_rate: dropconnect rate for drop connection (individual weights) layers. + + References: + [1] https://arxiv.org/abs/1704.04861 (MobileNet v1) + [2] https://arxiv.org/abs/1801.04381 (MobileNet v2) + [3] https://arxiv.org/abs/1905.02244 (MobileNet v3) + """ + super().__init__() + + # select the type of N-Dimensional layers to use + # these are based on spatial dims and selected from MONAI factories + conv_type = Conv["conv", spatial_dims] + adaptivepool_type = Pool["adaptiveavg", spatial_dims] + + self.in_channels = in_channels + self.out_channels = out_channels + self.id_skip = id_skip + self.stride = stride + self.expand_ratio = expand_ratio + self.drop_connect_rate = drop_connect_rate + + if (se_ratio is not None) and (0.0 < se_ratio <= 1.0): + self.has_se = True + self.se_ratio = se_ratio + else: + self.has_se = False + + # Expansion phase (Inverted Bottleneck) + inp = in_channels # number of input channels + oup = in_channels * expand_ratio # number of output channels + if self.expand_ratio != 1: + self._expand_conv = conv_type(in_channels=inp, out_channels=oup, kernel_size=1, bias=False) + self._expand_conv_padding = _make_same_padder(self._expand_conv, image_size) + + self._bn0 = get_norm_layer(name=norm, spatial_dims=spatial_dims, channels=oup) + else: + # need to have the following to fix JIT error: + # "Module 'MBConvBlock' has no attribute '_expand_conv'" + + # FIXME: find a better way to bypass JIT error + self._expand_conv = nn.Identity() + self._expand_conv_padding = nn.Identity() + self._bn0 = nn.Identity() + + # Depthwise convolution phase + self._depthwise_conv = conv_type( + in_channels=oup, + out_channels=oup, + groups=oup, # groups makes it depthwise + kernel_size=kernel_size, + stride=self.stride, + bias=False, + ) + self._depthwise_conv_padding = _make_same_padder(self._depthwise_conv, image_size) + self._bn1 = get_norm_layer(name=norm, spatial_dims=spatial_dims, channels=oup) + image_size = _calculate_output_image_size(image_size, self.stride) + + # Squeeze and Excitation layer, if desired + if self.has_se: + self._se_adaptpool = adaptivepool_type(1) + num_squeezed_channels = max(1, int(in_channels * self.se_ratio)) + self._se_reduce = conv_type(in_channels=oup, out_channels=num_squeezed_channels, kernel_size=1) + self._se_reduce_padding = _make_same_padder(self._se_reduce, [1] * spatial_dims) + self._se_expand = conv_type(in_channels=num_squeezed_channels, out_channels=oup, kernel_size=1) + self._se_expand_padding = _make_same_padder(self._se_expand, [1] * spatial_dims) + + # Pointwise convolution phase + final_oup = out_channels + self._project_conv = conv_type(in_channels=oup, out_channels=final_oup, kernel_size=1, bias=False) + self._project_conv_padding = _make_same_padder(self._project_conv, image_size) + self._bn2 = get_norm_layer(name=norm, spatial_dims=spatial_dims, channels=final_oup) + + # swish activation to use - using memory efficient swish by default + # can be switched to normal swish using self.set_swish() function call + self._swish = Act["memswish"](inplace=True) + + def forward(self, inputs: torch.Tensor): + """MBConvBlock"s forward function. + + Args: + inputs: Input tensor. + + Returns: + Output of this block after processing. + """ + # Expansion and Depthwise Convolution + x = inputs + if self.expand_ratio != 1: + x = self._expand_conv(self._expand_conv_padding(x)) + x = self._bn0(x) + x = self._swish(x) + + x = self._depthwise_conv(self._depthwise_conv_padding(x)) + x = self._bn1(x) + x = self._swish(x) + + # Squeeze and Excitation + if self.has_se: + x_squeezed = self._se_adaptpool(x) + x_squeezed = self._se_reduce(self._se_reduce_padding(x_squeezed)) + x_squeezed = self._swish(x_squeezed) + x_squeezed = self._se_expand(self._se_expand_padding(x_squeezed)) + x = torch.sigmoid(x_squeezed) * x + + # Pointwise Convolution + x = self._project_conv(self._project_conv_padding(x)) + x = self._bn2(x) + + # Skip connection and drop connect + if self.id_skip and self.stride == 1 and self.in_channels == self.out_channels: + # the combination of skip connection and drop connect brings about stochastic depth. + if self.drop_connect_rate: + x = drop_connect(x, p=self.drop_connect_rate, training=self.training) + x = x + inputs # skip connection + return x + + def set_swish(self, memory_efficient: bool = True) -> None: + """Sets swish function as memory efficient (for training) or standard (for export). + + Args: + memory_efficient (bool): Whether to use memory-efficient version of swish. + """ + self._swish = Act["memswish"](inplace=True) if memory_efficient else Act["swish"](alpha=1.0) + + +class EfficientNet(nn.Module): + + def __init__( + self, + blocks_args_str: list[str], + spatial_dims: int = 2, + in_channels: int = 3, + num_classes: int = 1000, + width_coefficient: float = 1.0, + depth_coefficient: float = 1.0, + dropout_rate: float = 0.2, + image_size: int = 224, + norm: str | tuple = ("batch", {"eps": 1e-3, "momentum": 0.01}), + drop_connect_rate: float = 0.2, + depth_divisor: int = 8, + ) -> None: + """ + EfficientNet based on `Rethinking Model Scaling for Convolutional Neural Networks `_. + Adapted from `EfficientNet-PyTorch `_. + + Args: + blocks_args_str: block definitions. + spatial_dims: number of spatial dimensions. + in_channels: number of input channels. + num_classes: number of output classes. + width_coefficient: width multiplier coefficient (w in paper). + depth_coefficient: depth multiplier coefficient (d in paper). + dropout_rate: dropout rate for dropout layers. + image_size: input image resolution. + norm: feature normalization type and arguments. + drop_connect_rate: dropconnect rate for drop connection (individual weights) layers. + depth_divisor: depth divisor for channel rounding. + + """ + super().__init__() + + if spatial_dims not in (1, 2, 3): + raise ValueError("spatial_dims can only be 1, 2 or 3.") + + # select the type of N-Dimensional layers to use + # these are based on spatial dims and selected from MONAI factories + conv_type: type[nn.Conv1d | nn.Conv2d | nn.Conv3d] = Conv["conv", spatial_dims] + adaptivepool_type: type[nn.AdaptiveAvgPool1d | nn.AdaptiveAvgPool2d | nn.AdaptiveAvgPool3d] = Pool[ + "adaptiveavg", spatial_dims + ] + + # decode blocks args into arguments for MBConvBlock + blocks_args = [BlockArgs.from_string(s) for s in blocks_args_str] + + # checks for successful decoding of blocks_args_str + if not isinstance(blocks_args, list): + raise ValueError("blocks_args must be a list") + + if blocks_args == []: + raise ValueError("block_args must be non-empty") + + self._blocks_args = blocks_args + self.num_classes = num_classes + self.in_channels = in_channels + self.drop_connect_rate = drop_connect_rate + + # expand input image dimensions to list + current_image_size = [image_size] * spatial_dims + + # Stem + stride = 2 + out_channels = _round_filters(32, width_coefficient, depth_divisor) # number of output channels + self._conv_stem = conv_type(self.in_channels, out_channels, kernel_size=3, stride=stride, bias=False) + self._conv_stem_padding = _make_same_padder(self._conv_stem, current_image_size) + self._bn0 = get_norm_layer(name=norm, spatial_dims=spatial_dims, channels=out_channels) + current_image_size = _calculate_output_image_size(current_image_size, stride) + + # build MBConv blocks + num_blocks = 0 + self._blocks = nn.Sequential() + + self.extract_stacks = [] + + # update baseline blocks to input/output filters and number of repeats based on width and depth multipliers. + for idx, block_args in enumerate(self._blocks_args): + block_args = block_args._replace( + input_filters=_round_filters(block_args.input_filters, width_coefficient, depth_divisor), + output_filters=_round_filters(block_args.output_filters, width_coefficient, depth_divisor), + num_repeat=_round_repeats(block_args.num_repeat, depth_coefficient), + ) + self._blocks_args[idx] = block_args + + # calculate the total number of blocks - needed for drop_connect estimation + num_blocks += block_args.num_repeat + + if block_args.stride > 1: + self.extract_stacks.append(idx) + + self.extract_stacks.append(len(self._blocks_args)) + + # create and add MBConvBlocks to self._blocks + idx = 0 # block index counter + for stack_idx, block_args in enumerate(self._blocks_args): + blk_drop_connect_rate = self.drop_connect_rate + + # scale drop connect_rate + if blk_drop_connect_rate: + blk_drop_connect_rate *= float(idx) / num_blocks + + sub_stack = nn.Sequential() + # the first block needs to take care of stride and filter size increase. + sub_stack.add_module( + str(idx), + MBConvBlock( + spatial_dims=spatial_dims, + in_channels=block_args.input_filters, + out_channels=block_args.output_filters, + kernel_size=block_args.kernel_size, + stride=block_args.stride, + image_size=current_image_size, + expand_ratio=block_args.expand_ratio, + se_ratio=block_args.se_ratio, + id_skip=block_args.id_skip, + norm=norm, + drop_connect_rate=blk_drop_connect_rate, + ), + ) + idx += 1 # increment blocks index counter + + current_image_size = _calculate_output_image_size(current_image_size, block_args.stride) + if block_args.num_repeat > 1: # modify block_args to keep same output size + block_args = block_args._replace(input_filters=block_args.output_filters, stride=1) + + # add remaining block repeated num_repeat times + for _ in range(block_args.num_repeat - 1): + blk_drop_connect_rate = self.drop_connect_rate + + # scale drop connect_rate + if blk_drop_connect_rate: + blk_drop_connect_rate *= float(idx) / num_blocks + + # add blocks + sub_stack.add_module( + str(idx), + MBConvBlock( + spatial_dims=spatial_dims, + in_channels=block_args.input_filters, + out_channels=block_args.output_filters, + kernel_size=block_args.kernel_size, + stride=block_args.stride, + image_size=current_image_size, + expand_ratio=block_args.expand_ratio, + se_ratio=block_args.se_ratio, + id_skip=block_args.id_skip, + norm=norm, + drop_connect_rate=blk_drop_connect_rate, + ), + ) + idx += 1 # increment blocks index counter + + 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: + raise ValueError("total number of blocks created != num_blocks") + + # Head + head_in_channels = block_args.output_filters + out_channels = _round_filters(1280, width_coefficient, depth_divisor) + self._conv_head = conv_type(head_in_channels, out_channels, kernel_size=1, bias=False) + self._conv_head_padding = _make_same_padder(self._conv_head, current_image_size) + self._bn1 = get_norm_layer(name=norm, spatial_dims=spatial_dims, channels=out_channels) + + # final linear layer + self._avg_pooling = adaptivepool_type(1) + self._dropout = nn.Dropout(dropout_rate) + self._fc = nn.Linear(out_channels, self.num_classes) + + # swish activation to use - using memory efficient swish by default + # can be switched to normal swish using self.set_swish() function call + self._swish = Act["memswish"]() + + # initialize weights using Tensorflow's init method from official impl. + self._initialize_weights() + + def set_swish(self, memory_efficient: bool = True) -> None: + """ + Sets swish function as memory efficient (for training) or standard (for JIT export). + + Args: + memory_efficient: whether to use memory-efficient version of swish. + + """ + self._swish = Act["memswish"]() if memory_efficient else Act["swish"](alpha=1.0) + for sub_stack in self._blocks: + for block in sub_stack: + block.set_swish(memory_efficient) + + def forward(self, inputs: torch.Tensor): + """ + Args: + inputs: input should have spatially N dimensions + ``(Batch, in_channels, dim_0[, dim_1, ..., dim_N])``, N is defined by `dimensions`. + + Returns: + a torch Tensor of classification prediction in shape ``(Batch, num_classes)``. + """ + # Stem + x = self._conv_stem(self._conv_stem_padding(inputs)) + x = self._swish(self._bn0(x)) + # Blocks + x = self._blocks(x) + # Head + x = self._conv_head(self._conv_head_padding(x)) + x = self._swish(self._bn1(x)) + + # Pooling and final linear layer + x = self._avg_pooling(x) + + x = x.flatten(start_dim=1) + x = self._dropout(x) + x = self._fc(x) + return x + + def _initialize_weights(self) -> None: + """ + Args: + None, initializes weights for conv/linear/batchnorm layers + following weight init methods from + `official Tensorflow EfficientNet implementation + `_. + Adapted from `EfficientNet-PyTorch's init method + `_. + """ + for _, m in self.named_modules(): + if isinstance(m, (nn.Conv1d, nn.Conv2d, nn.Conv3d)): + fan_out = reduce(operator.mul, m.kernel_size, 1) * m.out_channels + m.weight.data.normal_(0, math.sqrt(2.0 / fan_out)) + if m.bias is not None: + m.bias.data.zero_() + elif isinstance(m, (nn.BatchNorm1d, nn.BatchNorm2d, nn.BatchNorm3d)): + m.weight.data.fill_(1.0) + m.bias.data.zero_() + elif isinstance(m, nn.Linear): + fan_out = m.weight.size(0) + fan_in = 0 + init_range = 1.0 / math.sqrt(fan_in + fan_out) + m.weight.data.uniform_(-init_range, init_range) + m.bias.data.zero_() + + +class EfficientNetBN(EfficientNet): + + def __init__( + self, + model_name: str, + pretrained: bool = True, + progress: bool = True, + spatial_dims: int = 2, + in_channels: int = 3, + num_classes: int = 1000, + norm: str | tuple = ("batch", {"eps": 1e-3, "momentum": 0.01}), + adv_prop: bool = False, + ) -> None: + """ + Generic wrapper around EfficientNet, used to initialize EfficientNet-B0 to EfficientNet-B7 models + model_name is mandatory argument as there is no EfficientNetBN itself, + it needs the N in [0, 1, 2, 3, 4, 5, 6, 7, 8] to be a model + + Args: + model_name: name of model to initialize, can be from [efficientnet-b0, ..., efficientnet-b8, efficientnet-l2]. + pretrained: whether to initialize pretrained ImageNet weights, only available for spatial_dims=2 and batch + norm is used. + progress: whether to show download progress for pretrained weights download. + spatial_dims: number of spatial dimensions. + in_channels: number of input channels. + num_classes: number of output classes. + norm: feature normalization type and arguments. + adv_prop: whether to use weights trained with adversarial examples. + This argument only works when `pretrained` is `True`. + + Examples:: + + # for pretrained spatial 2D ImageNet + >>> image_size = get_efficientnet_image_size("efficientnet-b0") + >>> inputs = torch.rand(1, 3, image_size, image_size) + >>> model = EfficientNetBN("efficientnet-b0", pretrained=True) + >>> model.eval() + >>> outputs = model(inputs) + + # create spatial 2D + >>> model = EfficientNetBN("efficientnet-b0", spatial_dims=2) + + # create spatial 3D + >>> model = EfficientNetBN("efficientnet-b0", spatial_dims=3) + + # create EfficientNetB7 for spatial 2D + >>> model = EfficientNetBN("efficientnet-b7", spatial_dims=2) + + """ + # block args + blocks_args_str = [ + "r1_k3_s11_e1_i32_o16_se0.25", + "r2_k3_s22_e6_i16_o24_se0.25", + "r2_k5_s22_e6_i24_o40_se0.25", + "r3_k3_s22_e6_i40_o80_se0.25", + "r3_k5_s11_e6_i80_o112_se0.25", + "r4_k5_s22_e6_i112_o192_se0.25", + "r1_k3_s11_e6_i192_o320_se0.25", + ] + + # check if model_name is valid model + if model_name not in efficientnet_params: + model_name_string = ", ".join(efficientnet_params.keys()) + raise ValueError(f"invalid model_name {model_name} found, must be one of {model_name_string} ") + + # get network parameters + weight_coeff, depth_coeff, image_size, dropout_rate, dropconnect_rate = efficientnet_params[model_name] + + # create model and initialize random weights + super().__init__( + blocks_args_str=blocks_args_str, + spatial_dims=spatial_dims, + in_channels=in_channels, + num_classes=num_classes, + width_coefficient=weight_coeff, + depth_coefficient=depth_coeff, + dropout_rate=dropout_rate, + image_size=image_size, + drop_connect_rate=dropconnect_rate, + norm=norm, + ) + + # only pretrained for when `spatial_dims` is 2 + if pretrained and (spatial_dims == 2): + _load_state_dict(self, model_name, progress, adv_prop) + + +class EfficientNetBNFeatures(EfficientNet): + + def __init__( + self, + model_name: str, + pretrained: bool = True, + progress: bool = True, + spatial_dims: int = 2, + in_channels: int = 3, + num_classes: int = 1000, + norm: str | tuple = ("batch", {"eps": 1e-3, "momentum": 0.01}), + adv_prop: bool = False, + ) -> None: + """ + Initialize EfficientNet-B0 to EfficientNet-B7 models as a backbone, the backbone can + be used as an encoder for segmentation and objection models. + Compared with the class `EfficientNetBN`, the only different place is the forward function. + + This class refers to `PyTorch image models `_. + + """ + blocks_args_str = [ + "r1_k3_s11_e1_i32_o16_se0.25", + "r2_k3_s22_e6_i16_o24_se0.25", + "r2_k5_s22_e6_i24_o40_se0.25", + "r3_k3_s22_e6_i40_o80_se0.25", + "r3_k5_s11_e6_i80_o112_se0.25", + "r4_k5_s22_e6_i112_o192_se0.25", + "r1_k3_s11_e6_i192_o320_se0.25", + ] + + # check if model_name is valid model + if model_name not in efficientnet_params: + model_name_string = ", ".join(efficientnet_params.keys()) + raise ValueError(f"invalid model_name {model_name} found, must be one of {model_name_string} ") + + # get network parameters + weight_coeff, depth_coeff, image_size, dropout_rate, dropconnect_rate = efficientnet_params[model_name] + + # create model and initialize random weights + super().__init__( + blocks_args_str=blocks_args_str, + spatial_dims=spatial_dims, + in_channels=in_channels, + num_classes=num_classes, + width_coefficient=weight_coeff, + depth_coefficient=depth_coeff, + dropout_rate=dropout_rate, + image_size=image_size, + drop_connect_rate=dropconnect_rate, + norm=norm, + ) + + # only pretrained for when `spatial_dims` is 2 + if pretrained and (spatial_dims == 2): + _load_state_dict(self, model_name, progress, adv_prop) + + def forward(self, inputs: torch.Tensor): + """ + Args: + inputs: input should have spatially N dimensions + ``(Batch, in_channels, dim_0[, dim_1, ..., dim_N])``, N is defined by `dimensions`. + + Returns: + a list of torch Tensors. + """ + # Stem + x = self._conv_stem(self._conv_stem_padding(inputs)) + x = self._swish(self._bn0(x)) + + features = [] + if 0 in self.extract_stacks: + features.append(x) + for i, block in enumerate(self._blocks): + x = block(x) + if i + 1 in self.extract_stacks: + features.append(x) + return features + + +class EfficientNetEncoder(EfficientNetBNFeatures, BaseEncoder): + """ + Wrap the original efficientnet to an encoder for flexible-unet. + """ + + backbone_names = [ + "efficientnet-b0", + "efficientnet-b1", + "efficientnet-b2", + "efficientnet-b3", + "efficientnet-b4", + "efficientnet-b5", + "efficientnet-b6", + "efficientnet-b7", + "efficientnet-b8", + "efficientnet-l2", + ] + + @classmethod + def get_encoder_parameters(cls) -> list[dict]: + """ + Get the initialization parameter for efficientnet backbones. + """ + parameter_list = [] + for backbone_name in cls.backbone_names: + parameter_list.append( + { + "model_name": backbone_name, + "pretrained": True, + "progress": True, + "spatial_dims": 2, + "in_channels": 3, + "num_classes": 1000, + "norm": ("batch", {"eps": 1e-3, "momentum": 0.01}), + "adv_prop": "ap" in backbone_name, + } + ) + return parameter_list + + @classmethod + def num_channels_per_output(cls) -> list[tuple[int, ...]]: + """ + Get number of efficientnet backbone output feature maps' channel. + """ + return [ + (16, 24, 40, 112, 320), + (16, 24, 40, 112, 320), + (16, 24, 48, 120, 352), + (24, 32, 48, 136, 384), + (24, 32, 56, 160, 448), + (24, 40, 64, 176, 512), + (32, 40, 72, 200, 576), + (32, 48, 80, 224, 640), + (32, 56, 88, 248, 704), + (72, 104, 176, 480, 1376), + ] + + @classmethod + def num_outputs(cls) -> list[int]: + """ + Get number of efficientnet backbone output feature maps. + Since every backbone contains the same 5 output feature maps, + the number list should be `[5] * 10`. + """ + return [5] * 10 + + @classmethod + def get_encoder_names(cls) -> list[str]: + """ + Get names of efficient backbone. + """ + return cls.backbone_names + + +def get_efficientnet_image_size(model_name: str) -> int: + """ + Get the input image size for a given efficientnet model. + + Args: + model_name: name of model to initialize, can be from [efficientnet-b0, ..., efficientnet-b7]. + + Returns: + Image size for single spatial dimension as integer. + + """ + # check if model_name is valid model + if model_name not in efficientnet_params: + model_name_string = ", ".join(efficientnet_params.keys()) + raise ValueError(f"invalid model_name {model_name} found, must be one of {model_name_string} ") + + # return input image size (all dims equal so only need to return for one dim) + _, _, res, _, _ = efficientnet_params[model_name] + return res + + +def drop_connect(inputs: torch.Tensor, p: float, training: bool) -> torch.Tensor: + """ + Drop connect layer that drops individual connections. + Differs from dropout as dropconnect drops connections instead of whole neurons as in dropout. + + Based on `Deep Networks with Stochastic Depth `_. + Adapted from `Official Tensorflow EfficientNet utils + `_. + + This function is generalized for MONAI's N-Dimensional spatial activations + e.g. 1D activations [B, C, H], 2D activations [B, C, H, W] and 3D activations [B, C, H, W, D] + + Args: + inputs: input tensor with [B, C, dim_1, dim_2, ..., dim_N] where N=spatial_dims. + p: probability to use for dropping connections. + training: whether in training or evaluation mode. + + Returns: + output: output tensor after applying drop connection. + """ + if p < 0.0 or p > 1.0: + raise ValueError(f"p must be in range of [0, 1], found {p}") + + # eval mode: drop_connect is switched off - so return input without modifying + if not training: + return inputs + + # train mode: calculate and apply drop_connect + batch_size: int = inputs.shape[0] + keep_prob: float = 1 - p + num_dims: int = len(inputs.shape) - 2 + + # build dimensions for random tensor, use num_dims to populate appropriate spatial dims + random_tensor_shape: list[int] = [batch_size, 1] + [1] * num_dims + + # generate binary_tensor mask according to probability (p for 0, 1-p for 1) + random_tensor: torch.Tensor = torch.rand(random_tensor_shape, dtype=inputs.dtype, device=inputs.device) + random_tensor += keep_prob + + # round to form binary tensor + binary_tensor: torch.Tensor = torch.floor(random_tensor) + + # drop connect using binary tensor + output: torch.Tensor = inputs / keep_prob * binary_tensor + return output + + +def _load_state_dict(model: nn.Module, arch: str, progress: bool, adv_prop: bool) -> None: + if adv_prop: + arch = arch.split("efficientnet-")[-1] + "-ap" + model_url = look_up_option(arch, url_map, None) + if model_url is None: + print(f"pretrained weights of {arch} is not provided") + else: + # load state dict from url + model_url = url_map[arch] + pretrain_state_dict = model_zoo.load_url(model_url, progress=progress) + model_state_dict = model.state_dict() + + pattern = re.compile(r"(.+)\.\d+(\.\d+\..+)") + for key, value in model_state_dict.items(): + pretrain_key = re.sub(pattern, r"\1\2", key) + if pretrain_key in pretrain_state_dict and value.shape == pretrain_state_dict[pretrain_key].shape: + model_state_dict[key] = pretrain_state_dict[pretrain_key] + + model.load_state_dict(model_state_dict) + + +def _get_same_padding_conv_nd( + image_size: list[int], kernel_size: tuple[int, ...], dilation: tuple[int, ...], stride: tuple[int, ...] +) -> list[int]: + """ + Helper for getting padding (nn.ConstantPadNd) to be used to get SAME padding + conv operations similar to Tensorflow's SAME padding. + + This function is generalized for MONAI's N-Dimensional spatial operations (e.g. Conv1D, Conv2D, Conv3D) + + Args: + image_size: input image/feature spatial size. + kernel_size: conv kernel's spatial size. + dilation: conv dilation rate for Atrous conv. + stride: stride for conv operation. + + Returns: + paddings for ConstantPadNd padder to be used on input tensor to conv op. + """ + # get number of spatial dimensions, corresponds to kernel size length + num_dims = len(kernel_size) + + # additional checks to populate dilation and stride (in case they are single entry tuples) + if len(dilation) == 1: + dilation = dilation * num_dims + + if len(stride) == 1: + stride = stride * num_dims + + # equation to calculate (pad^+ + pad^-) size + _pad_size: list[int] = [ + max((math.ceil(_i_s / _s) - 1) * _s + (_k_s - 1) * _d + 1 - _i_s, 0) + for _i_s, _k_s, _d, _s in zip(image_size, kernel_size, dilation, stride) + ] + # distribute paddings into pad^+ and pad^- following Tensorflow's same padding strategy + _paddings: list[tuple[int, int]] = [(_p // 2, _p - _p // 2) for _p in _pad_size] + + # unroll list of tuples to tuples, and then to list + # reversed as nn.ConstantPadNd expects paddings starting with last dimension + _paddings_ret: list[int] = [outer for inner in reversed(_paddings) for outer in inner] + return _paddings_ret + + +def _make_same_padder(conv_op: nn.Conv1d | nn.Conv2d | nn.Conv3d, image_size: list[int]): + """ + Helper for initializing ConstantPadNd with SAME padding similar to Tensorflow. + Uses output of _get_same_padding_conv_nd() to get the padding size. + + This function is generalized for MONAI's N-Dimensional spatial operations (e.g. Conv1D, Conv2D, Conv3D) + + Args: + conv_op: nn.ConvNd operation to extract parameters for op from + image_size: input image/feature spatial size + + Returns: + If padding required then nn.ConstandNd() padder initialized to paddings otherwise nn.Identity() + """ + # calculate padding required + padding: list[int] = _get_same_padding_conv_nd(image_size, conv_op.kernel_size, conv_op.dilation, conv_op.stride) + + # initialize and return padder + padder = Pad["constantpad", len(padding) // 2] + if sum(padding) > 0: + return padder(padding=padding, value=0.0) + return nn.Identity() + + +def _round_filters(filters: int, width_coefficient: float | None, depth_divisor: float) -> int: + """ + Calculate and round number of filters based on width coefficient multiplier and depth divisor. + + Args: + filters: number of input filters. + width_coefficient: width coefficient for model. + depth_divisor: depth divisor to use. + + Returns: + new_filters: new number of filters after calculation. + """ + + if not width_coefficient: + return filters + + multiplier: float = width_coefficient + divisor: float = depth_divisor + filters_float: float = filters * multiplier + + # follow the formula transferred from official TensorFlow implementation + new_filters: float = max(divisor, int(filters_float + divisor / 2) // divisor * divisor) + if new_filters < 0.9 * filters_float: # prevent rounding by more than 10% + new_filters += divisor + return int(new_filters) + + +def _round_repeats(repeats: int, depth_coefficient: float | None) -> int: + """ + Re-calculate module's repeat number of a block based on depth coefficient multiplier. + + Args: + repeats: number of original repeats. + depth_coefficient: depth coefficient for model. + + Returns: + new repeat: new number of repeat after calculating. + """ + if not depth_coefficient: + return repeats + + # follow the formula transferred from official TensorFlow impl. + return int(math.ceil(depth_coefficient * repeats)) + + +def _calculate_output_image_size(input_image_size: list[int], stride: int | tuple[int]): + """ + Calculates the output image size when using _make_same_padder with a stride. + Required for static padding. + + Args: + input_image_size: input image/feature spatial size. + stride: Conv2d operation"s stride. + + Returns: + output_image_size: output image/feature spatial size. + """ + + # checks to extract integer stride in case tuple was received + if isinstance(stride, tuple): + all_strides_equal = all(stride[0] == s for s in stride) + if not all_strides_equal: + raise ValueError(f"unequal strides are not possible, got {stride}") + + stride = stride[0] + + # return output image size + return [int(math.ceil(im_sz / stride)) for im_sz in input_image_size] + + +class BlockArgs(NamedTuple): + """ + BlockArgs object to assist in decoding string notation + of arguments for MBConvBlock definition. + """ + + num_repeat: int + kernel_size: int + stride: int + expand_ratio: int + input_filters: int + output_filters: int + id_skip: bool + se_ratio: float | None = None + + @staticmethod + def from_string(block_string: str): + """ + Get a BlockArgs object from a string notation of arguments. + + Args: + block_string (str): A string notation of arguments. + Examples: "r1_k3_s11_e1_i32_o16_se0.25". + + Returns: + BlockArgs: namedtuple defined at the top of this function. + """ + ops = block_string.split("_") + options = {} + for op in ops: + splits = re.split(r"(\d.*)", op) + if len(splits) >= 2: + key, value = splits[:2] + options[key] = value + + # check stride + stride_check = ( + ("s" in options and len(options["s"]) == 1) + or (len(options["s"]) == 2 and options["s"][0] == options["s"][1]) + or (len(options["s"]) == 3 and options["s"][0] == options["s"][1] and options["s"][0] == options["s"][2]) + ) + if not stride_check: + raise ValueError("invalid stride option received") + + return BlockArgs( + num_repeat=int(options["r"]), + kernel_size=int(options["k"]), + stride=int(options["s"][0]), + expand_ratio=int(options["e"]), + input_filters=int(options["i"]), + output_filters=int(options["o"]), + id_skip=("noskip" not in block_string), + se_ratio=float(options["se"]) if "se" in options else None, + ) + + def to_string(self): + """ + Return a block string notation for current BlockArgs object + + Returns: + A string notation of BlockArgs object arguments. + Example: "r1_k3_s11_e1_i32_o16_se0.25_noskip". + """ + string = ( + f"r{self.num_repeat}_k{self.kernel_size}_s{self.stride}{self.stride}" + f"_e{self.expand_ratio}_i{self.input_filters}_o{self.output_filters}" + f"_se{self.se_ratio}" + ) + + if not self.id_skip: + string += "_noskip" + return string diff --git a/source_code/SegMamba/monai/networks/nets/fullyconnectednet.py b/source_code/SegMamba/monai/networks/nets/fullyconnectednet.py new file mode 100644 index 0000000000000000000000000000000000000000..fe9a8a0cd632299c3f7efa3706f1d690853c5ab2 --- /dev/null +++ b/source_code/SegMamba/monai/networks/nets/fullyconnectednet.py @@ -0,0 +1,185 @@ +# Copyright (c) MONAI Consortium +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from __future__ import annotations + +from collections.abc import Sequence + +import torch +import torch.nn as nn + +from monai.networks.blocks import ADN +from monai.networks.layers.factories import Act + +__all__ = ["FullyConnectedNet", "VarFullyConnectedNet"] + + +def _get_adn_layer(act: tuple | str | None, dropout: tuple | str | float | None, ordering: str | None) -> ADN: + if ordering: + return ADN(act=act, dropout=dropout, dropout_dim=1, ordering=ordering) + return ADN(act=act, dropout=dropout, dropout_dim=1) + + +class FullyConnectedNet(nn.Sequential): + """ + Simple full-connected layer neural network composed of a sequence of linear layers with PReLU activation and + dropout. The network accepts input with `in_channels` channels, has output with `out_channels` channels, and + hidden layer output channels given in `hidden_channels`. If `bias` is True then linear units have a bias term. + + Args: + in_channels: number of input channels. + out_channels: number of output channels. + hidden_channels: number of output channels for each hidden layer. + dropout: dropout ratio. Defaults to no dropout. + act: activation type and arguments. Defaults to PReLU. + bias: whether to have a bias term in linear units. Defaults to True. + adn_ordering: order of operations in :py:class:`monai.networks.blocks.ADN`. + + Examples:: + + # accepts 4 values and infers 3 values as output, has 3 hidden layers with 10, 20, 10 values as output + net = FullyConnectedNet(4, 3, [10, 20, 10], dropout=0.2) + + """ + + def __init__( + self, + in_channels: int, + out_channels: int, + hidden_channels: Sequence[int], + dropout: tuple | str | float | None = None, + act: tuple | str | None = Act.PRELU, + bias: bool = True, + adn_ordering: str | None = None, + ) -> None: + """ + Defines a network accept input with `in_channels` channels, output of `out_channels` channels, and hidden layers + with channels given in `hidden_channels`. If `bias` is True then linear units have a bias term. + """ + super().__init__() + self.in_channels = in_channels + self.out_channels = out_channels + self.hidden_channels = list(hidden_channels) + self.act = act + self.dropout = dropout + self.adn_ordering = adn_ordering + + self.add_module("flatten", nn.Flatten()) + + prev_channels = self.in_channels + for i, c in enumerate(hidden_channels): + self.add_module("hidden_%i" % i, self._get_layer(prev_channels, c, bias)) + prev_channels = c + + self.add_module("output", nn.Linear(prev_channels, out_channels, bias)) + + def _get_layer(self, in_channels: int, out_channels: int, bias: bool) -> nn.Sequential: + seq = nn.Sequential( + nn.Linear(in_channels, out_channels, bias), _get_adn_layer(self.act, self.dropout, self.adn_ordering) + ) + return seq + + +class VarFullyConnectedNet(nn.Module): + """ + Variational fully-connected network. This is composed of an encode layer, reparameterization layer, and then a + decode layer. + + Args: + in_channels: number of input channels. + out_channels: number of output channels. + latent_size: number of latent variables to use. + encode_channels: number of output channels for each hidden layer of the encode half. + decode_channels: number of output channels for each hidden layer of the decode half. + dropout: dropout ratio. Defaults to no dropout. + act: activation type and arguments. Defaults to PReLU. + bias: whether to have a bias term in linear units. Defaults to True. + adn_ordering: order of operations in :py:class:`monai.networks.blocks.ADN`. + + Examples:: + + # accepts inputs with 4 values, uses a latent space of 2 variables, and produces outputs of 3 values + net = VarFullyConnectedNet(4, 3, 2, [5, 10], [10, 5]) + + """ + + def __init__( + self, + in_channels: int, + out_channels: int, + latent_size: int, + encode_channels: Sequence[int], + decode_channels: Sequence[int], + dropout: tuple | str | float | None = None, + act: tuple | str | None = Act.PRELU, + bias: bool = True, + adn_ordering: str | None = None, + ) -> None: + super().__init__() + self.in_channels = in_channels + self.out_channels = out_channels + self.latent_size = latent_size + + self.encode = nn.Sequential() + self.decode = nn.Sequential() + self.flatten = nn.Flatten() + + self.adn_layer = _get_adn_layer(act, dropout, adn_ordering) + + prev_channels = self.in_channels + for i, c in enumerate(encode_channels): + self.encode.add_module("encode_%i" % i, self._get_layer(prev_channels, c, bias)) + prev_channels = c + + self.mu = nn.Linear(prev_channels, self.latent_size) + self.logvar = nn.Linear(prev_channels, self.latent_size) + self.decodeL = nn.Linear(self.latent_size, prev_channels) + + for i, c in enumerate(decode_channels): + self.decode.add_module("decode%i" % i, self._get_layer(prev_channels, c, bias)) + prev_channels = c + + self.decode.add_module("final", nn.Linear(prev_channels, out_channels, bias)) + + def _get_layer(self, in_channels: int, out_channels: int, bias: bool) -> nn.Sequential: + seq = nn.Sequential(nn.Linear(in_channels, out_channels, bias)) + seq.add_module("ADN", self.adn_layer) + return seq + + def encode_forward(self, x: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]: + x = self.encode(x) + x = self.flatten(x) + mu = self.mu(x) + logvar = self.logvar(x) + return mu, logvar + + def decode_forward(self, z: torch.Tensor, use_sigmoid: bool = True) -> torch.Tensor: + x: torch.Tensor + x = self.decodeL(z) + x = torch.relu(x) + x = self.flatten(x) + x = self.decode(x) + if use_sigmoid: + x = torch.sigmoid(x) + return x + + def reparameterize(self, mu: torch.Tensor, logvar: torch.Tensor) -> torch.Tensor: + std = torch.exp(0.5 * logvar) + + if self.training: # multiply random noise with std only during training + std = torch.randn_like(std).mul(std) + + return std.add_(mu) + + def forward(self, x: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]: + mu, logvar = self.encode_forward(x) + z = self.reparameterize(mu, logvar) + return self.decode_forward(z), mu, logvar, z diff --git a/source_code/SegMamba/monai/networks/nets/generator.py b/source_code/SegMamba/monai/networks/nets/generator.py new file mode 100644 index 0000000000000000000000000000000000000000..32428b26965ad032176e80ff677dac0c272b98db --- /dev/null +++ b/source_code/SegMamba/monai/networks/nets/generator.py @@ -0,0 +1,151 @@ +# Copyright (c) MONAI Consortium +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from __future__ import annotations + +from collections.abc import Sequence + +import numpy as np +import torch +import torch.nn as nn + +from monai.networks.blocks import Convolution, ResidualUnit +from monai.networks.layers.factories import Act, Norm +from monai.networks.layers.simplelayers import Reshape +from monai.utils import ensure_tuple, ensure_tuple_rep + + +class Generator(nn.Module): + """ + Defines a simple generator network accepting a latent vector and through a sequence of convolution layers + constructs an output tensor of greater size and high dimensionality. The method `_get_layer` is used to + create each of these layers, override this method to define layers beyond the default + :py:class:`monai.networks.blocks.Convolution` or :py:class:`monai.networks.blocks.ResidualUnit` layers. + + The layers are constructed using the values in the `channels` and `strides` arguments, the number being defined by + the length of these (which must match). Input is first passed through a :py:class:`torch.nn.Linear` layer to + convert the input vector to an image tensor with dimensions `start_shape`. This passes through the convolution + layers and is progressively upsampled if the `strides` values are greater than 1 using transpose convolutions. The + size of the final output is defined by the `start_shape` dimension and the amount of upsampling done through + strides. In the default definition the size of the output's spatial dimensions will be that of `start_shape` + multiplied by the product of `strides`, thus the example network below upsamples an starting size of (64, 8, 8) + to (1, 64, 64) since its `strides` are (2, 2, 2). + + Args: + latent_shape: tuple of integers stating the dimension of the input latent vector (minus batch dimension) + start_shape: tuple of integers stating the dimension of the tensor to pass to convolution subnetwork + channels: tuple of integers stating the output channels of each convolutional layer + strides: tuple of integers stating the stride (upscale factor) of each convolutional layer + kernel_size: integer or tuple of integers stating size of convolutional kernels + num_res_units: integer stating number of convolutions in residual units, 0 means no residual units + act: name or type defining activation layers + norm: name or type defining normalization layers + dropout: optional float value in range [0, 1] stating dropout probability for layers, None for no dropout + bias: boolean stating if convolution layers should have a bias component + + Examples:: + + # 3 layers, latent input vector of shape (42, 24), output volume of shape (1, 64, 64) + net = Generator((42, 24), (64, 8, 8), (32, 16, 1), (2, 2, 2)) + + """ + + def __init__( + self, + latent_shape: Sequence[int], + start_shape: Sequence[int], + channels: Sequence[int], + strides: Sequence[int], + kernel_size: Sequence[int] | int = 3, + num_res_units: int = 2, + act=Act.PRELU, + norm=Norm.INSTANCE, + dropout: float | None = None, + bias: bool = True, + ) -> None: + super().__init__() + + self.in_channels, *self.start_shape = ensure_tuple(start_shape) + self.dimensions = len(self.start_shape) + + self.latent_shape = ensure_tuple(latent_shape) + self.channels = ensure_tuple(channels) + self.strides = ensure_tuple(strides) + self.kernel_size = ensure_tuple_rep(kernel_size, self.dimensions) + self.num_res_units = num_res_units + self.act = act + self.norm = norm + self.dropout = dropout + self.bias = bias + + self.flatten = nn.Flatten() + self.linear = nn.Linear(int(np.prod(self.latent_shape)), int(np.prod(start_shape))) + self.reshape = Reshape(*start_shape) + self.conv = nn.Sequential() + + echannel = self.in_channels + + # transform tensor of shape `start_shape' into output shape through transposed convolutions and residual units + for i, (c, s) in enumerate(zip(channels, strides)): + is_last = i == len(channels) - 1 + layer = self._get_layer(echannel, c, s, is_last) + self.conv.add_module("layer_%i" % i, layer) + echannel = c + + def _get_layer( + self, in_channels: int, out_channels: int, strides: int, is_last: bool + ) -> Convolution | nn.Sequential: + """ + Returns a layer accepting inputs with `in_channels` number of channels and producing outputs of `out_channels` + number of channels. The `strides` indicates upsampling factor, ie. transpose convolutional stride. If `is_last` + is True this is the final layer and is not expected to include activation and normalization layers. + """ + + layer: Convolution | nn.Sequential + + layer = Convolution( + in_channels=in_channels, + strides=strides, + is_transposed=True, + conv_only=is_last or self.num_res_units > 0, + spatial_dims=self.dimensions, + out_channels=out_channels, + kernel_size=self.kernel_size, + act=self.act, + norm=self.norm, + dropout=self.dropout, + bias=self.bias, + ) + + if self.num_res_units > 0: + ru = ResidualUnit( + in_channels=out_channels, + subunits=self.num_res_units, + last_conv_only=is_last, + spatial_dims=self.dimensions, + out_channels=out_channels, + kernel_size=self.kernel_size, + act=self.act, + norm=self.norm, + dropout=self.dropout, + bias=self.bias, + ) + + layer = nn.Sequential(layer, ru) + + return layer + + def forward(self, x: torch.Tensor) -> torch.Tensor: + x = self.flatten(x) + x = self.linear(x) + x = self.reshape(x) + x = self.conv(x) + return x diff --git a/source_code/SegMamba/monai/networks/utils.py b/source_code/SegMamba/monai/networks/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..152911f4439db323815bf9597d48777ed052f03e --- /dev/null +++ b/source_code/SegMamba/monai/networks/utils.py @@ -0,0 +1,1169 @@ +# Copyright (c) MONAI Consortium +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +""" +Utilities and types for defining networks, these depend on PyTorch. +""" + +from __future__ import annotations + +import io +import re +import warnings +from collections import OrderedDict +from collections.abc import Callable, Mapping, Sequence +from contextlib import contextmanager +from copy import deepcopy +from typing import Any + +import numpy as np +import torch +import torch.nn as nn + +from monai.apps.utils import get_logger +from monai.config import PathLike +from monai.utils.misc import ensure_tuple, save_obj, set_determinism +from monai.utils.module import look_up_option, optional_import, pytorch_after +from monai.utils.type_conversion import convert_to_dst_type, convert_to_tensor + +onnx, _ = optional_import("onnx") +onnxreference, _ = optional_import("onnx.reference") +onnxruntime, _ = optional_import("onnxruntime") + +__all__ = [ + "one_hot", + "predict_segmentation", + "normalize_transform", + "to_norm_affine", + "normal_init", + "icnr_init", + "pixelshuffle", + "eval_mode", + "train_mode", + "get_state_dict", + "copy_model_state", + "save_state", + "convert_to_onnx", + "convert_to_torchscript", + "convert_to_trt", + "meshgrid_ij", + "meshgrid_xy", + "replace_modules", + "replace_modules_temp", + "look_up_named_module", + "set_named_module", + "has_nvfuser_instance_norm", +] + +logger = get_logger(module_name=__name__) + +_has_nvfuser = None + + +def has_nvfuser_instance_norm(): + """whether the current environment has InstanceNorm3dNVFuser + https://github.com/NVIDIA/apex/blob/23.05-devel/apex/normalization/instance_norm.py#L15-L16 + """ + global _has_nvfuser + if _has_nvfuser is not None: + return _has_nvfuser + + _, _has_nvfuser = optional_import("apex.normalization", name="InstanceNorm3dNVFuser") + if not _has_nvfuser: + return False + try: + import importlib + + importlib.import_module("instance_norm_nvfuser_cuda") + except ImportError: + _has_nvfuser = False + return _has_nvfuser + + +def look_up_named_module(name: str, mod, print_all_options=False): + """ + get the named module in `mod` by the attribute name, + for example ``look_up_named_module(net, "features.3.1.attn")`` + + Args: + name: a string representing the module attribute. + mod: a pytorch module to be searched (in ``mod.named_modules()``). + print_all_options: whether to print all named modules when `name` is not found in `mod`. Defaults to False. + + Returns: + the corresponding pytorch module's subcomponent such as ``net.features[3][1].attn`` + """ + name_str = look_up_option( + name, {n[0] for n in mod.named_modules()}, default=None, print_all_options=print_all_options + ) + if name_str is None: + return None + if name_str == "": + return mod + for n in name_str.split("."): + if n.isdigit(): + mod = mod[int(n)] + else: + n = look_up_option(n, {item[0] for item in mod.named_modules()}, default=None, print_all_options=False) + if n is None: + return None + mod = getattr(mod, n) + return mod + + +def set_named_module(mod, name: str, new_layer): + """ + look up `name` in `mod` and replace the layer with `new_layer`, return the updated `mod`. + + Args: + mod: a pytorch module to be updated. + name: a string representing the target module attribute. + new_layer: a new module replacing the corresponding layer at ``mod.name``. + + Returns: + an updated ``mod`` + + See also: :py:func:`monai.networks.utils.look_up_named_module`. + """ + mods_attr = name.rsplit(".", 1) + submods, attr = mods_attr if len(mods_attr) == 2 else ("", name) + if not attr: + return new_layer + _mod = look_up_named_module(submods, mod) + setattr(_mod, attr, new_layer) + return mod + + +def one_hot(labels: torch.Tensor, num_classes: int, dtype: torch.dtype = torch.float, dim: int = 1) -> torch.Tensor: + """ + For every value v in `labels`, the value in the output will be either 1 or 0. Each vector along the `dim`-th + dimension has the "one-hot" format, i.e., it has a total length of `num_classes`, + with a one and `num_class-1` zeros. + Note that this will include the background label, thus a binary mask should be treated as having two classes. + + Args: + labels: input tensor of integers to be converted into the 'one-hot' format. Internally `labels` will be + converted into integers `labels.long()`. + num_classes: number of output channels, the corresponding length of `labels[dim]` will be converted to + `num_classes` from `1`. + dtype: the data type of the output one_hot label. + dim: the dimension to be converted to `num_classes` channels from `1` channel, should be non-negative number. + + Example: + + For a tensor `labels` of dimensions [B]1[spatial_dims], return a tensor of dimensions `[B]N[spatial_dims]` + when `num_classes=N` number of classes and `dim=1`. + + .. code-block:: python + + from monai.networks.utils import one_hot + import torch + + a = torch.randint(0, 2, size=(1, 2, 2, 2)) + out = one_hot(a, num_classes=2, dim=0) + print(out.shape) # torch.Size([2, 2, 2, 2]) + + a = torch.randint(0, 2, size=(2, 1, 2, 2, 2)) + out = one_hot(a, num_classes=2, dim=1) + print(out.shape) # torch.Size([2, 2, 2, 2, 2]) + + """ + + # if `dim` is bigger, add singleton dim at the end + if labels.ndim < dim + 1: + shape = list(labels.shape) + [1] * (dim + 1 - len(labels.shape)) + labels = torch.reshape(labels, shape) + + sh = list(labels.shape) + + if sh[dim] != 1: + raise AssertionError("labels should have a channel with length equal to one.") + + sh[dim] = num_classes + + o = torch.zeros(size=sh, dtype=dtype, device=labels.device) + labels = o.scatter_(dim=dim, index=labels.long(), value=1) + + return labels + + +def predict_segmentation(logits: torch.Tensor, mutually_exclusive: bool = False, threshold: float = 0.0) -> Any: + """ + Given the logits from a network, computing the segmentation by thresholding all values above 0 + if multi-labels task, computing the `argmax` along the channel axis if multi-classes task, + logits has shape `BCHW[D]`. + + Args: + logits: raw data of model output. + mutually_exclusive: if True, `logits` will be converted into a binary matrix using + a combination of argmax, which is suitable for multi-classes task. Defaults to False. + threshold: thresholding the prediction values if multi-labels task. + """ + if not mutually_exclusive: + return (logits >= threshold).int() + if logits.shape[1] == 1: + warnings.warn("single channel prediction, `mutually_exclusive=True` ignored, use threshold instead.") + return (logits >= threshold).int() + return logits.argmax(1, keepdim=True) + + +def normalize_transform( + shape, + device: torch.device | str | None = None, + dtype: torch.dtype | None = None, + align_corners: bool = False, + zero_centered: bool = False, +) -> torch.Tensor: + """ + Compute an affine matrix according to the input shape. + The transform normalizes the homogeneous image coordinates to the + range of `[-1, 1]`. Currently the following source coordinates are supported: + + - `align_corners=False`, `zero_centered=False`, normalizing from ``[-0.5, d-0.5]``. + - `align_corners=True`, `zero_centered=False`, normalizing from ``[0, d-1]``. + - `align_corners=False`, `zero_centered=True`, normalizing from ``[-(d-1)/2, (d-1)/2]``. + - `align_corners=True`, `zero_centered=True`, normalizing from ``[-d/2, d/2]``. + + Args: + shape: input spatial shape, a sequence of integers. + device: device on which the returned affine will be allocated. + dtype: data type of the returned affine + align_corners: if True, consider -1 and 1 to refer to the centers of the + corner pixels rather than the image corners. + See also: https://pytorch.org/docs/stable/nn.functional.html#torch.nn.functional.grid_sample + zero_centered: whether the coordinates are normalized from a zero-centered range, default to `False`. + Setting this flag and `align_corners` will jointly specify the normalization source range. + """ + shape = convert_to_tensor(shape, torch.float64, device=device, wrap_sequence=True, track_meta=False) + norm = shape.clone().detach().to(dtype=torch.float64, device=device) # no in-place change + if align_corners: + norm[norm <= 1.0] = 2.0 + norm = 2.0 / (norm if zero_centered else norm - 1.0) + norm = torch.diag(torch.cat((norm, torch.ones((1,), dtype=torch.float64, device=device)))) + if not zero_centered: # else shift is 0 + norm[:-1, -1] = -1.0 + else: + norm[norm <= 0.0] = 2.0 + norm = 2.0 / (norm - 1.0 if zero_centered else norm) + norm = torch.diag(torch.cat((norm, torch.ones((1,), dtype=torch.float64, device=device)))) + if not zero_centered: + norm[:-1, -1] = 1.0 / shape - 1.0 + norm = norm.unsqueeze(0).to(dtype=dtype) + norm.requires_grad = False + return norm # type: ignore + + +def to_norm_affine( + affine: torch.Tensor, + src_size: Sequence[int], + dst_size: Sequence[int], + align_corners: bool = False, + zero_centered: bool = False, +) -> torch.Tensor: + """ + Given ``affine`` defined for coordinates in the pixel space, compute the corresponding affine + for the normalized coordinates. + + Args: + affine: Nxdxd batched square matrix + src_size: source image spatial shape + dst_size: target image spatial shape + align_corners: if True, consider -1 and 1 to refer to the centers of the + corner pixels rather than the image corners. + See also: https://pytorch.org/docs/stable/nn.functional.html#torch.nn.functional.grid_sample + zero_centered: whether the coordinates are normalized from a zero-centered range, default to `False`. + See also: :py:func:`monai.networks.utils.normalize_transform`. + + Raises: + TypeError: When ``affine`` is not a ``torch.Tensor``. + ValueError: When ``affine`` is not Nxdxd. + ValueError: When ``src_size`` or ``dst_size`` dimensions differ from ``affine``. + + """ + if not isinstance(affine, torch.Tensor): + raise TypeError(f"affine must be a torch.Tensor but is {type(affine).__name__}.") + if affine.ndimension() != 3 or affine.shape[1] != affine.shape[2]: + raise ValueError(f"affine must be Nxdxd, got {tuple(affine.shape)}.") + sr = affine.shape[1] - 1 + if sr != len(src_size) or sr != len(dst_size): + raise ValueError(f"affine suggests {sr}D, got src={len(src_size)}D, dst={len(dst_size)}D.") + + src_xform = normalize_transform(src_size, affine.device, affine.dtype, align_corners, zero_centered) + dst_xform = normalize_transform(dst_size, "cpu", affine.dtype, align_corners, zero_centered) + return src_xform @ affine @ convert_to_dst_type(np.linalg.inv(dst_xform.numpy()), dst=affine)[0] # monai#5983 + + +def normal_init( + m, std: float = 0.02, normal_func: Callable[[torch.Tensor, float, float], Any] = torch.nn.init.normal_ +) -> None: + """ + Initialize the weight and bias tensors of `m' and its submodules to values from a normal distribution with a + stddev of `std'. Weight tensors of convolution and linear modules are initialized with a mean of 0, batch + norm modules with a mean of 1. The callable `normal_func', used to assign values, should have the same arguments + as its default normal_(). This can be used with `nn.Module.apply` to visit submodules of a network. + """ + cname = m.__class__.__name__ + + if getattr(m, "weight", None) is not None and (cname.find("Conv") != -1 or cname.find("Linear") != -1): + normal_func(m.weight.data, 0.0, std) + if getattr(m, "bias", None) is not None: + nn.init.constant_(m.bias.data, 0.0) + + elif cname.find("BatchNorm") != -1: + normal_func(m.weight.data, 1.0, std) + nn.init.constant_(m.bias.data, 0) + + +def icnr_init(conv, upsample_factor, init=nn.init.kaiming_normal_): + """ + ICNR initialization for 2D/3D kernels adapted from Aitken et al.,2017 , "Checkerboard artifact free + sub-pixel convolution". + """ + out_channels, in_channels, *dims = conv.weight.shape + scale_factor = upsample_factor ** len(dims) + + oc2 = int(out_channels / scale_factor) + + kernel = torch.zeros([oc2, in_channels] + dims) + kernel = init(kernel) + kernel = kernel.transpose(0, 1) + kernel = kernel.reshape(oc2, in_channels, -1) + kernel = kernel.repeat(1, 1, scale_factor) + kernel = kernel.reshape([in_channels, out_channels] + dims) + kernel = kernel.transpose(0, 1) + conv.weight.data.copy_(kernel) + + +def pixelshuffle(x: torch.Tensor, spatial_dims: int, scale_factor: int) -> torch.Tensor: + """ + Apply pixel shuffle to the tensor `x` with spatial dimensions `spatial_dims` and scaling factor `scale_factor`. + + See: Shi et al., 2016, "Real-Time Single Image and Video Super-Resolution + Using a nEfficient Sub-Pixel Convolutional Neural Network." + + See: Aitken et al., 2017, "Checkerboard artifact free sub-pixel convolution". + + Args: + x: Input tensor + spatial_dims: number of spatial dimensions, typically 2 or 3 for 2D or 3D + scale_factor: factor to rescale the spatial dimensions by, must be >=1 + + Returns: + Reshuffled version of `x`. + + Raises: + ValueError: When input channels of `x` are not divisible by (scale_factor ** spatial_dims) + """ + dim, factor = spatial_dims, scale_factor + input_size = list(x.size()) + batch_size, channels = input_size[:2] + scale_divisor = factor**dim + + if channels % scale_divisor != 0: + raise ValueError( + f"Number of input channels ({channels}) must be evenly " + f"divisible by scale_factor ** dimensions ({factor}**{dim}={scale_divisor})." + ) + + org_channels = int(channels // scale_divisor) + output_size = [batch_size, org_channels] + [d * factor for d in input_size[2:]] + + indices = list(range(2, 2 + 2 * dim)) + indices = indices[dim:] + indices[:dim] + permute_indices = [0, 1] + for idx in range(dim): + permute_indices.extend(indices[idx::dim]) + + x = x.reshape([batch_size, org_channels] + [factor] * dim + input_size[2:]) + x = x.permute(permute_indices).reshape(output_size) + return x + + +@contextmanager +def eval_mode(*nets: nn.Module): + """ + Set network(s) to eval mode and then return to original state at the end. + + Args: + nets: Input network(s) + + Examples + + .. code-block:: python + + t=torch.rand(1,1,16,16) + p=torch.nn.Conv2d(1,1,3) + print(p.training) # True + with eval_mode(p): + print(p.training) # False + print(p(t).sum().backward()) # will correctly raise an exception as gradients are calculated + """ + + # Get original state of network(s). + # Check the training attribute in case it's TensorRT based models which don't have this attribute. + training = [n for n in nets if hasattr(n, "training") and n.training] + + try: + # set to eval mode + with torch.no_grad(): + yield [n.eval() if hasattr(n, "eval") else n for n in nets] + finally: + # Return required networks to training + for n in training: + if hasattr(n, "train"): + n.train() + + +@contextmanager +def train_mode(*nets: nn.Module): + """ + Set network(s) to train mode and then return to original state at the end. + + Args: + nets: Input network(s) + + Examples + + .. code-block:: python + + t=torch.rand(1,1,16,16) + p=torch.nn.Conv2d(1,1,3) + p.eval() + print(p.training) # False + with train_mode(p): + print(p.training) # True + print(p(t).sum().backward()) # No exception + """ + + # Get original state of network(s) + # Check the training attribute in case it's TensorRT based models which don't have this attribute. + eval_list = [n for n in nets if hasattr(n, "training") and (not n.training)] + + try: + # set to train mode + with torch.set_grad_enabled(True): + yield [n.train() if hasattr(n, "train") else n for n in nets] + finally: + # Return required networks to eval_list + for n in eval_list: + if hasattr(n, "eval"): + n.eval() + + +def get_state_dict(obj: torch.nn.Module | Mapping): + """ + Get the state dict of input object if has `state_dict`, otherwise, return object directly. + For data parallel model, automatically convert it to regular model first. + + Args: + obj: input object to check and get the state_dict. + + """ + if isinstance(obj, (nn.DataParallel, nn.parallel.DistributedDataParallel)): + obj = obj.module + return obj.state_dict() if hasattr(obj, "state_dict") else obj + + +def copy_model_state( + dst: torch.nn.Module | Mapping, + src: torch.nn.Module | Mapping, + dst_prefix="", + mapping=None, + exclude_vars=None, + inplace=True, + filter_func=None, +): + """ + Compute a module state_dict, of which the keys are the same as `dst`. The values of `dst` are overwritten + by the ones from `src` whenever their keys match. The method provides additional `dst_prefix` for + the `dst` key when matching them. `mapping` can be a `{"src_key": "dst_key"}` dict, indicating + `dst[dst_prefix + dst_key] = src[src_key]`. + This function is mainly to return a model state dict + for loading the `src` model state into the `dst` model, `src` and `dst` can have different dict keys, but + their corresponding values normally have the same shape. + + Args: + dst: a pytorch module or state dict to be updated. + src: a pytorch module or state dict used to get the values used for the update. + dst_prefix: `dst` key prefix, so that `dst[dst_prefix + src_key]` + will be assigned to the value of `src[src_key]`. + mapping: a `{"src_key": "dst_key"}` dict, indicating that `dst[dst_prefix + dst_key]` + to be assigned to the value of `src[src_key]`. + exclude_vars: a regular expression to match the `dst` variable names, + so that their values are not overwritten by `src`. + inplace: whether to set the `dst` module with the updated `state_dict` via `load_state_dict`. + This option is only available when `dst` is a `torch.nn.Module`. + filter_func: a filter function used to filter the weights to be loaded. + See 'filter_swinunetr' in "monai.networks.nets.swin_unetr.py". + + Examples: + .. code-block:: python + + from monai.networks.nets import BasicUNet + from monai.networks.utils import copy_model_state + + model_a = BasicUNet(in_channels=1, out_channels=4) + model_b = BasicUNet(in_channels=1, out_channels=2) + model_a_b, changed, unchanged = copy_model_state( + model_a, model_b, exclude_vars="conv_0.conv_0", inplace=False) + # dst model updated: 76 of 82 variables. + model_a.load_state_dict(model_a_b) + # + + Returns: an OrderedDict of the updated `dst` state, the changed, and unchanged keys. + + """ + src_dict = get_state_dict(src) + dst_dict = OrderedDict(get_state_dict(dst)) + + to_skip = {s_key for s_key in src_dict if exclude_vars and re.compile(exclude_vars).search(s_key)} + + # update dst with items from src + all_keys, updated_keys = list(dst_dict), list() + for s, val in src_dict.items(): + dst_key = f"{dst_prefix}{s}" + if dst_key in dst_dict and dst_key not in to_skip and dst_dict[dst_key].shape == val.shape: + dst_dict[dst_key] = val + updated_keys.append(dst_key) + for s in mapping if mapping else {}: + dst_key = f"{dst_prefix}{mapping[s]}" + if dst_key in dst_dict and dst_key not in to_skip: + if dst_dict[dst_key].shape != src_dict[s].shape: + warnings.warn(f"Param. shape changed from {dst_dict[dst_key].shape} to {src_dict[s].shape}.") + dst_dict[dst_key] = src_dict[s] + updated_keys.append(dst_key) + if filter_func is not None: + for key, value in src_dict.items(): + new_pair = filter_func(key, value) + if new_pair is not None and new_pair[0] not in to_skip: + dst_dict[new_pair[0]] = new_pair[1] + updated_keys.append(new_pair[0]) + + updated_keys = sorted(set(updated_keys)) + unchanged_keys = sorted(set(all_keys).difference(updated_keys)) + logger.info(f"'dst' model updated: {len(updated_keys)} of {len(dst_dict)} variables.") + if inplace and isinstance(dst, torch.nn.Module): + if isinstance(dst, (nn.DataParallel, nn.parallel.DistributedDataParallel)): + dst = dst.module + dst.load_state_dict(dst_dict) # type: ignore + return dst_dict, updated_keys, unchanged_keys + + +def save_state(src: torch.nn.Module | dict, path: PathLike, **kwargs): + """ + Save the state dict of input source data with PyTorch `save`. + It can save `nn.Module`, `state_dict`, a dictionary of `nn.Module` or `state_dict`. + And automatically convert the data parallel module to regular module. + For example:: + + save_state(net, path) + save_state(net.state_dict(), path) + save_state({"net": net, "opt": opt}, path) + net_dp = torch.nn.DataParallel(net) + save_state(net_dp, path) + + Refer to: https://pytorch.org/ignite/v0.4.8/generated/ignite.handlers.DiskSaver.html. + + Args: + src: input data to save, can be `nn.Module`, `state_dict`, a dictionary of `nn.Module` or `state_dict`. + path: target file path to save the input object. + kwargs: other args for the `save_obj` except for the `obj` and `path`. + default `func` is `torch.save()`, details of the args: + https://pytorch.org/docs/stable/generated/torch.save.html. + + """ + + ckpt: dict = {} + if isinstance(src, dict): + for k, v in src.items(): + ckpt[k] = get_state_dict(v) + else: + ckpt = get_state_dict(src) + + save_obj(obj=ckpt, path=path, **kwargs) + + +def convert_to_onnx( + model: nn.Module, + inputs: Sequence[Any], + input_names: Sequence[str] | None = None, + output_names: Sequence[str] | None = None, + opset_version: int | None = None, + dynamic_axes: Mapping[str, Mapping[int, str]] | Mapping[str, Sequence[int]] | None = None, + filename: Any | None = None, + verify: bool = False, + device: torch.device | None = None, + use_ort: bool = False, + ort_provider: Sequence[str] | None = None, + rtol: float = 1e-4, + atol: float = 0.0, + use_trace: bool = True, + **kwargs, +): + """ + Utility to convert a model into ONNX model and optionally verify with ONNX or onnxruntime. + See also: https://pytorch.org/docs/stable/onnx.html for how to convert a PyTorch model to ONNX. + + Args: + model: source PyTorch model to save. + inputs: input sample data used by pytorch.onnx.export. It is also used in ONNX model verification. + input_names: optional input names of the ONNX model. + output_names: optional output names of the ONNX model. + opset_version: version of the (ai.onnx) opset to target. Must be >= 7 and not exceed + the latest opset version supported by PyTorch, for more details: + https://github.com/onnx/onnx/blob/main/docs/Operators.md and + https://github.com/pytorch/pytorch/blob/master/torch/onnx/_constants.py + dynamic_axes: specifies axes of tensors as dynamic (i.e. known only at run-time). If set to None, + the exported model will have the shapes of all input and output tensors set to match given + ones, for more details: https://pytorch.org/docs/stable/onnx.html#torch.onnx.export. + filename: optional filename to save the ONNX model, if None, don't save the ONNX model. + verify: whether to verify the ONNX model with ONNX or onnxruntime. + device: target PyTorch device to verify the model, if None, use CUDA if available. + use_ort: whether to use onnxruntime to verify the model. + ort_provider": onnxruntime provider to use, default is ["CPUExecutionProvider"]. + rtol: the relative tolerance when comparing the outputs of PyTorch model and TorchScript model. + atol: the absolute tolerance when comparing the outputs of PyTorch model and TorchScript model. + use_trace: whether to use `torch.jit.trace` to export the torchscript model. + kwargs: other arguments except `obj` for `torch.jit.script()` to convert model, for more details: + https://pytorch.org/docs/master/generated/torch.jit.script.html. + + """ + model.eval() + with torch.no_grad(): + torch_versioned_kwargs = {} + if use_trace: + # let torch.onnx.export to trace the model. + mode_to_export = model + else: + if not pytorch_after(1, 10): + if "example_outputs" not in kwargs: + # https://github.com/pytorch/pytorch/blob/release/1.9/torch/onnx/__init__.py#L182 + raise TypeError( + "example_outputs is required in scripting mode before PyTorch 1.10." + "Please provide example outputs or use trace mode to export onnx model." + ) + torch_versioned_kwargs["example_outputs"] = kwargs["example_outputs"] + del kwargs["example_outputs"] + mode_to_export = torch.jit.script(model, **kwargs) + + if filename is None: + f = io.BytesIO() + torch.onnx.export( + mode_to_export, + tuple(inputs), + f=f, + input_names=input_names, + output_names=output_names, + dynamic_axes=dynamic_axes, + opset_version=opset_version, + **torch_versioned_kwargs, + ) + onnx_model = onnx.load_model_from_string(f.getvalue()) + else: + torch.onnx.export( + mode_to_export, + tuple(inputs), + f=filename, + input_names=input_names, + output_names=output_names, + dynamic_axes=dynamic_axes, + opset_version=opset_version, + **torch_versioned_kwargs, + ) + onnx_model = onnx.load(filename) + + if verify: + if device is None: + device = torch.device("cuda" if torch.cuda.is_available() else "cpu") + + inputs = [i.to(device) if isinstance(i, torch.Tensor) else i for i in inputs] + model = model.to(device) + + with torch.no_grad(): + set_determinism(seed=0) + torch_out = ensure_tuple(model(*inputs), True) + + set_determinism(seed=0) + model_input_names = [i.name for i in onnx_model.graph.input] + input_dict = dict(zip(model_input_names, [i.cpu().numpy() for i in inputs])) + if use_ort: + ort_sess = onnxruntime.InferenceSession( + onnx_model.SerializeToString(), providers=ort_provider if ort_provider else ["CPUExecutionProvider"] + ) + onnx_out = ort_sess.run(None, input_dict) + else: + sess = onnxreference.ReferenceEvaluator(onnx_model) + onnx_out = sess.run(None, input_dict) + set_determinism(seed=None) + # compare onnx/ort and PyTorch results + for r1, r2 in zip(torch_out, onnx_out): + if isinstance(r1, torch.Tensor): + assert_fn = torch.testing.assert_close if pytorch_after(1, 11) else torch.testing.assert_allclose + assert_fn(r1.cpu(), convert_to_tensor(r2, dtype=r1.dtype), rtol=rtol, atol=atol) # type: ignore + + return onnx_model + + +def convert_to_torchscript( + model: nn.Module, + filename_or_obj: Any | None = None, + extra_files: dict | None = None, + verify: bool = False, + inputs: Sequence[Any] | None = None, + device: torch.device | None = None, + rtol: float = 1e-4, + atol: float = 0.0, + use_trace: bool = False, + **kwargs, +): + """ + Utility to convert a model into TorchScript model and save to file, + with optional input / output data verification. + + Args: + model: source PyTorch model to save. + filename_or_obj: if not None, specify a file-like object (has to implement write and flush) + or a string containing a file path name to save the TorchScript model. + extra_files: map from filename to contents which will be stored as part of the save model file. + for more details: https://pytorch.org/docs/stable/generated/torch.jit.save.html. + verify: whether to verify the input and output of TorchScript model. + if `filename_or_obj` is not None, load the saved TorchScript model and verify. + inputs: input test data to verify model, should be a sequence of data, every item maps to a argument + of `model()` function. + device: target device to verify the model, if None, use CUDA if available. + rtol: the relative tolerance when comparing the outputs of PyTorch model and TorchScript model. + atol: the absolute tolerance when comparing the outputs of PyTorch model and TorchScript model. + use_trace: whether to use `torch.jit.trace` to export the TorchScript model. + kwargs: other arguments except `obj` for `torch.jit.script()` or `torch.jit.trace()` (if use_trace is True) + to convert model, for more details: https://pytorch.org/docs/master/generated/torch.jit.script.html. + + """ + model.eval() + with torch.no_grad(): + if use_trace: + if inputs is None: + raise ValueError("Missing input data for tracing convert.") + script_module = torch.jit.trace(model, example_inputs=inputs, **kwargs) + else: + script_module = torch.jit.script(model, **kwargs) + if filename_or_obj is not None: + torch.jit.save(m=script_module, f=filename_or_obj, _extra_files=extra_files) + + if verify: + if device is None: + device = torch.device("cuda" if torch.cuda.is_available() else "cpu") + if inputs is None: + raise ValueError("Missing input data for verification.") + + inputs = [i.to(device) if isinstance(i, torch.Tensor) else i for i in inputs] + ts_model = torch.jit.load(filename_or_obj) if filename_or_obj is not None else script_module + ts_model.eval().to(device) + model = model.to(device) + + with torch.no_grad(): + set_determinism(seed=0) + torch_out = ensure_tuple(model(*inputs)) + set_determinism(seed=0) + torchscript_out = ensure_tuple(ts_model(*inputs)) + set_determinism(seed=None) + # compare TorchScript and PyTorch results + for r1, r2 in zip(torch_out, torchscript_out): + if isinstance(r1, torch.Tensor) or isinstance(r2, torch.Tensor): + assert_fn = torch.testing.assert_close if pytorch_after(1, 11) else torch.testing.assert_allclose + assert_fn(r1, r2, rtol=rtol, atol=atol) # type: ignore + + return script_module + + +def _onnx_trt_compile( + onnx_model, + min_shape: Sequence[int], + opt_shape: Sequence[int], + max_shape: Sequence[int], + device: int, + precision: str, + input_names: Sequence[str] | None, + output_names: Sequence[str] | None, +): + """ + This function takes an ONNX model as input, exports it to a TensorRT engine, wraps the TensorRT engine + to a TensorRT engine-based TorchScript model and return the TorchScript model. + + Args: + onnx_model: the source ONNX model to compile. + min_shape: the minimum input shape of the converted TensorRT model. + opt_shape: the optimization input shape of the model, on which the TensorRT optimizes. + max_shape: the maximum input shape of the converted TensorRT model. + device: the target GPU index to convert and verify the model. + precision: the weight precision of the converted TensorRT engine-based TorchScript model. + Should be 'fp32' or 'fp16'. + input_names: optional input names of the ONNX model. Should be a sequence like + `['input_0', 'input_1', ..., 'input_N']` where N equals to the number of the + model inputs. + output_names: optional output names of the ONNX model. Should be a sequence like + `['output_0', 'output_1', ..., 'output_N']` where N equals to the number of + the model outputs. + + """ + trt, _ = optional_import("tensorrt", "8.5.3") + torch_tensorrt, _ = optional_import("torch_tensorrt", "1.4.0") + + input_shapes = (min_shape, opt_shape, max_shape) + # default to an empty list to fit the `torch_tensorrt.ts.embed_engine_in_new_module` function. + input_names = [] if not input_names else input_names + output_names = [] if not output_names else output_names + + # set up the TensorRT builder + torch_tensorrt.set_device(device) + logger = trt.Logger(trt.Logger.WARNING) + builder = trt.Builder(logger) + network = builder.create_network(1 << int(trt.NetworkDefinitionCreationFlag.EXPLICIT_BATCH)) + profile = builder.create_optimization_profile() + if input_names: + profile.set_shape(input_names[0], *input_shapes) + + # parse the ONNX model + parser = trt.OnnxParser(network, logger) + success = parser.parse(onnx_model.SerializeToString()) + if not success: + parser_error_message = "" + for idx in range(parser.num_errors): + parser_error_message += parser.get_error(idx).desc() + "\n" + raise Exception(f"TensorRT cannot parse the ONNX model, due to:\n{parser_error_message}") + + # set up the conversion configuration + config = builder.create_builder_config() + config.add_optimization_profile(profile) + if precision == "fp16": + config.set_flag(trt.BuilderFlag.FP16) + serialized_engine = builder.build_serialized_network(network, config) + f = io.BytesIO() + f.write(serialized_engine) + + # wrap the serialized TensorRT engine back to a TorchScript module. + trt_model = torch_tensorrt.ts.embed_engine_in_new_module( + f.getvalue(), + device=torch.device(f"cuda:{device}"), + input_binding_names=input_names, + output_binding_names=output_names, + ) + return trt_model + + +def convert_to_trt( + model: nn.Module, + precision: str, + input_shape: Sequence[int], + dynamic_batchsize: Sequence[int] | None = None, + use_trace: bool = False, + filename_or_obj: Any | None = None, + verify: bool = False, + device: int | None = None, + use_onnx: bool | None = False, + onnx_input_names: Sequence[str] | None = ("input_0",), + onnx_output_names: Sequence[str] | None = ("output_0",), + rtol: float = 1e-2, + atol: float = 0.0, + **kwargs, +): + """ + Utility to export a model into a TensorRT engine-based TorchScript model with optional input / output data verification. + + There are two ways to export a model: + 1, Torch-TensorRT way: PyTorch module ---> TorchScript module ---> TensorRT engine-based TorchScript. + 2, ONNX-TensorRT way: PyTorch module ---> TorchScript module ---> ONNX model ---> TensorRT engine ---> + TensorRT engine-based TorchScript. + + When exporting through the first way, some models suffer from the slowdown problem, since Torch-TensorRT + may only convert a little part of the PyTorch model to the TensorRT engine. However when exporting through + the second way, some Python data structures like `dict` are not supported. And some TorchScript models are + not supported by the ONNX if exported through `torch.jit.script`. + + Args: + model: a source PyTorch model to convert. + precision: the weight precision of the converted TensorRT engine based TorchScript models. Should be 'fp32' or 'fp16'. + input_shape: the input shape that is used to convert the model. Should be a list like [N, C, H, W] or + [N, C, H, W, D]. + dynamic_batchsize: a sequence with three elements to define the batch size range of the input for the model to be + converted. Should be a sequence like [MIN_BATCH, OPT_BATCH, MAX_BATCH]. After converted, the batchsize of model + input should between `MIN_BATCH` and `MAX_BATCH` and the `OPT_BATCH` is the best performance batchsize that the + TensorRT tries to fit. The `OPT_BATCH` should be the most frequently used input batchsize in the application, + default to None. + use_trace: whether using `torch.jit.trace` to convert the PyTorch model to a TorchScript model and then convert to + a TensorRT engine based TorchScript model or an ONNX model (if `use_onnx` is True), default to False. + filename_or_obj: if not None, specify a file-like object (has to implement write and flush) or a string containing a + file path name to load the TensorRT engine based TorchScript model for verifying. + verify: whether to verify the input and output of the TensorRT engine based TorchScript model. + device: the target GPU index to convert and verify the model. If None, use #0 GPU. + use_onnx: whether to use the ONNX-TensorRT way to export the TensorRT engine-based TorchScript model. + onnx_input_names: optional input names of the ONNX model. This arg is only useful when `use_onnx` is True. Should be + a sequence like `('input_0', 'input_1', ..., 'input_N')` where N equals to the number of the model inputs. If not + given, will use `('input_0',)`, which supposes the model only has one input. + onnx_output_names: optional output names of the ONNX model. This arg is only useful when `use_onnx` is True. Should be + a sequence like `('output_0', 'output_1', ..., 'output_N')` where N equals to the number of the model outputs. If + not given, will use `('output_0',)`, which supposes the model only has one output. + rtol: the relative tolerance when comparing the outputs between the PyTorch model and TensorRT model. + atol: the absolute tolerance when comparing the outputs between the PyTorch model and TensorRT model. + kwargs: other arguments except `module`, `inputs`, `enabled_precisions` and `device` for `torch_tensorrt.compile()` + to compile model, for more details: https://pytorch.org/TensorRT/py_api/torch_tensorrt.html#torch-tensorrt-py. + """ + + torch_tensorrt, _ = optional_import("torch_tensorrt", version="1.4.0") + + if not torch.cuda.is_available(): + raise Exception("Cannot find any GPU devices.") + + if not input_shape: + raise ValueError("Missing the input shape for model convert.") + + if not dynamic_batchsize: + warnings.warn(f"There is no dynamic batch range. The converted model only takes {input_shape} shape input.") + + if (dynamic_batchsize is not None) and (len(dynamic_batchsize) != 3): + warnings.warn(f"The dynamic batch range sequence should have 3 elements, but got {dynamic_batchsize} elements.") + + device = device if device else 0 + target_device = torch.device(f"cuda:{device}") if device else torch.device("cuda:0") + convert_precision = torch.float32 if precision == "fp32" else torch.half + inputs = [torch.rand(ensure_tuple(input_shape)).to(target_device)] + + def scale_batch_size(input_shape: Sequence[int], scale_num: int): + scale_shape = [*input_shape] + scale_shape[0] *= scale_num + return scale_shape + + # Use the dynamic batchsize range to generate the min, opt and max model input shape + if dynamic_batchsize: + min_input_shape = scale_batch_size(input_shape, dynamic_batchsize[0]) + opt_input_shape = scale_batch_size(input_shape, dynamic_batchsize[1]) + max_input_shape = scale_batch_size(input_shape, dynamic_batchsize[2]) + else: + min_input_shape = opt_input_shape = max_input_shape = input_shape + + # convert the torch model to a TorchScript model on target device + model = model.eval().to(target_device) + ir_model = convert_to_torchscript(model, device=target_device, inputs=inputs, use_trace=use_trace) + ir_model.eval() + + if use_onnx: + # set the batch dim as dynamic + dynamic_axes = {k: {0: "batchsize"} for k in onnx_input_names} if onnx_input_names else {} + dynamic_axes.update({k: {0: "batchsize"} for k in onnx_output_names} if onnx_output_names else {}) + ir_model = convert_to_onnx( + model, inputs, onnx_input_names, onnx_output_names, use_trace=use_trace, dynamic_axes=dynamic_axes + ) + + # convert the model through the ONNX-TensorRT way + trt_model = _onnx_trt_compile( + ir_model, + min_shape=min_input_shape, + opt_shape=opt_input_shape, + max_shape=max_input_shape, + device=device, + precision=precision, + input_names=onnx_input_names, + output_names=onnx_output_names, + ) + else: + # convert the model through the Torch-TensorRT way + ir_model.to(target_device) + with torch.no_grad(): + with torch.cuda.device(device=device): + input_placeholder = [ + torch_tensorrt.Input( + min_shape=min_input_shape, opt_shape=opt_input_shape, max_shape=max_input_shape + ) + ] + trt_model = torch_tensorrt.compile( + ir_model, + inputs=input_placeholder, + enabled_precisions=convert_precision, + device=target_device, + ir="torchscript", + **kwargs, + ) + + # verify the outputs between the TensorRT model and PyTorch model + if verify: + if inputs is None: + raise ValueError("Missing input data for verification.") + + trt_model = torch.jit.load(filename_or_obj) if filename_or_obj is not None else trt_model + + with torch.no_grad(): + set_determinism(seed=0) + torch_out = ensure_tuple(model(*inputs)) + set_determinism(seed=0) + trt_out = ensure_tuple(trt_model(*inputs)) + set_determinism(seed=None) + # compare TorchScript and PyTorch results + for r1, r2 in zip(torch_out, trt_out): + if isinstance(r1, torch.Tensor) or isinstance(r2, torch.Tensor): + assert_fn = torch.testing.assert_close if pytorch_after(1, 11) else torch.testing.assert_allclose + assert_fn(r1, r2, rtol=rtol, atol=atol) # type: ignore + + return trt_model + + +def meshgrid_ij(*tensors): + if torch.meshgrid.__kwdefaults__ is not None and "indexing" in torch.meshgrid.__kwdefaults__: + return torch.meshgrid(*tensors, indexing="ij") # new api pytorch after 1.10 + + return torch.meshgrid(*tensors) + + +def meshgrid_xy(*tensors): + if torch.meshgrid.__kwdefaults__ is not None and "indexing" in torch.meshgrid.__kwdefaults__: + return torch.meshgrid(*tensors, indexing="xy") # new api pytorch after 1.10 + + return torch.meshgrid(tensors[1], tensors[0], *tensors[2:]) + + +def _replace_modules( + parent: torch.nn.Module, + name: str, + new_module: torch.nn.Module, + out: list[tuple[str, torch.nn.Module]], + strict_match: bool = True, + match_device: bool = True, +) -> None: + """ + Helper function for :py:class:`monai.networks.utils.replace_modules`. + """ + if match_device: + devices = list({i.device for i in parent.parameters()}) + # if only one device for whole of model + if len(devices) == 1: + new_module.to(devices[0]) + idx = name.find(".") + # if there is "." in name, call recursively + if idx != -1: + parent_name = name[:idx] + parent = getattr(parent, parent_name) + name = name[idx + 1 :] + _out: list[tuple[str, torch.nn.Module]] = [] + _replace_modules(parent, name, new_module, _out) + # prepend the parent name + out += [(f"{parent_name}.{r[0]}", r[1]) for r in _out] + # no "." in module name, do the actual replacing + else: + if strict_match: + old_module = getattr(parent, name) + setattr(parent, name, new_module) + out += [(name, old_module)] + else: + for mod_name, _ in parent.named_modules(): + if name in mod_name: + _replace_modules(parent, mod_name, deepcopy(new_module), out, strict_match=True) + + +def replace_modules( + parent: torch.nn.Module, + name: str, + new_module: torch.nn.Module, + strict_match: bool = True, + match_device: bool = True, +) -> list[tuple[str, torch.nn.Module]]: + """ + Replace sub-module(s) in a parent module. + + The name of the module to be replace can be nested e.g., + `features.denseblock1.denselayer1.layers.relu1`. If this is the case (there are "." + in the module name), then this function will recursively call itself. + + Args: + parent: module that contains the module to be replaced + name: name of module to be replaced. Can include ".". + new_module: `torch.nn.Module` to be placed at position `name` inside `parent`. This will + be deep copied if `strict_match == False` multiple instances are independent. + strict_match: if `True`, module name must `== name`. If false then + `name in named_modules()` will be used. `True` can be used to change just + one module, whereas `False` can be used to replace all modules with similar + name (e.g., `relu`). + match_device: if `True`, the device of the new module will match the model. Requires all + of `parent` to be on the same device. + + Returns: + List of tuples of replaced modules. Element 0 is module name, element 1 is the replaced module. + + Raises: + AttributeError: if `strict_match` is `True` and `name` is not a named module in `parent`. + """ + out: list[tuple[str, torch.nn.Module]] = [] + _replace_modules(parent, name, new_module, out, strict_match, match_device) + return out + + +@contextmanager +def replace_modules_temp( + parent: torch.nn.Module, + name: str, + new_module: torch.nn.Module, + strict_match: bool = True, + match_device: bool = True, +): + """ + Temporarily replace sub-module(s) in a parent module (context manager). + + See :py:class:`monai.networks.utils.replace_modules`. + """ + replaced: list[tuple[str, torch.nn.Module]] = [] + try: + # replace + _replace_modules(parent, name, new_module, replaced, strict_match, match_device) + yield + finally: + # revert + for name, module in replaced: + _replace_modules(parent, name, module, [], strict_match=True, match_device=match_device) + + +def freeze_layers(model: nn.Module, freeze_vars=None, exclude_vars=None): + """ + A utilty function to help freeze specific layers. + + Args: + model: a source PyTorch model to freeze layer. + freeze_vars: a regular expression to match the `model` variable names, + so that their `requires_grad` will set to `False`. + exclude_vars: a regular expression to match the `model` variable names, + except for matched variable names, other `requires_grad` will set to `False`. + + Raises: + ValueError: when freeze_vars and exclude_vars are both specified. + + """ + if freeze_vars is not None and exclude_vars is not None: + raise ValueError("Incompatible values: freeze_vars and exclude_vars are both specified.") + src_dict = get_state_dict(model) + + frozen_keys = list() + if freeze_vars is not None: + to_freeze = {s_key for s_key in src_dict if freeze_vars and re.compile(freeze_vars).search(s_key)} + for name, param in model.named_parameters(): + if name in to_freeze: + param.requires_grad = False + frozen_keys.append(name) + elif not param.requires_grad: + param.requires_grad = True + warnings.warn( + f"The freeze_vars does not include {param}, but requires_grad is False, change it to True." + ) + if exclude_vars is not None: + to_exclude = {s_key for s_key in src_dict if exclude_vars and re.compile(exclude_vars).search(s_key)} + for name, param in model.named_parameters(): + if name not in to_exclude: + param.requires_grad = False + frozen_keys.append(name) + elif not param.requires_grad: + param.requires_grad = True + warnings.warn(f"The exclude_vars includes {param}, but requires_grad is False, change it to True.") + + logger.info(f"{len(frozen_keys)} of {len(src_dict)} variables frozen.") diff --git a/source_code/SegMamba/monai/optimizers/__init__.py b/source_code/SegMamba/monai/optimizers/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..f0a3858ced09baf8c55caf6a12d56024c6163eb9 --- /dev/null +++ b/source_code/SegMamba/monai/optimizers/__init__.py @@ -0,0 +1,17 @@ +# Copyright (c) MONAI Consortium +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from __future__ import annotations + +from .lr_finder import LearningRateFinder +from .lr_scheduler import ExponentialLR, LinearLR, WarmupCosineSchedule +from .novograd import Novograd +from .utils import generate_param_groups diff --git a/source_code/SegMamba/monai/optimizers/lr_finder.py b/source_code/SegMamba/monai/optimizers/lr_finder.py new file mode 100644 index 0000000000000000000000000000000000000000..045135628dced89a7fe2cac7fd6b9f8921f19e4c --- /dev/null +++ b/source_code/SegMamba/monai/optimizers/lr_finder.py @@ -0,0 +1,548 @@ +# Copyright (c) MONAI Consortium +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from __future__ import annotations + +import pickle +import types +import warnings +from functools import partial +from typing import TYPE_CHECKING, Any, Callable + +import numpy as np +import torch +import torch.nn as nn +from torch.optim import Optimizer +from torch.serialization import DEFAULT_PROTOCOL +from torch.utils.data import DataLoader + +from monai.networks.utils import eval_mode +from monai.optimizers.lr_scheduler import ExponentialLR, LinearLR +from monai.utils import StateCacher, copy_to_device, optional_import + +if TYPE_CHECKING: + import matplotlib.pyplot as plt + + has_matplotlib = True + import tqdm + + has_tqdm = True +else: + plt, has_matplotlib = optional_import("matplotlib.pyplot") + tqdm, has_tqdm = optional_import("tqdm") + +__all__ = ["LearningRateFinder"] + + +class DataLoaderIter: + + def __init__(self, data_loader: DataLoader, image_extractor: Callable, label_extractor: Callable) -> None: + if not isinstance(data_loader, DataLoader): + raise ValueError( + f"Loader has unsupported type: {type(data_loader)}. Expected type was `torch.utils.data.DataLoader`" + ) + self.data_loader = data_loader + self._iterator = iter(data_loader) + self.image_extractor = image_extractor + self.label_extractor = label_extractor + + @property + def dataset(self): + return self.data_loader.dataset + + def inputs_labels_from_batch(self, batch_data): + images = self.image_extractor(batch_data) + labels = self.label_extractor(batch_data) + return images, labels + + def __iter__(self): + return self + + def __next__(self): + batch = next(self._iterator) + return self.inputs_labels_from_batch(batch) + + +class TrainDataLoaderIter(DataLoaderIter): + + def __init__( + self, data_loader: DataLoader, image_extractor: Callable, label_extractor: Callable, auto_reset: bool = True + ) -> None: + super().__init__(data_loader, image_extractor, label_extractor) + self.auto_reset = auto_reset + + def __next__(self): + try: + batch = next(self._iterator) + inputs, labels = self.inputs_labels_from_batch(batch) + except StopIteration: + if not self.auto_reset: + raise + self._iterator = iter(self.data_loader) + batch = next(self._iterator) + inputs, labels = self.inputs_labels_from_batch(batch) + + return inputs, labels + + +class ValDataLoaderIter(DataLoaderIter): + """This iterator will reset itself **only** when it is acquired by + the syntax of normal `iterator`. That is, this iterator just works + like a `torch.data.DataLoader`. If you want to restart it, you + should use it like: + + ``` + loader_iter = ValDataLoaderIter(data_loader) + for batch in loader_iter: + ... + + # `loader_iter` should run out of values now, you can restart it by: + # 1. the way we use a `torch.data.DataLoader` + for batch in loader_iter: # __iter__ is called implicitly + ... + + # 2. passing it into `iter()` manually + loader_iter = iter(loader_iter) # __iter__ is called by `iter()` + ``` + """ + + def __init__(self, data_loader: DataLoader, image_extractor: Callable, label_extractor: Callable) -> None: + super().__init__(data_loader, image_extractor, label_extractor) + self.run_limit = len(self.data_loader) + self.run_counter = 0 + + def __iter__(self): + if self.run_counter >= self.run_limit: + self._iterator = iter(self.data_loader) + self.run_counter = 0 + return self + + def __next__(self): + self.run_counter += 1 + return super().__next__() + + +def default_image_extractor(x: Any) -> torch.Tensor: + """Default callable for getting image from batch data.""" + out: torch.Tensor = x["image"] if isinstance(x, dict) else x[0] + return out + + +def default_label_extractor(x: Any) -> torch.Tensor: + """Default callable for getting label from batch data.""" + out: torch.Tensor = x["label"] if isinstance(x, dict) else x[1] + return out + + +class LearningRateFinder: + """Learning rate range test. + + The learning rate range test increases the learning rate in a pre-training run + between two boundaries in a linear or exponential manner. It provides valuable + information on how well the network can be trained over a range of learning rates + and what is the optimal learning rate. + + Example (fastai approach): + >>> lr_finder = LearningRateFinder(net, optimizer, criterion) + >>> lr_finder.range_test(data_loader, end_lr=100, num_iter=100) + >>> lr_finder.get_steepest_gradient() + >>> lr_finder.plot() # to inspect the loss-learning rate graph + + Example (Leslie Smith's approach): + >>> lr_finder = LearningRateFinder(net, optimizer, criterion) + >>> lr_finder.range_test(train_loader, val_loader=val_loader, end_lr=1, num_iter=100, step_mode="linear") + + Gradient accumulation is supported; example: + >>> train_data = ... # prepared dataset + >>> desired_bs, real_bs = 32, 4 # batch size + >>> accumulation_steps = desired_bs // real_bs # required steps for accumulation + >>> data_loader = torch.utils.data.DataLoader(train_data, batch_size=real_bs, shuffle=True) + >>> acc_lr_finder = LearningRateFinder(net, optimizer, criterion) + >>> acc_lr_finder.range_test(data_loader, end_lr=10, num_iter=100, accumulation_steps=accumulation_steps) + + By default, image will be extracted from data loader with x["image"] and x[0], depending on whether + batch data is a dictionary or not (and similar behaviour for extracting the label). If your data loader + returns something other than this, pass a callable function to extract it, e.g.: + >>> image_extractor = lambda x: x["input"] + >>> label_extractor = lambda x: x[100] + >>> lr_finder = LearningRateFinder(net, optimizer, criterion) + >>> lr_finder.range_test(train_loader, val_loader, image_extractor, label_extractor) + + References: + Modified from: https://github.com/davidtvs/pytorch-lr-finder. + Cyclical Learning Rates for Training Neural Networks: https://arxiv.org/abs/1506.01186 + """ + + def __init__( + self, + model: nn.Module, + optimizer: Optimizer, + criterion: torch.nn.Module, + device: str | torch.device | None = None, + memory_cache: bool = True, + cache_dir: str | None = None, + amp: bool = False, + pickle_module: types.ModuleType = pickle, + pickle_protocol: int = DEFAULT_PROTOCOL, + verbose: bool = True, + ) -> None: + """Constructor. + + Args: + model: wrapped model. + optimizer: wrapped optimizer. + criterion: wrapped loss function. + device: device on which to test. run a string ("cpu" or "cuda") with an + optional ordinal for the device type (e.g. "cuda:X", where is the ordinal). + Alternatively, can be an object representing the device on which the + computation will take place. Default: None, uses the same device as `model`. + memory_cache: if this flag is set to True, `state_dict` of + model and optimizer will be cached in memory. Otherwise, they will be saved + to files under the `cache_dir`. + cache_dir: path for storing temporary files. If no path is + specified, system-wide temporary directory is used. Notice that this + parameter will be ignored if `memory_cache` is True. + amp: use Automatic Mixed Precision + pickle_module: module used for pickling metadata and objects, default to `pickle`. + this arg is used by `torch.save`, for more details, please check: + https://pytorch.org/docs/stable/generated/torch.save.html#torch.save. + pickle_protocol: can be specified to override the default protocol, default to `2`. + this arg is used by `torch.save`, for more details, please check: + https://pytorch.org/docs/stable/generated/torch.save.html#torch.save. + verbose: verbose output + Returns: + None + """ + # Check if the optimizer is already attached to a scheduler + self.optimizer = optimizer + self._check_for_scheduler() + + self.model = model + self.criterion = criterion + self.history: dict[str, list] = {"lr": [], "loss": []} + self.memory_cache = memory_cache + self.cache_dir = cache_dir + self.amp = amp + self.verbose = verbose + + # Save the original state of the model and optimizer so they can be restored if + # needed + self.model_device = next(self.model.parameters()).device + self.state_cacher = StateCacher( + in_memory=memory_cache, cache_dir=cache_dir, pickle_module=pickle_module, pickle_protocol=pickle_protocol + ) + self.state_cacher.store("model", self.model.state_dict()) + self.state_cacher.store("optimizer", self.optimizer.state_dict()) + + # If device is None, use the same as the model + self.device = device if device else self.model_device + + def reset(self) -> None: + """Restores the model and optimizer to their initial states.""" + + self.model.load_state_dict(self.state_cacher.retrieve("model")) + self.optimizer.load_state_dict(self.state_cacher.retrieve("optimizer")) + self.model.to(self.model_device) + + def range_test( + self, + train_loader: DataLoader, + val_loader: DataLoader | None = None, + image_extractor: Callable = default_image_extractor, + label_extractor: Callable = default_label_extractor, + start_lr: float | None = None, + end_lr: float = 10.0, + num_iter: int = 100, + step_mode: str = "exp", + smooth_f: float = 0.05, + diverge_th: int = 5, + accumulation_steps: int = 1, + non_blocking_transfer: bool = True, + auto_reset: bool = True, + ) -> None: + """Performs the learning rate range test. + + Args: + train_loader: training set data loader. + val_loader: validation data loader (if desired). + image_extractor: callable function to get the image from a batch of data. + Default: `x["image"] if isinstance(x, dict) else x[0]`. + label_extractor: callable function to get the label from a batch of data. + Default: `x["label"] if isinstance(x, dict) else x[1]`. + start_lr : the starting learning rate for the range test. + The default is the optimizer's learning rate. + end_lr: the maximum learning rate to test. The test may stop earlier than + this if the result starts diverging. + num_iter: the max number of iterations for test. + step_mode: schedule for increasing learning rate: (`linear` or `exp`). + smooth_f: the loss smoothing factor within the `[0, 1[` interval. Disabled + if set to `0`, otherwise loss is smoothed using exponential smoothing. + diverge_th: test is stopped when loss surpasses threshold: + `diverge_th * best_loss`. + accumulation_steps: steps for gradient accumulation. If set to `1`, + gradients are not accumulated. + non_blocking_transfer: when `True`, moves data to device asynchronously if + possible, e.g., moving CPU Tensors with pinned memory to CUDA devices. + auto_reset: if `True`, returns model and optimizer to original states at end + of test. + Returns: + None + """ + + # Reset test results + self.history = {"lr": [], "loss": []} + best_loss = -float("inf") + + # Move the model to the proper device + self.model.to(self.device) + + # Check if the optimizer is already attached to a scheduler + self._check_for_scheduler() + + # Set the starting learning rate + if start_lr: + self._set_learning_rate(start_lr) + + # Check number of iterations + if num_iter <= 1: + raise ValueError("`num_iter` must be larger than 1") + + # Initialize the proper learning rate policy + lr_schedule: ExponentialLR | LinearLR + if step_mode.lower() == "exp": + lr_schedule = ExponentialLR(self.optimizer, end_lr, num_iter) + elif step_mode.lower() == "linear": + lr_schedule = LinearLR(self.optimizer, end_lr, num_iter) + else: + raise ValueError(f"expected one of (exp, linear), got {step_mode}") + + if smooth_f < 0 or smooth_f >= 1: + raise ValueError("smooth_f is outside the range [0, 1[") + + # Create an iterator to get data batch by batch + train_iter = TrainDataLoaderIter(train_loader, image_extractor, label_extractor) + if val_loader: + val_iter = ValDataLoaderIter(val_loader, image_extractor, label_extractor) + + trange: partial[tqdm.trange] | type[range] + if self.verbose and has_tqdm: + trange = partial(tqdm.trange, desc="Computing optimal learning rate") + tprint = tqdm.tqdm.write + else: + trange = range + tprint = print + + for iteration in trange(num_iter): + if self.verbose and not has_tqdm: + 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) + if val_loader: + loss = self._validate(val_iter, non_blocking_transfer=non_blocking_transfer) + + # Update the learning rate + self.history["lr"].append(lr_schedule.get_lr()[0]) + lr_schedule.step() + + # Track the best loss and smooth it if smooth_f is specified + if iteration == 0: + best_loss = loss + else: + if smooth_f > 0: + loss = smooth_f * loss + (1 - smooth_f) * self.history["loss"][-1] + if loss < best_loss: + best_loss = loss + + # Check if the loss has diverged; if it has, stop the test + self.history["loss"].append(loss) + if loss > diverge_th * best_loss: + if self.verbose: + tprint("Stopping early, the loss has diverged") + break + + if auto_reset: + if self.verbose: + print("Resetting model and optimizer") + self.reset() + + def _set_learning_rate(self, new_lrs: float | list) -> None: + """Set learning rate(s) for optimizer.""" + if not isinstance(new_lrs, list): + new_lrs = [new_lrs] * len(self.optimizer.param_groups) + if len(new_lrs) != len(self.optimizer.param_groups): + raise ValueError( + "Length of `new_lrs` is not equal to the number of parameter groups " + "in the given optimizer" + ) + + for param_group, new_lr in zip(self.optimizer.param_groups, new_lrs): + param_group["lr"] = new_lr + + def _check_for_scheduler(self): + """Check optimizer doesn't already have scheduler.""" + for param_group in self.optimizer.param_groups: + if "initial_lr" in param_group: + raise RuntimeError("Optimizer already has a scheduler attached to it") + + def _train_batch( + self, train_iter: TrainDataLoaderIter, accumulation_steps: int, non_blocking_transfer: bool = True + ) -> float: + self.model.train() + total_loss = 0 + + self.optimizer.zero_grad() + for i in range(accumulation_steps): + inputs, labels = next(train_iter) + inputs, labels = copy_to_device([inputs, labels], device=self.device, non_blocking=non_blocking_transfer) + + # Forward pass + outputs = self.model(inputs) + loss = self.criterion(outputs, labels) + + # Loss should be averaged in each step + loss /= accumulation_steps + + # Backward pass + if self.amp and hasattr(self.optimizer, "_amp_stash"): + # For minor performance optimization, see also: + # https://nvidia.github.io/apex/advanced.html#gradient-accumulation-across-iterations + delay_unscale = ((i + 1) % accumulation_steps) != 0 + + with torch.cuda.amp.scale_loss(loss, self.optimizer, delay_unscale=delay_unscale) as scaled_loss: # type: ignore + scaled_loss.backward() + else: + loss.backward() + + total_loss += loss.item() + + self.optimizer.step() + + return total_loss + + def _validate(self, val_iter: ValDataLoaderIter, non_blocking_transfer: bool = True) -> float: + # Set model to evaluation mode and disable gradient computation + running_loss = 0 + with eval_mode(self.model): + for inputs, labels in val_iter: + # Copy data to the correct device + inputs, labels = copy_to_device( + [inputs, labels], device=self.device, non_blocking=non_blocking_transfer + ) + + # Forward pass and loss computation + outputs = self.model(inputs) + loss = self.criterion(outputs, labels) + running_loss += loss.item() * len(labels) + + return running_loss / len(val_iter.dataset) + + 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: + skip_start: number of batches to trim from the start. + skip_end: number of batches to trim from the end. + """ + if skip_start < 0: + raise ValueError("skip_start cannot be negative") + if skip_end < 0: + raise ValueError("skip_end cannot be negative") + + lrs = self.history["lr"] + losses = self.history["loss"] + end_idx = len(lrs) - skip_end - 1 + lrs = lrs[skip_start:end_idx] + losses = losses[skip_start:end_idx] + + return lrs, losses + + def get_steepest_gradient(self, skip_start: int = 0, skip_end: int = 0) -> tuple[float, float] | tuple[None, None]: + """Get learning rate which has steepest gradient and its corresponding loss + + Args: + skip_start: number of batches to trim from the start. + skip_end: number of batches to trim from the end. + + Returns: + Learning rate which has steepest gradient and its corresponding loss + """ + lrs, losses = self.get_lrs_and_losses(skip_start, skip_end) + + try: + min_grad_idx = np.gradient(np.array(losses)).argmin() + return lrs[min_grad_idx], losses[min_grad_idx] + except ValueError: + 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: Any | None = None, + steepest_lr: bool = True, + ) -> Any | None: + """Plots the learning rate range test. + + Args: + skip_start: number of batches to trim from the start. + skip_end: number of batches to trim from the start. + log_lr: True to plot the learning rate in a logarithmic + scale; otherwise, plotted in a linear scale. + ax: the plot is created in the specified matplotlib axes object and the + figure is not be shown. If `None`, then the figure and axes object are + created in this method and the figure is shown. + steepest_lr: plot the learning rate which had the steepest gradient. + + Returns: + The `matplotlib.axes.Axes` object that contains the plot. Returns `None` if + `matplotlib` is not installed. + """ + if not has_matplotlib: + warnings.warn("Matplotlib is missing, can't plot result") + return None + + lrs, losses = self.get_lrs_and_losses(skip_start, skip_end) + + # Create the figure and axes object if axes was not already given + fig = None + if ax is None: + fig, ax = plt.subplots() + + # Plot loss as a function of the learning rate + ax.plot(lrs, losses) + + # Plot the LR with steepest gradient + if steepest_lr: + lr_at_steepest_grad, loss_at_steepest_grad = self.get_steepest_gradient(skip_start, skip_end) + if lr_at_steepest_grad is not None: + ax.scatter( + lr_at_steepest_grad, + loss_at_steepest_grad, + s=75, + marker="o", + color="red", + zorder=3, + label="steepest gradient", + ) + ax.legend() + + if log_lr: + ax.set_xscale("log") + ax.set_xlabel("Learning rate") + ax.set_ylabel("Loss") + + # Show only if the figure was created internally + if fig is not None: + plt.show() + + return ax diff --git a/source_code/SegMamba/monai/optimizers/lr_scheduler.py b/source_code/SegMamba/monai/optimizers/lr_scheduler.py new file mode 100644 index 0000000000000000000000000000000000000000..8f893521586e44ccce3b3d4e73fdde9b758093bf --- /dev/null +++ b/source_code/SegMamba/monai/optimizers/lr_scheduler.py @@ -0,0 +1,110 @@ +# Copyright (c) MONAI Consortium +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from __future__ import annotations + +import math + +from torch.optim import Optimizer +from torch.optim.lr_scheduler import LambdaLR, _LRScheduler + +__all__ = ["LinearLR", "ExponentialLR"] + + +class _LRSchedulerMONAI(_LRScheduler): + """Base class for increasing the learning rate between two boundaries over a number + of iterations""" + + def __init__(self, optimizer: Optimizer, end_lr: float, num_iter: int, last_epoch: int = -1) -> None: + """ + Args: + optimizer: wrapped optimizer. + end_lr: the final learning rate. + num_iter: the number of iterations over which the test occurs. + last_epoch: the index of last epoch. + Returns: + None + """ + self.end_lr = end_lr + self.num_iter = num_iter + super().__init__(optimizer, last_epoch) + + +class LinearLR(_LRSchedulerMONAI): + """Linearly increases the learning rate between two boundaries over a number of + iterations. + """ + + def get_lr(self): + r = self.last_epoch / (self.num_iter - 1) + return [base_lr + r * (self.end_lr - base_lr) for base_lr in self.base_lrs] + + +class ExponentialLR(_LRSchedulerMONAI): + """Exponentially increases the learning rate between two boundaries over a number of + iterations. + """ + + def get_lr(self): + r = self.last_epoch / (self.num_iter - 1) + return [base_lr * (self.end_lr / base_lr) ** r for base_lr in self.base_lrs] + + +class WarmupCosineSchedule(LambdaLR): + """Linear warmup and then cosine decay. + Based on https://huggingface.co/ implementation. + """ + + def __init__( + self, + optimizer: Optimizer, + warmup_steps: int, + t_total: int, + end_lr: float = 0.0, + cycles: float = 0.5, + last_epoch: int = -1, + warmup_multiplier: float = 0, + ) -> None: + """ + Args: + optimizer: wrapped optimizer. + warmup_steps: number of warmup iterations. + t_total: total number of training iterations. + end_lr: the final learning rate. Defaults to 0.0. + cycles: cosine cycles parameter. + last_epoch: the index of last epoch. + warmup_multiplier: if provided, starts the linear warmup from this fraction of the initial lr. + Must be in 0..1 interval. Defaults to 0 + Returns: + None + """ + self.warmup_steps = min(max(warmup_steps, 0), t_total) + self.warmup_multiplier = warmup_multiplier + self.t_total = t_total + self.cycles = cycles + self.end_lr = end_lr + if warmup_multiplier < 0 or warmup_multiplier > 1: + raise ValueError("warmup_multiplier must be in 0..1 range") + super().__init__(optimizer, self.lr_lambda, last_epoch) + + def lr_lambda(self, step): + if step < self.warmup_steps: + f = float(step) / float(max(1.0, self.warmup_steps)) + return self.warmup_multiplier + (1 - self.warmup_multiplier) * f + progress = float(step - self.warmup_steps) / float(max(1, self.t_total - self.warmup_steps)) + return max(0.0, 0.5 * (1.0 + math.cos(math.pi * float(self.cycles) * 2.0 * progress))) + + def get_lr(self): + current_lr = [base_lr * lmbda(self.last_epoch) for lmbda, base_lr in zip(self.lr_lambdas, self.base_lrs)] + if self.last_epoch < self.warmup_steps: + return current_lr + else: + return [max(self.end_lr, _current_lr) for _current_lr in current_lr] diff --git a/source_code/SegMamba/monai/optimizers/novograd.py b/source_code/SegMamba/monai/optimizers/novograd.py new file mode 100644 index 0000000000000000000000000000000000000000..9ca612fc564de99d6c456ab9a02afaf7ed11004a --- /dev/null +++ b/source_code/SegMamba/monai/optimizers/novograd.py @@ -0,0 +1,136 @@ +# Copyright (c) MONAI Consortium +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from __future__ import annotations + +from collections.abc import Callable, Iterable +from typing import TypeVar + +import torch +from torch.optim import Optimizer + +T = TypeVar("T") + + +class Novograd(Optimizer): + """ + Novograd based on `Stochastic Gradient Methods with Layer-wise Adaptive Moments for Training of Deep Networks + `_. + The code is adapted from the implementations in `Jasper for PyTorch + `_, + and `OpenSeq2Seq `_. + + Args: + params: iterable of parameters to optimize or dicts defining parameter groups. + lr: learning rate. Defaults to 1e-3. + betas: coefficients used for computing running averages of gradient and its square. Defaults to (0.9, 0.98). + eps: term added to the denominator to improve numerical stability. Defaults to 1e-8. + weight_decay: weight decay (L2 penalty). Defaults to 0. + grad_averaging: gradient averaging. Defaults to ``False``. + amsgrad: whether to use the AMSGrad variant of this algorithm from the paper + `On the Convergence of Adam and Beyond `_. Defaults to ``False``. + """ + + def __init__( + self, + params: Iterable, + lr: float = 1e-3, + betas: tuple[float, float] = (0.9, 0.98), + eps: float = 1e-8, + weight_decay: float = 0, + grad_averaging: bool = False, + amsgrad: bool = False, + ): + if 0.0 > lr: + raise ValueError(f"Invalid learning rate: {lr}") + if 0.0 > eps: + raise ValueError(f"Invalid epsilon value: {eps}") + if not 0.0 <= betas[0] < 1.0: + raise ValueError(f"Invalid beta parameter at index 0: {betas[0]}") + if not 0.0 <= betas[1] < 1.0: + raise ValueError(f"Invalid beta parameter at index 1: {betas[1]}") + 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 + ) + + super().__init__(params, defaults) + + def __setstate__(self, state): + super().__setstate__(state) + for group in self.param_groups: + group.setdefault("amsgrad", False) + + def step(self, closure: Callable[[], T] | None = None) -> T | None: # type: ignore + """Performs a single optimization step. + + Arguments: + closure: A closure that reevaluates the model and returns the loss. Defaults to ``None``. + """ + loss = None + if closure is not None: + loss = closure() + + for group in self.param_groups: + for p in group["params"]: + if p.grad is None: + continue + grad = p.grad.data + if grad.is_sparse: + raise RuntimeError("Sparse gradients are not supported.") + amsgrad = group["amsgrad"] + + state = self.state[p] + + # State initialization + if len(state) == 0: + state["step"] = 0 + # Exponential moving average of gradient values + state["exp_avg"] = torch.zeros_like(p.data) + # Exponential moving average of squared gradient values + state["exp_avg_sq"] = torch.zeros([]).to(state["exp_avg"].device) + if amsgrad: + # Maintains max of all exp. moving avg. of sq. grad. values + state["max_exp_avg_sq"] = torch.zeros([]).to(state["exp_avg"].device) + + exp_avg, exp_avg_sq = state["exp_avg"], state["exp_avg_sq"] + if amsgrad: + max_exp_avg_sq = state["max_exp_avg_sq"] + beta1, beta2 = group["betas"] + + state["step"] += 1 + + norm = torch.sum(torch.pow(grad, 2)) + + if exp_avg_sq == 0: + exp_avg_sq.copy_(norm) + else: + exp_avg_sq.mul_(beta2).add_(norm, alpha=1 - beta2) + + if amsgrad: + # Maintains the maximum of all 2nd moment running avg. till now + torch.max(max_exp_avg_sq, exp_avg_sq, out=max_exp_avg_sq) + # Use the max. for normalizing running avg. of gradient + denom = max_exp_avg_sq.sqrt().add_(group["eps"]) + else: + denom = exp_avg_sq.sqrt().add_(group["eps"]) + + grad.div_(denom) + if group["weight_decay"] != 0: + grad.add_(p.data, alpha=group["weight_decay"]) + if group["grad_averaging"]: + grad.mul_(1 - beta1) + exp_avg.mul_(beta1).add_(grad) + + p.data.add_(exp_avg, alpha=-group["lr"]) + + return loss diff --git a/source_code/SegMamba/monai/transforms/__init__.py b/source_code/SegMamba/monai/transforms/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..ab9adb6a990e2f8ce3136d33c60eebc63e88f489 --- /dev/null +++ b/source_code/SegMamba/monai/transforms/__init__.py @@ -0,0 +1,711 @@ +# Copyright (c) MONAI Consortium +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from __future__ import annotations + +from .adaptors import FunctionSignature, adaptor, apply_alias, to_kwargs +from .compose import Compose, OneOf, RandomOrder, SomeOf +from .croppad.array import ( + BorderPad, + BoundingRect, + CenterScaleCrop, + CenterSpatialCrop, + Crop, + CropForeground, + DivisiblePad, + Pad, + RandCropByLabelClasses, + RandCropByPosNegLabel, + RandScaleCrop, + RandSpatialCrop, + RandSpatialCropSamples, + RandWeightedCrop, + ResizeWithPadOrCrop, + SpatialCrop, + SpatialPad, +) +from .croppad.batch import PadListDataCollate +from .croppad.dictionary import ( + BorderPadd, + BorderPadD, + BorderPadDict, + BoundingRectd, + BoundingRectD, + BoundingRectDict, + CenterScaleCropd, + CenterScaleCropD, + CenterScaleCropDict, + CenterSpatialCropd, + CenterSpatialCropD, + CenterSpatialCropDict, + Cropd, + CropD, + CropDict, + CropForegroundd, + CropForegroundD, + CropForegroundDict, + DivisiblePadd, + DivisiblePadD, + DivisiblePadDict, + Padd, + PadD, + PadDict, + RandCropByLabelClassesd, + RandCropByLabelClassesD, + RandCropByLabelClassesDict, + RandCropByPosNegLabeld, + RandCropByPosNegLabelD, + RandCropByPosNegLabelDict, + RandCropd, + RandCropD, + RandCropDict, + RandScaleCropd, + RandScaleCropD, + RandScaleCropDict, + RandSpatialCropd, + RandSpatialCropD, + RandSpatialCropDict, + RandSpatialCropSamplesd, + RandSpatialCropSamplesD, + RandSpatialCropSamplesDict, + RandWeightedCropd, + RandWeightedCropD, + RandWeightedCropDict, + ResizeWithPadOrCropd, + ResizeWithPadOrCropD, + ResizeWithPadOrCropDict, + SpatialCropd, + SpatialCropD, + SpatialCropDict, + SpatialPadd, + SpatialPadD, + SpatialPadDict, +) +from .croppad.functional import crop_func, crop_or_pad_nd, pad_func, pad_nd +from .intensity.array import ( + AdjustContrast, + ClipIntensityPercentiles, + ComputeHoVerMaps, + DetectEnvelope, + ForegroundMask, + GaussianSharpen, + GaussianSmooth, + GibbsNoise, + HistogramNormalize, + IntensityRemap, + KSpaceSpikeNoise, + MaskIntensity, + MedianSmooth, + NormalizeIntensity, + RandAdjustContrast, + RandBiasField, + RandCoarseDropout, + RandCoarseShuffle, + RandCoarseTransform, + RandGaussianNoise, + RandGaussianSharpen, + RandGaussianSmooth, + RandGibbsNoise, + RandHistogramShift, + RandIntensityRemap, + RandKSpaceSpikeNoise, + RandRicianNoise, + RandScaleIntensity, + RandScaleIntensityFixedMean, + RandShiftIntensity, + RandStdShiftIntensity, + SavitzkyGolaySmooth, + ScaleIntensity, + ScaleIntensityFixedMean, + ScaleIntensityRange, + ScaleIntensityRangePercentiles, + ShiftIntensity, + StdShiftIntensity, + ThresholdIntensity, + UltrasoundConfidenceMapTransform, +) +from .intensity.dictionary import ( + AdjustContrastd, + AdjustContrastD, + AdjustContrastDict, + ClipIntensityPercentilesd, + ClipIntensityPercentilesD, + ClipIntensityPercentilesDict, + ComputeHoVerMapsd, + ComputeHoVerMapsD, + ComputeHoVerMapsDict, + ForegroundMaskd, + ForegroundMaskD, + ForegroundMaskDict, + GaussianSharpend, + GaussianSharpenD, + GaussianSharpenDict, + GaussianSmoothd, + GaussianSmoothD, + GaussianSmoothDict, + GibbsNoised, + GibbsNoiseD, + GibbsNoiseDict, + HistogramNormalized, + HistogramNormalizeD, + HistogramNormalizeDict, + KSpaceSpikeNoised, + KSpaceSpikeNoiseD, + KSpaceSpikeNoiseDict, + MaskIntensityd, + MaskIntensityD, + MaskIntensityDict, + MedianSmoothd, + MedianSmoothD, + MedianSmoothDict, + NormalizeIntensityd, + NormalizeIntensityD, + NormalizeIntensityDict, + RandAdjustContrastd, + RandAdjustContrastD, + RandAdjustContrastDict, + RandBiasFieldd, + RandBiasFieldD, + RandBiasFieldDict, + RandCoarseDropoutd, + RandCoarseDropoutD, + RandCoarseDropoutDict, + RandCoarseShuffled, + RandCoarseShuffleD, + RandCoarseShuffleDict, + RandGaussianNoised, + RandGaussianNoiseD, + RandGaussianNoiseDict, + RandGaussianSharpend, + RandGaussianSharpenD, + RandGaussianSharpenDict, + RandGaussianSmoothd, + RandGaussianSmoothD, + RandGaussianSmoothDict, + RandGibbsNoised, + RandGibbsNoiseD, + RandGibbsNoiseDict, + RandHistogramShiftd, + RandHistogramShiftD, + RandHistogramShiftDict, + RandKSpaceSpikeNoised, + RandKSpaceSpikeNoiseD, + RandKSpaceSpikeNoiseDict, + RandRicianNoised, + RandRicianNoiseD, + RandRicianNoiseDict, + RandScaleIntensityd, + RandScaleIntensityD, + RandScaleIntensityDict, + RandScaleIntensityFixedMeand, + RandScaleIntensityFixedMeanD, + RandScaleIntensityFixedMeanDict, + RandShiftIntensityd, + RandShiftIntensityD, + RandShiftIntensityDict, + RandStdShiftIntensityd, + RandStdShiftIntensityD, + RandStdShiftIntensityDict, + SavitzkyGolaySmoothd, + SavitzkyGolaySmoothD, + SavitzkyGolaySmoothDict, + ScaleIntensityd, + ScaleIntensityD, + ScaleIntensityDict, + ScaleIntensityRanged, + ScaleIntensityRangeD, + ScaleIntensityRangeDict, + ScaleIntensityRangePercentilesd, + ScaleIntensityRangePercentilesD, + ScaleIntensityRangePercentilesDict, + ShiftIntensityd, + ShiftIntensityD, + ShiftIntensityDict, + StdShiftIntensityd, + StdShiftIntensityD, + StdShiftIntensityDict, + ThresholdIntensityd, + ThresholdIntensityD, + ThresholdIntensityDict, +) +from .inverse import InvertibleTransform, TraceableTransform +from .inverse_batch_transform import BatchInverseTransform, Decollated, DecollateD, DecollateDict +from .io.array import SUPPORTED_READERS, LoadImage, SaveImage +from .io.dictionary import LoadImaged, LoadImageD, LoadImageDict, SaveImaged, SaveImageD, SaveImageDict +from .lazy.array import ApplyPending +from .lazy.dictionary import ApplyPendingd, ApplyPendingD, ApplyPendingDict +from .lazy.functional import apply_pending +from .lazy.utils import combine_transforms, resample +from .meta_utility.dictionary import ( + FromMetaTensord, + FromMetaTensorD, + FromMetaTensorDict, + ToMetaTensord, + ToMetaTensorD, + ToMetaTensorDict, +) +from .nvtx import ( + Mark, + Markd, + MarkD, + MarkDict, + RandMark, + RandMarkd, + RandMarkD, + RandMarkDict, + RandRangePop, + RandRangePopd, + RandRangePopD, + RandRangePopDict, + RandRangePush, + RandRangePushd, + RandRangePushD, + RandRangePushDict, + RangePop, + RangePopd, + RangePopD, + RangePopDict, + RangePush, + RangePushd, + RangePushD, + RangePushDict, +) +from .post.array import ( + Activations, + AsDiscrete, + DistanceTransformEDT, + FillHoles, + Invert, + KeepLargestConnectedComponent, + LabelFilter, + LabelToContour, + MeanEnsemble, + ProbNMS, + RemoveSmallObjects, + SobelGradients, + VoteEnsemble, +) +from .post.dictionary import ( + ActivationsD, + Activationsd, + ActivationsDict, + AsDiscreteD, + AsDiscreted, + AsDiscreteDict, + DistanceTransformEDTd, + DistanceTransformEDTD, + DistanceTransformEDTDict, + Ensembled, + EnsembleD, + EnsembleDict, + FillHolesD, + FillHolesd, + FillHolesDict, + InvertD, + Invertd, + InvertDict, + KeepLargestConnectedComponentD, + KeepLargestConnectedComponentd, + KeepLargestConnectedComponentDict, + LabelFilterD, + LabelFilterd, + LabelFilterDict, + LabelToContourD, + LabelToContourd, + LabelToContourDict, + MeanEnsembleD, + MeanEnsembled, + MeanEnsembleDict, + ProbNMSD, + ProbNMSd, + ProbNMSDict, + RemoveSmallObjectsD, + RemoveSmallObjectsd, + RemoveSmallObjectsDict, + SaveClassificationD, + SaveClassificationd, + SaveClassificationDict, + SobelGradientsd, + SobelGradientsD, + SobelGradientsDict, + VoteEnsembleD, + VoteEnsembled, + VoteEnsembleDict, +) +from .regularization.array import CutMix, CutOut, MixUp +from .regularization.dictionary import ( + CutMixd, + CutMixD, + CutMixDict, + CutOutd, + CutOutD, + CutOutDict, + MixUpd, + MixUpD, + MixUpDict, +) +from .signal.array import ( + SignalContinuousWavelet, + SignalFillEmpty, + SignalRandAddGaussianNoise, + SignalRandAddSine, + SignalRandAddSinePartial, + SignalRandAddSquarePulse, + SignalRandAddSquarePulsePartial, + SignalRandDrop, + SignalRandScale, + SignalRandShift, + SignalRemoveFrequency, +) +from .signal.dictionary import SignalFillEmptyd, SignalFillEmptyD, SignalFillEmptyDict +from .smooth_field.array import ( + RandSmoothDeform, + RandSmoothFieldAdjustContrast, + RandSmoothFieldAdjustIntensity, + SmoothField, +) +from .smooth_field.dictionary import ( + RandSmoothDeformd, + RandSmoothDeformD, + RandSmoothDeformDict, + RandSmoothFieldAdjustContrastd, + RandSmoothFieldAdjustContrastD, + RandSmoothFieldAdjustContrastDict, + RandSmoothFieldAdjustIntensityd, + RandSmoothFieldAdjustIntensityD, + RandSmoothFieldAdjustIntensityDict, +) +from .spatial.array import ( + Affine, + AffineGrid, + Flip, + GridDistortion, + GridPatch, + GridSplit, + Orientation, + Rand2DElastic, + Rand3DElastic, + RandAffine, + RandAffineGrid, + RandAxisFlip, + RandDeformGrid, + RandFlip, + RandGridDistortion, + RandGridPatch, + RandRotate, + RandRotate90, + RandSimulateLowResolution, + RandZoom, + Resample, + ResampleToMatch, + Resize, + Rotate, + Rotate90, + Spacing, + SpatialResample, + Zoom, +) +from .spatial.dictionary import ( + Affined, + AffineD, + AffineDict, + Flipd, + FlipD, + FlipDict, + GridDistortiond, + GridDistortionD, + GridDistortionDict, + GridPatchd, + GridPatchD, + GridPatchDict, + GridSplitd, + GridSplitD, + GridSplitDict, + Orientationd, + OrientationD, + OrientationDict, + Rand2DElasticd, + Rand2DElasticD, + Rand2DElasticDict, + Rand3DElasticd, + Rand3DElasticD, + Rand3DElasticDict, + RandAffined, + RandAffineD, + RandAffineDict, + RandAxisFlipd, + RandAxisFlipD, + RandAxisFlipDict, + RandFlipd, + RandFlipD, + RandFlipDict, + RandGridDistortiond, + RandGridDistortionD, + RandGridDistortionDict, + RandGridPatchd, + RandGridPatchD, + RandGridPatchDict, + RandRotate90d, + RandRotate90D, + RandRotate90Dict, + RandRotated, + RandRotateD, + RandRotateDict, + RandSimulateLowResolutiond, + RandSimulateLowResolutionD, + RandSimulateLowResolutionDict, + RandZoomd, + RandZoomD, + RandZoomDict, + ResampleToMatchd, + ResampleToMatchD, + ResampleToMatchDict, + Resized, + ResizeD, + ResizeDict, + Rotate90d, + Rotate90D, + Rotate90Dict, + Rotated, + RotateD, + RotateDict, + Spacingd, + SpacingD, + SpacingDict, + SpatialResampled, + SpatialResampleD, + SpatialResampleDict, + Zoomd, + ZoomD, + ZoomDict, +) +from .spatial.functional import spatial_resample +from .traits import LazyTrait, MultiSampleTrait, RandomizableTrait, ThreadUnsafe +from .transform import LazyTransform, MapTransform, Randomizable, RandomizableTransform, Transform, apply_transform +from .utility.array import ( + AddCoordinateChannels, + AddExtremePointsChannel, + AsChannelLast, + CastToType, + ClassesToIndices, + ConvertToMultiChannelBasedOnBratsClasses, + CuCIM, + DataStats, + EnsureChannelFirst, + EnsureType, + FgBgToIndices, + Identity, + ImageFilter, + IntensityStats, + LabelToMask, + Lambda, + MapLabelValue, + RandCuCIM, + RandIdentity, + RandImageFilter, + RandLambda, + RemoveRepeatedChannel, + RepeatChannel, + SimulateDelay, + SplitDim, + SqueezeDim, + ToCupy, + ToDevice, + ToNumpy, + ToPIL, + TorchVision, + ToTensor, + Transpose, +) +from .utility.dictionary import ( + AddCoordinateChannelsd, + AddCoordinateChannelsD, + AddCoordinateChannelsDict, + AddExtremePointsChanneld, + AddExtremePointsChannelD, + AddExtremePointsChannelDict, + AsChannelLastd, + AsChannelLastD, + AsChannelLastDict, + CastToTyped, + CastToTypeD, + CastToTypeDict, + ClassesToIndicesd, + ClassesToIndicesD, + ClassesToIndicesDict, + ConcatItemsd, + ConcatItemsD, + ConcatItemsDict, + ConvertToMultiChannelBasedOnBratsClassesd, + ConvertToMultiChannelBasedOnBratsClassesD, + ConvertToMultiChannelBasedOnBratsClassesDict, + CopyItemsd, + CopyItemsD, + CopyItemsDict, + CuCIMd, + CuCIMD, + CuCIMDict, + DataStatsd, + DataStatsD, + DataStatsDict, + DeleteItemsd, + DeleteItemsD, + DeleteItemsDict, + EnsureChannelFirstd, + EnsureChannelFirstD, + EnsureChannelFirstDict, + EnsureTyped, + EnsureTypeD, + EnsureTypeDict, + FgBgToIndicesd, + FgBgToIndicesD, + FgBgToIndicesDict, + FlattenSubKeysd, + FlattenSubKeysD, + FlattenSubKeysDict, + Identityd, + IdentityD, + IdentityDict, + ImageFilterd, + ImageFilterD, + ImageFilterDict, + IntensityStatsd, + IntensityStatsD, + IntensityStatsDict, + LabelToMaskd, + LabelToMaskD, + LabelToMaskDict, + Lambdad, + LambdaD, + LambdaDict, + MapLabelValued, + MapLabelValueD, + MapLabelValueDict, + RandCuCIMd, + RandCuCIMD, + RandCuCIMDict, + RandImageFilterd, + RandImageFilterD, + RandImageFilterDict, + RandLambdad, + RandLambdaD, + RandLambdaDict, + RandTorchVisiond, + RandTorchVisionD, + RandTorchVisionDict, + RemoveRepeatedChanneld, + RemoveRepeatedChannelD, + RemoveRepeatedChannelDict, + RepeatChanneld, + RepeatChannelD, + RepeatChannelDict, + SelectItemsd, + SelectItemsD, + SelectItemsDict, + SimulateDelayd, + SimulateDelayD, + SimulateDelayDict, + SplitDimd, + SplitDimD, + SplitDimDict, + SqueezeDimd, + SqueezeDimD, + SqueezeDimDict, + ToCupyd, + ToCupyD, + ToCupyDict, + ToDeviced, + ToDeviceD, + ToDeviceDict, + ToNumpyd, + ToNumpyD, + ToNumpyDict, + ToPILd, + ToPILD, + ToPILDict, + TorchVisiond, + TorchVisionD, + TorchVisionDict, + ToTensord, + ToTensorD, + ToTensorDict, + Transposed, + TransposeD, + TransposeDict, +) +from .utils import ( + Fourier, + allow_missing_keys_mode, + attach_hook, + check_non_lazy_pending_ops, + compute_divisible_spatial_size, + convert_applied_interp_mode, + convert_pad_mode, + convert_to_contiguous, + copypaste_arrays, + create_control_grid, + create_grid, + create_rotate, + create_scale, + create_shear, + create_translate, + distance_transform_edt, + equalize_hist, + extreme_points_to_image, + generate_label_classes_crop_centers, + generate_pos_neg_label_crop_centers, + generate_spatial_bounding_box, + get_extreme_points, + get_largest_connected_component_mask, + get_number_image_type_conversions, + get_transform_backends, + img_bounds, + in_bounds, + is_empty, + is_positive, + map_binary_to_indices, + map_classes_to_indices, + map_spatial_axes, + print_transform_backends, + rand_choice, + remove_small_objects, + rescale_array, + rescale_array_int_max, + rescale_instance_array, + reset_ops_id, + resize_center, + resolves_modes, + sync_meta_info, + weighted_patch_samples, + zero_margins, +) +from .utils_pytorch_numpy_unification import ( + allclose, + any_np_pt, + ascontiguousarray, + clip, + concatenate, + cumsum, + floor_divide, + in1d, + isfinite, + isnan, + maximum, + mode, + moveaxis, + nonzero, + percentile, + ravel, + repeat, + stack, + unravel_index, + where, +) diff --git a/source_code/SegMamba/monai/transforms/adaptors.py b/source_code/SegMamba/monai/transforms/adaptors.py new file mode 100644 index 0000000000000000000000000000000000000000..f5f1a4fc18e3bed9009cb9baa35c069a79030861 --- /dev/null +++ b/source_code/SegMamba/monai/transforms/adaptors.py @@ -0,0 +1,272 @@ +# Copyright (c) MONAI Consortium +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +""" +How to use the adaptor function +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +The key to using 'adaptor' lies in understanding the function that want to +adapt. The 'inputs' and 'outputs' parameters take either strings, lists/tuples +of strings or a dictionary mapping strings, depending on call signature of the +function being called. + +The adaptor function is written to minimise the cognitive load on the caller. +There should be a minimal number of cases where the caller has to set anything +on the input parameter, and for functions that return a single value, it is +only necessary to name the dictionary keyword to which that value is assigned. + +Use of `outputs` +---------------- + +`outputs` can take either a string, a list/tuple of string or a dict of string +to string, depending on what the transform being adapted returns: + + - If the transform returns a single argument, then outputs can be supplied a + string that indicates what key to assign the return value to in the + dictionary + - If the transform returns a list/tuple of values, then outputs can be supplied + a list/tuple of the same length. The strings in outputs map the return value + at the corresponding position to a key in the dictionary + - If the transform returns a dictionary of values, then outputs must be supplied + a dictionary that maps keys in the function's return dictionary to the + dictionary being passed between functions + +Note, the caller is free to use a more complex way of specifying the outputs +parameter than is required. The following are synonymous and will be treated +identically: + +.. code-block:: python + + # single argument + adaptor(MyTransform(), 'image') + adaptor(MyTransform(), ['image']) + adaptor(MyTransform(), {'image': 'image'}) + + # multiple arguments + adaptor(MyTransform(), ['image', 'label']) + adaptor(MyTransform(), {'image': 'image', 'label': 'label'}) + +Use of `inputs` +--------------- + +`inputs` can usually be omitted when using `adaptor`. It is only required when a +the function's parameter names do not match the names in the dictionary that is +used to chain transform calls. + +.. code-block:: python + + class MyTransform1: + def __call__(self, image): + # do stuff to image + return image + 1 + + + class MyTransform2: + def __call__(self, img_dict): + # do stuff to image + img_dict["image"] += 1 + return img_dict + + + xform = Compose([adaptor(MyTransform1(), "image"), MyTransform2()]) + d = {"image": 1} + print(xform(d)) + + >>> {'image': 3} + +.. code-block:: python + + class MyTransform3: + def __call__(self, img_dict): + # do stuff to image + img_dict["image"] -= 1 + img_dict["segment"] = img_dict["image"] + return img_dict + + + class MyTransform4: + def __call__(self, img, seg): + # do stuff to image + img -= 1 + seg -= 1 + return img, seg + + + xform = Compose([MyTransform3(), adaptor(MyTransform4(), ["img", "seg"], {"image": "img", "segment": "seg"})]) + d = {"image": 1} + print(xform(d)) + + >>> {'image': 0, 'segment': 0, 'img': -1, 'seg': -1} + +Inputs: + +- dictionary in: None | Name maps +- params in (match): None | Name list | Name maps +- params in (mismatch): Name maps +- params & `**kwargs` (match) : None | Name maps +- params & `**kwargs` (mismatch) : Name maps + +Outputs: + +- dictionary out: None | Name maps +- list/tuple out: list/tuple +- variable out: string + +""" + +from __future__ import annotations + +from typing import Callable + +from monai.utils import export as _monai_export + +__all__ = ["adaptor", "apply_alias", "to_kwargs", "FunctionSignature"] + + +@_monai_export("monai.transforms") +def adaptor(function, outputs, inputs=None): + + def must_be_types_or_none(variable_name, variable, types): + if variable is not None: + if not isinstance(variable, types): + raise TypeError(f"'{variable_name}' must be None or one of {types} but is {type(variable)}") + + def must_be_types(variable_name, variable, types): + if not isinstance(variable, types): + raise TypeError(f"'{variable_name}' must be one of {types} but is {type(variable)}") + + def map_names(ditems, input_map): + return {input_map(k, k): v for k, v in ditems.items()} + + def map_only_names(ditems, input_map): + return {v: ditems[k] for k, v in input_map.items()} + + def _inner(ditems): + sig = FunctionSignature(function) + + if sig.found_kwargs: + must_be_types_or_none("inputs", inputs, (dict,)) + # we just forward all arguments unless we have been provided an input map + if inputs is None: + dinputs = dict(ditems) + else: + # dict + dinputs = map_names(ditems, inputs) + + else: + # no **kwargs + # select only items from the method signature + dinputs = {k: v for k, v in ditems.items() if k in sig.non_var_parameters} + must_be_types_or_none("inputs", inputs, (str, list, tuple, dict)) + if inputs is None: + pass + elif isinstance(inputs, str): + if len(sig.non_var_parameters) != 1: + raise ValueError("if 'inputs' is a string, function may only have a single non-variadic parameter") + dinputs = {inputs: ditems[inputs]} + elif isinstance(inputs, (list, tuple)): + dinputs = {k: dinputs[k] for k in inputs} + else: + # dict + dinputs = map_only_names(ditems, inputs) + + ret = function(**dinputs) + + # now the mapping back to the output dictionary depends on outputs and what was returned from the function + op = outputs + if isinstance(ret, dict): + must_be_types_or_none("outputs", op, (dict,)) + if op is not None: + ret = {v: ret[k] for k, v in op.items()} + elif isinstance(ret, (list, tuple)): + if len(ret) == 1: + must_be_types("outputs", op, (str, list, tuple)) + else: + must_be_types("outputs", op, (list, tuple)) + + if isinstance(op, str): + op = [op] + + if len(ret) != len(outputs): + raise ValueError("'outputs' must have the same length as the number of elements that were returned") + + ret = dict(zip(op, ret)) + else: + must_be_types("outputs", op, (str, list, tuple)) + if isinstance(op, (list, tuple)): + if len(op) != 1: + raise ValueError("'outputs' must be of length one if it is a list or tuple") + op = op[0] + ret = {op: ret} + + ditems = dict(ditems) + for k, v in ret.items(): + ditems[k] = v + + return ditems + + return _inner + + +@_monai_export("monai.transforms") +def apply_alias(fn, name_map): + + def _inner(data): + # map names + pre_call = dict(data) + for _from, _to in name_map.items(): + pre_call[_to] = pre_call.pop(_from) + + # execute + post_call = fn(pre_call) + + # map names back + for _from, _to in name_map.items(): + post_call[_from] = post_call.pop(_to) + + return post_call + + return _inner + + +@_monai_export("monai.transforms") +def to_kwargs(fn): + + def _inner(data): + return fn(**data) + + return _inner + + +class FunctionSignature: + + def __init__(self, function: Callable) -> None: + import inspect + + sfn = inspect.signature(function) + self.found_args = False + self.found_kwargs = False + self.defaults = {} + self.non_var_parameters = set() + for p in sfn.parameters.values(): + if p.kind is inspect.Parameter.VAR_POSITIONAL: + self.found_args = True + if p.kind is inspect.Parameter.VAR_KEYWORD: + self.found_kwargs = True + else: + self.non_var_parameters.add(p.name) + self.defaults[p.name] = p.default is not p.empty + + def __repr__(self) -> str: + s = " str: + return self.__repr__() diff --git a/source_code/SegMamba/monai/transforms/compose.py b/source_code/SegMamba/monai/transforms/compose.py new file mode 100644 index 0000000000000000000000000000000000000000..236d3cc4c51677b8d65d9865bfffe4d140a5b04d --- /dev/null +++ b/source_code/SegMamba/monai/transforms/compose.py @@ -0,0 +1,786 @@ +# Copyright (c) MONAI Consortium +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +""" +A collection of generic interfaces for MONAI transforms. +""" + +from __future__ import annotations + +import warnings +from collections.abc import Callable, Mapping, Sequence +from copy import deepcopy +from typing import Any + +import numpy as np + +import monai +from monai.apps.utils import get_logger +from monai.config import NdarrayOrTensor +from monai.transforms.inverse import InvertibleTransform + +# For backwards compatibility (so this still works: from monai.transforms.compose import MapTransform) +from monai.transforms.lazy.functional import apply_pending_transforms +from monai.transforms.traits import ThreadUnsafe +from monai.transforms.transform import ( # noqa: F401 + LazyTransform, + MapTransform, + Randomizable, + RandomizableTransform, + Transform, + apply_transform, +) +from monai.utils import MAX_SEED, TraceKeys, TraceStatusKeys, ensure_tuple, get_seed + +logger = get_logger(__name__) + +__all__ = ["Compose", "OneOf", "RandomOrder", "SomeOf", "execute_compose"] + + +def execute_compose( + data: NdarrayOrTensor | Sequence[NdarrayOrTensor] | Mapping[Any, NdarrayOrTensor], + transforms: Sequence[Any], + map_items: bool = True, + unpack_items: bool = False, + start: int = 0, + end: int | None = None, + lazy: bool | None = False, + overrides: dict | None = None, + threading: bool = False, + log_stats: bool | str = False, +) -> NdarrayOrTensor | Sequence[NdarrayOrTensor] | Mapping[Any, NdarrayOrTensor]: + """ + ``execute_compose`` provides the implementation that the ``Compose`` class uses to execute a sequence + of transforms. As well as being used by Compose, it can be used by subclasses of + Compose and by code that doesn't have a Compose instance but needs to execute a + sequence of transforms is if it were executed by Compose. It should only be used directly + when it is not possible to use ``Compose.__call__`` to achieve the same goal. + Args: + data: a tensor-like object to be transformed + transforms: a sequence of transforms to be carried out + map_items: whether to apply transform to each item in the input `data` if `data` is a list or tuple. + defaults to `True`. + unpack_items: whether to unpack input `data` with `*` as parameters for the callable function of transform. + defaults to `False`. + start: the index of the first transform to be executed. If not set, this defaults to 0 + end: the index after the last transform to be executed. If set, the transform at index-1 + is the last transform that is executed. If this is not set, it defaults to len(transforms) + lazy: whether to enable :ref:`lazy evaluation` for lazy transforms. If False, transforms will be + carried out on a transform by transform basis. If True, all lazy transforms will + be executed by accumulating changes and resampling as few times as possible. + overrides: this optional parameter allows you to specify a dictionary of parameters that should be overridden + when executing a pipeline. These each parameter that is compatible with a given transform is then applied + to that transform before it is executed. Note that overrides are currently only applied when + :ref:`lazy evaluation` is enabled for the pipeline or a given transform. If lazy is False + they are ignored. Currently supported args are: + {``"mode"``, ``"padding_mode"``, ``"dtype"``, ``"align_corners"``, ``"resample_mode"``, ``device``}. + threading: whether executing is happening in a threaded environment. If set, copies are made + of transforms that have the ``RandomizedTrait`` interface. + log_stats: this optional parameter allows you to specify a logger by name for logging of pipeline execution. + Setting this to False disables logging. Setting it to True enables logging to the default loggers. + Setting a string overrides the logger name to which logging is performed. + + Returns: + A tensorlike, sequence of tensorlikes or dict of tensorlists containing the result of running + `data`` through the sequence of ``transforms``. + """ + end_ = len(transforms) if end is None else end + if start is None: + raise ValueError(f"'start' ({start}) cannot be None") + if start < 0: + raise ValueError(f"'start' ({start}) cannot be less than 0") + if start > end_: + raise ValueError(f"'start' ({start}) must be less than 'end' ({end_})") + if end_ > len(transforms): + raise ValueError(f"'end' ({end_}) must be less than or equal to the transform count ({len(transforms)}") + + # no-op if the range is empty + if start == end: + return data + + for _transform in transforms[start:end]: + if threading: + _transform = deepcopy(_transform) if isinstance(_transform, ThreadUnsafe) else _transform + data = apply_transform( + _transform, data, map_items, unpack_items, lazy=lazy, overrides=overrides, log_stats=log_stats + ) + data = apply_pending_transforms(data, None, overrides, logger_name=log_stats) + return data + + +class Compose(Randomizable, InvertibleTransform, LazyTransform): + """ + ``Compose`` provides the ability to chain a series of callables together in + a sequential manner. Each transform in the sequence must take a single + argument and return a single value. + + ``Compose`` can be used in two ways: + + #. With a series of transforms that accept and return a single + ndarray / tensor / tensor-like parameter. + #. With a series of transforms that accept and return a dictionary that + contains one or more parameters. Such transforms must have pass-through + semantics that unused values in the dictionary must be copied to the return + dictionary. It is required that the dictionary is copied between input + and output of each transform. + + If some transform takes a data item dictionary as input, and returns a + sequence of data items in the transform chain, all following transforms + will be applied to each item of this list if `map_items` is `True` (the + default). If `map_items` is `False`, the returned sequence is passed whole + to the next callable in the chain. + + For example: + + A `Compose([transformA, transformB, transformC], + map_items=True)(data_dict)` could achieve the following patch-based + transformation on the `data_dict` input: + + #. transformA normalizes the intensity of 'img' field in the `data_dict`. + #. transformB crops out image patches from the 'img' and 'seg' of + `data_dict`, and return a list of three patch samples:: + + {'img': 3x100x100 data, 'seg': 1x100x100 data, 'shape': (100, 100)} + applying transformB + ----------> + [{'img': 3x20x20 data, 'seg': 1x20x20 data, 'shape': (20, 20)}, + {'img': 3x20x20 data, 'seg': 1x20x20 data, 'shape': (20, 20)}, + {'img': 3x20x20 data, 'seg': 1x20x20 data, 'shape': (20, 20)},] + + #. transformC then randomly rotates or flips 'img' and 'seg' of + each dictionary item in the list returned by transformB. + + The composed transforms will be set the same global random seed if user called + `set_determinism()`. + + When using the pass-through dictionary operation, you can make use of + :class:`monai.transforms.adaptors.adaptor` to wrap transforms that don't conform + to the requirements. This approach allows you to use transforms from + otherwise incompatible libraries with minimal additional work. + + Note: + + In many cases, Compose is not the best way to create pre-processing + pipelines. Pre-processing is often not a strictly sequential series of + operations, and much of the complexity arises when a not-sequential + set of functions must be called as if it were a sequence. + + Example: images and labels + Images typically require some kind of normalization that labels do not. + Both are then typically augmented through the use of random rotations, + flips, and deformations. + Compose can be used with a series of transforms that take a dictionary + that contains 'image' and 'label' entries. This might require wrapping + `torchvision` transforms before passing them to compose. + Alternatively, one can create a class with a `__call__` function that + calls your pre-processing functions taking into account that not all of + them are called on the labels. + + Lazy resampling: + + Lazy resampling is an experimental feature introduced in 1.2. Its purpose is + to reduce the number of resample operations that must be carried out when executing + a pipeline of transforms. This can provide significant performance improvements in + terms of pipeline executing speed and memory usage, and can also significantly + reduce the loss of information that occurs when performing a number of spatial + resamples in succession. + + Lazy resampling can be enabled or disabled through the ``lazy`` parameter, either by + specifying it at initialisation time or overriding it at call time. + + * False (default): Don't perform any lazy resampling + * None: Perform lazy resampling based on the 'lazy' properties of the transform instances. + * True: Always perform lazy resampling if possible. This will ignore the ``lazy`` properties + of the transform instances + + Please see the :ref:`Lazy Resampling topic` for more details of this feature + and examples of its use. + + Args: + transforms: sequence of callables. + map_items: whether to apply transform to each item in the input `data` if `data` is a list or tuple. + defaults to `True`. + unpack_items: whether to unpack input `data` with `*` as parameters for the callable function of transform. + defaults to `False`. + log_stats: this optional parameter allows you to specify a logger by name for logging of pipeline execution. + Setting this to False disables logging. Setting it to True enables logging to the default loggers. + Setting a string overrides the logger name to which logging is performed. + lazy: whether to enable :ref:`Lazy Resampling` for lazy transforms. If False, transforms will + be carried out on a transform by transform basis. If True, all lazy transforms will be executed by + accumulating changes and resampling as few times as possible. If lazy is None, `Compose` will + perform lazy execution on lazy transforms that have their `lazy` property set to True. + overrides: this optional parameter allows you to specify a dictionary of parameters that should be overridden + when executing a pipeline. These each parameter that is compatible with a given transform is then applied + to that transform before it is executed. Note that overrides are currently only applied when + :ref:`Lazy Resampling` is enabled for the pipeline or a given transform. If lazy is False + they are ignored. Currently supported args are: + {``"mode"``, ``"padding_mode"``, ``"dtype"``, ``"align_corners"``, ``"resample_mode"``, ``device``}. + """ + + def __init__( + self, + transforms: Sequence[Callable] | Callable | None = None, + map_items: bool = True, + unpack_items: bool = False, + log_stats: bool | str = False, + lazy: bool | None = False, + overrides: dict | None = None, + ) -> None: + LazyTransform.__init__(self, lazy=lazy) + + if transforms is None: + transforms = [] + + if not isinstance(map_items, bool): + raise ValueError( + f"Argument 'map_items' should be boolean. Got {type(map_items)}." + "Check brackets when passing a sequence of callables." + ) + + self.transforms = ensure_tuple(transforms) + self.map_items = map_items + self.unpack_items = unpack_items + self.log_stats = log_stats + self.set_random_state(seed=get_seed()) + self.overrides = overrides + + @LazyTransform.lazy.setter # type: ignore + def lazy(self, val: bool): + self._lazy = val + + def set_random_state(self, seed: int | None = None, state: np.random.RandomState | None = None) -> Compose: + super().set_random_state(seed=seed, state=state) + for _transform in self.transforms: + if not isinstance(_transform, Randomizable): + continue + _transform.set_random_state(seed=self.R.randint(MAX_SEED, dtype="uint32")) + return self + + def randomize(self, data: Any | None = None) -> None: + for _transform in self.transforms: + if not isinstance(_transform, Randomizable): + continue + try: + _transform.randomize(data) + except TypeError as type_error: + tfm_name: str = type(_transform).__name__ + warnings.warn( + f"Transform '{tfm_name}' in Compose not randomized\n{tfm_name}.{type_error}.", RuntimeWarning + ) + + def get_index_of_first(self, predicate): + """ + get_index_of_first takes a ``predicate`` and returns the index of the first transform that + satisfies the predicate (ie. makes the predicate return True). If it is unable to find + a transform that satisfies the ``predicate``, it returns None. + + Example: + c = Compose([Flip(...), Rotate90(...), Zoom(...), RandRotate(...), Resize(...)]) + + print(c.get_index_of_first(lambda t: isinstance(t, RandomTrait))) + >>> 3 + print(c.get_index_of_first(lambda t: isinstance(t, Compose))) + >>> None + + Note: + This is only performed on the transforms directly held by this instance. If this + instance has nested ``Compose`` transforms or other transforms that contain transforms, + it does not iterate into them. + + + Args: + predicate: a callable that takes a single argument and returns a bool. When called + it is passed a transform from the sequence of transforms contained by this compose + instance. + + Returns: + The index of the first transform in the sequence for which ``predicate`` returns + True. None if no transform satisfies the ``predicate`` + + """ + for i in range(len(self.transforms)): + if predicate(self.transforms[i]): + return i + return None + + def flatten(self): + """Return a Composition with a simple list of transforms, as opposed to any nested Compositions. + + e.g., `t1 = Compose([x, x, x, x, Compose([Compose([x, x]), x, x])]).flatten()` + will result in the equivalent of `t1 = Compose([x, x, x, x, x, x, x, x])`. + + """ + new_transforms = [] + for t in self.transforms: + if type(t) is Compose: # nopep8 + new_transforms += t.flatten().transforms + else: + new_transforms.append(t) + + return Compose(new_transforms) + + def __len__(self): + """Return number of transformations.""" + return len(self.flatten().transforms) + + def __call__(self, input_, start=0, end=None, threading=False, lazy: bool | None = None): + _lazy = self._lazy if lazy is None else lazy + result = execute_compose( + input_, + transforms=self.transforms, + start=start, + end=end, + map_items=self.map_items, + unpack_items=self.unpack_items, + lazy=_lazy, + overrides=self.overrides, + threading=threading, + log_stats=self.log_stats, + ) + + return result + + def inverse(self, data): + self._raise_if_not_invertible(data) + + invertible_transforms = [t for t in self.flatten().transforms if isinstance(t, InvertibleTransform)] + if not invertible_transforms: + warnings.warn("inverse has been called but no invertible transforms have been supplied") + + if self._lazy is True: + warnings.warn( + f"'lazy' is set to {self._lazy} but lazy execution is not supported when inverting. " + f"'lazy' has been overridden to False for the call to inverse" + ) + # loop backwards over transforms + for t in reversed(invertible_transforms): + data = apply_transform( + t.inverse, data, self.map_items, self.unpack_items, lazy=False, log_stats=self.log_stats + ) + return data + + @staticmethod + def _raise_if_not_invertible(data: Any): + from monai.transforms.utils import has_status_keys + + invertible, reasons = has_status_keys( + data, TraceStatusKeys.PENDING_DURING_APPLY, "Pending operations while applying an operation" + ) + + if invertible is False: + if reasons is not None: + reason_text = "\n".join(reasons) + raise RuntimeError(f"Unable to run inverse on 'data' for the following reasons:\n{reason_text}") + else: + raise RuntimeError("Unable to run inverse on 'data'; no reason logged in trace data") + + +class OneOf(Compose): + """ + ``OneOf`` provides the ability to randomly choose one transform out of a + list of callables with pre-defined probabilities for each. + + Args: + transforms: sequence of callables. + weights: probabilities corresponding to each callable in transforms. + Probabilities are normalized to sum to one. + map_items: whether to apply transform to each item in the input `data` if `data` is a list or tuple. + defaults to `True`. + unpack_items: whether to unpack input `data` with `*` as parameters for the callable function of transform. + defaults to `False`. + log_stats: this optional parameter allows you to specify a logger by name for logging of pipeline execution. + Setting this to False disables logging. Setting it to True enables logging to the default loggers. + Setting a string overrides the logger name to which logging is performed. + lazy: whether to enable :ref:`Lazy Resampling` for lazy transforms. If False, transforms will + be carried out on a transform by transform basis. If True, all lazy transforms will be executed by + accumulating changes and resampling as few times as possible. If lazy is None, `Compose` will + perform lazy execution on lazy transforms that have their `lazy` property set to True. + overrides: this optional parameter allows you to specify a dictionary of parameters that should be overridden + when executing a pipeline. These each parameter that is compatible with a given transform is then applied + to that transform before it is executed. Note that overrides are currently only applied when + :ref:`Lazy Resampling` is enabled for the pipeline or a given transform. If lazy is False + they are ignored. Currently supported args are: + {``"mode"``, ``"padding_mode"``, ``"dtype"``, ``"align_corners"``, ``"resample_mode"``, ``device``}. + """ + + def __init__( + self, + transforms: Sequence[Callable] | Callable | None = None, + weights: Sequence[float] | float | None = None, + map_items: bool = True, + unpack_items: bool = False, + log_stats: bool | str = False, + lazy: bool | None = False, + overrides: dict | None = None, + ) -> None: + super().__init__(transforms, map_items, unpack_items, log_stats, lazy, overrides) + if len(self.transforms) == 0: + weights = [] + elif weights is None or isinstance(weights, float): + weights = [1.0 / len(self.transforms)] * len(self.transforms) + if len(weights) != len(self.transforms): + raise ValueError( + "transforms and weights should be same size if both specified as sequences, " + f"got {len(weights)} and {len(self.transforms)}." + ) + self.weights = ensure_tuple(self._normalize_probabilities(weights)) + self.log_stats = log_stats + + def _normalize_probabilities(self, weights): + if len(weights) == 0: + return weights + weights = np.array(weights) + if np.any(weights < 0): + raise ValueError(f"Probabilities must be greater than or equal to zero, got {weights}.") + if np.all(weights == 0): + raise ValueError(f"At least one probability must be greater than zero, got {weights}.") + weights = weights / weights.sum() + return list(weights) + + def flatten(self): + transforms = [] + weights = [] + for t, w in zip(self.transforms, self.weights): + # if nested, probability is the current weight multiplied by the nested weights, + # and so on recursively + if isinstance(t, OneOf): + tr = t.flatten() + for t_, w_ in zip(tr.transforms, tr.weights): + transforms.append(t_) + weights.append(w_ * w) + else: + transforms.append(t) + weights.append(w) + return OneOf(transforms, weights, self.map_items, self.unpack_items) + + def __call__(self, data, start=0, end=None, threading=False, lazy: bool | None = None): + if start != 0: + raise ValueError(f"OneOf requires 'start' parameter to be 0 (start set to {start})") + if end is not None: + raise ValueError(f"OneOf requires 'end' parameter to be None (end set to {end}") + + if len(self.transforms) == 0: + return data + + index = self.R.multinomial(1, self.weights).argmax() + _transform = self.transforms[index] + _lazy = self._lazy if lazy is None else lazy + + data = execute_compose( + data, + [_transform], + start=start, + end=end, + map_items=self.map_items, + unpack_items=self.unpack_items, + lazy=_lazy, + overrides=self.overrides, + threading=threading, + log_stats=self.log_stats, + ) + + # if the data is a mapping (dictionary), append the OneOf transform to the end + if isinstance(data, monai.data.MetaTensor): + self.push_transform(data, extra_info={"index": index}) + elif isinstance(data, Mapping): + for key in data: # dictionary not change size during iteration + if isinstance(data[key], monai.data.MetaTensor): + self.push_transform(data[key], extra_info={"index": index}) + return data + + def inverse(self, data): + if len(self.transforms) == 0: + return data + + index = None + if isinstance(data, monai.data.MetaTensor): + index = self.pop_transform(data)[TraceKeys.EXTRA_INFO]["index"] + elif isinstance(data, Mapping): + for key in data: + if isinstance(data[key], monai.data.MetaTensor): + index = self.pop_transform(data, key)[TraceKeys.EXTRA_INFO]["index"] + else: + raise RuntimeError( + f"Inverse only implemented for Mapping (dictionary) or MetaTensor data, got type {type(data)}." + ) + if index is None: + # no invertible transforms have been applied + return data + + _transform = self.transforms[index] + # apply the inverse + return _transform.inverse(data) if isinstance(_transform, InvertibleTransform) else data + + +class RandomOrder(Compose): + """ + ``RandomOrder`` provides the ability to apply a list of transformations in random order. + + Args: + transforms: sequence of callables. + map_items: whether to apply transform to each item in the input `data` if `data` is a list or tuple. + defaults to `True`. + unpack_items: whether to unpack input `data` with `*` as parameters for the callable function of transform. + defaults to `False`. + log_stats: this optional parameter allows you to specify a logger by name for logging of pipeline execution. + Setting this to False disables logging. Setting it to True enables logging to the default loggers. + Setting a string overrides the logger name to which logging is performed. + lazy: whether to enable :ref:`Lazy Resampling` for lazy transforms. If False, transforms will + be carried out on a transform by transform basis. If True, all lazy transforms will be executed by + accumulating changes and resampling as few times as possible. If lazy is None, `Compose` will + perform lazy execution on lazy transforms that have their `lazy` property set to True. + overrides: this optional parameter allows you to specify a dictionary of parameters that should be overridden + when executing a pipeline. These each parameter that is compatible with a given transform is then applied + to that transform before it is executed. Note that overrides are currently only applied when + :ref:`Lazy Resampling` is enabled for the pipeline or a given transform. If lazy is False + they are ignored. Currently supported args are: + {``"mode"``, ``"padding_mode"``, ``"dtype"``, ``"align_corners"``, ``"resample_mode"``, ``device``}. + """ + + def __init__( + self, + transforms: Sequence[Callable] | Callable | None = None, + map_items: bool = True, + unpack_items: bool = False, + log_stats: bool | str = False, + lazy: bool | None = False, + overrides: dict | None = None, + ) -> None: + super().__init__(transforms, map_items, unpack_items, log_stats, lazy, overrides) + self.log_stats = log_stats + + def __call__(self, input_, start=0, end=None, threading=False, lazy: bool | None = None): + if start != 0: + raise ValueError(f"RandomOrder requires 'start' parameter to be 0 (start set to {start})") + if end is not None: + raise ValueError(f"RandomOrder requires 'end' parameter to be None (end set to {end}") + + if len(self.transforms) == 0: + return input_ + + num = len(self.transforms) + applied_order = self.R.permutation(range(num)) + _lazy = self._lazy if lazy is None else lazy + + input_ = execute_compose( + input_, + [self.transforms[ind] for ind in applied_order], + start=start, + end=end, + map_items=self.map_items, + unpack_items=self.unpack_items, + lazy=_lazy, + threading=threading, + log_stats=self.log_stats, + ) + + # if the data is a mapping (dictionary), append the RandomOrder transform to the end + if isinstance(input_, monai.data.MetaTensor): + self.push_transform(input_, extra_info={"applied_order": applied_order}) + elif isinstance(input_, Mapping): + for key in input_: # dictionary not change size during iteration + if isinstance(input_[key], monai.data.MetaTensor): + self.push_transform(input_[key], extra_info={"applied_order": applied_order}) + return input_ + + def inverse(self, data): + if len(self.transforms) == 0: + return data + + applied_order = None + if isinstance(data, monai.data.MetaTensor): + applied_order = self.pop_transform(data)[TraceKeys.EXTRA_INFO]["applied_order"] + elif isinstance(data, Mapping): + for key in data: + if isinstance(data[key], monai.data.MetaTensor): + applied_order = self.pop_transform(data, key)[TraceKeys.EXTRA_INFO]["applied_order"] + else: + raise RuntimeError( + f"Inverse only implemented for Mapping (dictionary) or MetaTensor data, got type {type(data)}." + ) + if applied_order is None: + # no invertible transforms have been applied + return data + + # loop backwards over transforms + for o in reversed(applied_order): + if isinstance(self.transforms[o], InvertibleTransform): + data = apply_transform( + self.transforms[o].inverse, data, self.map_items, self.unpack_items, log_stats=self.log_stats + ) + return data + + +class SomeOf(Compose): + """ + ``SomeOf`` samples a different sequence of transforms to apply each time it is called. + + It can be configured to sample a fixed or varying number of transforms each time its called. Samples are drawn + uniformly, or from user supplied transform weights. When varying the number of transforms sampled per call, + the number of transforms to sample that call is sampled uniformly from a range supplied by the user. + + Args: + transforms: list of callables. + map_items: whether to apply transform to each item in the input `data` if `data` is a list or tuple. + Defaults to `True`. + unpack_items: whether to unpack input `data` with `*` as parameters for the callable function of transform. + Defaults to `False`. + log_stats: this optional parameter allows you to specify a logger by name for logging of pipeline execution. + Setting this to False disables logging. Setting it to True enables logging to the default loggers. + Setting a string overrides the logger name to which logging is performed. + num_transforms: a 2-tuple, int, or None. The 2-tuple specifies the minimum and maximum (inclusive) number of + transforms to sample at each iteration. If an int is given, the lower and upper bounds are set equal. + None sets it to `len(transforms)`. Default to `None`. + replace: whether to sample with replacement. Defaults to `False`. + weights: weights to use in for sampling transforms. Will be normalized to 1. Default: None (uniform). + lazy: whether to enable :ref:`Lazy Resampling` for lazy transforms. If False, transforms will + be carried out on a transform by transform basis. If True, all lazy transforms will be executed by + accumulating changes and resampling as few times as possible. If lazy is None, `Compose` will + perform lazy execution on lazy transforms that have their `lazy` property set to True. + overrides: this optional parameter allows you to specify a dictionary of parameters that should be overridden + when executing a pipeline. These each parameter that is compatible with a given transform is then applied + to that transform before it is executed. Note that overrides are currently only applied when + :ref:`Lazy Resampling` is enabled for the pipeline or a given transform. If lazy is False + they are ignored. Currently supported args are: + {``"mode"``, ``"padding_mode"``, ``"dtype"``, ``"align_corners"``, ``"resample_mode"``, ``device``}. + """ + + def __init__( + self, + transforms: Sequence[Callable] | Callable | None = None, + map_items: bool = True, + unpack_items: bool = False, + log_stats: bool | str = False, + num_transforms: int | tuple[int, int] | None = None, + replace: bool = False, + weights: list[int] | None = None, + lazy: bool | None = False, + overrides: dict | None = None, + ) -> None: + super().__init__(transforms, map_items, unpack_items, log_stats=log_stats, lazy=lazy, overrides=overrides) + self.min_num_transforms, self.max_num_transforms = self._ensure_valid_num_transforms(num_transforms) + self.replace = replace + self.weights = self._normalize_probabilities(weights) + self.log_stats = log_stats + + def _ensure_valid_num_transforms(self, num_transforms: int | tuple[int, int] | None) -> tuple: + if ( + not isinstance(num_transforms, tuple) + and not isinstance(num_transforms, list) + and not isinstance(num_transforms, int) + and num_transforms is not None + ): + raise ValueError( + f"Expected num_transforms to be of type int, list, tuple or None, but it's {type(num_transforms)}" + ) + + if num_transforms is None: + result = [len(self.transforms), len(self.transforms)] + elif isinstance(num_transforms, int): + n = min(len(self.transforms), num_transforms) + result = [n, n] + else: + if len(num_transforms) != 2: + raise ValueError(f"Expected len(num_transforms)=2, but it was {len(num_transforms)}") + if not isinstance(num_transforms[0], int) or not isinstance(num_transforms[1], int): + raise ValueError( + f"Expected (int,int), but received ({type(num_transforms[0])}, {type(num_transforms[1])})" + ) + + result = [num_transforms[0], num_transforms[1]] + + if result[0] < 0 or result[1] > len(self.transforms): + raise ValueError(f"num_transforms={num_transforms} are out of the bounds [0, {len(self.transforms)}].") + + return ensure_tuple(result) + + # Modified from OneOf + def _normalize_probabilities(self, weights): + if weights is None or len(self.transforms) == 0: + return None + + weights = np.array(weights) + + n_weights = len(weights) + if n_weights != len(self.transforms): + raise ValueError(f"Expected len(weights)={len(self.transforms)}, got: {n_weights}.") + + if np.any(weights < 0): + raise ValueError(f"Probabilities must be greater than or equal to zero, got {weights}.") + + if np.all(weights == 0): + raise ValueError(f"At least one probability must be greater than zero, got {weights}.") + + weights = weights / weights.sum() + + return ensure_tuple(list(weights)) + + def __call__(self, data, start=0, end=None, threading=False, lazy: bool | None = None): + if start != 0: + raise ValueError(f"SomeOf requires 'start' parameter to be 0 (start set to {start})") + if end is not None: + raise ValueError(f"SomeOf requires 'end' parameter to be None (end set to {end}") + + if len(self.transforms) == 0: + return data + + sample_size = self.R.randint(self.min_num_transforms, self.max_num_transforms + 1) + applied_order = self.R.choice(len(self.transforms), sample_size, replace=self.replace, p=self.weights).tolist() + _lazy = self._lazy if lazy is None else lazy + + data = execute_compose( + data, + [self.transforms[a] for a in applied_order], + start=start, + end=end, + map_items=self.map_items, + unpack_items=self.unpack_items, + lazy=_lazy, + overrides=self.overrides, + threading=threading, + log_stats=self.log_stats, + ) + if isinstance(data, monai.data.MetaTensor): + self.push_transform(data, extra_info={"applied_order": applied_order}) + elif isinstance(data, Mapping): + for key in data: # dictionary not change size during iteration + if isinstance(data[key], monai.data.MetaTensor) or self.trace_key(key) in data: + self.push_transform(data, key, extra_info={"applied_order": applied_order}) + + return data + + # From RandomOrder + def inverse(self, data): + if len(self.transforms) == 0: + return data + + applied_order = None + if isinstance(data, monai.data.MetaTensor): + applied_order = self.pop_transform(data)[TraceKeys.EXTRA_INFO]["applied_order"] + elif isinstance(data, Mapping): + for key in data: + if isinstance(data[key], monai.data.MetaTensor) or self.trace_key(key) in data: + applied_order = self.pop_transform(data, key)[TraceKeys.EXTRA_INFO]["applied_order"] + else: + raise RuntimeError( + f"Inverse only implemented for Mapping (dictionary) or MetaTensor data, got type {type(data)}." + ) + if applied_order is None: + # no invertible transforms have been applied + return data + + # loop backwards over transforms + for o in reversed(applied_order): + if isinstance(self.transforms[o], InvertibleTransform): + data = apply_transform( + self.transforms[o].inverse, data, self.map_items, self.unpack_items, log_stats=self.log_stats + ) + + return data diff --git a/source_code/SegMamba/monai/transforms/croppad/dictionary.py b/source_code/SegMamba/monai/transforms/croppad/dictionary.py new file mode 100644 index 0000000000000000000000000000000000000000..be9441dc4a8fb1dc9824fc7f363ca8f4e7c37cce --- /dev/null +++ b/source_code/SegMamba/monai/transforms/croppad/dictionary.py @@ -0,0 +1,1267 @@ +# Copyright (c) MONAI Consortium +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +""" +A collection of dictionary-based wrappers around the "vanilla" transforms for crop and pad operations +defined in :py:class:`monai.transforms.croppad.array`. + +Class names are ended with 'd' to denote dictionary-based transforms. +""" + +from __future__ import annotations + +from collections.abc import Callable, Hashable, Mapping, Sequence +from copy import deepcopy +from typing import Any + +import numpy as np +import torch + +from monai.config import IndexSelection, KeysCollection, SequenceStr +from monai.config.type_definitions import NdarrayOrTensor +from monai.data.meta_tensor import MetaTensor +from monai.transforms.croppad.array import ( + BorderPad, + BoundingRect, + CenterScaleCrop, + CenterSpatialCrop, + Crop, + CropForeground, + DivisiblePad, + Pad, + RandCropByLabelClasses, + RandCropByPosNegLabel, + RandScaleCrop, + RandSpatialCrop, + RandSpatialCropSamples, + RandWeightedCrop, + ResizeWithPadOrCrop, + SpatialCrop, + SpatialPad, +) +from monai.transforms.inverse import InvertibleTransform +from monai.transforms.traits import LazyTrait, MultiSampleTrait +from monai.transforms.transform import LazyTransform, MapTransform, Randomizable +from monai.transforms.utils import is_positive +from monai.utils import MAX_SEED, Method, PytorchPadMode, deprecated_arg_default, ensure_tuple_rep + +__all__ = [ + "Padd", + "SpatialPadd", + "BorderPadd", + "DivisiblePadd", + "Cropd", + "RandCropd", + "SpatialCropd", + "CenterSpatialCropd", + "CenterScaleCropd", + "RandScaleCropd", + "RandSpatialCropd", + "RandSpatialCropSamplesd", + "CropForegroundd", + "RandWeightedCropd", + "RandCropByPosNegLabeld", + "ResizeWithPadOrCropd", + "BoundingRectd", + "RandCropByLabelClassesd", + "PadD", + "PadDict", + "SpatialPadD", + "SpatialPadDict", + "BorderPadD", + "BorderPadDict", + "DivisiblePadD", + "DivisiblePadDict", + "CropD", + "CropDict", + "RandCropD", + "RandCropDict", + "SpatialCropD", + "SpatialCropDict", + "CenterSpatialCropD", + "CenterSpatialCropDict", + "CenterScaleCropD", + "CenterScaleCropDict", + "RandScaleCropD", + "RandScaleCropDict", + "RandSpatialCropD", + "RandSpatialCropDict", + "RandSpatialCropSamplesD", + "RandSpatialCropSamplesDict", + "CropForegroundD", + "CropForegroundDict", + "RandWeightedCropD", + "RandWeightedCropDict", + "RandCropByPosNegLabelD", + "RandCropByPosNegLabelDict", + "ResizeWithPadOrCropD", + "ResizeWithPadOrCropDict", + "BoundingRectD", + "BoundingRectDict", + "RandCropByLabelClassesD", + "RandCropByLabelClassesDict", +] + + +class Padd(MapTransform, InvertibleTransform, LazyTransform): + """ + Dictionary-based wrapper of :py:class:`monai.transforms.Pad`. + + This transform is capable of lazy execution. See the :ref:`Lazy Resampling topic` + for more information. + """ + + backend = Pad.backend + + def __init__( + self, + keys: KeysCollection, + padder: Pad, + mode: SequenceStr = PytorchPadMode.CONSTANT, + allow_missing_keys: bool = False, + lazy: bool = False, + ) -> None: + """ + Args: + keys: keys of the corresponding items to be transformed. + See also: :py:class:`monai.transforms.compose.MapTransform` + padder: pad transform for the input image. + mode: available modes for numpy array:{``"constant"``, ``"edge"``, ``"linear_ramp"``, ``"maximum"``, + ``"mean"``, ``"median"``, ``"minimum"``, ``"reflect"``, ``"symmetric"``, ``"wrap"``, ``"empty"``} + available modes for PyTorch Tensor: {``"constant"``, ``"reflect"``, ``"replicate"``, ``"circular"``}. + One of the listed string values or a user supplied function. Defaults to ``"constant"``. + See also: https://numpy.org/doc/1.18/reference/generated/numpy.pad.html + https://pytorch.org/docs/stable/generated/torch.nn.functional.pad.html + It also can be a sequence of string, each element corresponds to a key in ``keys``. + allow_missing_keys: don't raise exception if key is missing. + lazy: a flag to indicate whether this transform should execute lazily or not. Defaults to False. + """ + MapTransform.__init__(self, keys, allow_missing_keys) + LazyTransform.__init__(self, lazy) + if lazy is True and not isinstance(padder, LazyTrait): + raise ValueError("'padder' must inherit LazyTrait if lazy is True " f"'padder' is of type({type(padder)})") + self.padder = padder + self.mode = ensure_tuple_rep(mode, len(self.keys)) + + @LazyTransform.lazy.setter # type: ignore + def lazy(self, value: bool) -> None: + self._lazy = value + if isinstance(self.padder, LazyTransform): + self.padder.lazy = value + + def __call__(self, data: Mapping[Hashable, torch.Tensor], lazy: bool | None = None) -> dict[Hashable, torch.Tensor]: + d = dict(data) + lazy_ = self.lazy if lazy is None else lazy + if lazy_ is True and not isinstance(self.padder, LazyTrait): + raise ValueError( + "'self.padder' must inherit LazyTrait if lazy is True " f"'self.padder' is of type({type(self.padder)}" + ) + for key, m in self.key_iterator(d, self.mode): + if isinstance(self.padder, LazyTrait): + d[key] = self.padder(d[key], mode=m, lazy=lazy_) + else: + d[key] = self.padder(d[key], mode=m) + + return d + + def inverse(self, data: Mapping[Hashable, MetaTensor]) -> dict[Hashable, MetaTensor]: + d = dict(data) + for key in self.key_iterator(d): + d[key] = self.padder.inverse(d[key]) + return d + + +class SpatialPadd(Padd): + """ + Dictionary-based wrapper of :py:class:`monai.transforms.SpatialPad`. + Performs padding to the data, symmetric for all sides or all on one side for each dimension. + + This transform is capable of lazy execution. See the :ref:`Lazy Resampling topic` + for more information. + """ + + def __init__( + self, + keys: KeysCollection, + spatial_size: Sequence[int] | int, + method: str = Method.SYMMETRIC, + mode: SequenceStr = PytorchPadMode.CONSTANT, + allow_missing_keys: bool = False, + lazy: bool = False, + **kwargs, + ) -> None: + """ + Args: + keys: keys of the corresponding items to be transformed. + See also: :py:class:`monai.transforms.compose.MapTransform` + spatial_size: the spatial size of output data after padding, if a dimension of the input + data size is larger than the pad size, will not pad that dimension. + If its components have non-positive values, the corresponding size of input image will be used. + for example: if the spatial size of input data is [30, 30, 30] and `spatial_size=[32, 25, -1]`, + the spatial size of output data will be [32, 30, 30]. + method: {``"symmetric"``, ``"end"``} + Pad image symmetrically on every side or only pad at the end sides. Defaults to ``"symmetric"``. + mode: available modes for numpy array:{``"constant"``, ``"edge"``, ``"linear_ramp"``, ``"maximum"``, + ``"mean"``, ``"median"``, ``"minimum"``, ``"reflect"``, ``"symmetric"``, ``"wrap"``, ``"empty"``} + available modes for PyTorch Tensor: {``"constant"``, ``"reflect"``, ``"replicate"``, ``"circular"``}. + One of the listed string values or a user supplied function. Defaults to ``"constant"``. + See also: https://numpy.org/doc/1.18/reference/generated/numpy.pad.html + https://pytorch.org/docs/stable/generated/torch.nn.functional.pad.html + It also can be a sequence of string, each element corresponds to a key in ``keys``. + allow_missing_keys: don't raise exception if key is missing. + lazy: a flag to indicate whether this transform should execute lazily or not. Defaults to False. + kwargs: other arguments for the `np.pad` or `torch.pad` function. + note that `np.pad` treats channel dimension as the first dimension. + + """ + padder = SpatialPad(spatial_size, method, lazy=lazy, **kwargs) + Padd.__init__(self, keys, padder=padder, mode=mode, allow_missing_keys=allow_missing_keys, lazy=lazy) + + +class BorderPadd(Padd): + """ + Pad the input data by adding specified borders to every dimension. + Dictionary-based wrapper of :py:class:`monai.transforms.BorderPad`. + + This transform is capable of lazy execution. See the :ref:`Lazy Resampling topic` + for more information. + """ + + backend = BorderPad.backend + + def __init__( + self, + keys: KeysCollection, + spatial_border: Sequence[int] | int, + mode: SequenceStr = PytorchPadMode.CONSTANT, + allow_missing_keys: bool = False, + lazy: bool = False, + **kwargs, + ) -> None: + """ + Args: + keys: keys of the corresponding items to be transformed. + See also: :py:class:`monai.transforms.compose.MapTransform` + spatial_border: specified size for every spatial border. it can be 3 shapes: + + - single int number, pad all the borders with the same size. + - length equals the length of image shape, pad every spatial dimension separately. + for example, image shape(CHW) is [1, 4, 4], spatial_border is [2, 1], + pad every border of H dim with 2, pad every border of W dim with 1, result shape is [1, 8, 6]. + - length equals 2 x (length of image shape), pad every border of every dimension separately. + for example, image shape(CHW) is [1, 4, 4], spatial_border is [1, 2, 3, 4], pad top of H dim with 1, + pad bottom of H dim with 2, pad left of W dim with 3, pad right of W dim with 4. + the result shape is [1, 7, 11]. + + mode: available modes for numpy array:{``"constant"``, ``"edge"``, ``"linear_ramp"``, ``"maximum"``, + ``"mean"``, ``"median"``, ``"minimum"``, ``"reflect"``, ``"symmetric"``, ``"wrap"``, ``"empty"``} + available modes for PyTorch Tensor: {``"constant"``, ``"reflect"``, ``"replicate"``, ``"circular"``}. + One of the listed string values or a user supplied function. Defaults to ``"constant"``. + See also: https://numpy.org/doc/1.18/reference/generated/numpy.pad.html + https://pytorch.org/docs/stable/generated/torch.nn.functional.pad.html + It also can be a sequence of string, each element corresponds to a key in ``keys``. + allow_missing_keys: don't raise exception if key is missing. + lazy: a flag to indicate whether this transform should execute lazily or not. Defaults to False. + kwargs: other arguments for the `np.pad` or `torch.pad` function. + note that `np.pad` treats channel dimension as the first dimension. + + """ + padder = BorderPad(spatial_border=spatial_border, lazy=lazy, **kwargs) + Padd.__init__(self, keys, padder=padder, mode=mode, allow_missing_keys=allow_missing_keys, lazy=lazy) + + +class DivisiblePadd(Padd): + """ + Pad the input data, so that the spatial sizes are divisible by `k`. + Dictionary-based wrapper of :py:class:`monai.transforms.DivisiblePad`. + + This transform is capable of lazy execution. See the :ref:`Lazy Resampling topic` + for more information. + """ + + backend = DivisiblePad.backend + + def __init__( + self, + keys: KeysCollection, + k: Sequence[int] | int, + mode: SequenceStr = PytorchPadMode.CONSTANT, + method: str = Method.SYMMETRIC, + allow_missing_keys: bool = False, + lazy: bool = False, + **kwargs, + ) -> None: + """ + Args: + keys: keys of the corresponding items to be transformed. + See also: :py:class:`monai.transforms.compose.MapTransform` + k: the target k for each spatial dimension. + if `k` is negative or 0, the original size is preserved. + if `k` is an int, the same `k` be applied to all the input spatial dimensions. + mode: available modes for numpy array:{``"constant"``, ``"edge"``, ``"linear_ramp"``, ``"maximum"``, + ``"mean"``, ``"median"``, ``"minimum"``, ``"reflect"``, ``"symmetric"``, ``"wrap"``, ``"empty"``} + available modes for PyTorch Tensor: {``"constant"``, ``"reflect"``, ``"replicate"``, ``"circular"``}. + One of the listed string values or a user supplied function. Defaults to ``"constant"``. + See also: https://numpy.org/doc/1.18/reference/generated/numpy.pad.html + https://pytorch.org/docs/stable/generated/torch.nn.functional.pad.html + It also can be a sequence of string, each element corresponds to a key in ``keys``. + method: {``"symmetric"``, ``"end"``} + Pad image symmetrically on every side or only pad at the end sides. Defaults to ``"symmetric"``. + allow_missing_keys: don't raise exception if key is missing. + lazy: a flag to indicate whether this transform should execute lazily or not. Defaults to False. + kwargs: other arguments for the `np.pad` or `torch.pad` function. + note that `np.pad` treats channel dimension as the first dimension. + + See also :py:class:`monai.transforms.SpatialPad` + + """ + padder = DivisiblePad(k=k, method=method, lazy=lazy, **kwargs) + Padd.__init__(self, keys, padder=padder, mode=mode, allow_missing_keys=allow_missing_keys, lazy=lazy) + + +class Cropd(MapTransform, InvertibleTransform, LazyTransform): + """ + Dictionary-based wrapper of abstract class :py:class:`monai.transforms.Crop`. + + This transform is capable of lazy execution. See the :ref:`Lazy Resampling topic` + for more information. + + Args: + keys: keys of the corresponding items to be transformed. + See also: :py:class:`monai.transforms.compose.MapTransform` + cropper: crop transform for the input image. + allow_missing_keys: don't raise exception if key is missing. + lazy: a flag to indicate whether this transform should execute lazily or not. Defaults to False. + """ + + backend = Crop.backend + + def __init__(self, keys: KeysCollection, cropper: Crop, allow_missing_keys: bool = False, lazy: bool = False): + MapTransform.__init__(self, keys, allow_missing_keys) + LazyTransform.__init__(self, lazy) + self.cropper = cropper + + @LazyTransform.lazy.setter # type: ignore + def lazy(self, value: bool) -> None: + self._lazy = value + if isinstance(self.cropper, LazyTransform): + self.cropper.lazy = value + + def __call__(self, data: Mapping[Hashable, torch.Tensor], lazy: bool | None = None) -> dict[Hashable, torch.Tensor]: + d = dict(data) + lazy_ = self.lazy if lazy is None else lazy + for key in self.key_iterator(d): + d[key] = self.cropper(d[key], lazy=lazy_) # type: ignore + return d + + def inverse(self, data: Mapping[Hashable, MetaTensor]) -> dict[Hashable, MetaTensor]: + d = dict(data) + for key in self.key_iterator(d): + d[key] = self.cropper.inverse(d[key]) + return d + + +class RandCropd(Cropd, Randomizable): + """ + Base class for random crop transform. + + This transform is capable of lazy execution. See the :ref:`Lazy Resampling topic` + for more information. + + Args: + keys: keys of the corresponding items to be transformed. + See also: :py:class:`monai.transforms.compose.MapTransform` + cropper: random crop transform for the input image. + allow_missing_keys: don't raise exception if key is missing. + lazy: a flag to indicate whether this transform should execute lazily or not. Defaults to False. + """ + + backend = Crop.backend + + def __init__(self, keys: KeysCollection, cropper: Crop, allow_missing_keys: bool = False, lazy: bool = False): + super().__init__(keys, cropper=cropper, allow_missing_keys=allow_missing_keys, lazy=lazy) + + def set_random_state(self, seed: int | None = None, state: np.random.RandomState | None = None) -> RandCropd: + super().set_random_state(seed, state) + if isinstance(self.cropper, Randomizable): + self.cropper.set_random_state(seed, state) + return self + + def randomize(self, img_size: Sequence[int]) -> None: + if isinstance(self.cropper, Randomizable): + self.cropper.randomize(img_size) + + def __call__(self, data: Mapping[Hashable, torch.Tensor], lazy: bool | None = None) -> dict[Hashable, torch.Tensor]: + d = dict(data) + # the first key must exist to execute random operations + first_item = d[self.first_key(d)] + self.randomize(first_item.peek_pending_shape() if isinstance(first_item, MetaTensor) else first_item.shape[1:]) + lazy_ = self.lazy if lazy is None else lazy + if lazy_ is True and not isinstance(self.cropper, LazyTrait): + raise ValueError( + "'self.cropper' must inherit LazyTrait if lazy is True " + f"'self.cropper' is of type({type(self.cropper)}" + ) + for key in self.key_iterator(d): + kwargs = {"randomize": False} if isinstance(self.cropper, Randomizable) else {} + if isinstance(self.cropper, LazyTrait): + kwargs["lazy"] = lazy_ + d[key] = self.cropper(d[key], **kwargs) # type: ignore + return d + + +class SpatialCropd(Cropd): + """ + Dictionary-based wrapper of :py:class:`monai.transforms.SpatialCrop`. + General purpose cropper to produce sub-volume region of interest (ROI). + If a dimension of the expected ROI size is larger than the input image size, will not crop that dimension. + So the cropped result may be smaller than the expected ROI, and the cropped results of several images may + not have exactly the same shape. + It can support to crop ND spatial (channel-first) data. + + The cropped region can be parameterised in various ways: + - a list of slices for each spatial dimension (allows for use of -ve indexing and `None`) + - a spatial center and size + - the start and end coordinates of the ROI + + This transform is capable of lazy execution. See the :ref:`Lazy Resampling topic` + for more information. + """ + + def __init__( + self, + keys: KeysCollection, + roi_center: Sequence[int] | None = None, + roi_size: Sequence[int] | None = None, + roi_start: Sequence[int] | None = None, + roi_end: Sequence[int] | None = None, + roi_slices: Sequence[slice] | None = None, + allow_missing_keys: bool = False, + lazy: bool = False, + ) -> None: + """ + Args: + keys: keys of the corresponding items to be transformed. + See also: :py:class:`monai.transforms.compose.MapTransform` + roi_center: voxel coordinates for center of the crop ROI. + roi_size: size of the crop ROI, if a dimension of ROI size is larger than image size, + will not crop that dimension of the image. + roi_start: voxel coordinates for start of the crop ROI. + roi_end: voxel coordinates for end of the crop ROI, if a coordinate is out of image, + use the end coordinate of image. + roi_slices: list of slices for each of the spatial dimensions. + allow_missing_keys: don't raise exception if key is missing. + lazy: a flag to indicate whether this transform should execute lazily or not. Defaults to False. + """ + cropper = SpatialCrop(roi_center, roi_size, roi_start, roi_end, roi_slices, lazy=lazy) + super().__init__(keys, cropper=cropper, allow_missing_keys=allow_missing_keys, lazy=lazy) + + +class CenterSpatialCropd(Cropd): + """ + Dictionary-based wrapper of :py:class:`monai.transforms.CenterSpatialCrop`. + If a dimension of the expected ROI size is larger than the input image size, will not crop that dimension. + So the cropped result may be smaller than the expected ROI, and the cropped results of several images may + not have exactly the same shape. + + This transform is capable of lazy execution. See the :ref:`Lazy Resampling topic` + for more information. + + Args: + keys: keys of the corresponding items to be transformed. + See also: monai.transforms.MapTransform + roi_size: the size of the crop region e.g. [224,224,128] + if a dimension of ROI size is larger than image size, will not crop that dimension of the image. + If its components have non-positive values, the corresponding size of input image will be used. + for example: if the spatial size of input data is [40, 40, 40] and `roi_size=[32, 64, -1]`, + the spatial size of output data will be [32, 40, 40]. + allow_missing_keys: don't raise exception if key is missing. + lazy: a flag to indicate whether this transform should execute lazily or not. Defaults to False. + """ + + def __init__( + self, keys: KeysCollection, roi_size: Sequence[int] | int, allow_missing_keys: bool = False, lazy: bool = False + ) -> None: + cropper = CenterSpatialCrop(roi_size, lazy=lazy) + super().__init__(keys, cropper=cropper, allow_missing_keys=allow_missing_keys, lazy=lazy) + + +class CenterScaleCropd(Cropd): + """ + Dictionary-based wrapper of :py:class:`monai.transforms.CenterScaleCrop`. + Note: as using the same scaled ROI to crop, all the input data specified by `keys` should have + the same spatial shape. + + This transform is capable of lazy execution. See the :ref:`Lazy Resampling topic` + for more information. + + Args: + keys: keys of the corresponding items to be transformed. + See also: monai.transforms.MapTransform + roi_scale: specifies the expected scale of image size to crop. e.g. [0.3, 0.4, 0.5] or a number for all dims. + If its components have non-positive values, will use `1.0` instead, which means the input image size. + allow_missing_keys: don't raise exception if key is missing. + lazy: a flag to indicate whether this transform should execute lazily or not. Defaults to False. + """ + + def __init__( + self, + keys: KeysCollection, + roi_scale: Sequence[float] | float, + allow_missing_keys: bool = False, + lazy: bool = False, + ) -> None: + cropper = CenterScaleCrop(roi_scale, lazy=lazy) + super().__init__(keys, cropper=cropper, allow_missing_keys=allow_missing_keys, lazy=lazy) + + +class RandSpatialCropd(RandCropd): + """ + Dictionary-based version :py:class:`monai.transforms.RandSpatialCrop`. + Crop image with random size or specific size ROI. It can crop at a random position as + center or at the image center. And allows to set the minimum and maximum size to limit the randomly + generated ROI. Suppose all the expected fields specified by `keys` have same shape. + + Note: even `random_size=False`, if a dimension of the expected ROI size is larger than the input image size, + will not crop that dimension. So the cropped result may be smaller than the expected ROI, and the cropped + results of several images may not have exactly the same shape. + + This transform is capable of lazy execution. See the :ref:`Lazy Resampling topic` + for more information. + + Args: + keys: keys of the corresponding items to be transformed. + See also: monai.transforms.MapTransform + roi_size: if `random_size` is True, it specifies the minimum crop region. + if `random_size` is False, it specifies the expected ROI size to crop. e.g. [224, 224, 128] + if a dimension of ROI size is larger than image size, will not crop that dimension of the image. + If its components have non-positive values, the corresponding size of input image will be used. + for example: if the spatial size of input data is [40, 40, 40] and `roi_size=[32, 64, -1]`, + the spatial size of output data will be [32, 40, 40]. + max_roi_size: if `random_size` is True and `roi_size` specifies the min crop region size, `max_roi_size` + can specify the max crop region size. if None, defaults to the input image size. + if its components have non-positive values, the corresponding size of input image will be used. + random_center: crop at random position as center or the image center. + random_size: crop with random size or specific size ROI. + if True, the actual size is sampled from: + `randint(roi_scale * image spatial size, max_roi_scale * image spatial size + 1)`. + allow_missing_keys: don't raise exception if key is missing. + lazy: a flag to indicate whether this transform should execute lazily or not. Defaults to False. + """ + + def __init__( + self, + keys: KeysCollection, + roi_size: Sequence[int] | int, + max_roi_size: Sequence[int] | int | None = None, + random_center: bool = True, + random_size: bool = False, + allow_missing_keys: bool = False, + lazy: bool = False, + ) -> None: + cropper = RandSpatialCrop(roi_size, max_roi_size, random_center, random_size, lazy=lazy) + super().__init__(keys, cropper=cropper, allow_missing_keys=allow_missing_keys, lazy=lazy) + + +class RandScaleCropd(RandCropd): + """ + Dictionary-based version :py:class:`monai.transforms.RandScaleCrop`. + Crop image with random size or specific size ROI. + It can crop at a random position as center or at the image center. + And allows to set the minimum and maximum scale of image size to limit the randomly generated ROI. + Suppose all the expected fields specified by `keys` have same shape. + + This transform is capable of lazy execution. See the :ref:`Lazy Resampling topic` + for more information. + + Args: + keys: keys of the corresponding items to be transformed. + See also: monai.transforms.MapTransform + roi_scale: if `random_size` is True, it specifies the minimum crop size: `roi_scale * image spatial size`. + if `random_size` is False, it specifies the expected scale of image size to crop. e.g. [0.3, 0.4, 0.5]. + If its components have non-positive values, will use `1.0` instead, which means the input image size. + max_roi_scale: if `random_size` is True and `roi_scale` specifies the min crop region size, `max_roi_scale` + can specify the max crop region size: `max_roi_scale * image spatial size`. + if None, defaults to the input image size. if its components have non-positive values, + will use `1.0` instead, which means the input image size. + random_center: crop at random position as center or the image center. + random_size: crop with random size or specified size ROI by `roi_scale * image spatial size`. + if True, the actual size is sampled from: + `randint(roi_scale * image spatial size, max_roi_scale * image spatial size + 1)`. + allow_missing_keys: don't raise exception if key is missing. + lazy: a flag to indicate whether this transform should execute lazily or not. Defaults to False. + """ + + def __init__( + self, + keys: KeysCollection, + roi_scale: Sequence[float] | float, + max_roi_scale: Sequence[float] | float | None = None, + random_center: bool = True, + random_size: bool = False, + allow_missing_keys: bool = False, + lazy: bool = False, + ) -> None: + cropper = RandScaleCrop(roi_scale, max_roi_scale, random_center, random_size, lazy=lazy) + super().__init__(keys, cropper=cropper, allow_missing_keys=allow_missing_keys, lazy=lazy) + + +class RandSpatialCropSamplesd(Randomizable, MapTransform, LazyTransform, MultiSampleTrait): + """ + Dictionary-based version :py:class:`monai.transforms.RandSpatialCropSamples`. + Crop image with random size or specific size ROI to generate a list of N samples. + It can crop at a random position as center or at the image center. And allows to set + the minimum size to limit the randomly generated ROI. Suppose all the expected fields + specified by `keys` have same shape, and add `patch_index` to the corresponding metadata. + It will return a list of dictionaries for all the cropped images. + + Note: even `random_size=False`, if a dimension of the expected ROI size is larger than the input image size, + will not crop that dimension. So the cropped result may be smaller than the expected ROI, and the cropped + results of several images may not have exactly the same shape. + + This transform is capable of lazy execution. See the :ref:`Lazy Resampling topic` + for more information. + + Args: + keys: keys of the corresponding items to be transformed. + See also: monai.transforms.MapTransform + roi_size: if `random_size` is True, it specifies the minimum crop region. + if `random_size` is False, it specifies the expected ROI size to crop. e.g. [224, 224, 128] + if a dimension of ROI size is larger than image size, will not crop that dimension of the image. + If its components have non-positive values, the corresponding size of input image will be used. + for example: if the spatial size of input data is [40, 40, 40] and `roi_size=[32, 64, -1]`, + the spatial size of output data will be [32, 40, 40]. + num_samples: number of samples (crop regions) to take in the returned list. + max_roi_size: if `random_size` is True and `roi_size` specifies the min crop region size, `max_roi_size` + can specify the max crop region size. if None, defaults to the input image size. + if its components have non-positive values, the corresponding size of input image will be used. + random_center: crop at random position as center or the image center. + random_size: crop with random size or specific size ROI. + The actual size is sampled from `randint(roi_size, img_size)`. + allow_missing_keys: don't raise exception if key is missing. + lazy: a flag to indicate whether this transform should execute lazily or not. Defaults to False. + + Raises: + ValueError: When ``num_samples`` is nonpositive. + + """ + + backend = RandSpatialCropSamples.backend + + def __init__( + self, + keys: KeysCollection, + roi_size: Sequence[int] | int, + num_samples: int, + max_roi_size: Sequence[int] | int | None = None, + random_center: bool = True, + random_size: bool = False, + allow_missing_keys: bool = False, + lazy: bool = False, + ) -> None: + MapTransform.__init__(self, keys, allow_missing_keys) + LazyTransform.__init__(self, lazy) + self.cropper = RandSpatialCropSamples( + roi_size, num_samples, max_roi_size, random_center, random_size, lazy=lazy + ) + + @LazyTransform.lazy.setter # type: ignore + def lazy(self, value: bool) -> None: + self._lazy = value + self.cropper.lazy = value + + def randomize(self, data: Any | None = None) -> None: + self.sub_seed = self.R.randint(MAX_SEED, dtype="uint32") + + def __call__( + self, data: Mapping[Hashable, torch.Tensor], lazy: bool | None = None + ) -> list[dict[Hashable, torch.Tensor]]: + ret: list[dict[Hashable, torch.Tensor]] = [dict(data) for _ in range(self.cropper.num_samples)] + # deep copy all the unmodified data + for i in range(self.cropper.num_samples): + for key in set(data.keys()).difference(set(self.keys)): + ret[i][key] = deepcopy(data[key]) + + # for each key we reset the random state to ensure crops are the same + self.randomize() + + lazy_ = self.lazy if lazy is None else lazy + for key in self.key_iterator(dict(data)): + self.cropper.set_random_state(seed=self.sub_seed) + for i, im in enumerate(self.cropper(data[key], lazy=lazy_)): + ret[i][key] = im + return ret + + +class CropForegroundd(Cropd): + """ + Dictionary-based version :py:class:`monai.transforms.CropForeground`. + Crop only the foreground object of the expected images. + The typical usage is to help training and evaluation if the valid part is small in the whole medical image. + The valid part can be determined by any field in the data with `source_key`, for example: + - Select values > 0 in image field as the foreground and crop on all fields specified by `keys`. + - Select label = 3 in label field as the foreground to crop on all fields specified by `keys`. + - Select label > 0 in the third channel of a One-Hot label field as the foreground to crop all `keys` fields. + Users can define arbitrary function to select expected foreground from the whole source image or specified + channels. And it can also add margin to every dim of the bounding box of foreground object. + + This transform is capable of lazy execution. See the :ref:`Lazy Resampling topic` + for more information. + """ + + @deprecated_arg_default("allow_smaller", old_default=True, new_default=False, since="1.2", replaced="1.5") + def __init__( + self, + keys: KeysCollection, + source_key: str, + select_fn: Callable = is_positive, + channel_indices: IndexSelection | None = None, + margin: Sequence[int] | int = 0, + allow_smaller: bool = True, + k_divisible: Sequence[int] | int = 1, + mode: SequenceStr = PytorchPadMode.CONSTANT, + start_coord_key: str | None = "foreground_start_coord", + end_coord_key: str | None = "foreground_end_coord", + allow_missing_keys: bool = False, + lazy: bool = False, + **pad_kwargs, + ) -> None: + """ + Args: + keys: keys of the corresponding items to be transformed. + See also: :py:class:`monai.transforms.compose.MapTransform` + source_key: data source to generate the bounding box of foreground, can be image or label, etc. + select_fn: function to select expected foreground, default is to select values > 0. + channel_indices: if defined, select foreground only on the specified channels + of image. if None, select foreground on the whole image. + margin: add margin value to spatial dims of the bounding box, if only 1 value provided, use it for all dims. + allow_smaller: when computing box size with `margin`, whether to allow the image edges to be smaller than the + final box edges. If `False`, part of a padded output box might be outside of the original image, if `True`, + the image edges will be used as the box edges. Default to `True`. + k_divisible: make each spatial dimension to be divisible by k, default to 1. + if `k_divisible` is an int, the same `k` be applied to all the input spatial dimensions. + mode: available modes for numpy array:{``"constant"``, ``"edge"``, ``"linear_ramp"``, ``"maximum"``, + ``"mean"``, ``"median"``, ``"minimum"``, ``"reflect"``, ``"symmetric"``, ``"wrap"``, ``"empty"``} + available modes for PyTorch Tensor: {``"constant"``, ``"reflect"``, ``"replicate"``, ``"circular"``}. + One of the listed string values or a user supplied function. Defaults to ``"constant"``. + See also: https://numpy.org/doc/1.18/reference/generated/numpy.pad.html + https://pytorch.org/docs/stable/generated/torch.nn.functional.pad.html + it also can be a sequence of string, each element corresponds to a key in ``keys``. + start_coord_key: key to record the start coordinate of spatial bounding box for foreground. + end_coord_key: key to record the end coordinate of spatial bounding box for foreground. + allow_missing_keys: don't raise exception if key is missing. + lazy: a flag to indicate whether this transform should execute lazily or not. Defaults to False. + pad_kwargs: other arguments for the `np.pad` or `torch.pad` function. + note that `np.pad` treats channel dimension as the first dimension. + + """ + self.source_key = source_key + self.start_coord_key = start_coord_key + self.end_coord_key = end_coord_key + cropper = CropForeground( + select_fn=select_fn, + channel_indices=channel_indices, + margin=margin, + allow_smaller=allow_smaller, + k_divisible=k_divisible, + lazy=lazy, + **pad_kwargs, + ) + super().__init__(keys, cropper=cropper, allow_missing_keys=allow_missing_keys, lazy=lazy) + self.mode = ensure_tuple_rep(mode, len(self.keys)) + + @LazyTransform.lazy.setter # type: ignore + def lazy(self, value: bool) -> None: + self._lazy = value + self.cropper.lazy = value + + @property + def requires_current_data(self): + return True + + def __call__(self, data: Mapping[Hashable, torch.Tensor], lazy: bool | None = None) -> dict[Hashable, torch.Tensor]: + d = dict(data) + self.cropper: CropForeground + box_start, box_end = self.cropper.compute_bounding_box(img=d[self.source_key]) + if self.start_coord_key is not None: + d[self.start_coord_key] = box_start # type: ignore + if self.end_coord_key is not None: + d[self.end_coord_key] = box_end # type: ignore + + lazy_ = self.lazy if lazy is None else lazy + for key, m in self.key_iterator(d, self.mode): + d[key] = self.cropper.crop_pad(img=d[key], box_start=box_start, box_end=box_end, mode=m, lazy=lazy_) + return d + + +class RandWeightedCropd(Randomizable, MapTransform, LazyTransform, MultiSampleTrait): + """ + Samples a list of `num_samples` image patches according to the provided `weight_map`. + + This transform is capable of lazy execution. See the :ref:`Lazy Resampling topic` + for more information. + + Args: + keys: keys of the corresponding items to be transformed. + See also: :py:class:`monai.transforms.compose.MapTransform` + w_key: key for the weight map. The corresponding value will be used as the sampling weights, + it should be a single-channel array in size, for example, `(1, spatial_dim_0, spatial_dim_1, ...)` + spatial_size: the spatial size of the image patch e.g. [224, 224, 128]. + If its components have non-positive values, the corresponding size of `img` will be used. + num_samples: number of samples (image patches) to take in the returned list. + allow_missing_keys: don't raise exception if key is missing. + lazy: a flag to indicate whether this transform should execute lazily or not. Defaults to False. + + See Also: + :py:class:`monai.transforms.RandWeightedCrop` + """ + + backend = SpatialCrop.backend + + def __init__( + self, + keys: KeysCollection, + w_key: str, + spatial_size: Sequence[int] | int, + num_samples: int = 1, + allow_missing_keys: bool = False, + lazy: bool = False, + ): + MapTransform.__init__(self, keys, allow_missing_keys) + LazyTransform.__init__(self, lazy) + self.w_key = w_key + self.cropper = RandWeightedCrop(spatial_size, num_samples, lazy=lazy) + + def set_random_state( + self, seed: int | None = None, state: np.random.RandomState | None = None + ) -> RandWeightedCropd: + super().set_random_state(seed, state) + self.cropper.set_random_state(seed, state) + return self + + def randomize(self, weight_map: NdarrayOrTensor) -> None: + self.cropper.randomize(weight_map) + + @LazyTransform.lazy.setter # type: ignore + def lazy(self, value: bool) -> None: + self._lazy = value + self.cropper.lazy = value + + def __call__( + self, data: Mapping[Hashable, torch.Tensor], lazy: bool | None = None + ) -> list[dict[Hashable, torch.Tensor]]: + # output starts as empty list of dictionaries + ret: list = [dict(data) for _ in range(self.cropper.num_samples)] + # deep copy all the unmodified data + for i in range(self.cropper.num_samples): + for key in set(data.keys()).difference(set(self.keys)): + ret[i][key] = deepcopy(data[key]) + + self.randomize(weight_map=data[self.w_key]) + lazy_ = self.lazy if lazy is None else lazy + for key in self.key_iterator(data): + for i, im in enumerate(self.cropper(data[key], randomize=False, lazy=lazy_)): + ret[i][key] = im + return ret + + +class RandCropByPosNegLabeld(Randomizable, MapTransform, LazyTransform, MultiSampleTrait): + """ + Dictionary-based version :py:class:`monai.transforms.RandCropByPosNegLabel`. + Crop random fixed sized regions with the center being a foreground or background voxel + based on the Pos Neg Ratio. + Suppose all the expected fields specified by `keys` have same shape, + and add `patch_index` to the corresponding metadata. + And will return a list of dictionaries for all the cropped images. + + If a dimension of the expected spatial size is larger than the input image size, + will not crop that dimension. So the cropped result may be smaller than the expected size, + and the cropped results of several images may not have exactly the same shape. + And if the crop ROI is partly out of the image, will automatically adjust the crop center + to ensure the valid crop ROI. + + This transform is capable of lazy execution. See the :ref:`Lazy Resampling topic` + for more information. + + Args: + keys: keys of the corresponding items to be transformed. + See also: :py:class:`monai.transforms.compose.MapTransform` + label_key: name of key for label image, this will be used for finding foreground/background. + spatial_size: the spatial size of the crop region e.g. [224, 224, 128]. + if a dimension of ROI size is larger than image size, will not crop that dimension of the image. + if its components have non-positive values, the corresponding size of `data[label_key]` will be used. + for example: if the spatial size of input data is [40, 40, 40] and `spatial_size=[32, 64, -1]`, + the spatial size of output data will be [32, 40, 40]. + pos: used with `neg` together to calculate the ratio ``pos / (pos + neg)`` for the probability + to pick a foreground voxel as a center rather than a background voxel. + neg: used with `pos` together to calculate the ratio ``pos / (pos + neg)`` for the probability + to pick a foreground voxel as a center rather than a background voxel. + num_samples: number of samples (crop regions) to take in each list. + image_key: if image_key is not None, use ``label == 0 & image > image_threshold`` to select + the negative sample(background) center. so the crop center will only exist on valid image area. + image_threshold: if enabled image_key, use ``image > image_threshold`` to determine + the valid image content area. + fg_indices_key: if provided pre-computed foreground indices of `label`, will ignore above `image_key` and + `image_threshold`, and randomly select crop centers based on them, need to provide `fg_indices_key` + and `bg_indices_key` together, expect to be 1 dim array of spatial indices after flattening. + a typical usage is to call `FgBgToIndicesd` transform first and cache the results. + bg_indices_key: if provided pre-computed background indices of `label`, will ignore above `image_key` and + `image_threshold`, and randomly select crop centers based on them, need to provide `fg_indices_key` + and `bg_indices_key` together, expect to be 1 dim array of spatial indices after flattening. + a typical usage is to call `FgBgToIndicesd` transform first and cache the results. + allow_smaller: if `False`, an exception will be raised if the image is smaller than + the requested ROI in any dimension. If `True`, any smaller dimensions will be set to + match the cropped size (i.e., no cropping in that dimension). + allow_missing_keys: don't raise exception if key is missing. + lazy: a flag to indicate whether this transform should execute lazily or not. Defaults to False. + + Raises: + ValueError: When ``pos`` or ``neg`` are negative. + ValueError: When ``pos=0`` and ``neg=0``. Incompatible values. + + """ + + backend = RandCropByPosNegLabel.backend + + def __init__( + self, + keys: KeysCollection, + label_key: str, + spatial_size: Sequence[int] | int, + pos: float = 1.0, + neg: float = 1.0, + num_samples: int = 1, + image_key: str | None = None, + image_threshold: float = 0.0, + fg_indices_key: str | None = None, + bg_indices_key: str | None = None, + allow_smaller: bool = False, + allow_missing_keys: bool = False, + lazy: bool = False, + ) -> None: + MapTransform.__init__(self, keys, allow_missing_keys) + LazyTransform.__init__(self, lazy) + self.label_key = label_key + self.image_key = image_key + self.fg_indices_key = fg_indices_key + self.bg_indices_key = bg_indices_key + self.cropper = RandCropByPosNegLabel( + spatial_size=spatial_size, + pos=pos, + neg=neg, + num_samples=num_samples, + image_threshold=image_threshold, + allow_smaller=allow_smaller, + lazy=lazy, + ) + + def set_random_state( + self, seed: int | None = None, state: np.random.RandomState | None = None + ) -> RandCropByPosNegLabeld: + super().set_random_state(seed, state) + self.cropper.set_random_state(seed, state) + return self + + def randomize( + self, + label: torch.Tensor | None = None, + fg_indices: NdarrayOrTensor | None = None, + bg_indices: NdarrayOrTensor | None = None, + image: torch.Tensor | None = None, + ) -> None: + self.cropper.randomize(label=label, fg_indices=fg_indices, bg_indices=bg_indices, image=image) + + @LazyTransform.lazy.setter # type: ignore + def lazy(self, value: bool) -> None: + self._lazy = value + self.cropper.lazy = value + + @property + def requires_current_data(self): + return True + + def __call__( + self, data: Mapping[Hashable, torch.Tensor], lazy: bool | None = None + ) -> list[dict[Hashable, torch.Tensor]]: + d = dict(data) + fg_indices = d.pop(self.fg_indices_key, None) + bg_indices = d.pop(self.bg_indices_key, None) + + self.randomize(d.get(self.label_key), fg_indices, bg_indices, d.get(self.image_key)) + + # initialize returned list with shallow copy to preserve key ordering + ret: list = [dict(d) for _ in range(self.cropper.num_samples)] + # deep copy all the unmodified data + for i in range(self.cropper.num_samples): + for key in set(d.keys()).difference(set(self.keys)): + ret[i][key] = deepcopy(d[key]) + + lazy_ = self.lazy if lazy is None else lazy + for key in self.key_iterator(d): + for i, im in enumerate(self.cropper(d[key], randomize=False, lazy=lazy_)): + ret[i][key] = im + return ret + + +class RandCropByLabelClassesd(Randomizable, MapTransform, LazyTransform, MultiSampleTrait): + """ + Dictionary-based version :py:class:`monai.transforms.RandCropByLabelClasses`. + Crop random fixed sized regions with the center being a class based on the specified ratios of every class. + The label data can be One-Hot format array or Argmax data. And will return a list of arrays for all the + cropped images. For example, crop two (3 x 3) arrays from (5 x 5) array with `ratios=[1, 2, 3, 1]`:: + + cropper = RandCropByLabelClassesd( + keys=["image", "label"], + label_key="label", + spatial_size=[3, 3], + ratios=[1, 2, 3, 1], + num_classes=4, + num_samples=2, + ) + data = { + "image": np.array([ + [[0.0, 0.3, 0.4, 0.2, 0.0], + [0.0, 0.1, 0.2, 0.1, 0.4], + [0.0, 0.3, 0.5, 0.2, 0.0], + [0.1, 0.2, 0.1, 0.1, 0.0], + [0.0, 0.1, 0.2, 0.1, 0.0]] + ]), + "label": np.array([ + [[0, 0, 0, 0, 0], + [0, 1, 2, 1, 0], + [0, 1, 3, 0, 0], + [0, 0, 0, 0, 0], + [0, 0, 0, 0, 0]] + ]), + } + result = cropper(data) + + The 2 randomly cropped samples of `label` can be: + [[0, 1, 2], [[0, 0, 0], + [0, 1, 3], [1, 2, 1], + [0, 0, 0]] [1, 3, 0]] + + If a dimension of the expected spatial size is larger than the input image size, + will not crop that dimension. So the cropped result may be smaller than expected size, and the cropped + results of several images may not have exactly same shape. + And if the crop ROI is partly out of the image, will automatically adjust the crop center to ensure the + valid crop ROI. + + This transform is capable of lazy execution. See the :ref:`Lazy Resampling topic` + for more information. + + Args: + keys: keys of the corresponding items to be transformed. + See also: :py:class:`monai.transforms.compose.MapTransform` + label_key: name of key for label image, this will be used for finding indices of every class. + spatial_size: the spatial size of the crop region e.g. [224, 224, 128]. + if a dimension of ROI size is larger than image size, will not crop that dimension of the image. + if its components have non-positive values, the corresponding size of `label` will be used. + for example: if the spatial size of input data is [40, 40, 40] and `spatial_size=[32, 64, -1]`, + the spatial size of output data will be [32, 40, 40]. + ratios: specified ratios of every class in the label to generate crop centers, including background class. + if None, every class will have the same ratio to generate crop centers. + num_classes: number of classes for argmax label, not necessary for One-Hot label. + num_samples: number of samples (crop regions) to take in each list. + image_key: if image_key is not None, only return the indices of every class that are within the valid + region of the image (``image > image_threshold``). + image_threshold: if enabled `image_key`, use ``image > image_threshold`` to + determine the valid image content area and select class indices only in this area. + indices_key: if provided pre-computed indices of every class, will ignore above `image` and + `image_threshold`, and randomly select crop centers based on them, expect to be 1 dim array + of spatial indices after flattening. a typical usage is to call `ClassesToIndices` transform first + and cache the results for better performance. + allow_smaller: if `False`, an exception will be raised if the image is smaller than + the requested ROI in any dimension. If `True`, any smaller dimensions will remain + unchanged. + allow_missing_keys: don't raise exception if key is missing. + warn: if `True` prints a warning if a class is not present in the label. + max_samples_per_class: maximum length of indices in each class to reduce memory consumption. + Default is None, no subsampling. + lazy: a flag to indicate whether this transform should execute lazily or not. Defaults to False. + """ + + backend = RandCropByLabelClasses.backend + + def __init__( + self, + keys: KeysCollection, + label_key: str, + spatial_size: Sequence[int] | int, + ratios: list[float | int] | None = None, + num_classes: int | None = None, + num_samples: int = 1, + image_key: str | None = None, + image_threshold: float = 0.0, + indices_key: str | None = None, + allow_smaller: bool = False, + allow_missing_keys: bool = False, + warn: bool = True, + max_samples_per_class: int | None = None, + lazy: bool = False, + ) -> None: + MapTransform.__init__(self, keys, allow_missing_keys) + LazyTransform.__init__(self, lazy) + self.label_key = label_key + self.image_key = image_key + self.indices_key = indices_key + self.cropper = RandCropByLabelClasses( + spatial_size=spatial_size, + ratios=ratios, + num_classes=num_classes, + num_samples=num_samples, + image_threshold=image_threshold, + allow_smaller=allow_smaller, + warn=warn, + max_samples_per_class=max_samples_per_class, + lazy=lazy, + ) + + def set_random_state( + self, seed: int | None = None, state: np.random.RandomState | None = None + ) -> RandCropByLabelClassesd: + super().set_random_state(seed, state) + self.cropper.set_random_state(seed, state) + return self + + def randomize( + self, label: torch.Tensor, indices: list[NdarrayOrTensor] | None = None, image: torch.Tensor | None = None + ) -> None: + self.cropper.randomize(label=label, indices=indices, image=image) + + @LazyTransform.lazy.setter # type: ignore + def lazy(self, value: bool) -> None: + self._lazy = value + self.cropper.lazy = value + + @property + def requires_current_data(self): + return True + + def __call__(self, data: Mapping[Hashable, Any], lazy: bool | None = None) -> list[dict[Hashable, torch.Tensor]]: + d = dict(data) + self.randomize(d.get(self.label_key), d.pop(self.indices_key, None), d.get(self.image_key)) # type: ignore + + # initialize returned list with shallow copy to preserve key ordering + ret: list = [dict(d) for _ in range(self.cropper.num_samples)] + # deep copy all the unmodified data + for i in range(self.cropper.num_samples): + for key in set(d.keys()).difference(set(self.keys)): + ret[i][key] = deepcopy(d[key]) + + lazy_ = self.lazy if lazy is None else lazy + for key in self.key_iterator(d): + for i, im in enumerate(self.cropper(d[key], randomize=False, lazy=lazy_)): + ret[i][key] = im + return ret + + +class ResizeWithPadOrCropd(Padd): + """ + Dictionary-based wrapper of :py:class:`monai.transforms.ResizeWithPadOrCrop`. + + This transform is capable of lazy execution. See the :ref:`Lazy Resampling topic` + for more information. + + Args: + keys: keys of the corresponding items to be transformed. + See also: monai.transforms.MapTransform + spatial_size: the spatial size of output data after padding or crop. + If has non-positive values, the corresponding size of input image will be used (no padding). + mode: available modes for numpy array:{``"constant"``, ``"edge"``, ``"linear_ramp"``, ``"maximum"``, + ``"mean"``, ``"median"``, ``"minimum"``, ``"reflect"``, ``"symmetric"``, ``"wrap"``, ``"empty"``} + available modes for PyTorch Tensor: {``"constant"``, ``"reflect"``, ``"replicate"``, ``"circular"``}. + One of the listed string values or a user supplied function. Defaults to ``"constant"``. + See also: https://numpy.org/doc/1.18/reference/generated/numpy.pad.html + https://pytorch.org/docs/stable/generated/torch.nn.functional.pad.html + It also can be a sequence of string, each element corresponds to a key in ``keys``. + allow_missing_keys: don't raise exception if key is missing. + method: {``"symmetric"``, ``"end"``} + Pad image symmetrically on every side or only pad at the end sides. Defaults to ``"symmetric"``. + lazy: a flag to indicate whether this transform should execute lazily or not. Defaults to False. + pad_kwargs: other arguments for the `np.pad` or `torch.pad` function. + note that `np.pad` treats channel dimension as the first dimension. + + """ + + def __init__( + self, + keys: KeysCollection, + spatial_size: Sequence[int] | int, + mode: SequenceStr = PytorchPadMode.CONSTANT, + allow_missing_keys: bool = False, + method: str = Method.SYMMETRIC, + lazy: bool = False, + **pad_kwargs, + ) -> None: + padcropper = ResizeWithPadOrCrop(spatial_size=spatial_size, method=method, **pad_kwargs, lazy=lazy) + super().__init__( + keys, padder=padcropper, mode=mode, allow_missing_keys=allow_missing_keys, lazy=lazy # type: ignore + ) + + +class BoundingRectd(MapTransform): + """ + Dictionary-based wrapper of :py:class:`monai.transforms.BoundingRect`. + + Args: + keys: keys of the corresponding items to be transformed. + See also: monai.transforms.MapTransform + bbox_key_postfix: the output bounding box coordinates will be + written to the value of `{key}_{bbox_key_postfix}`. + select_fn: function to select expected foreground, default is to select values > 0. + allow_missing_keys: don't raise exception if key is missing. + """ + + backend = BoundingRect.backend + + def __init__( + self, + keys: KeysCollection, + bbox_key_postfix: str = "bbox", + select_fn: Callable = is_positive, + allow_missing_keys: bool = False, + ): + super().__init__(keys, allow_missing_keys) + self.bbox = BoundingRect(select_fn=select_fn) + self.bbox_key_postfix = bbox_key_postfix + + def __call__(self, data: Mapping[Hashable, NdarrayOrTensor]) -> dict[Hashable, NdarrayOrTensor]: + """ + See also: :py:class:`monai.transforms.utils.generate_spatial_bounding_box`. + """ + d = dict(data) + for key in self.key_iterator(d): + bbox = self.bbox(d[key]) + key_to_add = f"{key}_{self.bbox_key_postfix}" + if key_to_add in d: + raise KeyError(f"Bounding box data with key {key_to_add} already exists.") + d[key_to_add] = bbox + return d + + +PadD = PadDict = Padd +SpatialPadD = SpatialPadDict = SpatialPadd +BorderPadD = BorderPadDict = BorderPadd +DivisiblePadD = DivisiblePadDict = DivisiblePadd +CropD = CropDict = Cropd +RandCropD = RandCropDict = RandCropd +SpatialCropD = SpatialCropDict = SpatialCropd +CenterSpatialCropD = CenterSpatialCropDict = CenterSpatialCropd +CenterScaleCropD = CenterScaleCropDict = CenterScaleCropd +RandSpatialCropD = RandSpatialCropDict = RandSpatialCropd +RandScaleCropD = RandScaleCropDict = RandScaleCropd +RandSpatialCropSamplesD = RandSpatialCropSamplesDict = RandSpatialCropSamplesd +CropForegroundD = CropForegroundDict = CropForegroundd +RandWeightedCropD = RandWeightedCropDict = RandWeightedCropd +RandCropByPosNegLabelD = RandCropByPosNegLabelDict = RandCropByPosNegLabeld +RandCropByLabelClassesD = RandCropByLabelClassesDict = RandCropByLabelClassesd +ResizeWithPadOrCropD = ResizeWithPadOrCropDict = ResizeWithPadOrCropd +BoundingRectD = BoundingRectDict = BoundingRectd diff --git a/source_code/SegMamba/monai/transforms/inverse.py b/source_code/SegMamba/monai/transforms/inverse.py new file mode 100644 index 0000000000000000000000000000000000000000..f94f11eca9157da77b095ff611496d7b456a4e07 --- /dev/null +++ b/source_code/SegMamba/monai/transforms/inverse.py @@ -0,0 +1,410 @@ +# Copyright (c) MONAI Consortium +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from __future__ import annotations + +import warnings +from collections.abc import Hashable, Mapping +from contextlib import contextmanager +from typing import Any + +import torch + +from monai import transforms +from monai.data.meta_obj import MetaObj, get_track_meta +from monai.data.meta_tensor import MetaTensor +from monai.data.utils import to_affine_nd +from monai.transforms.traits import InvertibleTrait +from monai.transforms.transform import Transform +from monai.utils import ( + LazyAttr, + MetaKeys, + TraceKeys, + TraceStatusKeys, + convert_to_dst_type, + convert_to_numpy, + convert_to_tensor, +) +from monai.utils.misc import MONAIEnvVars + +__all__ = ["TraceableTransform", "InvertibleTransform"] + + +class TraceableTransform(Transform): + """ + Maintains a stack of applied transforms to data. + + Data can be one of two types: + 1. A `MetaTensor` (this is the preferred data type). + 2. A dictionary of data containing arrays/tensors and auxiliary metadata. In + this case, a key must be supplied (this dictionary-based approach is deprecated). + + If `data` is of type `MetaTensor`, then the applied transform will be added to ``data.applied_operations``. + + If `data` is a dictionary, then one of two things can happen: + 1. If data[key] is a `MetaTensor`, the applied transform will be added to ``data[key].applied_operations``. + 2. Else, the applied transform will be appended to an adjacent list using + `trace_key`. If, for example, the key is `image`, then the transform + will be appended to `image_transforms` (this dictionary-based approach is deprecated). + + Hopefully it is clear that there are three total possibilities: + 1. data is `MetaTensor` + 2. data is dictionary, data[key] is `MetaTensor` + 3. data is dictionary, data[key] is not `MetaTensor` (this is a deprecated approach). + + The ``__call__`` method of this transform class must be implemented so + that the transformation information is stored during the data transformation. + + The information in the stack of applied transforms must be compatible with the + default collate, by only storing strings, numbers and arrays. + + `tracing` could be enabled by `self.set_tracing` or setting + `MONAI_TRACE_TRANSFORM` when initializing the class. + """ + + tracing = MONAIEnvVars.trace_transform() != "0" + + def set_tracing(self, tracing: bool) -> None: + """Set whether to trace transforms.""" + self.tracing = tracing + + @staticmethod + def trace_key(key: Hashable = None): + """The key to store the stack of applied transforms.""" + if key is None: + return f"{TraceKeys.KEY_SUFFIX}" + return f"{key}{TraceKeys.KEY_SUFFIX}" + + @staticmethod + def transform_info_keys(): + """The keys to store necessary info of an applied transform.""" + return (TraceKeys.CLASS_NAME, TraceKeys.ID, TraceKeys.TRACING, TraceKeys.DO_TRANSFORM) + + def get_transform_info(self) -> dict: + """ + Return a dictionary with the relevant information pertaining to an applied transform. + """ + vals = ( + self.__class__.__name__, + id(self), + self.tracing, + self._do_transform if hasattr(self, "_do_transform") else True, + ) + return dict(zip(self.transform_info_keys(), vals)) + + def push_transform(self, data, *args, **kwargs): + """ + Push to a stack of applied transforms of ``data``. + + Args: + data: dictionary of data or `MetaTensor`. + args: additional positional arguments to track_transform_meta. + kwargs: additional keyword arguments to track_transform_meta, + set ``replace=True`` (default False) to rewrite the last transform infor in + applied_operation/pending_operation based on ``self.get_transform_info()``. + """ + lazy_eval = kwargs.get("lazy", False) + transform_info = self.get_transform_info() + do_transform = transform_info.get(TraceKeys.DO_TRANSFORM, True) + kwargs = kwargs or {} + replace = kwargs.pop("replace", False) # whether to rewrite the most recently pushed transform info + if replace and get_track_meta() and isinstance(data, MetaTensor): + if not lazy_eval: + xform = self.pop_transform(data, check=False) if do_transform else {} + meta_obj = self.push_transform(data, orig_size=xform.get(TraceKeys.ORIG_SIZE), extra_info=xform) + return data.copy_meta_from(meta_obj) + if do_transform: + xform = data.pending_operations.pop() + extra = xform.copy() + xform.update(transform_info) + else: # lazy, replace=True, do_transform=False + xform, extra = transform_info, {} + meta_obj = self.push_transform(data, transform_info=xform, lazy=True, extra_info=extra) + return data.copy_meta_from(meta_obj) + kwargs["lazy"] = lazy_eval + if "transform_info" in kwargs and isinstance(kwargs["transform_info"], dict): + kwargs["transform_info"].update(transform_info) + else: + kwargs["transform_info"] = transform_info + meta_obj = TraceableTransform.track_transform_meta(data, *args, **kwargs) + return data.copy_meta_from(meta_obj) if isinstance(data, MetaTensor) else data + + @classmethod + def track_transform_meta( + cls, + data, + key: Hashable = None, + sp_size=None, + affine=None, + extra_info: dict | None = None, + orig_size: tuple | None = None, + transform_info=None, + lazy=False, + ): + """ + Update a stack of applied/pending transforms metadata of ``data``. + + Args: + data: dictionary of data or `MetaTensor`. + key: if data is a dictionary, data[key] will be modified. + sp_size: the expected output spatial size when the transform is applied. + it can be tensor or numpy, but will be converted to a list of integers. + affine: the affine representation of the (spatial) transform in the image space. + When the transform is applied, meta_tensor.affine will be updated to ``meta_tensor.affine @ affine``. + extra_info: if desired, any extra information pertaining to the applied + transform can be stored in this dictionary. These are often needed for + computing the inverse transformation. + orig_size: sometimes during the inverse it is useful to know what the size + of the original image was, in which case it can be supplied here. + transform_info: info from self.get_transform_info(). + lazy: whether to push the transform to pending_operations or applied_operations. + + Returns: + + For backward compatibility, if ``data`` is a dictionary, it returns the dictionary with + updated ``data[key]``. Otherwise, this function returns a MetaObj with updated transform metadata. + """ + data_t = data[key] if key is not None else data # compatible with the dict data representation + out_obj = MetaObj() + # after deprecating metadict, we should always convert data_t to metatensor here + if isinstance(data_t, MetaTensor): + out_obj.copy_meta_from(data_t, keys=out_obj.__dict__.keys()) + + if lazy and (not get_track_meta()): + warnings.warn("metadata is not tracked, please call 'set_track_meta(True)' if doing lazy evaluation.") + + if not lazy and affine is not None and isinstance(data_t, MetaTensor): + # not lazy evaluation, directly update the metatensor affine (don't push to the stack) + orig_affine = data_t.peek_pending_affine() + orig_affine = convert_to_dst_type(orig_affine, affine, dtype=torch.float64)[0] + try: + affine = orig_affine @ to_affine_nd(len(orig_affine) - 1, affine, dtype=torch.float64) + except RuntimeError as e: + if orig_affine.ndim > 2: + if data_t.is_batch: + msg = "Transform applied to batched tensor, should be applied to instances only" + else: + msg = "Mismatch affine matrix, ensured that the batch dimension is not included in the calculation." + raise RuntimeError(msg) from e + else: + raise + out_obj.meta[MetaKeys.AFFINE] = convert_to_tensor(affine, device=torch.device("cpu"), dtype=torch.float64) + + if not (get_track_meta() and transform_info and transform_info.get(TraceKeys.TRACING)): + if isinstance(data, Mapping): + if not isinstance(data, dict): + data = dict(data) + data[key] = data_t.copy_meta_from(out_obj) if isinstance(data_t, MetaTensor) else data_t + return data + return out_obj # return with data_t as tensor if get_track_meta() is False + + info = transform_info.copy() + # track the current spatial shape + if orig_size is not None: + info[TraceKeys.ORIG_SIZE] = orig_size + elif isinstance(data_t, MetaTensor): + info[TraceKeys.ORIG_SIZE] = data_t.peek_pending_shape() + elif hasattr(data_t, "shape"): + info[TraceKeys.ORIG_SIZE] = data_t.shape[1:] + + # add lazy status to the transform info + info[TraceKeys.LAZY] = lazy + + # include extra_info + if extra_info is not None: + extra_info.pop(LazyAttr.SHAPE, None) + extra_info.pop(LazyAttr.AFFINE, None) + info[TraceKeys.EXTRA_INFO] = extra_info + + # push the transform info to the applied_operation or pending_operation stack + if lazy: + if sp_size is None: + if LazyAttr.SHAPE not in info: + info[LazyAttr.SHAPE] = info.get(TraceKeys.ORIG_SIZE, []) + else: + info[LazyAttr.SHAPE] = sp_size + info[LazyAttr.SHAPE] = tuple(convert_to_numpy(info[LazyAttr.SHAPE], wrap_sequence=True).tolist()) + if affine is None: + if LazyAttr.AFFINE not in info: + info[LazyAttr.AFFINE] = MetaTensor.get_default_affine() + else: + info[LazyAttr.AFFINE] = affine + info[LazyAttr.AFFINE] = convert_to_tensor(info[LazyAttr.AFFINE], device=torch.device("cpu")) + out_obj.push_pending_operation(info) + else: + if out_obj.pending_operations: + transform_name = info.get(TraceKeys.CLASS_NAME, "") if isinstance(info, dict) else "" + msg = ( + f"Transform {transform_name} has been applied to a MetaTensor with pending operations: " + f"{[x.get(TraceKeys.CLASS_NAME) for x in out_obj.pending_operations]}" + ) + if key is not None: + msg += f" for key {key}" + + pend = out_obj.pending_operations[-1] + statuses = pend.get(TraceKeys.STATUSES, dict()) + messages = statuses.get(TraceStatusKeys.PENDING_DURING_APPLY, list()) + messages.append(msg) + statuses[TraceStatusKeys.PENDING_DURING_APPLY] = messages + info[TraceKeys.STATUSES] = statuses + out_obj.push_applied_operation(info) + if isinstance(data, Mapping): + if not isinstance(data, dict): + data = dict(data) + if isinstance(data_t, MetaTensor): + data[key] = data_t.copy_meta_from(out_obj) + else: + x_k = TraceableTransform.trace_key(key) + if x_k not in data: + data[x_k] = [] # If this is the first, create list + data[x_k].append(info) + return data + return out_obj + + def check_transforms_match(self, transform: Mapping) -> None: + """Check transforms are of same instance.""" + xform_id = transform.get(TraceKeys.ID, "") + if xform_id == id(self): + return + # TraceKeys.NONE to skip the id check + if xform_id == TraceKeys.NONE: + return + xform_name = transform.get(TraceKeys.CLASS_NAME, "") + warning_msg = transform.get(TraceKeys.EXTRA_INFO, {}).get("warn") + if warning_msg: + warnings.warn(warning_msg) + # basic check if multiprocessing uses 'spawn' (objects get recreated so don't have same ID) + if torch.multiprocessing.get_start_method() in ("spawn", None) and xform_name == self.__class__.__name__: + return + raise RuntimeError( + f"Error {self.__class__.__name__} getting the most recently " + f"applied invertible transform {xform_name} {xform_id} != {id(self)}." + ) + + def get_most_recent_transform(self, data, key: Hashable = None, check: bool = True, pop: bool = False): + """ + Get most recent transform for the stack. + + Args: + data: dictionary of data or `MetaTensor`. + key: if data is a dictionary, data[key] will be modified. + check: if true, check that `self` is the same type as the most recently-applied transform. + pop: if true, remove the transform as it is returned. + + Returns: + Dictionary of most recently applied transform + + Raises: + - RuntimeError: data is neither `MetaTensor` nor dictionary + """ + if not self.tracing: + raise RuntimeError("Transform Tracing must be enabled to get the most recent transform.") + if isinstance(data, MetaTensor): + all_transforms = data.applied_operations + elif isinstance(data, Mapping): + if key in data and isinstance(data[key], MetaTensor): + all_transforms = data[key].applied_operations + else: + all_transforms = data.get(self.trace_key(key), MetaTensor.get_default_applied_operations()) + else: + raise ValueError(f"`data` should be either `MetaTensor` or dictionary, got {type(data)}.") + if check: + self.check_transforms_match(all_transforms[-1]) + return all_transforms.pop() if pop else all_transforms[-1] + + def pop_transform(self, data, key: Hashable = None, check: bool = True): + """ + Return and pop the most recent transform. + + Args: + data: dictionary of data or `MetaTensor` + key: if data is a dictionary, data[key] will be modified + check: if true, check that `self` is the same type as the most recently-applied transform. + + Returns: + Dictionary of most recently applied transform + + Raises: + - RuntimeError: data is neither `MetaTensor` nor dictionary + """ + return self.get_most_recent_transform(data, key, check, pop=True) + + @contextmanager + def trace_transform(self, to_trace: bool): + """Temporarily set the tracing status of a transform with a context manager.""" + prev = self.tracing + self.tracing = to_trace + yield + self.tracing = prev + + +class InvertibleTransform(TraceableTransform, InvertibleTrait): + """Classes for invertible transforms. + + This class exists so that an ``invert`` method can be implemented. This allows, for + example, images to be cropped, rotated, padded, etc., during training and inference, + and after be returned to their original size before saving to file for comparison in + an external viewer. + + When the ``inverse`` method is called: + + - the inverse is called on each key individually, which allows for + different parameters being passed to each label (e.g., different + interpolation for image and label). + + - the inverse transforms are applied in a last-in-first-out order. As + the inverse is applied, its entry is removed from the list detailing + the applied transformations. That is to say that during the forward + pass, the list of applied transforms grows, and then during the + inverse it shrinks back down to an empty list. + + We currently check that the ``id()`` of the transform is the same in the forward and + inverse directions. This is a useful check to ensure that the inverses are being + processed in the correct order. + + Note to developers: When converting a transform to an invertible transform, you need to: + + #. Inherit from this class. + #. In ``__call__``, add a call to ``push_transform``. + #. Any extra information that might be needed for the inverse can be included with the + dictionary ``extra_info``. This dictionary should have the same keys regardless of + whether ``do_transform`` was `True` or `False` and can only contain objects that are + accepted in pytorch data loader's collate function (e.g., `None` is not allowed). + #. Implement an ``inverse`` method. Make sure that after performing the inverse, + ``pop_transform`` is called. + + """ + + def inverse_update(self, data): + """ + This function is to be called before every `self.inverse(data)`, + update each MetaTensor `data[key]` using `data[key_transforms]` and `data[key_meta_dict]`, + for MetaTensor backward compatibility 0.9.0. + """ + if not isinstance(data, dict) or not isinstance(self, transforms.MapTransform): + return data + d = dict(data) + for k in self.key_iterator(data): + transform_key = transforms.TraceableTransform.trace_key(k) + if transform_key not in data or not data[transform_key]: + continue + d = transforms.sync_meta_info(k, data, t=False) + return d + + def inverse(self, data: Any) -> Any: + """ + Inverse of ``__call__``. + + Raises: + NotImplementedError: When the subclass does not override this method. + + """ + raise NotImplementedError(f"Subclass {self.__class__.__name__} must implement this method.") diff --git a/source_code/SegMamba/monai/transforms/inverse_batch_transform.py b/source_code/SegMamba/monai/transforms/inverse_batch_transform.py new file mode 100644 index 0000000000000000000000000000000000000000..1a7d16fb8c265ec95cf40f4b19026da8d0e751fc --- /dev/null +++ b/source_code/SegMamba/monai/transforms/inverse_batch_transform.py @@ -0,0 +1,162 @@ +# Copyright (c) MONAI Consortium +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from __future__ import annotations + +import warnings +from collections.abc import Callable, Sequence +from typing import Any + +from torch.utils.data import Dataset +from torch.utils.data.dataloader import DataLoader as TorchDataLoader + +from monai.config import KeysCollection +from monai.data.dataloader import DataLoader +from monai.data.utils import decollate_batch, no_collation, pad_list_data_collate +from monai.transforms.croppad.batch import PadListDataCollate +from monai.transforms.inverse import InvertibleTransform +from monai.transforms.transform import MapTransform, Transform +from monai.utils import first + +__all__ = ["BatchInverseTransform", "Decollated", "DecollateD", "DecollateDict"] + + +class _BatchInverseDataset(Dataset): + + 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 + + def __getitem__(self, index: int): + data = dict(self.data[index]) + # If pad collation was used, then we need to undo this first + if self.pad_collation_used: + data = PadListDataCollate.inverse(data) + + if not isinstance(self.invertible_transform, InvertibleTransform): + warnings.warn("transform is not invertible, can't invert transform for the input data.") + return data + return self.invertible_transform.inverse(data) + + def __len__(self) -> int: + return len(self.data) + + +class BatchInverseTransform(Transform): + """ + Perform inverse on a batch of data. This is useful if you have inferred a batch of images and want to invert + them all. + """ + + def __init__( + self, + transform: InvertibleTransform, + loader: TorchDataLoader, + collate_fn: Callable | None = no_collation, + num_workers: int | None = 0, + detach: bool = True, + pad_batch: bool = True, + fill_value=None, + ) -> None: + """ + Args: + transform: a callable data transform on input data. + loader: data loader used to run `transforms` and generate the batch of data. + collate_fn: how to collate data after inverse transformations. + default won't do any collation, so the output will be a list of size batch size. + num_workers: number of workers when run data loader for inverse transforms, + default to 0 as only run 1 iteration and multi-processing may be even slower. + if the transforms are really slow, set num_workers for multi-processing. + if set to `None`, use the `num_workers` of the transform data loader. + detach: whether to detach the tensors. Scalars tensors will be detached into number types + instead of torch tensors. + pad_batch: when the items in a batch indicate different batch size, + whether to pad all the sequences to the longest. + If False, the batch size will be the length of the shortest sequence. + fill_value: the value to fill the padded sequences when `pad_batch=True`. + + """ + self.transform = transform + self.batch_size = loader.batch_size + self.num_workers = loader.num_workers if num_workers is None else num_workers + self.collate_fn = collate_fn + self.detach = detach + self.pad_batch = pad_batch + self.fill_value = fill_value + self.pad_collation_used = loader.collate_fn.__doc__ == pad_list_data_collate.__doc__ or isinstance( + loader.collate_fn, PadListDataCollate + ) + + def __call__(self, data: dict[str, Any]) -> Any: + decollated_data = decollate_batch(data, detach=self.detach, pad=self.pad_batch, fill_value=self.fill_value) + inv_ds = _BatchInverseDataset(decollated_data, self.transform, self.pad_collation_used) + inv_loader = DataLoader( + inv_ds, batch_size=self.batch_size, num_workers=self.num_workers, collate_fn=self.collate_fn + ) + try: + return first(inv_loader) + except RuntimeError as re: + re_str = str(re) + if "equal size" in re_str: + re_str += "\nMONAI hint: try creating `BatchInverseTransform` with `collate_fn=lambda x: x`." + raise RuntimeError(re_str) from re + + +class Decollated(MapTransform): + """ + Decollate a batch of data. If input is a dictionary, it also supports to only decollate specified keys. + Note that unlike most MapTransforms, it will delete the other keys that are not specified. + if `keys=None`, it will decollate all the data in the input. + It replicates the scalar values to every item of the decollated list. + + Args: + keys: keys of the corresponding items to decollate, note that it will delete other keys not specified. + if None, will decollate all the keys. see also: :py:class:`monai.transforms.compose.MapTransform`. + detach: whether to detach the tensors. Scalars tensors will be detached into number types + instead of torch tensors. + pad_batch: when the items in a batch indicate different batch size, + whether to pad all the sequences to the longest. + If False, the batch size will be the length of the shortest sequence. + fill_value: the value to fill the padded sequences when `pad_batch=True`. + allow_missing_keys: don't raise exception if key is missing. + + """ + + def __init__( + self, + keys: KeysCollection | None = None, + detach: bool = True, + pad_batch: bool = True, + fill_value=None, + allow_missing_keys: bool = False, + ) -> None: + super().__init__(keys, allow_missing_keys) + self.detach = detach + self.pad_batch = pad_batch + self.fill_value = fill_value + + def __call__(self, data: dict | list): + d: dict | list + if len(self.keys) == 1 and self.keys[0] is None: + # it doesn't support `None` as the key + d = data + else: + if not isinstance(data, dict): + raise TypeError("input data is not a dictionary, but specified keys to decollate.") + d = {} + for key in self.key_iterator(data): + d[key] = data[key] + + return decollate_batch(d, detach=self.detach, pad=self.pad_batch, fill_value=self.fill_value) + + +DecollateD = DecollateDict = Decollated diff --git a/source_code/SegMamba/monai/transforms/traits.py b/source_code/SegMamba/monai/transforms/traits.py new file mode 100644 index 0000000000000000000000000000000000000000..016effc59d8199b43a2a7f90b57954e5f6ae96d3 --- /dev/null +++ b/source_code/SegMamba/monai/transforms/traits.py @@ -0,0 +1,101 @@ +# Copyright (c) MONAI Consortium +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +""" +A collection of generic traits for MONAI transforms. +""" + +from __future__ import annotations + +__all__ = ["LazyTrait", "InvertibleTrait", "RandomizableTrait", "MultiSampleTrait", "ThreadUnsafe"] + +from typing import Any + + +class LazyTrait: + """ + An interface to indicate that the transform has the capability to execute using + MONAI's lazy resampling feature. In order to do this, the implementing class needs + to be able to describe its operation as an affine matrix or grid with accompanying metadata. + This interface can be extended from by people adapting transforms to the MONAI framework as + well as by implementors of MONAI transforms. + """ + + @property + def lazy(self): + """ + Get whether lazy evaluation is enabled for this transform instance. + Returns: + True if the transform is operating in a lazy fashion, False if not. + """ + raise NotImplementedError() + + @lazy.setter + def lazy(self, enabled: bool): + """ + Set whether lazy evaluation is enabled for this transform instance. + Args: + enabled: True if the transform should operate in a lazy fashion, False if not. + """ + raise NotImplementedError() + + @property + def requires_current_data(self): + """ + Get whether the transform requires the input data to be up to date before the transform executes. + Such transforms can still execute lazily by adding pending operations to the output tensors. + Returns: + True if the transform requires its inputs to be up to date and False if it does not + """ + + +class InvertibleTrait: + """ + An interface to indicate that the transform can be inverted, i.e. undone by performing + the inverse of the operation performed during `__call__`. + """ + + def inverse(self, data: Any) -> Any: + raise NotImplementedError() + + +class RandomizableTrait: + """ + An interface to indicate that the transform has the capability to perform + randomized transforms to the data that it is called upon. This interface + can be extended from by people adapting transforms to the MONAI framework as well as by + implementors of MONAI transforms. + """ + + pass + + +class MultiSampleTrait: + """ + An interface to indicate that the transform has the capability to return multiple samples + given an input, such as when performing random crops of a sample. This interface can be + extended from by people adapting transforms to the MONAI framework as well as by implementors + of MONAI transforms. + """ + + pass + + +class ThreadUnsafe: + """ + A class to denote that the transform will mutate its member variables, + when being applied. Transforms inheriting this class should be used + cautiously in a multi-thread context. + + This type is typically used by :py:class:`monai.data.CacheDataset` and + its extensions, where the transform cache is built with multiple threads. + """ + + pass diff --git a/source_code/SegMamba/monai/transforms/transform.py b/source_code/SegMamba/monai/transforms/transform.py new file mode 100644 index 0000000000000000000000000000000000000000..3d09cea54500f33b972d880eae70a9592897e6c8 --- /dev/null +++ b/source_code/SegMamba/monai/transforms/transform.py @@ -0,0 +1,489 @@ +# Copyright (c) MONAI Consortium +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +""" +A collection of generic interfaces for MONAI transforms. +""" + +from __future__ import annotations + +import logging +from abc import ABC, abstractmethod +from collections.abc import Callable, Generator, Hashable, Iterable, Mapping +from typing import Any, TypeVar + +import numpy as np +import torch + +from monai import config, transforms +from monai.config import KeysCollection +from monai.data.meta_tensor import MetaTensor +from monai.transforms.traits import LazyTrait, RandomizableTrait, ThreadUnsafe +from monai.utils import MAX_SEED, ensure_tuple, first +from monai.utils.enums import TransformBackends +from monai.utils.misc import MONAIEnvVars + +__all__ = [ + "ThreadUnsafe", + "apply_transform", + "Randomizable", + "LazyTransform", + "RandomizableTransform", + "Transform", + "MapTransform", +] + +ReturnType = TypeVar("ReturnType") + + +def _apply_transform( + transform: Callable[..., ReturnType], + data: Any, + unpack_parameters: bool = False, + lazy: bool | None = False, + overrides: dict | None = None, + logger_name: bool | str = False, +) -> ReturnType: + """ + Perform a transform 'transform' on 'data', according to the other parameters specified. + + If `data` is a tuple and `unpack_parameters` is True, each parameter of `data` is unpacked + as arguments to `transform`. Otherwise `data` is considered as single argument to `transform`. + + If 'lazy' is True, this method first checks whether it can execute this method lazily. If it + can't, it will ensure that all pending lazy transforms on 'data' are applied before applying + this 'transform' to it. If 'lazy' is True, and 'overrides' are provided, those overrides will + be applied to the pending operations on 'data'. See ``Compose`` for more details on lazy + resampling, which is an experimental feature for 1.2. + + Please note, this class is function is designed to be called by ``apply_transform``. + In general, you should not need to make specific use of it unless you are implementing + pipeline execution mechanisms. + + Args: + transform: a callable to be used to transform `data`. + data: the tensorlike or dictionary of tensorlikes to be executed on + unpack_parameters: whether to unpack parameters for `transform`. Defaults to False. + lazy: whether to enable lazy evaluation for lazy transforms. If False, transforms will be + carried out on a transform by transform basis. If True, all lazy transforms will + be executed by accumulating changes and resampling as few times as possible. + See the :ref:`Lazy Resampling topic for more information about lazy resampling. + overrides: this optional parameter allows you to specify a dictionary of parameters that should be overridden + when executing a pipeline. These each parameter that is compatible with a given transform is then applied + to that transform before it is executed. Note that overrides are currently only applied when + :ref:`Lazy Resampling` is enabled for the pipeline or a given transform. If lazy is False + they are ignored. Currently supported args are: + {``"mode"``, ``"padding_mode"``, ``"dtype"``, ``"align_corners"``, ``"resample_mode"``, ``device``}. + logger_name: this optional parameter allows you to specify a logger by name for logging of pipeline execution. + Setting this to False disables logging. Setting it to True enables logging to the default loggers. + Setting a string overrides the logger name to which logging is performed. + + Returns: + ReturnType: The return type of `transform`. + """ + from monai.transforms.lazy.functional import apply_pending_transforms_in_order + + data = apply_pending_transforms_in_order(transform, data, lazy, overrides, logger_name) + + if isinstance(data, tuple) and unpack_parameters: + return transform(*data, lazy=lazy) if isinstance(transform, LazyTrait) else transform(*data) + + return transform(data, lazy=lazy) if isinstance(transform, LazyTrait) else transform(data) + + +def apply_transform( + transform: Callable[..., ReturnType], + data: Any, + map_items: bool = True, + unpack_items: bool = False, + log_stats: bool | str = False, + lazy: bool | None = None, + overrides: dict | None = None, +) -> list[ReturnType] | ReturnType: + """ + Transform `data` with `transform`. + + If `data` is a list or tuple and `map_data` is True, each item of `data` will be transformed + and this method returns a list of outcomes. + otherwise transform will be applied once with `data` as the argument. + + Args: + transform: a callable to be used to transform `data`. + data: an object to be transformed. + map_items: whether to apply transform to each item in `data`, + if `data` is a list or tuple. Defaults to True. + unpack_items: whether to unpack parameters using `*`. Defaults to False. + log_stats: log errors when they occur in the processing pipeline. By default, this is set to False, which + disables the logger for processing pipeline errors. Setting it to None or True will enable logging to the + default logger name. Setting it to a string specifies the logger to which errors should be logged. + lazy: whether to execute in lazy mode or not. See the :ref:`Lazy Resampling topic for more + information about lazy resampling. Defaults to None. + overrides: optional overrides to apply to transform parameters. This parameter is ignored unless transforms + are being executed lazily. See the :ref:`Lazy Resampling topic for more details and + examples of its usage. + + Raises: + Exception: When ``transform`` raises an exception. + + Returns: + Union[List[ReturnType], ReturnType]: The return type of `transform` or a list thereof. + """ + try: + if isinstance(data, (list, tuple)) and map_items: + return [_apply_transform(transform, item, unpack_items, lazy, overrides, log_stats) for item in data] + return _apply_transform(transform, data, unpack_items, lazy, overrides, log_stats) + except Exception as e: + # if in debug mode, don't swallow exception so that the breakpoint + # appears where the exception was raised. + if MONAIEnvVars.debug(): + raise + if log_stats is not False and not isinstance(transform, transforms.compose.Compose): + # log the input data information of exact transform in the transform chain + if isinstance(log_stats, str): + datastats = transforms.utility.array.DataStats(data_shape=False, value_range=False, name=log_stats) + else: + datastats = transforms.utility.array.DataStats(data_shape=False, value_range=False) + logger = logging.getLogger(datastats._logger_name) + logger.error(f"\n=== Transform input info -- {type(transform).__name__} ===") + if isinstance(data, (list, tuple)): + data = data[0] + + def _log_stats(data, prefix: str | None = "Data"): + if isinstance(data, (np.ndarray, torch.Tensor)): + # log data type, shape, range for array + datastats(img=data, data_shape=True, value_range=True, prefix=prefix) + else: + # log data type and value for other metadata + datastats(img=data, data_value=True, prefix=prefix) + + if isinstance(data, dict): + for k, v in data.items(): + _log_stats(data=v, prefix=k) + else: + _log_stats(data=data) + raise RuntimeError(f"applying transform {transform}") from e + + +class Randomizable(ThreadUnsafe, RandomizableTrait): + """ + An interface for handling random state locally, currently based on a class + variable `R`, which is an instance of `np.random.RandomState`. This + provides the flexibility of component-specific determinism without + affecting the global states. It is recommended to use this API with + :py:class:`monai.data.DataLoader` for deterministic behaviour of the + preprocessing pipelines. This API is not thread-safe. Additionally, + deepcopying instance of this class often causes insufficient randomness as + the random states will be duplicated. + """ + + R: np.random.RandomState = np.random.RandomState() + + def set_random_state(self, seed: int | None = None, state: np.random.RandomState | None = None) -> Randomizable: + """ + Set the random state locally, to control the randomness, the derived + classes should use :py:attr:`self.R` instead of `np.random` to introduce random + factors. + + Args: + seed: set the random state with an integer seed. + state: set the random state with a `np.random.RandomState` object. + + Raises: + TypeError: When ``state`` is not an ``Optional[np.random.RandomState]``. + + Returns: + a Randomizable instance. + + """ + if seed is not None: + _seed = id(seed) if not isinstance(seed, (int, np.integer)) else seed + _seed = _seed % MAX_SEED + self.R = np.random.RandomState(_seed) + return self + + if state is not None: + if not isinstance(state, np.random.RandomState): + raise TypeError(f"state must be None or a np.random.RandomState but is {type(state).__name__}.") + self.R = state + return self + + self.R = np.random.RandomState() + return self + + def randomize(self, data: Any) -> None: + """ + Within this method, :py:attr:`self.R` should be used, instead of `np.random`, to introduce random factors. + + all :py:attr:`self.R` calls happen here so that we have a better chance to + identify errors of sync the random state. + + This method can generate the random factors based on properties of the input data. + + Raises: + NotImplementedError: When the subclass does not override this method. + """ + raise NotImplementedError(f"Subclass {self.__class__.__name__} must implement this method.") + + +class Transform(ABC): + """ + An abstract class of a ``Transform``. + A transform is callable that processes ``data``. + + It could be stateful and may modify ``data`` in place, + the implementation should be aware of: + + #. thread safety when mutating its own states. + When used from a multi-process context, transform's instance variables are read-only. + thread-unsafe transforms should inherit :py:class:`monai.transforms.ThreadUnsafe`. + #. ``data`` content unused by this transform may still be used in the + subsequent transforms in a composed transform. + #. storing too much information in ``data`` may cause some memory issue or IPC sync issue, + especially in the multi-processing environment of PyTorch DataLoader. + + See Also + + :py:class:`monai.transforms.Compose` + """ + + # Transforms should add `monai.transforms.utils.TransformBackends` to this list if they are performing + # the data processing using the corresponding backend APIs. + # Most of MONAI transform's inputs and outputs will be converted into torch.Tensor or monai.data.MetaTensor. + # This variable provides information about whether the input will be converted + # to other data types during the transformation. Note that not all `dtype` (such as float32, uint8) are supported + # by all the data types, the `dtype` during the conversion is determined automatically by each transform, + # please refer to the transform's docstring. + backend: list[TransformBackends] = [] + + @abstractmethod + def __call__(self, data: Any): + """ + ``data`` is an element which often comes from an iteration over an + iterable, such as :py:class:`torch.utils.data.Dataset`. This method should + return an updated version of ``data``. + To simplify the input validations, most of the transforms assume that + + - ``data`` is a Numpy ndarray, PyTorch Tensor or string, + - the data shape can be: + + #. string data without shape, `LoadImage` transform expects file paths, + #. most of the pre-/post-processing transforms expect: ``(num_channels, spatial_dim_1[, spatial_dim_2, ...])``, + except for example: `AddChannel` expects (spatial_dim_1[, spatial_dim_2, ...]) + + - the channel dimension is often not omitted even if number of channels is one. + + This method can optionally take additional arguments to help execute transformation operation. + + Raises: + NotImplementedError: When the subclass does not override this method. + + """ + raise NotImplementedError(f"Subclass {self.__class__.__name__} must implement this method.") + + +class LazyTransform(Transform, LazyTrait): + """ + An implementation of functionality for lazy transforms that can be subclassed by array and + dictionary transforms to simplify implementation of new lazy transforms. + """ + + def __init__(self, lazy: bool | None = False): + if lazy is not None: + if not isinstance(lazy, bool): + raise TypeError(f"lazy must be a bool but is of type {type(lazy)}") + self._lazy = lazy + + @property + def lazy(self): + return self._lazy + + @lazy.setter + def lazy(self, lazy: bool | None): + if lazy is not None: + if not isinstance(lazy, bool): + raise TypeError(f"lazy must be a bool but is of type {type(lazy)}") + self._lazy = lazy + + @property + def requires_current_data(self): + return False + + +class RandomizableTransform(Randomizable, Transform): + """ + An interface for handling random state locally, currently based on a class variable `R`, + which is an instance of `np.random.RandomState`. + This class introduces a randomized flag `_do_transform`, is mainly for randomized data augmentation transforms. + For example: + + .. code-block:: python + + from monai.transforms import RandomizableTransform + + class RandShiftIntensity100(RandomizableTransform): + def randomize(self): + super().randomize(None) + self._offset = self.R.uniform(low=0, high=100) + + def __call__(self, img): + self.randomize() + if not self._do_transform: + return img + return img + self._offset + + transform = RandShiftIntensity() + transform.set_random_state(seed=0) + print(transform(10)) + + """ + + def __init__(self, prob: float = 1.0, do_transform: bool = True): + self._do_transform = do_transform + self.prob = min(max(prob, 0.0), 1.0) + + def randomize(self, data: Any) -> None: + """ + Within this method, :py:attr:`self.R` should be used, instead of `np.random`, to introduce random factors. + + all :py:attr:`self.R` calls happen here so that we have a better chance to + identify errors of sync the random state. + + This method can generate the random factors based on properties of the input data. + """ + self._do_transform = self.R.rand() < self.prob + + +class MapTransform(Transform): + """ + A subclass of :py:class:`monai.transforms.Transform` with an assumption + that the ``data`` input of ``self.__call__`` is a MutableMapping such as ``dict``. + + The ``keys`` parameter will be used to get and set the actual data + item to transform. That is, the callable of this transform should + follow the pattern: + + .. code-block:: python + + def __call__(self, data): + for key in self.keys: + if key in data: + # update output data with some_transform_function(data[key]). + else: + # raise exception unless allow_missing_keys==True. + return data + + Raises: + ValueError: When ``keys`` is an empty iterable. + TypeError: When ``keys`` type is not in ``Union[Hashable, Iterable[Hashable]]``. + + """ + + def __new__(cls, *args, **kwargs): + if config.USE_META_DICT: + # call_update after MapTransform.__call__ + cls.__call__ = transforms.attach_hook(cls.__call__, MapTransform.call_update, "post") # type: ignore + + if hasattr(cls, "inverse"): + # inverse_update before InvertibleTransform.inverse + cls.inverse: Any = transforms.attach_hook(cls.inverse, transforms.InvertibleTransform.inverse_update) + return Transform.__new__(cls) + + def __init__(self, keys: KeysCollection, allow_missing_keys: bool = False) -> None: + super().__init__() + self.keys: tuple[Hashable, ...] = ensure_tuple(keys) + self.allow_missing_keys = allow_missing_keys + if not self.keys: + raise ValueError("keys must be non empty.") + for key in self.keys: + if not isinstance(key, Hashable): + raise TypeError(f"keys must be one of (Hashable, Iterable[Hashable]) but is {type(keys).__name__}.") + + def call_update(self, data): + """ + This function is to be called after every `self.__call__(data)`, + update `data[key_transforms]` and `data[key_meta_dict]` using the content from MetaTensor `data[key]`, + for MetaTensor backward compatibility 0.9.0. + """ + if not isinstance(data, (list, tuple, Mapping)): + return data + is_dict = False + if isinstance(data, Mapping): + data, is_dict = [data], True + if not data or not isinstance(data[0], Mapping): + return data[0] if is_dict else data + list_d = [dict(x) for x in data] # list of dict for crop samples + for idx, dict_i in enumerate(list_d): + for k in dict_i: + if not isinstance(dict_i[k], MetaTensor): + continue + list_d[idx] = transforms.sync_meta_info(k, dict_i, t=not isinstance(self, transforms.InvertD)) + return list_d[0] if is_dict else list_d + + @abstractmethod + def __call__(self, data): + """ + ``data`` often comes from an iteration over an iterable, + such as :py:class:`torch.utils.data.Dataset`. + + To simplify the input validations, this method assumes: + + - ``data`` is a Python dictionary, + - ``data[key]`` is a Numpy ndarray, PyTorch Tensor or string, where ``key`` is an element + of ``self.keys``, the data shape can be: + + #. string data without shape, `LoadImaged` transform expects file paths, + #. most of the pre-/post-processing transforms expect: ``(num_channels, spatial_dim_1[, spatial_dim_2, ...])``, + except for example: `AddChanneld` expects (spatial_dim_1[, spatial_dim_2, ...]) + + - the channel dimension is often not omitted even if number of channels is one. + + Raises: + NotImplementedError: When the subclass does not override this method. + + returns: + An updated dictionary version of ``data`` by applying the transform. + + """ + raise NotImplementedError(f"Subclass {self.__class__.__name__} must implement this method.") + + def key_iterator(self, data: Mapping[Hashable, Any], *extra_iterables: Iterable | None) -> 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. + + Args: + data: data that the transform will be applied to + extra_iterables: anything else to be iterated through + """ + # if no extra iterables given, create a dummy list of Nones + ex_iters = extra_iterables or [[None] * len(self.keys)] + + # loop over keys and any extra iterables + _ex_iters: list[Any] + for key, *_ex_iters in zip(self.keys, *ex_iters): + # all normal, yield (what we yield depends on whether extra iterables were given) + if key in data: + yield (key,) + tuple(_ex_iters) if extra_iterables else key + elif not self.allow_missing_keys: + raise KeyError( + f"Key `{key}` of transform `{self.__class__.__name__}` was missing in the data" + " and allow_missing_keys==False." + ) + + def first_key(self, data: dict[Hashable, Any]): + """ + Get the first available key of `self.keys` in the input `data` dictionary. + If no available key, return an empty tuple `()`. + + Args: + data: data that the transform will be applied to. + + """ + return first(self.key_iterator(data), ()) diff --git a/source_code/SegMamba/monai/transforms/utils.py b/source_code/SegMamba/monai/transforms/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..560dbac34667aac0786f65ea7a554c4454ba7985 --- /dev/null +++ b/source_code/SegMamba/monai/transforms/utils.py @@ -0,0 +1,2265 @@ +# Copyright (c) MONAI Consortium +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from __future__ import annotations + +import itertools +import random +import warnings +from collections.abc import Callable, Hashable, Iterable, Mapping, Sequence +from contextlib import contextmanager +from functools import lru_cache, wraps +from inspect import getmembers, isclass +from typing import Any + +import numpy as np +import torch + +import monai +from monai.config import DtypeLike, IndexSelection +from monai.config.type_definitions import NdarrayOrTensor, NdarrayTensor +from monai.networks.layers import GaussianFilter +from monai.networks.utils import meshgrid_ij +from monai.transforms.compose import Compose +from monai.transforms.transform import MapTransform, Transform, apply_transform +from monai.transforms.utils_pytorch_numpy_unification import ( + any_np_pt, + ascontiguousarray, + cumsum, + isfinite, + nonzero, + ravel, + searchsorted, + softplus, + unique, + unravel_index, + where, +) +from monai.utils import ( + GridSampleMode, + GridSamplePadMode, + InterpolateMode, + NdimageMode, + NumpyPadMode, + PostFix, + PytorchPadMode, + SplineMode, + TraceKeys, + TraceStatusKeys, + deprecated_arg_default, + ensure_tuple, + ensure_tuple_rep, + ensure_tuple_size, + fall_back_tuple, + get_equivalent_dtype, + issequenceiterable, + look_up_option, + min_version, + optional_import, + pytorch_after, +) +from monai.utils.enums import TransformBackends +from monai.utils.type_conversion import ( + convert_data_type, + convert_to_cupy, + convert_to_dst_type, + convert_to_numpy, + convert_to_tensor, +) + +measure, has_measure = optional_import("skimage.measure", "0.14.2", min_version) +morphology, has_morphology = optional_import("skimage.morphology") +ndimage, has_ndimage = optional_import("scipy.ndimage") +cp, has_cp = optional_import("cupy") +cp_ndarray, _ = optional_import("cupy", name="ndarray") +exposure, has_skimage = optional_import("skimage.exposure") + +__all__ = [ + "allow_missing_keys_mode", + "check_boundaries", + "compute_divisible_spatial_size", + "convert_applied_interp_mode", + "copypaste_arrays", + "check_non_lazy_pending_ops", + "create_control_grid", + "create_grid", + "create_rotate", + "create_scale", + "create_shear", + "create_translate", + "extreme_points_to_image", + "fill_holes", + "Fourier", + "generate_label_classes_crop_centers", + "generate_pos_neg_label_crop_centers", + "generate_spatial_bounding_box", + "get_extreme_points", + "get_largest_connected_component_mask", + "remove_small_objects", + "img_bounds", + "in_bounds", + "is_empty", + "is_positive", + "map_binary_to_indices", + "map_classes_to_indices", + "map_spatial_axes", + "rand_choice", + "rescale_array", + "rescale_array_int_max", + "rescale_instance_array", + "resize_center", + "weighted_patch_samples", + "zero_margins", + "equalize_hist", + "get_number_image_type_conversions", + "get_transform_backends", + "print_transform_backends", + "convert_pad_mode", + "convert_to_contiguous", + "get_unique_labels", + "scale_affine", + "attach_hook", + "sync_meta_info", + "reset_ops_id", + "resolves_modes", + "has_status_keys", + "distance_transform_edt", + "soft_clip", +] + + +def soft_clip( + arr: NdarrayOrTensor, + sharpness_factor: float = 1.0, + minv: NdarrayOrTensor | float | int | None = None, + maxv: NdarrayOrTensor | float | int | None = None, + dtype: DtypeLike | torch.dtype = np.float32, +) -> NdarrayOrTensor: + """ + Apply soft clip to the input array or tensor. + The intensity values will be soft clipped according to + f(x) = x + (1/sharpness_factor)*softplus(- c(x - minv)) - (1/sharpness_factor)*softplus(c(x - maxv)) + From https://medium.com/life-at-hopper/clip-it-clip-it-good-1f1bf711b291 + + To perform one-sided clipping, set either minv or maxv to None. + Args: + arr: input array to clip. + sharpness_factor: the sharpness of the soft clip function, default to 1. + minv: minimum value of target clipped array. + maxv: maximum value of target clipped array. + dtype: if not None, convert input array to dtype before computation. + + """ + + if dtype is not None: + arr, *_ = convert_data_type(arr, dtype=dtype) + + v = arr + if minv is not None: + v = v + softplus(-sharpness_factor * (arr - minv)) / sharpness_factor + if maxv is not None: + v = v - softplus(sharpness_factor * (arr - maxv)) / sharpness_factor + + return v + + +def rand_choice(prob: float = 0.5) -> bool: + """ + Returns True if a randomly chosen number is less than or equal to `prob`, by default this is a 50/50 chance. + """ + return bool(random.random() <= prob) + + +def img_bounds(img: np.ndarray): + """ + Returns the minimum and maximum indices of non-zero lines in axis 0 of `img`, followed by that for axis 1. + """ + ax0 = np.any(img, axis=0) + ax1 = np.any(img, axis=1) + return np.concatenate((np.where(ax0)[0][[0, -1]], np.where(ax1)[0][[0, -1]])) + + +def in_bounds(x: float, y: float, margin: float, maxx: float, maxy: float) -> bool: + """ + Returns True if (x,y) is within the rectangle (margin, margin, maxx-margin, maxy-margin). + """ + return bool(margin <= x < (maxx - margin) and margin <= y < (maxy - margin)) + + +def is_empty(img: np.ndarray | torch.Tensor) -> bool: + """ + Returns True if `img` is empty, that is its maximum value is not greater than its minimum. + """ + return not (img.max() > img.min()) # use > instead of <= so that an image full of NaNs will result in True + + +def is_positive(img): + """ + Returns a boolean version of `img` where the positive values are converted into True, the other values are False. + """ + return img > 0 + + +def zero_margins(img: np.ndarray, margin: int) -> bool: + """ + Returns True if the values within `margin` indices of the edges of `img` in dimensions 1 and 2 are 0. + """ + if np.any(img[:, :, :margin]) or np.any(img[:, :, -margin:]): + return False + + return not np.any(img[:, :margin, :]) and not np.any(img[:, -margin:, :]) + + +def rescale_array( + arr: NdarrayOrTensor, + minv: float | None = 0.0, + maxv: float | None = 1.0, + dtype: DtypeLike | torch.dtype = np.float32, +) -> NdarrayOrTensor: + """ + Rescale the values of numpy array `arr` to be from `minv` to `maxv`. + If either `minv` or `maxv` is None, it returns `(a - min_a) / (max_a - min_a)`. + + Args: + arr: input array to rescale. + minv: minimum value of target rescaled array. + maxv: maximum value of target rescaled array. + dtype: if not None, convert input array to dtype before computation. + + """ + if dtype is not None: + arr, *_ = convert_data_type(arr, dtype=dtype) + mina = arr.min() + maxa = arr.max() + + if mina == maxa: + return arr * minv if minv is not None else arr + + norm = (arr - mina) / (maxa - mina) # normalize the array first + if (minv is None) or (maxv is None): + return norm + return (norm * (maxv - minv)) + minv # rescale by minv and maxv, which is the normalized array by default + + +def rescale_instance_array( + arr: np.ndarray, minv: float | None = 0.0, maxv: float | None = 1.0, dtype: DtypeLike = np.float32 +) -> np.ndarray: + """ + Rescale each array slice along the first dimension of `arr` independently. + """ + out: np.ndarray = np.zeros(arr.shape, dtype or arr.dtype) + for i in range(arr.shape[0]): + out[i] = rescale_array(arr[i], minv, maxv, dtype) + + return out + + +def rescale_array_int_max(arr: np.ndarray, dtype: DtypeLike = np.uint16) -> np.ndarray: + """ + Rescale the array `arr` to be between the minimum and maximum values of the type `dtype`. + """ + info: np.iinfo = np.iinfo(dtype or arr.dtype) + return np.asarray(rescale_array(arr, info.min, info.max), dtype=dtype or arr.dtype) + + +def copypaste_arrays( + src_shape, dest_shape, srccenter: Sequence[int], destcenter: Sequence[int], dims: Sequence[int | None] +) -> tuple[tuple[slice, ...], tuple[slice, ...]]: + """ + Calculate the slices to copy a sliced area of array in `src_shape` into array in `dest_shape`. + + The area has dimensions `dims` (use 0 or None to copy everything in that dimension), + the source area is centered at `srccenter` index in `src` and copied into area centered at `destcenter` in `dest`. + The dimensions of the copied area will be clipped to fit within the + source and destination arrays so a smaller area may be copied than expected. Return value is the tuples of slice + objects indexing the copied area in `src`, and those indexing the copy area in `dest`. + + Example + + .. code-block:: python + + src_shape = (6,6) + src = np.random.randint(0,10,src_shape) + dest = np.zeros_like(src) + srcslices, destslices = copypaste_arrays(src_shape, dest.shape, (3, 2),(2, 1),(3, 4)) + dest[destslices] = src[srcslices] + print(src) + print(dest) + + >>> [[9 5 6 6 9 6] + [4 3 5 6 1 2] + [0 7 3 2 4 1] + [3 0 0 1 5 1] + [9 4 7 1 8 2] + [6 6 5 8 6 7]] + [[0 0 0 0 0 0] + [7 3 2 4 0 0] + [0 0 1 5 0 0] + [4 7 1 8 0 0] + [0 0 0 0 0 0] + [0 0 0 0 0 0]] + + """ + s_ndim = len(src_shape) + d_ndim = len(dest_shape) + srcslices = [slice(None)] * s_ndim + destslices = [slice(None)] * d_ndim + + for i, ss, ds, sc, dc, dim in zip(range(s_ndim), src_shape, dest_shape, srccenter, destcenter, dims): + if dim: + # dimension before midpoint, clip to size fitting in both arrays + d1 = np.clip(dim // 2, 0, min(sc, dc)) + # dimension after midpoint, clip to size fitting in both arrays + d2 = np.clip(dim // 2 + 1, 0, min(ss - sc, ds - dc)) + + srcslices[i] = slice(sc - d1, sc + d2) + destslices[i] = slice(dc - d1, dc + d2) + + return tuple(srcslices), tuple(destslices) + + +def resize_center(img: np.ndarray, *resize_dims: int | None, fill_value: float = 0.0, inplace: bool = True): + """ + Resize `img` by cropping or expanding the image from the center. The `resize_dims` values are the output dimensions + (or None to use original dimension of `img`). If a dimension is smaller than that of `img` then the result will be + cropped and if larger padded with zeros, in both cases this is done relative to the center of `img`. The result is + a new image with the specified dimensions and values from `img` copied into its center. + """ + + resize_dims = fall_back_tuple(resize_dims, img.shape) + + half_img_shape = (np.asarray(img.shape) // 2).tolist() + half_dest_shape = (np.asarray(resize_dims) // 2).tolist() + srcslices, destslices = copypaste_arrays(img.shape, resize_dims, half_img_shape, half_dest_shape, resize_dims) + + if not inplace: + dest = np.full(resize_dims, fill_value, img.dtype) # type: ignore + dest[destslices] = img[srcslices] + return dest + return img[srcslices] + + +def check_non_lazy_pending_ops( + input_array: NdarrayOrTensor, name: None | str = None, raise_error: bool = False +) -> None: + """ + Check whether the input array has pending operations, raise an error or warn when it has. + + Args: + input_array: input array to be checked. + name: an optional name to be included in the error message. + raise_error: whether to raise an error, default to False, a warning message will be issued instead. + """ + if isinstance(input_array, monai.data.MetaTensor) and input_array.pending_operations: + msg = ( + "The input image is a MetaTensor and has pending operations,\n" + f"but the function {name or ''} assumes non-lazy input, result may be incorrect." + ) + if raise_error: + raise ValueError(msg) + warnings.warn(msg) + + +def map_binary_to_indices( + label: NdarrayOrTensor, image: NdarrayOrTensor | None = None, image_threshold: float = 0.0 +) -> tuple[NdarrayOrTensor, NdarrayOrTensor]: + """ + Compute the foreground and background of input label data, return the indices after fattening. + For example: + ``label = np.array([[[0, 1, 1], [1, 0, 1], [1, 1, 0]]])`` + ``foreground indices = np.array([1, 2, 3, 5, 6, 7])`` and ``background indices = np.array([0, 4, 8])`` + + Args: + label: use the label data to get the foreground/background information. + image: if image is not None, use ``label = 0 & image > image_threshold`` + to define background. so the output items will not map to all the voxels in the label. + image_threshold: if enabled `image`, use ``image > image_threshold`` to + determine the valid image content area and select background only in this area. + """ + check_non_lazy_pending_ops(label, name="map_binary_to_indices") + # Prepare fg/bg indices + if label.shape[0] > 1: + label = label[1:] # for One-Hot format data, remove the background channel + label_flat = ravel(any_np_pt(label, 0)) # in case label has multiple dimensions + fg_indices = nonzero(label_flat) + if image is not None: + check_non_lazy_pending_ops(image, name="map_binary_to_indices") + img_flat = ravel(any_np_pt(image > image_threshold, 0)) + img_flat, *_ = convert_to_dst_type(img_flat, label, dtype=bool) + bg_indices = nonzero(img_flat & ~label_flat) + else: + bg_indices = nonzero(~label_flat) + + # no need to save the indices in GPU, otherwise, still need to move to CPU at runtime when crop by indices + fg_indices, *_ = convert_data_type(fg_indices, device=torch.device("cpu")) + bg_indices, *_ = convert_data_type(bg_indices, device=torch.device("cpu")) + return fg_indices, bg_indices + + +def map_classes_to_indices( + label: NdarrayOrTensor, + num_classes: int | None = None, + image: NdarrayOrTensor | None = None, + image_threshold: float = 0.0, + max_samples_per_class: int | None = None, +) -> list[NdarrayOrTensor]: + """ + Filter out indices of every class of the input label data, return the indices after fattening. + It can handle both One-Hot format label and Argmax format label, must provide `num_classes` for + Argmax label. + + For example: + ``label = np.array([[[0, 1, 2], [2, 0, 1], [1, 2, 0]]])`` and `num_classes=3`, will return a list + which contains the indices of the 3 classes: + ``[np.array([0, 4, 8]), np.array([1, 5, 6]), np.array([2, 3, 7])]`` + + Args: + label: use the label data to get the indices of every class. + num_classes: number of classes for argmax label, not necessary for One-Hot label. + image: if image is not None, only return the indices of every class that are within the valid + region of the image (``image > image_threshold``). + image_threshold: if enabled `image`, use ``image > image_threshold`` to + determine the valid image content area and select class indices only in this area. + max_samples_per_class: maximum length of indices in each class to reduce memory consumption. + Default is None, no subsampling. + + """ + check_non_lazy_pending_ops(label, name="map_classes_to_indices") + img_flat: NdarrayOrTensor | None = None + if image is not None: + check_non_lazy_pending_ops(image, name="map_classes_to_indices") + img_flat = ravel((image > image_threshold).any(0)) + + # assuming the first dimension is channel + channels = len(label) + + num_classes_: int = channels + if channels == 1: + if num_classes is None: + raise ValueError("channels==1 indicates not using One-Hot format label, must provide ``num_classes``.") + num_classes_ = num_classes + + indices: list[NdarrayOrTensor] = [] + for c in range(num_classes_): + if channels > 1: + label_flat = ravel(convert_data_type(label[c], dtype=bool)[0]) + else: + label_flat = ravel(label == c) + if img_flat is not None: + label_flat = img_flat & label_flat + # no need to save the indices in GPU, otherwise, still need to move to CPU at runtime when crop by indices + output_type = torch.Tensor if isinstance(label, monai.data.MetaTensor) else None + cls_indices: NdarrayOrTensor = convert_data_type( + nonzero(label_flat), output_type=output_type, device=torch.device("cpu") + )[0] + if max_samples_per_class and len(cls_indices) > max_samples_per_class and len(cls_indices) > 1: + sample_id = np.round(np.linspace(0, len(cls_indices) - 1, max_samples_per_class)).astype(int) + indices.append(cls_indices[sample_id]) + else: + indices.append(cls_indices) + + return indices + + +def weighted_patch_samples( + spatial_size: int | Sequence[int], + w: NdarrayOrTensor, + n_samples: int = 1, + r_state: np.random.RandomState | None = None, +) -> list: + """ + Computes `n_samples` of random patch sampling locations, given the sampling weight map `w` and patch `spatial_size`. + + Args: + spatial_size: length of each spatial dimension of the patch. + w: weight map, the weights must be non-negative. each element denotes a sampling weight of the spatial location. + 0 indicates no sampling. + The weight map shape is assumed ``(spatial_dim_0, spatial_dim_1, ..., spatial_dim_n)``. + n_samples: number of patch samples + r_state: a random state container + + Returns: + a list of `n_samples` N-D integers representing the spatial sampling location of patches. + + """ + check_non_lazy_pending_ops(w, name="weighted_patch_samples") + if w is None: + raise ValueError("w must be an ND array, got None.") + if r_state is None: + r_state = np.random.RandomState() + img_size = np.asarray(w.shape, dtype=int) + win_size = np.asarray(fall_back_tuple(spatial_size, img_size), dtype=int) + + s = tuple(slice(w // 2, m - w + w // 2) if m > w else slice(m // 2, m // 2 + 1) for w, m in zip(win_size, img_size)) + v = w[s] # weight map in the 'valid' mode + v_size = v.shape + v = ravel(v) # always copy + if (v < 0).any(): + v -= v.min() # shifting to non-negative + v = cumsum(v) + if not v[-1] or not isfinite(v[-1]) or v[-1] < 0: # uniform sampling + idx = r_state.randint(0, len(v), size=n_samples) + else: + r, *_ = convert_to_dst_type(r_state.random(n_samples), v) + idx = searchsorted(v, r * v[-1], right=True) # type: ignore + idx, *_ = convert_to_dst_type(idx, v, dtype=torch.int) # type: ignore + # compensate 'valid' mode + diff = np.minimum(win_size, img_size) // 2 + diff, *_ = convert_to_dst_type(diff, v) # type: ignore + return [unravel_index(i, v_size) + diff for i in idx] + + +def correct_crop_centers( + centers: list[int], + spatial_size: Sequence[int] | int, + label_spatial_shape: Sequence[int], + allow_smaller: bool = False, +) -> tuple[Any]: + """ + Utility to correct the crop center if the crop size and centers are not compatible with the image size. + + Args: + centers: pre-computed crop centers of every dim, will correct based on the valid region. + spatial_size: spatial size of the ROIs to be sampled. + label_spatial_shape: spatial shape of the original label data to compare with ROI. + allow_smaller: if `False`, an exception will be raised if the image is smaller than + the requested ROI in any dimension. If `True`, any smaller dimensions will be set to + match the cropped size (i.e., no cropping in that dimension). + + """ + spatial_size = fall_back_tuple(spatial_size, default=label_spatial_shape) + if any(np.subtract(label_spatial_shape, spatial_size) < 0): + if not allow_smaller: + raise ValueError( + "The size of the proposed random crop ROI is larger than the image size, " + f"got ROI size {spatial_size} and label image size {label_spatial_shape} respectively." + ) + spatial_size = tuple(min(l, s) for l, s in zip(label_spatial_shape, spatial_size)) + + # Select subregion to assure valid roi + valid_start = np.floor_divide(spatial_size, 2) + # add 1 for random + valid_end = np.subtract(label_spatial_shape + np.array(1), spatial_size / np.array(2)).astype(np.uint16) + # int generation to have full range on upper side, but subtract unfloored size/2 to prevent rounded range + # from being too high + for i, valid_s in enumerate(valid_start): + # need this because np.random.randint does not work with same start and end + if valid_s == valid_end[i]: + valid_end[i] += 1 + valid_centers = [] + for c, v_s, v_e in zip(centers, valid_start, valid_end): + center_i = min(max(c, v_s), v_e - 1) + valid_centers.append(int(center_i)) + return ensure_tuple(valid_centers) + + +def generate_pos_neg_label_crop_centers( + spatial_size: Sequence[int] | int, + num_samples: int, + pos_ratio: float, + label_spatial_shape: Sequence[int], + fg_indices: NdarrayOrTensor, + bg_indices: NdarrayOrTensor, + rand_state: np.random.RandomState | None = None, + allow_smaller: bool = False, +) -> tuple[tuple]: + """ + Generate valid sample locations based on the label with option for specifying foreground ratio + Valid: samples sitting entirely within image, expected input shape: [C, H, W, D] or [C, H, W] + + Args: + spatial_size: spatial size of the ROIs to be sampled. + num_samples: total sample centers to be generated. + pos_ratio: ratio of total locations generated that have center being foreground. + label_spatial_shape: spatial shape of the original label data to unravel selected centers. + fg_indices: pre-computed foreground indices in 1 dimension. + bg_indices: pre-computed background indices in 1 dimension. + rand_state: numpy randomState object to align with other modules. + allow_smaller: if `False`, an exception will be raised if the image is smaller than + the requested ROI in any dimension. If `True`, any smaller dimensions will be set to + match the cropped size (i.e., no cropping in that dimension). + + Raises: + ValueError: When the proposed roi is larger than the image. + ValueError: When the foreground and background indices lengths are 0. + + """ + if rand_state is None: + rand_state = np.random.random.__self__ # type: ignore + + centers = [] + fg_indices = np.asarray(fg_indices) if isinstance(fg_indices, Sequence) else fg_indices + bg_indices = np.asarray(bg_indices) if isinstance(bg_indices, Sequence) else bg_indices + if len(fg_indices) == 0 and len(bg_indices) == 0: + raise ValueError("No sampling location available.") + + if len(fg_indices) == 0 or len(bg_indices) == 0: + pos_ratio = 0 if len(fg_indices) == 0 else 1 + warnings.warn( + f"Num foregrounds {len(fg_indices)}, Num backgrounds {len(bg_indices)}, " + f"unable to generate class balanced samples, setting `pos_ratio` to {pos_ratio}." + ) + + for _ in range(num_samples): + indices_to_use = fg_indices if rand_state.rand() < pos_ratio else bg_indices + random_int = rand_state.randint(len(indices_to_use)) + idx = indices_to_use[random_int] + center = unravel_index(idx, label_spatial_shape).tolist() + # shift center to range of valid centers + centers.append(correct_crop_centers(center, spatial_size, label_spatial_shape, allow_smaller)) + + return ensure_tuple(centers) + + +def generate_label_classes_crop_centers( + spatial_size: Sequence[int] | int, + num_samples: int, + label_spatial_shape: Sequence[int], + indices: Sequence[NdarrayOrTensor], + ratios: list[float | int] | None = None, + rand_state: np.random.RandomState | None = None, + allow_smaller: bool = False, + warn: bool = True, +) -> tuple[tuple]: + """ + Generate valid sample locations based on the specified ratios of label classes. + Valid: samples sitting entirely within image, expected input shape: [C, H, W, D] or [C, H, W] + + Args: + spatial_size: spatial size of the ROIs to be sampled. + num_samples: total sample centers to be generated. + label_spatial_shape: spatial shape of the original label data to unravel selected centers. + indices: sequence of pre-computed foreground indices of every class in 1 dimension. + ratios: ratios of every class in the label to generate crop centers, including background class. + if None, every class will have the same ratio to generate crop centers. + rand_state: numpy randomState object to align with other modules. + allow_smaller: if `False`, an exception will be raised if the image is smaller than + the requested ROI in any dimension. If `True`, any smaller dimensions will be set to + match the cropped size (i.e., no cropping in that dimension). + warn: if `True` prints a warning if a class is not present in the label. + + """ + if rand_state is None: + rand_state = np.random.random.__self__ # type: ignore + + if num_samples < 1: + raise ValueError(f"num_samples must be an int number and greater than 0, got {num_samples}.") + ratios_: list[float | int] = list(ensure_tuple([1] * len(indices) if ratios is None else ratios)) + if len(ratios_) != len(indices): + raise ValueError( + f"random crop ratios must match the number of indices of classes, got {len(ratios_)} and {len(indices)}." + ) + if any(i < 0 for i in ratios_): + raise ValueError(f"ratios should not contain negative number, got {ratios_}.") + + for i, array in enumerate(indices): + if len(array) == 0: + if ratios_[i] != 0: + ratios_[i] = 0 + if warn: + warnings.warn( + f"no available indices of class {i} to crop, setting the crop ratio of this class to zero." + ) + + centers = [] + classes = rand_state.choice(len(ratios_), size=num_samples, p=np.asarray(ratios_) / np.sum(ratios_)) + for i in classes: + # randomly select the indices of a class based on the ratios + indices_to_use = indices[i] + random_int = rand_state.randint(len(indices_to_use)) + center = unravel_index(indices_to_use[random_int], label_spatial_shape).tolist() + # shift center to range of valid centers + centers.append(correct_crop_centers(center, spatial_size, label_spatial_shape, allow_smaller)) + + return ensure_tuple(centers) + + +def create_grid( + spatial_size: Sequence[int], + spacing: Sequence[float] | None = None, + homogeneous: bool = True, + dtype: DtypeLike | torch.dtype = float, + device: torch.device | None = None, + backend=TransformBackends.NUMPY, +) -> NdarrayOrTensor: + """ + compute a `spatial_size` mesh. + + - when ``homogeneous=True``, the output shape is (N+1, dim_size_1, dim_size_2, ..., dim_size_N) + - when ``homogeneous=False``, the output shape is (N, dim_size_1, dim_size_2, ..., dim_size_N) + + Args: + spatial_size: spatial size of the grid. + spacing: same len as ``spatial_size``, defaults to 1.0 (dense grid). + homogeneous: whether to make homogeneous coordinates. + dtype: output grid data type, defaults to `float`. + device: device to compute and store the output (when the backend is "torch"). + backend: APIs to use, ``numpy`` or ``torch``. + + """ + _backend = look_up_option(backend, TransformBackends) + _dtype = dtype or float + if _backend == TransformBackends.NUMPY: + return _create_grid_numpy(spatial_size, spacing, homogeneous, _dtype) # type: ignore + if _backend == TransformBackends.TORCH: + return _create_grid_torch(spatial_size, spacing, homogeneous, _dtype, device) # type: ignore + raise ValueError(f"backend {backend} is not supported") + + +def _create_grid_numpy( + spatial_size: Sequence[int], + spacing: Sequence[float] | None = None, + homogeneous: bool = True, + dtype: DtypeLike | torch.dtype = float, +): + """ + compute a `spatial_size` mesh with the numpy API. + """ + spacing = spacing or tuple(1.0 for _ in spatial_size) + ranges = [np.linspace(-(d - 1.0) / 2.0 * s, (d - 1.0) / 2.0 * s, int(d)) for d, s in zip(spatial_size, spacing)] + coords = np.asarray(np.meshgrid(*ranges, indexing="ij"), dtype=get_equivalent_dtype(dtype, np.ndarray)) + if not homogeneous: + return coords + return np.concatenate([coords, np.ones_like(coords[:1])]) + + +def _create_grid_torch( + spatial_size: Sequence[int], + spacing: Sequence[float] | None = None, + homogeneous: bool = True, + dtype=torch.float32, + device: torch.device | None = None, +): + """ + compute a `spatial_size` mesh with the torch API. + """ + spacing = spacing or tuple(1.0 for _ in spatial_size) + ranges = [ + torch.linspace( + -(d - 1.0) / 2.0 * s, + (d - 1.0) / 2.0 * s, + int(d), + device=device, + dtype=get_equivalent_dtype(dtype, torch.Tensor), + ) + for d, s in zip(spatial_size, spacing) + ] + coords = meshgrid_ij(*ranges) + if not homogeneous: + return torch.stack(coords) + return torch.stack([*coords, torch.ones_like(coords[0])]) + + +def create_control_grid( + spatial_shape: Sequence[int], + spacing: Sequence[float], + homogeneous: bool = True, + dtype: DtypeLike = float, + device: torch.device | None = None, + backend=TransformBackends.NUMPY, +): + """ + control grid with two additional point in each direction + """ + torch_backend = look_up_option(backend, TransformBackends) == TransformBackends.TORCH + ceil_func: Callable = torch.ceil if torch_backend else np.ceil # type: ignore + grid_shape = [] + for d, s in zip(spatial_shape, spacing): + d = torch.as_tensor(d, device=device) if torch_backend else int(d) # type: ignore + if d % 2 == 0: + grid_shape.append(ceil_func((d - 1.0) / (2.0 * s) + 0.5) * 2.0 + 2.0) + else: + grid_shape.append(ceil_func((d - 1.0) / (2.0 * s)) * 2.0 + 3.0) + return create_grid( + spatial_size=grid_shape, spacing=spacing, homogeneous=homogeneous, dtype=dtype, device=device, backend=backend + ) + + +def create_rotate( + spatial_dims: int, + radians: Sequence[float] | float, + device: torch.device | None = None, + backend: str = TransformBackends.NUMPY, +) -> NdarrayOrTensor: + """ + create a 2D or 3D rotation matrix + + Args: + spatial_dims: {``2``, ``3``} spatial rank + radians: rotation radians + when spatial_dims == 3, the `radians` sequence corresponds to + rotation in the 1st, 2nd, and 3rd dim respectively. + device: device to compute and store the output (when the backend is "torch"). + backend: APIs to use, ``numpy`` or ``torch``. + + Raises: + ValueError: When ``radians`` is empty. + ValueError: When ``spatial_dims`` is not one of [2, 3]. + + """ + _backend = look_up_option(backend, TransformBackends) + if _backend == TransformBackends.NUMPY: + return _create_rotate( + spatial_dims=spatial_dims, radians=radians, sin_func=np.sin, cos_func=np.cos, eye_func=np.eye + ) + if _backend == TransformBackends.TORCH: + return _create_rotate( + spatial_dims=spatial_dims, + radians=radians, + sin_func=lambda th: torch.sin(torch.as_tensor(th, dtype=torch.float32, device=device)), + cos_func=lambda th: torch.cos(torch.as_tensor(th, dtype=torch.float32, device=device)), + eye_func=lambda rank: torch.eye(rank, device=device), + ) + raise ValueError(f"backend {backend} is not supported") + + +def _create_rotate( + spatial_dims: int, + radians: Sequence[float] | float, + sin_func: Callable = np.sin, + cos_func: Callable = np.cos, + eye_func: Callable = np.eye, +) -> NdarrayOrTensor: + radians = ensure_tuple(radians) + if spatial_dims == 2: + if len(radians) >= 1: + sin_, cos_ = sin_func(radians[0]), cos_func(radians[0]) + out = eye_func(3) + out[0, 0], out[0, 1] = cos_, -sin_ + out[1, 0], out[1, 1] = sin_, cos_ + return out # type: ignore + raise ValueError("radians must be non empty.") + + if spatial_dims == 3: + affine = None + if len(radians) >= 1: + sin_, cos_ = sin_func(radians[0]), cos_func(radians[0]) + affine = eye_func(4) + affine[1, 1], affine[1, 2] = cos_, -sin_ + affine[2, 1], affine[2, 2] = sin_, cos_ + if len(radians) >= 2: + sin_, cos_ = sin_func(radians[1]), cos_func(radians[1]) + if affine is None: + raise ValueError("Affine should be a matrix.") + _affine = eye_func(4) + _affine[0, 0], _affine[0, 2] = cos_, sin_ + _affine[2, 0], _affine[2, 2] = -sin_, cos_ + affine = affine @ _affine + if len(radians) >= 3: + sin_, cos_ = sin_func(radians[2]), cos_func(radians[2]) + if affine is None: + raise ValueError("Affine should be a matrix.") + _affine = eye_func(4) + _affine[0, 0], _affine[0, 1] = cos_, -sin_ + _affine[1, 0], _affine[1, 1] = sin_, cos_ + affine = affine @ _affine + if affine is None: + raise ValueError("radians must be non empty.") + return affine # type: ignore + + raise ValueError(f"Unsupported spatial_dims: {spatial_dims}, available options are [2, 3].") + + +def create_shear( + spatial_dims: int, + coefs: Sequence[float] | float, + device: torch.device | None = None, + backend=TransformBackends.NUMPY, +) -> NdarrayOrTensor: + """ + create a shearing matrix + + Args: + spatial_dims: spatial rank + coefs: shearing factors, a tuple of 2 floats for 2D, a tuple of 6 floats for 3D), + take a 3D affine as example:: + + [ + [1.0, coefs[0], coefs[1], 0.0], + [coefs[2], 1.0, coefs[3], 0.0], + [coefs[4], coefs[5], 1.0, 0.0], + [0.0, 0.0, 0.0, 1.0], + ] + + device: device to compute and store the output (when the backend is "torch"). + backend: APIs to use, ``numpy`` or ``torch``. + + Raises: + NotImplementedError: When ``spatial_dims`` is not one of [2, 3]. + + """ + _backend = look_up_option(backend, TransformBackends) + if _backend == TransformBackends.NUMPY: + return _create_shear(spatial_dims=spatial_dims, coefs=coefs, eye_func=np.eye) + if _backend == TransformBackends.TORCH: + return _create_shear( + spatial_dims=spatial_dims, coefs=coefs, eye_func=lambda rank: torch.eye(rank, device=device) + ) + raise ValueError(f"backend {backend} is not supported") + + +def _create_shear(spatial_dims: int, coefs: Sequence[float] | float, eye_func=np.eye) -> NdarrayOrTensor: + if spatial_dims == 2: + coefs = ensure_tuple_size(coefs, dim=2, pad_val=0.0) + out = eye_func(3) + out[0, 1], out[1, 0] = coefs[0], coefs[1] + return out # type: ignore + if spatial_dims == 3: + coefs = ensure_tuple_size(coefs, dim=6, pad_val=0.0) + out = eye_func(4) + out[0, 1], out[0, 2] = coefs[0], coefs[1] + out[1, 0], out[1, 2] = coefs[2], coefs[3] + out[2, 0], out[2, 1] = coefs[4], coefs[5] + return out # type: ignore + raise NotImplementedError("Currently only spatial_dims in [2, 3] are supported.") + + +def create_scale( + spatial_dims: int, + scaling_factor: Sequence[float] | float, + device: torch.device | str | None = None, + backend=TransformBackends.NUMPY, +) -> NdarrayOrTensor: + """ + create a scaling matrix + + Args: + spatial_dims: spatial rank + scaling_factor: scaling factors for every spatial dim, defaults to 1. + device: device to compute and store the output (when the backend is "torch"). + backend: APIs to use, ``numpy`` or ``torch``. + """ + _backend = look_up_option(backend, TransformBackends) + if _backend == TransformBackends.NUMPY: + return _create_scale(spatial_dims=spatial_dims, scaling_factor=scaling_factor, array_func=np.diag) + if _backend == TransformBackends.TORCH: + return _create_scale( + spatial_dims=spatial_dims, + scaling_factor=scaling_factor, + array_func=lambda x: torch.diag(torch.as_tensor(x, device=device)), + ) + raise ValueError(f"backend {backend} is not supported") + + +def _create_scale(spatial_dims: int, scaling_factor: Sequence[float] | float, array_func=np.diag) -> NdarrayOrTensor: + scaling_factor = ensure_tuple_size(scaling_factor, dim=spatial_dims, pad_val=1.0) + return array_func(scaling_factor[:spatial_dims] + (1.0,)) # type: ignore + + +def create_translate( + spatial_dims: int, + shift: Sequence[float] | float, + device: torch.device | None = None, + backend=TransformBackends.NUMPY, +) -> NdarrayOrTensor: + """ + create a translation matrix + + Args: + spatial_dims: spatial rank + shift: translate pixel/voxel for every spatial dim, defaults to 0. + device: device to compute and store the output (when the backend is "torch"). + backend: APIs to use, ``numpy`` or ``torch``. + """ + _backend = look_up_option(backend, TransformBackends) + spatial_dims = int(spatial_dims) + if _backend == TransformBackends.NUMPY: + return _create_translate(spatial_dims=spatial_dims, shift=shift, eye_func=np.eye, array_func=np.asarray) + if _backend == TransformBackends.TORCH: + return _create_translate( + spatial_dims=spatial_dims, + shift=shift, + eye_func=lambda x: torch.eye(torch.as_tensor(x), device=device), # type: ignore + array_func=lambda x: torch.as_tensor(x, device=device), + ) + raise ValueError(f"backend {backend} is not supported") + + +def _create_translate( + spatial_dims: int, shift: Sequence[float] | float, eye_func=np.eye, array_func=np.asarray +) -> NdarrayOrTensor: + shift = ensure_tuple(shift) + affine = eye_func(spatial_dims + 1) + for i, a in enumerate(shift[:spatial_dims]): + affine[i, spatial_dims] = a + return array_func(affine) # type: ignore + + +@deprecated_arg_default("allow_smaller", old_default=True, new_default=False, since="1.2", replaced="1.5") +def generate_spatial_bounding_box( + img: NdarrayOrTensor, + select_fn: Callable = is_positive, + channel_indices: IndexSelection | None = None, + margin: Sequence[int] | int = 0, + allow_smaller: bool = True, +) -> tuple[list[int], list[int]]: + """ + Generate the spatial bounding box of foreground in the image with start-end positions (inclusive). + Users can define arbitrary function to select expected foreground from the whole image or specified channels. + And it can also add margin to every dim of the bounding box. + The output format of the coordinates is: + + [1st_spatial_dim_start, 2nd_spatial_dim_start, ..., Nth_spatial_dim_start], + [1st_spatial_dim_end, 2nd_spatial_dim_end, ..., Nth_spatial_dim_end] + + This function returns [0, 0, ...], [0, 0, ...] if there's no positive intensity. + + Args: + img: a "channel-first" image of shape (C, spatial_dim1[, spatial_dim2, ...]) to generate bounding box from. + select_fn: function to select expected foreground, default is to select values > 0. + channel_indices: if defined, select foreground only on the specified channels + of image. if None, select foreground on the whole image. + margin: add margin value to spatial dims of the bounding box, if only 1 value provided, use it for all dims. + allow_smaller: when computing box size with `margin`, whether to allow the image edges to be smaller than the + final box edges. If `True`, the bounding boxes edges are aligned with the input image edges, if `False`, + the bounding boxes edges are aligned with the final box edges. Default to `True`. + + """ + check_non_lazy_pending_ops(img, name="generate_spatial_bounding_box") + spatial_size = img.shape[1:] + data = img[list(ensure_tuple(channel_indices))] if channel_indices is not None else img + data = select_fn(data).any(0) + ndim = len(data.shape) + margin = ensure_tuple_rep(margin, ndim) + for m in margin: + if m < 0: + raise ValueError(f"margin value should not be negative number, got {margin}.") + + box_start = [0] * ndim + box_end = [0] * ndim + + for di, ax in enumerate(itertools.combinations(reversed(range(ndim)), ndim - 1)): + dt = data + if len(ax) != 0: + dt = any_np_pt(dt, ax) + + if not dt.any(): + # if no foreground, return all zero bounding box coords + return [0] * ndim, [0] * ndim + + arg_max = where(dt == dt.max())[0] + min_d = arg_max[0] - margin[di] + max_d = arg_max[-1] + margin[di] + 1 + if allow_smaller: + min_d = max(min_d, 0) + max_d = min(max_d, spatial_size[di]) + + box_start[di] = min_d.detach().cpu().item() if isinstance(min_d, torch.Tensor) else min_d + box_end[di] = max_d.detach().cpu().item() if isinstance(max_d, torch.Tensor) else max_d + + return box_start, box_end + + +def get_largest_connected_component_mask( + img: NdarrayTensor, connectivity: int | None = None, num_components: int = 1 +) -> NdarrayTensor: + """ + Gets the largest connected component mask of an image. + + Args: + img: Image to get largest connected component from. Shape is (spatial_dim1 [, spatial_dim2, ...]) + connectivity: Maximum number of orthogonal hops to consider a pixel/voxel as a neighbor. + Accepted values are ranging from 1 to input.ndim. If ``None``, a full + connectivity of ``input.ndim`` is used. for more details: + https://scikit-image.org/docs/dev/api/skimage.measure.html#skimage.measure.label. + num_components: The number of largest components to preserve. + """ + # use skimage/cucim.skimage and np/cp depending on whether packages are + # available and input is non-cpu torch.tensor + skimage, has_cucim = optional_import("cucim.skimage") + use_cp = has_cp and has_cucim and isinstance(img, torch.Tensor) and img.device != torch.device("cpu") + if use_cp: + img_ = convert_to_cupy(img.short()) # type: ignore + label = skimage.measure.label + lib = cp + else: + if not has_measure: + raise RuntimeError("Skimage.measure required.") + img_, *_ = convert_data_type(img, np.ndarray) + label = measure.label + lib = np + + # features will be an image -- 0 for background and then each different + # feature will have its own index. + features, num_features = label(img_, connectivity=connectivity, return_num=True) + # if num features less than max desired, nothing to do. + if num_features <= num_components: + out = img_.astype(bool) + else: + # ignore background + nonzeros = features[lib.nonzero(features)] + # get number voxels per feature (bincount). argsort[::-1] to get indices + # of largest components. + features_to_keep = lib.argsort(lib.bincount(nonzeros))[::-1] + # only keep the first n non-background indices + features_to_keep = features_to_keep[:num_components] + # generate labelfield. True if in list of features to keep + out = lib.isin(features, features_to_keep) + + return convert_to_dst_type(out, dst=img, dtype=out.dtype)[0] + + +def remove_small_objects( + img: NdarrayTensor, + min_size: int = 64, + connectivity: int = 1, + independent_channels: bool = True, + by_measure: bool = False, + pixdim: Sequence[float] | float | np.ndarray | None = None, +) -> NdarrayTensor: + """ + Use `skimage.morphology.remove_small_objects` to remove small objects from images. + See: https://scikit-image.org/docs/dev/api/skimage.morphology.html#remove-small-objects. + + Data should be one-hotted. + + Args: + img: image to process. Expected shape: C, H,W,[D]. Expected to only have singleton channel dimension, + i.e., not be one-hotted. Converted to type int. + min_size: objects smaller than this size are removed. + connectivity: Maximum number of orthogonal hops to consider a pixel/voxel as a neighbor. + Accepted values are ranging from 1 to input.ndim. If ``None``, a full + connectivity of ``input.ndim`` is used. For more details refer to linked scikit-image + documentation. + independent_channels: Whether to consider each channel independently. + by_measure: Whether the specified min_size is in number of voxels. if this is True then min_size + represents a surface area or volume value of whatever units your image is in (mm^3, cm^2, etc.) + default is False. + pixdim: the pixdim of the input image. if a single number, this is used for all axes. + If a sequence of numbers, the length of the sequence must be equal to the image dimensions. + """ + # if all equal to one value, no need to call skimage + if len(unique(img)) == 1: + return img + + if not has_morphology: + raise RuntimeError("Skimage required.") + + if by_measure: + sr = len(img.shape[1:]) + if isinstance(img, monai.data.MetaTensor): + _pixdim = img.pixdim + elif pixdim is not None: + _pixdim = ensure_tuple_rep(pixdim, sr) + else: + warnings.warn("`img` is not of type MetaTensor and `pixdim` is None, assuming affine to be identity.") + _pixdim = (1.0,) * sr + voxel_volume = np.prod(np.array(_pixdim)) + if voxel_volume == 0: + warnings.warn("Invalid `pixdim` value detected, set it to 1. Please verify the pixdim settings.") + voxel_volume = 1 + min_size = np.ceil(min_size / voxel_volume) + elif pixdim is not None: + warnings.warn("`pixdim` is specified but not in use when computing the volume.") + + img_np: np.ndarray + img_np, *_ = convert_data_type(img, np.ndarray) + + # morphology.remove_small_objects assumes them to be independent by default + # else, convert to foreground vs background, remove small objects, then convert + # back by multiplying the output by the input + if not independent_channels: + img_np = img_np > 0 + else: + # if binary, convert to boolean, else int + img_np = img_np.astype(bool if img_np.max() <= 1 else np.int32) + + out_np = morphology.remove_small_objects(img_np, min_size, connectivity) + out, *_ = convert_to_dst_type(out_np, img) + + # convert back by multiplying + if not independent_channels: + out = img * out # type: ignore + return out + + +def get_unique_labels(img: NdarrayOrTensor, is_onehot: bool, discard: int | Iterable[int] | None = None) -> set[int]: + """Get list of non-background labels in an image. + + Args: + img: Image to be processed. Shape should be [C, W, H, [D]] with C=1 if not onehot else `num_classes`. + is_onehot: Boolean as to whether input image is one-hotted. If one-hotted, only return channels with + discard: Can be used to remove labels (e.g., background). Can be any value, sequence of values, or + `None` (nothing is discarded). + + Returns: + Set of labels + """ + applied_labels: set[int] + n_channels = img.shape[0] + if is_onehot: + applied_labels = {i for i, s in enumerate(img) if s.sum() > 0} + else: + if n_channels != 1: + raise ValueError(f"If input not one-hotted, should only be 1 channel, got {n_channels}.") + applied_labels = set(unique(img).tolist()) + if discard is not None: + for i in ensure_tuple(discard): + applied_labels.discard(i) + return applied_labels + + +def fill_holes( + img_arr: np.ndarray, applied_labels: Iterable[int] | None = None, connectivity: int | None = None +) -> np.ndarray: + """ + Fill the holes in the provided image. + + The label 0 will be treated as background and the enclosed holes will be set to the neighboring class label. + What is considered to be an enclosed hole is defined by the connectivity. + Holes on the edge are always considered to be open (not enclosed). + + Note: + + The performance of this method heavily depends on the number of labels. + It is a bit faster if the list of `applied_labels` is provided. + Limiting the number of `applied_labels` results in a big decrease in processing time. + + If the image is one-hot-encoded, then the `applied_labels` need to match the channel index. + + Args: + img_arr: numpy array of shape [C, spatial_dim1[, spatial_dim2, ...]]. + applied_labels: Labels for which to fill holes. Defaults to None, + that is filling holes for all labels. + connectivity: Maximum number of orthogonal hops to + consider a pixel/voxel as a neighbor. Accepted values are ranging from 1 to input.ndim. + Defaults to a full connectivity of ``input.ndim``. + + Returns: + numpy array of shape [C, spatial_dim1[, spatial_dim2, ...]]. + """ + channel_axis = 0 + num_channels = img_arr.shape[channel_axis] + is_one_hot = num_channels > 1 + spatial_dims = img_arr.ndim - 1 + structure = ndimage.generate_binary_structure(spatial_dims, connectivity or spatial_dims) + + # Get labels if not provided. Exclude background label. + applied_labels = set(applied_labels) if applied_labels is not None else get_unique_labels(img_arr, is_one_hot) + background_label = 0 + applied_labels.discard(background_label) + + for label in applied_labels: + tmp = np.zeros(img_arr.shape[1:], dtype=bool) + ndimage.binary_dilation( + tmp, + structure=structure, + iterations=-1, + mask=np.logical_not(img_arr[label]) if is_one_hot else img_arr[0] != label, + origin=0, + border_value=1, + output=tmp, + ) + if is_one_hot: + img_arr[label] = np.logical_not(tmp) + else: + img_arr[0, np.logical_not(tmp)] = label + + return img_arr + + +def get_extreme_points( + img: NdarrayOrTensor, rand_state: np.random.RandomState | None = None, background: int = 0, pert: float = 0.0 +) -> list[tuple[int, ...]]: + """ + Generate extreme points from an image. These are used to generate initial segmentation + for annotation models. An optional perturbation can be passed to simulate user clicks. + + Args: + img: + Image to generate extreme points from. Expected Shape is ``(spatial_dim1, [, spatial_dim2, ...])``. + rand_state: `np.random.RandomState` object used to select random indices. + background: Value to be consider as background, defaults to 0. + pert: Random perturbation amount to add to the points, defaults to 0.0. + + Returns: + A list of extreme points, its length is equal to 2 * spatial dimension of input image. + The output format of the coordinates is: + + [1st_spatial_dim_min, 1st_spatial_dim_max, 2nd_spatial_dim_min, ..., Nth_spatial_dim_max] + + Raises: + ValueError: When the input image does not have any foreground pixel. + """ + check_non_lazy_pending_ops(img, name="get_extreme_points") + if rand_state is None: + rand_state = np.random.random.__self__ # type: ignore + indices = where(img != background) + if np.size(indices[0]) == 0: + raise ValueError("get_extreme_points: no foreground object in mask!") + + def _get_point(val, dim): + """ + Select one of the indices within slice containing val. + + Args: + val : value for comparison + dim : dimension in which to look for value + """ + idx = where(indices[dim] == val)[0] + idx = idx.cpu() if isinstance(idx, torch.Tensor) else idx + idx = rand_state.choice(idx) if rand_state is not None else idx + pt = [] + for j in range(img.ndim): + # add +- pert to each dimension + val = int(indices[j][idx] + 2.0 * pert * (rand_state.rand() if rand_state is not None else 0.5 - 0.5)) + val = max(val, 0) + val = min(val, img.shape[j] - 1) + pt.append(val) + return pt + + points = [] + for i in range(img.ndim): + points.append(tuple(_get_point(indices[i].min(), i))) + points.append(tuple(_get_point(indices[i].max(), i))) + + return points + + +def extreme_points_to_image( + points: list[tuple[int, ...]], + label: NdarrayOrTensor, + sigma: Sequence[float] | float | Sequence[torch.Tensor] | torch.Tensor = 0.0, + rescale_min: float = -1.0, + rescale_max: float = 1.0, +) -> torch.Tensor: + """ + Please refer to :py:class:`monai.transforms.AddExtremePointsChannel` for the usage. + + Applies a gaussian filter to the extreme points image. Then the pixel values in points image are rescaled + to range [rescale_min, rescale_max]. + + Args: + points: Extreme points of the object/organ. + label: label image to get extreme points from. Shape must be + (1, spatial_dim1, [, spatial_dim2, ...]). Doesn't support one-hot labels. + sigma: if a list of values, must match the count of spatial dimensions of input data, + and apply every value in the list to 1 spatial dimension. if only 1 value provided, + use it for all spatial dimensions. + rescale_min: minimum value of output data. + rescale_max: maximum value of output data. + """ + # points to image + # points_image = torch.zeros(label.shape[1:], dtype=torch.float) + points_image = torch.zeros_like(torch.as_tensor(label[0]), dtype=torch.float) + for p in points: + points_image[p] = 1.0 + + if isinstance(sigma, Sequence): + sigma = [torch.as_tensor(s, device=points_image.device) for s in sigma] + else: + sigma = torch.as_tensor(sigma, device=points_image.device) + + # add channel and add batch + points_image = points_image.unsqueeze(0).unsqueeze(0) + gaussian_filter = GaussianFilter(label.ndim - 1, sigma=sigma) + points_image = gaussian_filter(points_image).squeeze(0).detach() + + # rescale the points image to [rescale_min, rescale_max] + min_intensity = points_image.min() + max_intensity = points_image.max() + points_image = (points_image - min_intensity) / (max_intensity - min_intensity) + return points_image * (rescale_max - rescale_min) + rescale_min + + +def map_spatial_axes( + img_ndim: int, spatial_axes: Sequence[int] | int | None = None, channel_first: bool = True +) -> list[int]: + """ + Utility to map the spatial axes to real axes in channel first/last shape. + For example: + If `channel_first` is True, and `img` has 3 spatial dims, map spatial axes to real axes as below: + None -> [1, 2, 3] + [0, 1] -> [1, 2] + [0, -1] -> [1, -1] + If `channel_first` is False, and `img` has 3 spatial dims, map spatial axes to real axes as below: + None -> [0, 1, 2] + [0, 1] -> [0, 1] + [0, -1] -> [0, -2] + + Args: + img_ndim: dimension number of the target image. + spatial_axes: spatial axes to be converted, default is None. + The default `None` will convert to all the spatial axes of the image. + If axis is negative it counts from the last to the first axis. + If axis is a tuple of ints. + channel_first: the image data is channel first or channel last, default to channel first. + + """ + if spatial_axes is None: + return list(range(1, img_ndim) if channel_first else range(img_ndim - 1)) + spatial_axes_ = [] + for a in ensure_tuple(spatial_axes): + if channel_first: + spatial_axes_.append(a % img_ndim if a < 0 else a + 1) + else: + spatial_axes_.append((a - 1) % (img_ndim - 1) if a < 0 else a) + return spatial_axes_ + + +@contextmanager +def allow_missing_keys_mode(transform: MapTransform | Compose | tuple[MapTransform] | tuple[Compose]): + """Temporarily set all MapTransforms to not throw an error if keys are missing. After, revert to original states. + + Args: + transform: either MapTransform or a Compose + + Example: + + .. code-block:: python + + data = {"image": np.arange(16, dtype=float).reshape(1, 4, 4)} + t = SpatialPadd(["image", "label"], 10, allow_missing_keys=False) + _ = t(data) # would raise exception + with allow_missing_keys_mode(t): + _ = t(data) # OK! + """ + # If given a sequence of transforms, Compose them to get a single list + if issequenceiterable(transform): + transform = Compose(transform) + + # Get list of MapTransforms + transforms = [] + if isinstance(transform, MapTransform): + transforms = [transform] + elif isinstance(transform, Compose): + # Only keep contained MapTransforms + transforms = [t for t in transform.flatten().transforms if isinstance(t, MapTransform)] + if len(transforms) == 0: + raise TypeError( + "allow_missing_keys_mode expects either MapTransform(s) or Compose(s) containing MapTransform(s)" + ) + + # Get the state of each `allow_missing_keys` + orig_states = [t.allow_missing_keys for t in transforms] + + try: + # Set all to True + for t in transforms: + t.allow_missing_keys = True + yield + finally: + # Revert + for t, o_s in zip(transforms, orig_states): + t.allow_missing_keys = o_s + + +_interp_modes = list(InterpolateMode) + list(GridSampleMode) + + +def convert_applied_interp_mode(trans_info, mode: str = "nearest", align_corners: bool | None = None): + """ + Recursively change the interpolation mode in the applied operation stacks, default to "nearest". + + See also: :py:class:`monai.transform.inverse.InvertibleTransform` + + Args: + trans_info: applied operation stack, tracking the previously applied invertible transform. + mode: target interpolation mode to convert, default to "nearest" as it's usually used to save the mode output. + align_corners: target align corner value in PyTorch interpolation API, need to align with the `mode`. + + """ + if isinstance(trans_info, (list, tuple)): + return [convert_applied_interp_mode(x, mode=mode, align_corners=align_corners) for x in trans_info] + if not isinstance(trans_info, Mapping): + return trans_info + trans_info = dict(trans_info) + if "mode" in trans_info: + current_mode = trans_info["mode"] + if isinstance(current_mode, int) or current_mode in _interp_modes: + trans_info["mode"] = mode + elif isinstance(current_mode[0], int) or current_mode[0] in _interp_modes: + trans_info["mode"] = [mode for _ in range(len(mode))] + if "align_corners" in trans_info: + _align_corners = TraceKeys.NONE if align_corners is None else align_corners + current_value = trans_info["align_corners"] + trans_info["align_corners"] = ( + [_align_corners for _ in mode] if issequenceiterable(current_value) else _align_corners + ) + if ("mode" not in trans_info) and ("align_corners" not in trans_info): + return { + k: convert_applied_interp_mode(trans_info[k], mode=mode, align_corners=align_corners) for k in trans_info + } + return trans_info + + +def reset_ops_id(data): + """find MetaTensors in list or dict `data` and (in-place) set ``TraceKeys.ID`` to ``Tracekeys.NONE``.""" + if isinstance(data, (list, tuple)): + return [reset_ops_id(d) for d in data] + if isinstance(data, monai.data.MetaTensor): + data.applied_operations = reset_ops_id(data.applied_operations) + return data + if not isinstance(data, Mapping): + return data + data = dict(data) + if TraceKeys.ID in data: + data[TraceKeys.ID] = TraceKeys.NONE + return {k: reset_ops_id(v) for k, v in data.items()} + + +def compute_divisible_spatial_size(spatial_shape: Sequence[int], k: Sequence[int] | int): + """ + Compute the target spatial size which should be divisible by `k`. + + Args: + spatial_shape: original spatial shape. + k: the target k for each spatial dimension. + if `k` is negative or 0, the original size is preserved. + if `k` is an int, the same `k` be applied to all the input spatial dimensions. + + """ + k = fall_back_tuple(k, (1,) * len(spatial_shape)) + new_size = [] + for k_d, dim in zip(k, spatial_shape): + new_dim = int(np.ceil(dim / k_d) * k_d) if k_d > 0 else dim + new_size.append(new_dim) + + return tuple(new_size) + + +def equalize_hist( + img: np.ndarray, mask: np.ndarray | None = None, num_bins: int = 256, min: int = 0, max: int = 255 +) -> np.ndarray: + """ + Utility to equalize input image based on the histogram. + If `skimage` installed, will leverage `skimage.exposure.histogram`, otherwise, use + `np.histogram` instead. + + Args: + img: input image to equalize. + mask: if provided, must be ndarray of bools or 0s and 1s, and same shape as `image`. + only points at which `mask==True` are used for the equalization. + num_bins: number of the bins to use in histogram, default to `256`. for more details: + https://numpy.org/doc/stable/reference/generated/numpy.histogram.html. + min: the min value to normalize input image, default to `0`. + max: the max value to normalize input image, default to `255`. + + """ + + orig_shape = img.shape + hist_img = img[np.array(mask, dtype=bool)] if mask is not None else img + if has_skimage: + hist, bins = exposure.histogram(hist_img.flatten(), num_bins) + else: + hist, bins = np.histogram(hist_img.flatten(), num_bins) + bins = (bins[:-1] + bins[1:]) / 2 + + cum = hist.cumsum() + # normalize the cumulative result + cum = rescale_array(arr=cum, minv=min, maxv=max) + + # apply linear interpolation + img = np.interp(img.flatten(), bins, cum) + return img.reshape(orig_shape) + + +class Fourier: + """ + Helper class storing Fourier mappings + """ + + @staticmethod + def shift_fourier(x: NdarrayOrTensor, spatial_dims: int) -> NdarrayOrTensor: + """ + Applies fourier transform and shifts the zero-frequency component to the + center of the spectrum. Only the spatial dimensions get transformed. + + Args: + x: Image to transform. + spatial_dims: Number of spatial dimensions. + + Returns + k: K-space data. + """ + dims = tuple(range(-spatial_dims, 0)) + k: NdarrayOrTensor + if isinstance(x, torch.Tensor): + if hasattr(torch.fft, "fftshift"): # `fftshift` is new in torch 1.8.0 + k = torch.fft.fftshift(torch.fft.fftn(x, dim=dims), dim=dims) + else: + # if using old PyTorch, will convert to numpy array and return + k = np.fft.fftshift(np.fft.fftn(x.cpu().numpy(), axes=dims), axes=dims) + else: + k = np.fft.fftshift(np.fft.fftn(x, axes=dims), axes=dims) + return k + + @staticmethod + def inv_shift_fourier(k: NdarrayOrTensor, spatial_dims: int, n_dims: int | None = None) -> NdarrayOrTensor: + """ + Applies inverse shift and fourier transform. Only the spatial + dimensions are transformed. + + Args: + k: K-space data. + spatial_dims: Number of spatial dimensions. + + Returns: + x: Tensor in image space. + """ + dims = tuple(range(-spatial_dims, 0)) + out: NdarrayOrTensor + if isinstance(k, torch.Tensor): + if hasattr(torch.fft, "ifftshift"): # `ifftshift` is new in torch 1.8.0 + out = torch.fft.ifftn(torch.fft.ifftshift(k, dim=dims), dim=dims, norm="backward").real + else: + # if using old PyTorch, will convert to numpy array and return + out = np.fft.ifftn(np.fft.ifftshift(k.cpu().numpy(), axes=dims), axes=dims).real + else: + out = np.fft.ifftn(np.fft.ifftshift(k, axes=dims), axes=dims).real + return out + + +def get_number_image_type_conversions(transform: Compose, test_data: Any, key: Hashable | None = None) -> int: + """ + Get the number of times that the data need to be converted (e.g., numpy to torch). + Conversions between different devices are also counted (e.g., CPU to GPU). + + Args: + transform: composed transforms to be tested + test_data: data to be used to count the number of conversions + key: if using dictionary transforms, this key will be used to check the number of conversions. + """ + from monai.transforms.compose import OneOf + + def _get_data(obj, key): + return obj if key is None else obj[key] + + # if the starting point is a string (e.g., input to LoadImage), start + # at -1 since we don't want to count the string -> image conversion. + num_conversions = 0 if not isinstance(_get_data(test_data, key), str) else -1 + + tr = transform.flatten().transforms + + if isinstance(transform, OneOf) or any(isinstance(i, OneOf) for i in tr): + raise RuntimeError("Not compatible with `OneOf`, as the applied transform is deterministically chosen.") + + for _transform in tr: + prev_data = _get_data(test_data, key) + prev_type = type(prev_data) + prev_device = prev_data.device if isinstance(prev_data, torch.Tensor) else None + test_data = apply_transform(_transform, test_data, transform.map_items, transform.unpack_items) + # every time the type or device changes, increment the counter + curr_data = _get_data(test_data, key) + curr_device = curr_data.device if isinstance(curr_data, torch.Tensor) else None + if not isinstance(curr_data, prev_type) or curr_device != prev_device: + num_conversions += 1 + return num_conversions + + +def get_transform_backends(): + """Get the backends of all MONAI transforms. + + Returns: + Dictionary, where each key is a transform, and its + corresponding values are a boolean list, stating + whether that transform supports (1) `torch.Tensor`, + and (2) `np.ndarray` as input without needing to + convert. + """ + backends = {} + unique_transforms = [] + for n, obj in getmembers(monai.transforms): + # skip aliases + if obj in unique_transforms: + continue + unique_transforms.append(obj) + + if ( + isclass(obj) + and issubclass(obj, Transform) + and n + not in [ + "BatchInverseTransform", + "Compose", + "CuCIM", + "CuCIMD", + "Decollated", + "InvertD", + "InvertibleTransform", + "Lambda", + "LambdaD", + "MapTransform", + "OneOf", + "RandCuCIM", + "RandCuCIMD", + "RandomOrder", + "PadListDataCollate", + "RandLambda", + "RandLambdaD", + "RandTorchVisionD", + "RandomizableTransform", + "TorchVisionD", + "Transform", + ] + ): + backends[n] = [TransformBackends.TORCH in obj.backend, TransformBackends.NUMPY in obj.backend] + return backends + + +def print_transform_backends(): + """Prints a list of backends of all MONAI transforms.""" + + class Colors: + none = "" + red = "91" + green = "92" + yellow = "93" + + def print_color(t, color): + print(f"\033[{color}m{t}\033[00m") + + def print_table_column(name, torch, numpy, color=Colors.none): + print_color(f"{name:<50} {torch:<8} {numpy:<8}", color) + + backends = get_transform_backends() + n_total = len(backends) + n_t_or_np, n_t, n_np, n_uncategorized = 0, 0, 0, 0 + print_table_column("Transform", "Torch?", "Numpy?") + for k, v in backends.items(): + if all(v): + color = Colors.green + n_t_or_np += 1 + elif v[0]: + color = Colors.green + n_t += 1 + elif v[1]: + color = Colors.yellow + n_np += 1 + else: + color = Colors.red + n_uncategorized += 1 + print_table_column(k, v[0], v[1], color=color) + + print("Total number of transforms:", n_total) + print_color(f"Number transforms allowing both torch and numpy: {n_t_or_np}", Colors.green) + print_color(f"Number of TorchTransform: {n_t}", Colors.green) + print_color(f"Number of NumpyTransform: {n_np}", Colors.yellow) + print_color(f"Number of uncategorized: {n_uncategorized}", Colors.red) + + +def convert_pad_mode(dst: NdarrayOrTensor, mode: str | None): + """ + Utility to convert padding mode between numpy array and PyTorch Tensor. + + Args: + dst: target data to convert padding mode for, should be numpy array or PyTorch Tensor. + mode: current padding mode. + + """ + if isinstance(dst, torch.Tensor): + if mode == "wrap": + mode = "circular" + elif mode == "edge": + mode = "replicate" + return look_up_option(mode, PytorchPadMode) + if isinstance(dst, np.ndarray): + if mode == "circular": + mode = "wrap" + elif mode == "replicate": + mode = "edge" + return look_up_option(mode, NumpyPadMode) + raise ValueError(f"unsupported data type: {type(dst)}.") + + +def convert_to_contiguous( + data: NdarrayOrTensor | str | bytes | Mapping | Sequence[Any], **kwargs +) -> NdarrayOrTensor | Mapping | Sequence[Any]: + """ + Check and ensure the numpy array or PyTorch Tensor in data to be contiguous in memory. + + Args: + data: input data to convert, will recursively convert the numpy array or PyTorch Tensor in dict and sequence. + kwargs: if `x` is PyTorch Tensor, additional args for `torch.contiguous`, more details: + https://pytorch.org/docs/stable/generated/torch.Tensor.contiguous.html#torch.Tensor.contiguous. + + """ + if isinstance(data, (np.ndarray, torch.Tensor, str, bytes)): + return ascontiguousarray(data, **kwargs) + elif isinstance(data, Mapping): + return {k: convert_to_contiguous(v, **kwargs) for k, v in data.items()} + elif isinstance(data, Sequence): + return type(data)(convert_to_contiguous(i, **kwargs) for i in data) # type: ignore + else: + return data + + +def scale_affine(spatial_size, new_spatial_size, centered: bool = True): + """ + Compute the scaling matrix according to the new spatial size + + Args: + spatial_size: original spatial size. + new_spatial_size: new spatial size. + centered: whether the scaling is with respect to the image center (True, default) or corner (False). + + Returns: + the scaling matrix. + + """ + r = max(len(new_spatial_size), len(spatial_size)) + if spatial_size == new_spatial_size: + return np.eye(r + 1) + s = np.array([float(o) / float(max(n, 1)) for o, n in zip(spatial_size, new_spatial_size)], dtype=float) + scale = create_scale(r, s.tolist()) + if centered: + scale[:r, -1] = (np.diag(scale)[:r] - 1) / 2.0 # type: ignore + return scale + + +def attach_hook(func, hook, mode="pre"): + """ + Adds `hook` before or after a `func` call. If mode is "pre", the wrapper will call hook then func. + If the mode is "post", the wrapper will call func then hook. + """ + supported = {"pre", "post"} + if look_up_option(mode, supported) == "pre": + _hook, _func = hook, func + else: + _hook, _func = func, hook + + @wraps(func) + def wrapper(inst, data): + data = _hook(inst, data) + return _func(inst, data) + + return wrapper + + +def sync_meta_info(key, data_dict, t: bool = True): + """ + Given the key, sync up between metatensor `data_dict[key]` and meta_dict `data_dict[key_transforms/meta_dict]`. + t=True: the one with more applied_operations in metatensor vs meta_dict is the output, False: less is the output. + """ + if not isinstance(data_dict, Mapping): + return data_dict + d = dict(data_dict) + + # update meta dicts + meta_dict_key = PostFix.meta(key) + if meta_dict_key not in d: + d[meta_dict_key] = monai.data.MetaTensor.get_default_meta() + if not isinstance(d[key], monai.data.MetaTensor): + d[key] = monai.data.MetaTensor(data_dict[key]) + d[key].meta = d[meta_dict_key] + d[meta_dict_key].update(d[key].meta) # prefer metatensor's data + + # update xform info + xform_key = monai.transforms.TraceableTransform.trace_key(key) + if xform_key not in d: + d[xform_key] = monai.data.MetaTensor.get_default_applied_operations() + from_meta, from_dict = d[key].applied_operations, d[xform_key] + if not from_meta: # avoid [] + d[key].applied_operations = d[xform_key] = from_dict + return d + if not from_dict: + d[key].applied_operations = d[xform_key] = from_meta + return d + if t: # larger transform info stack is used as the result + ref = from_meta if len(from_meta) > len(from_dict) else from_dict + else: # smaller transform info stack is used as the result + ref = from_dict if len(from_meta) > len(from_dict) else from_meta + d[key].applied_operations = d[xform_key] = ref + return d + + +def check_boundaries(boundaries) -> None: + """ + Check boundaries for Signal transforms + """ + if not ( + isinstance(boundaries, Sequence) and len(boundaries) == 2 and all(isinstance(i, float) for i in boundaries) + ): + raise ValueError("Incompatible values: boundaries needs to be a list of float.") + + +def paste_slices(tup): + """ + given a tuple (pos,w,max_w), return a tuple of slices + """ + pos, w, max_w = tup + max_w = max_w.shape[-1] + orig_min = max(pos, 0) + orig_max = min(pos + w, max_w) + block_min = -min(pos, 0) + block_max = max_w - max(pos + w, max_w) + block_max = block_max if block_max != 0 else None + return slice(orig_min, orig_max), slice(block_min, block_max) + + +def paste(orig, block, loc): + """ + given a location (loc) and an original array (orig), paste a block array into it + """ + loc_zip = zip(loc, block.shape, orig) + orig_slices, block_slices = zip(*map(paste_slices, loc_zip)) + + orig[:, orig_slices[0]] = block[block_slices[0]] + + if orig.shape[0] == 1: + orig = orig.squeeze() + return orig + + +def squarepulse(sig, duty: float = 0.5): + """ + compute squarepulse using pytorch + equivalent to numpy implementation from + https://docs.scipy.org/doc/scipy/reference/generated/scipy.signal.square.html + """ + t, w = convert_to_tensor(sig), convert_to_tensor(duty) + w = convert_to_tensor(w) + t = convert_to_tensor(t) + + y = torch.zeros(t.shape) + + mask1 = (w > 1) | (w < 0) + + tmod = torch.remainder(t, 2 * torch.pi) + mask2 = (~mask1) & (tmod < w * 2 * torch.pi) + y[mask2] = 1 + mask3 = (~mask1) & (~mask2) + y[mask3] = -1 + return y + + +def _to_numpy_resample_interp_mode(interp_mode): + ret = look_up_option(str(interp_mode), SplineMode, default=None) + if ret is not None: + return int(ret) + _mapping = { + InterpolateMode.NEAREST: SplineMode.ZERO, + InterpolateMode.NEAREST_EXACT: SplineMode.ZERO, + InterpolateMode.LINEAR: SplineMode.ONE, + InterpolateMode.BILINEAR: SplineMode.ONE, + InterpolateMode.TRILINEAR: SplineMode.ONE, + InterpolateMode.BICUBIC: SplineMode.THREE, + InterpolateMode.AREA: SplineMode.ZERO, + } + ret = look_up_option(str(interp_mode), _mapping, default=None) + if ret is not None: + return ret + return look_up_option(str(interp_mode), list(_mapping) + list(SplineMode)) # for better error msg + + +def _to_torch_resample_interp_mode(interp_mode): + ret = look_up_option(str(interp_mode), InterpolateMode, default=None) + if ret is not None: + return ret + _mapping = { + SplineMode.ZERO: InterpolateMode.NEAREST_EXACT if pytorch_after(1, 11) else InterpolateMode.NEAREST, + SplineMode.ONE: InterpolateMode.LINEAR, + SplineMode.THREE: InterpolateMode.BICUBIC, + } + ret = look_up_option(str(interp_mode), _mapping, default=None) + if ret is not None: + return ret + return look_up_option(str(interp_mode), list(_mapping) + list(InterpolateMode)) + + +def _to_numpy_resample_padding_mode(m): + ret = look_up_option(str(m), NdimageMode, default=None) + if ret is not None: + return ret + _mapping = { + GridSamplePadMode.ZEROS: NdimageMode.CONSTANT, + GridSamplePadMode.BORDER: NdimageMode.NEAREST, + GridSamplePadMode.REFLECTION: NdimageMode.REFLECT, + } + ret = look_up_option(str(m), _mapping, default=None) + if ret is not None: + return ret + return look_up_option(str(m), list(_mapping) + list(NdimageMode)) + + +def _to_torch_resample_padding_mode(m): + ret = look_up_option(str(m), GridSamplePadMode, default=None) + if ret is not None: + return ret + _mapping = { + NdimageMode.CONSTANT: GridSamplePadMode.ZEROS, + NdimageMode.GRID_CONSTANT: GridSamplePadMode.ZEROS, + NdimageMode.NEAREST: GridSamplePadMode.BORDER, + NdimageMode.REFLECT: GridSamplePadMode.REFLECTION, + NdimageMode.WRAP: GridSamplePadMode.REFLECTION, + NdimageMode.GRID_WRAP: GridSamplePadMode.REFLECTION, + NdimageMode.GRID_MIRROR: GridSamplePadMode.REFLECTION, + } + ret = look_up_option(str(m), _mapping, default=None) + if ret is not None: + return ret + return look_up_option(str(m), list(_mapping) + list(GridSamplePadMode)) + + +@lru_cache(None) +def resolves_modes( + interp_mode: str | None = "constant", padding_mode="zeros", backend=TransformBackends.TORCH, **kwargs +): + """ + Automatically adjust the resampling interpolation mode and padding mode, + so that they are compatible with the corresponding API of the `backend`. + Depending on the availability of the backends, when there's no exact + equivalent, a similar mode is returned. + + Args: + interp_mode: interpolation mode. + padding_mode: padding mode. + backend: optional backend of `TransformBackends`. If None, the backend will be decided from `interp_mode`. + kwargs: additional keyword arguments. currently support ``torch_interpolate_spatial_nd``, to provide + additional information to determine ``linear``, ``bilinear`` and ``trilinear``; + ``use_compiled`` to use MONAI's precompiled backend (pytorch c++ extensions), default to ``False``. + """ + _interp_mode, _padding_mode, _kwargs = None, None, (kwargs or {}).copy() + if backend is None: # infer backend + backend = ( + TransformBackends.NUMPY + if look_up_option(str(interp_mode), SplineMode, default=None) is not None + else TransformBackends.TORCH + ) + if backend == TransformBackends.NUMPY: + _interp_mode = _to_numpy_resample_interp_mode(interp_mode) + _padding_mode = _to_numpy_resample_padding_mode(padding_mode) + return backend, _interp_mode, _padding_mode, _kwargs + _interp_mode = _to_torch_resample_interp_mode(interp_mode) + _padding_mode = _to_torch_resample_padding_mode(padding_mode) + if str(_interp_mode).endswith("linear"): + nd = _kwargs.pop("torch_interpolate_spatial_nd", 2) + if nd == 1: + _interp_mode = InterpolateMode.LINEAR + elif nd == 3: + _interp_mode = InterpolateMode.TRILINEAR + else: + _interp_mode = InterpolateMode.BILINEAR # torch grid_sample bilinear is trilinear in 3D + if not _kwargs.pop("use_compiled", False): + return backend, _interp_mode, _padding_mode, _kwargs + _padding_mode = 1 if _padding_mode == "reflection" else _padding_mode + if _interp_mode == "bicubic": + _interp_mode = 3 + elif str(_interp_mode).endswith("linear"): + _interp_mode = 1 + else: + _interp_mode = GridSampleMode(_interp_mode) + return backend, _interp_mode, _padding_mode, _kwargs + + +def check_applied_operations(entry: list | dict, status_key: str, default_message: str = "No message provided"): + """ + Check the operations of a MetaTensor to determine whether there are any statuses + Args: + entry: a dictionary that may contain TraceKey.STATUS entries, or a list of such dictionaries + status_key: the status key to search for. This must be an entry in `TraceStatusKeys`_ + default_message: The message to provide if no messages are provided for the given status key entry + + Returns: + A list of status messages matching the providing status key + + """ + if isinstance(entry, list): + results = list() + for sub_entry in entry: + results.extend(check_applied_operations(sub_entry, status_key, default_message)) + return results + else: + status_key_ = TraceStatusKeys(status_key) + if TraceKeys.STATUSES in entry: + if status_key_ in entry[TraceKeys.STATUSES]: + reason = entry[TraceKeys.STATUSES][status_key_] + if reason is None: + return [default_message] + return reason if isinstance(reason, list) else [reason] + return [] + + +def has_status_keys(data: torch.Tensor, status_key: Any, default_message: str = "No message provided"): + """ + Checks whether a given tensor is has a particular status key message on any of its + applied operations. If it doesn't, it returns the tuple `(False, None)`. If it does + it returns a tuple of True and a list of status messages for that status key. + + Status keys are defined in :class:`TraceStatusKeys`. + + This function also accepts: + + * dictionaries of tensors + * lists or tuples of tensors + * list or tuples of dictionaries of tensors + + In any of the above scenarios, it iterates through the collections and executes itself recursively until it is + operating on tensors. + + Args: + data: a `torch.Tensor` or `MetaTensor` or collections of torch.Tensor or MetaTensor, as described above + status_key: the status key to look for, from `TraceStatusKeys` + default_message: a default message to use if the status key entry doesn't have a message set + + Returns: + A tuple. The first entry is `False` or `True`. The second entry is the status messages that can be used for the + user to help debug their pipelines. + + """ + status_key_occurrences = list() + if isinstance(data, (list, tuple)): + for d in data: + _, reasons = has_status_keys(d, status_key, default_message) + if reasons is not None: + status_key_occurrences.extend(reasons) + elif isinstance(data, monai.data.MetaTensor): + for op in data.applied_operations: + status_key_occurrences.extend(check_applied_operations(op, status_key, default_message)) + elif isinstance(data, dict): + for d in data.values(): + _, reasons = has_status_keys(d, status_key, default_message) + if reasons is not None: + status_key_occurrences.extend(reasons) + + if len(status_key_occurrences) > 0: + return False, status_key_occurrences + return True, None + + +def distance_transform_edt( + img: NdarrayOrTensor, + sampling: None | float | list[float] = None, + return_distances: bool = True, + return_indices: bool = False, + distances: NdarrayOrTensor | None = None, + indices: NdarrayOrTensor | None = None, + *, + block_params: tuple[int, int, int] | None = None, + float64_distances: bool = False, +) -> None | NdarrayOrTensor | tuple[NdarrayOrTensor, NdarrayOrTensor]: + """ + Euclidean distance transform, either GPU based with CuPy / cuCIM or CPU based with scipy. + To use the GPU implementation, make sure cuCIM is available and that the data is a `torch.tensor` on a GPU device. + + Note that the results of the libraries can differ, so stick to one if possible. + For details, check out the `SciPy`_ and `cuCIM`_ documentation. + + .. _SciPy: https://docs.scipy.org/doc/scipy/reference/generated/scipy.ndimage.distance_transform_edt.html + .. _cuCIM: https://docs.rapids.ai/api/cucim/nightly/api/#cucim.core.operations.morphology.distance_transform_edt + + Args: + img: Input image on which the distance transform shall be run. + Has to be a channel first array, must have shape: (num_channels, H, W [,D]). + Can be of any type but will be converted into binary: 1 wherever image equates to True, 0 elsewhere. + Input gets passed channel-wise to the distance-transform, thus results from this function will differ + from directly calling ``distance_transform_edt()`` in CuPy or SciPy. + sampling: Spacing of elements along each dimension. If a sequence, must be of length equal to the input rank -1; + if a single number, this is used for all axes. If not specified, a grid spacing of unity is implied. + return_distances: Whether to calculate the distance transform. + return_indices: Whether to calculate the feature transform. + distances: An output array to store the calculated distance transform, instead of returning it. + `return_distances` must be True. + indices: An output array to store the calculated feature transform, instead of returning it. `return_indicies` must be True. + block_params: This parameter is specific to cuCIM and does not exist in SciPy. For details, look into `cuCIM`_. + float64_distances: This parameter is specific to cuCIM and does not exist in SciPy. + If True, use double precision in the distance computation (to match SciPy behavior). + Otherwise, single precision will be used for efficiency. + + Returns: + distances: The calculated distance transform. Returned only when `return_distances` is True and `distances` is not supplied. + It will have the same shape and type as image. For cuCIM: Will have dtype torch.float64 if float64_distances is True, + otherwise it will have dtype torch.float32. For SciPy: Will have dtype np.float64. + indices: The calculated feature transform. It has an image-shaped array for each dimension of the image. + The type will be equal to the type of the image. + Returned only when `return_indices` is True and `indices` is not supplied. dtype np.float64. + + """ + distance_transform_edt, has_cucim = optional_import( + "cucim.core.operations.morphology", name="distance_transform_edt" + ) + use_cp = has_cp and has_cucim and isinstance(img, torch.Tensor) and img.device.type == "cuda" + if not return_distances and not return_indices: + raise RuntimeError("Neither return_distances nor return_indices True") + + if not (img.ndim >= 3 and img.ndim <= 4): + raise RuntimeError("Wrong input dimensionality. Use (num_channels, H, W [,D])") + + distances_original, indices_original = distances, indices + distances, indices = None, None + if use_cp: + distances_, indices_ = None, None + if return_distances: + dtype = torch.float64 if float64_distances else torch.float32 + if distances is None: + distances = torch.zeros_like(img, memory_format=torch.contiguous_format, dtype=dtype) # type: ignore + else: + if not isinstance(distances, torch.Tensor) and distances.device != img.device: + raise TypeError("distances must be a torch.Tensor on the same device as img") + if not distances.dtype == dtype: + raise TypeError("distances must be a torch.Tensor of dtype float32 or float64") + distances_ = convert_to_cupy(distances) + if return_indices: + dtype = torch.int32 + if indices is None: + indices = torch.zeros((img.dim(),) + img.shape, dtype=dtype) # type: ignore + else: + if not isinstance(indices, torch.Tensor) and indices.device != img.device: + raise TypeError("indices must be a torch.Tensor on the same device as img") + if not indices.dtype == dtype: + raise TypeError("indices must be a torch.Tensor of dtype int32") + indices_ = convert_to_cupy(indices) + img_ = convert_to_cupy(img) + for channel_idx in range(img_.shape[0]): + distance_transform_edt( + img_[channel_idx], + sampling=sampling, + return_distances=return_distances, + return_indices=return_indices, + distances=distances_[channel_idx] if distances_ is not None else None, + indices=indices_[channel_idx] if indices_ is not None else None, + block_params=block_params, + float64_distances=float64_distances, + ) + else: + if not has_ndimage: + raise RuntimeError("scipy.ndimage required if cupy is not available") + img_ = convert_to_numpy(img) + if return_distances: + if distances is None: + distances = np.zeros_like(img_, dtype=np.float64) + else: + if not isinstance(distances, np.ndarray): + raise TypeError("distances must be a numpy.ndarray") + if not distances.dtype == np.float64: + raise TypeError("distances must be a numpy.ndarray of dtype float64") + if return_indices: + if indices is None: + indices = np.zeros((img_.ndim,) + img_.shape, dtype=np.int32) + else: + if not isinstance(indices, np.ndarray): + raise TypeError("indices must be a numpy.ndarray") + if not indices.dtype == np.int32: + raise TypeError("indices must be a numpy.ndarray of dtype int32") + + for channel_idx in range(img_.shape[0]): + ndimage.distance_transform_edt( + img_[channel_idx], + sampling=sampling, + return_distances=return_distances, + return_indices=return_indices, + distances=distances[channel_idx] if distances is not None else None, + indices=indices[channel_idx] if indices is not None else None, + ) + + r_vals = [] + if return_distances and distances_original is None: + r_vals.append(distances) + if return_indices and indices_original is None: + r_vals.append(indices) + if not r_vals: + return None + device = img.device if isinstance(img, torch.Tensor) else None + return convert_data_type(r_vals[0] if len(r_vals) == 1 else r_vals, output_type=type(img), device=device)[0] + + +if __name__ == "__main__": + print_transform_backends() diff --git a/source_code/SegMamba/monai/transforms/utils_create_transform_ims.py b/source_code/SegMamba/monai/transforms/utils_create_transform_ims.py new file mode 100644 index 0000000000000000000000000000000000000000..4b5990abd3b03096ed3dcda0fc2fa7ffed0f35ef --- /dev/null +++ b/source_code/SegMamba/monai/transforms/utils_create_transform_ims.py @@ -0,0 +1,752 @@ +# Copyright (c) MONAI Consortium +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from __future__ import annotations + +import os +import pathlib +import tempfile +import textwrap +from copy import deepcopy +from glob import glob +from typing import TYPE_CHECKING + +import numpy as np +import torch + +from monai.apps import download_and_extract +from monai.transforms import ( + Affine, + Affined, + AsDiscrete, + Compose, + EnsureChannelFirstd, + Flip, + Flipd, + LoadImaged, + MapTransform, + Orientation, + Orientationd, + Rand3DElastic, + Rand3DElasticd, + RandFlip, + RandFlipd, + Randomizable, + RandRotate, + RandRotated, + RandZoom, + RandZoomd, + Rotate, + Rotate90, + Rotate90d, + Rotated, + ScaleIntensity, + ScaleIntensityd, + SpatialPadd, + Zoom, + Zoomd, +) +from monai.transforms.croppad.array import ( + BorderPad, + CenterScaleCrop, + CenterSpatialCrop, + CropForeground, + DivisiblePad, + RandCropByLabelClasses, + RandCropByPosNegLabel, + RandScaleCrop, + RandSpatialCrop, + RandSpatialCropSamples, + RandWeightedCrop, + ResizeWithPadOrCrop, + SpatialCrop, + SpatialPad, +) +from monai.transforms.croppad.dictionary import ( + BorderPadd, + CenterScaleCropd, + CenterSpatialCropd, + CropForegroundd, + DivisiblePadd, + RandCropByLabelClassesd, + RandCropByPosNegLabeld, + RandScaleCropd, + RandSpatialCropd, + RandSpatialCropSamplesd, + RandWeightedCropd, + ResizeWithPadOrCropd, + SpatialCropd, +) +from monai.transforms.intensity.array import ( + AdjustContrast, + ForegroundMask, + GaussianSharpen, + GaussianSmooth, + GibbsNoise, + HistogramNormalize, + KSpaceSpikeNoise, + MaskIntensity, + MedianSmooth, + NormalizeIntensity, + RandAdjustContrast, + RandBiasField, + RandCoarseDropout, + RandCoarseShuffle, + RandGaussianNoise, + RandGaussianSharpen, + RandGaussianSmooth, + RandGibbsNoise, + RandHistogramShift, + RandKSpaceSpikeNoise, + RandRicianNoise, + RandScaleIntensity, + RandShiftIntensity, + RandStdShiftIntensity, + SavitzkyGolaySmooth, + ScaleIntensityRange, + ScaleIntensityRangePercentiles, + ShiftIntensity, + StdShiftIntensity, + ThresholdIntensity, +) +from monai.transforms.intensity.dictionary import ( + AdjustContrastd, + ForegroundMaskd, + GaussianSharpend, + GaussianSmoothd, + GibbsNoised, + HistogramNormalized, + KSpaceSpikeNoised, + MaskIntensityd, + MedianSmoothD, + NormalizeIntensityd, + RandAdjustContrastd, + RandBiasFieldd, + RandCoarseDropoutd, + RandCoarseShuffled, + RandGaussianNoised, + RandGaussianSharpend, + RandGaussianSmoothd, + RandGibbsNoised, + RandHistogramShiftd, + RandKSpaceSpikeNoised, + RandRicianNoised, + RandScaleIntensityd, + RandShiftIntensityd, + RandStdShiftIntensityd, + SavitzkyGolaySmoothd, + ScaleIntensityRanged, + ScaleIntensityRangePercentilesd, + ShiftIntensityd, + StdShiftIntensityd, + ThresholdIntensityd, +) +from monai.transforms.post.array import KeepLargestConnectedComponent, LabelFilter, LabelToContour, RemoveSmallObjects +from monai.transforms.post.dictionary import ( + AsDiscreted, + KeepLargestConnectedComponentd, + LabelFilterd, + LabelToContourd, + RemoveSmallObjectsd, +) +from monai.transforms.smooth_field.array import ( + RandSmoothDeform, + RandSmoothFieldAdjustContrast, + RandSmoothFieldAdjustIntensity, +) +from monai.transforms.smooth_field.dictionary import ( + RandSmoothDeformd, + RandSmoothFieldAdjustContrastd, + RandSmoothFieldAdjustIntensityd, +) +from monai.transforms.spatial.array import ( + GridDistortion, + Rand2DElastic, + RandAffine, + RandAxisFlip, + RandGridDistortion, + RandRotate90, + Resize, + Spacing, +) +from monai.transforms.spatial.dictionary import ( + GridDistortiond, + Rand2DElasticd, + RandAffined, + RandAxisFlipd, + RandGridDistortiond, + RandRotate90d, + Resized, + Spacingd, +) +from monai.utils.enums import CommonKeys +from monai.utils.misc import MONAIEnvVars +from monai.utils.module import optional_import + +if TYPE_CHECKING: + import matplotlib.pyplot as plt + + has_matplotlib = True + +else: + plt, has_matplotlib = optional_import("matplotlib.pyplot") + + +def get_data(keys): + """Get the example data to be used. + + Use MarsAtlas as it only contains 1 image for quick download and + that image is parcellated. + """ + cache_dir = MONAIEnvVars.data_dir() or tempfile.mkdtemp() + fname = "MarsAtlas-MNI-Colin27.zip" + url = "https://www.dropbox.com/s/ndz8qtqblkciole/" + fname + "?dl=1" + out_path = os.path.join(cache_dir, "MarsAtlas-MNI-Colin27") + zip_path = os.path.join(cache_dir, fname) + + download_and_extract(url, zip_path, out_path) + + image, label = sorted(glob(os.path.join(out_path, "*.nii"))) + + transforms = Compose( + [ + LoadImaged(keys), + EnsureChannelFirstd(keys), + ScaleIntensityd(CommonKeys.IMAGE), + Rotate90d(keys, spatial_axes=(0, 2)), + ] + ) + data = transforms({CommonKeys.IMAGE: image, CommonKeys.LABEL: label}) + max_size = max(data[keys[0]].shape) + padder = SpatialPadd(keys, (max_size, max_size, max_size)) + return padder(data) + + +def update_docstring(code_path, transform_name): + """ + Find the documentation for a given transform and if it's missing, + add a pointer to the transform's example image. + """ + with open(code_path) as f: + contents = f.readlines() + doc_start = None + for i, line in enumerate(contents): + # find the line containing start of the transform documentation + if "`" + transform_name + "`" in line: + doc_start = i + break + if doc_start is None: + raise RuntimeError("Couldn't find transform documentation") + + # if image is already in docs, nothing to do + image_line = doc_start + 2 + if ".. image" in contents[image_line]: + return + + # add the line for the image and the alt text + contents_orig = deepcopy(contents) + contents.insert( + image_line, + ".. image:: https://github.com/Project-MONAI/DocImages/raw/main/transforms/" + transform_name + ".png\n", + ) + contents.insert(image_line + 1, " :alt: example of " + transform_name + "\n") + + # check that we've only added two lines + if len(contents) != len(contents_orig) + 2: + raise AssertionError + + # write the updated doc to overwrite the original + with open(code_path, "w") as f: + f.writelines(contents) + + +def pre_process_data(data, ndim, is_map, is_post): + """If transform requires 2D data, then convert to 2D""" + if ndim == 2: + for k in keys: + data[k] = data[k][..., data[k].shape[-1] // 2] + + if is_map: + return data + return data[CommonKeys.LABEL] if is_post else data[CommonKeys.IMAGE] + + +def get_2d_slice(image, view: int, is_label): + """If image is 3d, get the central slice. If is already 2d, return as-is. + If image is label, set 0 to np.nan. + """ + if image.ndim == 2: + out = image + else: + shape = image.shape + slices = [slice(0, s) for s in shape] + _slice = shape[view] // 2 + slices[view] = slice(_slice, _slice + 1) + out = np.squeeze(image[tuple(slices)], view) + if is_label: + out[out == 0] = np.nan + return out + + +def get_stacked_2d_ims(im, is_label): + """Get the 3 orthogonal views and stack them into 1 image. + Requires that all images be same size, but this is taken care + of by the `SpatialPadd` earlier. + """ + return [get_2d_slice(im, i, is_label) for i in range(3)] + + +def get_stacked_before_after(before, after, is_label=False): + """Stack before and after images into 1 image if 3d. + Requires that before and after images be the same size. + """ + return [get_stacked_2d_ims(d, is_label) for d in (before, after)] + + +def save_image(images, labels, filename, transform_name, transform_args, shapes, colorbar=False): + """Save image to file, ensuring there's no whitespace around the edge.""" + plt.rcParams.update({"font.family": "monospace"}) + plt.style.use("dark_background") + nrow = len(images) # before and after (should always be 2) + ncol = len(images[0]) # num orthogonal views (either 1 or 3) + # roughly estimate the height_ratios of the first:second row + hs = [float(r[0].shape[0]) for r in images] + fig = plt.figure(tight_layout=True) + spec = fig.add_gridspec(nrow, ncol, hspace=0, wspace=0, height_ratios=hs) + for row in range(nrow): + vmin = min(i.min() for i in images[row]) + vmax = max(i.max() for i in images[row]) + for col in range(ncol): + ax = fig.add_subplot(spec[row, col]) + imshow = ax.imshow(images[row][col], cmap="gray", vmin=vmin, vmax=vmax) + ax.set_aspect("equal") + if colorbar and col == ncol - 1: + plt.colorbar(imshow, ax=ax) + if col == 0: + y_label = "After" if row else "Before" + y_label += ("\n" + shapes[row]) if shapes[0] != shapes[1] else "" + ax.set_ylabel(y_label) + # print yticks for the right most column + if col != ncol - 1 or colorbar: + ax.set_yticks([]) + else: + ax.yaxis.tick_right() + for n, label in enumerate(ax.yaxis.get_ticklabels()): + if n > 2: + label.set_visible(False) + ax.set_xticks([]) + ax.set_frame_on(False) + if labels is not None: + ax.imshow(labels[row][col], cmap="hsv", alpha=0.9, interpolation="nearest") + # title is e.g., Flipd(keys=keys, spatial_axis=0) + title = transform_name + "(" + for k, v in transform_args.items(): + title += k + "=" + if isinstance(v, str): + title += "'" + v + "'" + elif isinstance(v, (np.ndarray, torch.Tensor)): + title += "[array]" + elif callable(v): + title += "[callable]" + else: + title += str(v) + title += ", " + if len(transform_args) > 0: + title = title[:-2] + title += ")" + # shorten the lines + title = textwrap.fill(title, 50, break_long_words=False, subsequent_indent=" " * (len(transform_name) + 1)) + fig.suptitle(title, x=0.1, horizontalalignment="left") + fig.savefig(filename) + plt.close(fig) + + +def get_images(data, is_label=False): + """Get image. If is dictionary, extract key. If is list, stack. If both dictionary and list, do both. + Also return the image size as string to be used im the imshow. If it's a list, return `N x (H,W,D)`. + """ + # If not a list, convert + if not isinstance(data, list): + data = [data] + key = CommonKeys.LABEL if is_label else CommonKeys.IMAGE + is_map = isinstance(data[0], dict) + # length of the list will be equal to number of samples produced. This will be 1 except for transforms that + # produce `num_samples`. + data = [d[key] if is_map else d for d in data] + data = [d[0] for d in data] # remove channel component + + # for each sample, create a list of the orthogonal views. If image is 2d, length will be 1. If 3d, there + # will be three orthogonal views + num_samples = len(data) + num_orthog_views = 3 if data[0].ndim == 3 else 1 + shape_str = (f"{num_samples} x " if num_samples > 1 else "") + str(data[0].shape) + for i in range(num_samples): + data[i] = [get_2d_slice(data[i], view, is_label) for view in range(num_orthog_views)] + + out = [] + if num_samples == 1: + out = data[0] + else: + # we might need to panel the images. this happens if a transform produces e.g. 4 output images. + # In this case, we create a 2-by-2 grid from them. Output will be a list containing n_orthog_views, + # each element being either the image (if num_samples is 1) or the panelled image. + nrows = int(np.floor(num_samples**0.5)) + for view in range(num_orthog_views): + result = np.asarray([d[view] for d in data]) + nindex, height, width = result.shape + ncols = nindex // nrows + # only implemented for square number of images (e.g. 4 images goes to a 2-by-2 panel) + if nindex != nrows * ncols: + raise NotImplementedError + # want result.shape = (height*nrows, width*ncols), have to be careful about striding + result = result.reshape(nrows, ncols, height, width).swapaxes(1, 2).reshape(height * nrows, width * ncols) + out.append(result) + return out, shape_str + + +def create_transform_im( + transform, transform_args, data, ndim=3, colorbar=False, update_doc=True, seed=0, is_post=False +): + """Create an image with the before and after of the transform. + Also update the transform's documentation to point to this image.""" + + transform = transform(**transform_args) + + if not has_matplotlib: + raise RuntimeError + + if isinstance(transform, Randomizable): + # increment the seed for map transforms so they're different to the array versions. + seed = seed + 1 if isinstance(transform, MapTransform) else seed + transform.set_random_state(seed) + + out_dir = MONAIEnvVars.doc_images() + if out_dir is None: + raise RuntimeError( + "Please git clone https://github.com/Project-MONAI/DocImages" + + " and then set the environment variable `MONAI_DOC_IMAGES`" + ) + out_dir = os.path.join(out_dir, "transforms") + + # Path is transform name + transform_name = transform.__class__.__name__ + out_fname = transform_name + ".png" + out_file = os.path.join(out_dir, out_fname) + + is_map = isinstance(transform, MapTransform) + data_in = pre_process_data(deepcopy(data), ndim, is_map, is_post) + + data_tr = transform(deepcopy(data_in)) + + images_before, before_shape = get_images(data_in) + images_after, after_shape = get_images(data_tr) + images = (images_before, images_after) + shapes = (before_shape, after_shape) + + labels = None + if is_map: + labels_before, *_ = get_images(data_in, is_label=True) + labels_after, *_ = get_images(data_tr, is_label=True) + labels = (labels_before, labels_after) + + save_image(images, labels, out_file, transform_name, transform_args, shapes, colorbar) + + if update_doc: + base_dir = pathlib.Path(__file__).parent.parent.parent + rst_path = os.path.join(base_dir, "docs", "source", "transforms.rst") + update_docstring(rst_path, transform_name) + + +if __name__ == "__main__": + keys = [CommonKeys.IMAGE, CommonKeys.LABEL] + data = get_data(keys) + create_transform_im(RandFlip, dict(prob=1, spatial_axis=1), data) + create_transform_im(RandFlipd, dict(keys=keys, prob=1, spatial_axis=2), data) + create_transform_im(Flip, dict(spatial_axis=1), data) + create_transform_im(Flipd, dict(keys=keys, spatial_axis=2), data) + create_transform_im(Orientation, dict(axcodes="RPI"), data) + create_transform_im(Orientationd, dict(keys=keys, axcodes="RPI"), data) + create_transform_im( + Rand3DElastic, dict(prob=1.0, sigma_range=(1, 2), magnitude_range=(0.5, 0.5), shear_range=(1, 1, 1)), data + ) + create_transform_im(Affine, dict(shear_params=(0, 0.5, 0), image_only=True, padding_mode="zeros"), data) + create_transform_im( + Affined, dict(keys=keys, shear_params=(0, 0.5, 0), mode=["bilinear", "nearest"], padding_mode="zeros"), data + ) + create_transform_im(RandAffine, dict(prob=1, shear_range=(0.5, 0.5), padding_mode="zeros"), data) + create_transform_im( + RandAffined, + dict(keys=keys, prob=1, shear_range=(0.5, 0.5), mode=["bilinear", "nearest"], padding_mode="zeros"), + data, + ) + create_transform_im( + Rand3DElastic, dict(sigma_range=(5, 7), magnitude_range=(50, 150), prob=1, padding_mode="zeros"), data + ) + create_transform_im( + Rand2DElastic, dict(prob=1, spacing=(20, 20), magnitude_range=(1, 2), padding_mode="zeros"), data, 2 + ) + create_transform_im( + Rand2DElasticd, + dict( + keys=keys, + prob=1, + spacing=(20, 20), + magnitude_range=(1, 2), + padding_mode="zeros", + mode=["bilinear", "nearest"], + ), + data, + 2, + ) + create_transform_im( + Rand3DElasticd, + dict( + keys=keys, + sigma_range=(5, 7), + magnitude_range=(50, 150), + prob=1, + padding_mode="zeros", + mode=["bilinear", "nearest"], + ), + data, + ) + create_transform_im(Rotate90, dict(spatial_axes=(1, 2)), data) + create_transform_im(Rotate90d, dict(keys=keys, spatial_axes=(1, 2)), data) + create_transform_im(RandRotate90, dict(prob=1), data) + create_transform_im(RandRotate90d, dict(keys=keys, prob=1), data) + create_transform_im(Rotate, dict(angle=0.1), data) + create_transform_im(Rotated, dict(keys=keys, angle=0.1, mode=["bilinear", "nearest"]), data) + create_transform_im(RandRotate, dict(prob=1, range_x=[0.4, 0.4]), data) + create_transform_im(RandRotated, dict(keys=keys, prob=1, range_x=[0.4, 0.4], mode=["bilinear", "nearest"]), data) + create_transform_im(Zoom, dict(zoom=0.6), data) + create_transform_im(Zoomd, dict(keys=keys, zoom=1.3, mode=["area", "nearest"]), data) + create_transform_im(RandZoom, dict(prob=1, min_zoom=0.6, max_zoom=0.8), data) + create_transform_im(RandZoomd, dict(keys=keys, prob=1, min_zoom=1.3, max_zoom=1.5, mode=["area", "nearest"]), data) + create_transform_im(ScaleIntensity, dict(minv=0, maxv=10), data, colorbar=True) + create_transform_im(ScaleIntensityd, dict(keys=CommonKeys.IMAGE, minv=0, maxv=10), data, colorbar=True) + create_transform_im(RandScaleIntensity, dict(prob=1.0, factors=(5, 10)), data, colorbar=True) + create_transform_im( + RandScaleIntensityd, dict(keys=CommonKeys.IMAGE, prob=1.0, factors=(5, 10)), data, colorbar=True + ) + create_transform_im(DivisiblePad, dict(k=64), data) + create_transform_im(DivisiblePadd, dict(keys=keys, k=64), data) + create_transform_im(CropForeground, dict(allow_smaller=False), data) + create_transform_im(CropForegroundd, dict(keys=keys, source_key=CommonKeys.IMAGE, allow_smaller=False), data) + create_transform_im(RandGaussianNoise, dict(prob=1, mean=0, std=0.1), data) + create_transform_im(RandGaussianNoised, dict(keys=CommonKeys.IMAGE, prob=1, mean=0, std=0.1), data) + create_transform_im(KSpaceSpikeNoise, dict(loc=(100, 100, 100), k_intensity=13), data) + create_transform_im(KSpaceSpikeNoised, dict(keys=CommonKeys.IMAGE, loc=(100, 100, 100), k_intensity=13), data) + create_transform_im(RandKSpaceSpikeNoise, dict(prob=1, intensity_range=(10, 13)), data) + create_transform_im(RandKSpaceSpikeNoised, dict(keys=CommonKeys.IMAGE, prob=1, intensity_range=(13, 15)), data) + create_transform_im(RandRicianNoise, dict(prob=1.0, mean=1, std=0.5), data) + create_transform_im(RandRicianNoised, dict(keys=CommonKeys.IMAGE, prob=1.0, mean=1, std=0.5), data) + create_transform_im(SavitzkyGolaySmooth, dict(window_length=5, order=1), data) + create_transform_im(SavitzkyGolaySmoothd, dict(keys=CommonKeys.IMAGE, window_length=5, order=1), data) + create_transform_im(GibbsNoise, dict(alpha=0.8), data) + create_transform_im(GibbsNoised, dict(keys=CommonKeys.IMAGE, alpha=0.8), data) + create_transform_im(RandGibbsNoise, dict(prob=1.0, alpha=(0.6, 0.8)), data) + create_transform_im(RandGibbsNoised, dict(keys=CommonKeys.IMAGE, prob=1.0, alpha=(0.6, 0.8)), data) + create_transform_im(ShiftIntensity, dict(offset=1), data, colorbar=True) + create_transform_im(ShiftIntensityd, dict(keys=CommonKeys.IMAGE, offset=1), data, colorbar=True) + create_transform_im(RandShiftIntensity, dict(prob=1.0, offsets=(10, 20)), data, colorbar=True) + create_transform_im( + RandShiftIntensityd, dict(keys=CommonKeys.IMAGE, prob=1.0, offsets=(10, 20)), data, colorbar=True + ) + create_transform_im(StdShiftIntensity, dict(factor=10), data, colorbar=True) + create_transform_im(StdShiftIntensityd, dict(keys=CommonKeys.IMAGE, factor=10), data, colorbar=True) + create_transform_im(RandStdShiftIntensity, dict(prob=1.0, factors=(5, 10)), data, colorbar=True) + create_transform_im( + RandStdShiftIntensityd, dict(keys=CommonKeys.IMAGE, prob=1.0, factors=(5, 10)), data, colorbar=True + ) + create_transform_im(RandBiasField, dict(prob=1, coeff_range=(0.2, 0.3)), data) + create_transform_im(RandBiasFieldd, dict(keys=CommonKeys.IMAGE, prob=1, coeff_range=(0.2, 0.3)), data) + create_transform_im(NormalizeIntensity, dict(subtrahend=0, divisor=10), data, colorbar=True) + create_transform_im(NormalizeIntensityd, dict(keys=CommonKeys.IMAGE, subtrahend=0, divisor=10), data, colorbar=True) + create_transform_im(ThresholdIntensity, dict(threshold=0.4, above=False, cval=0.9), data, colorbar=True) + create_transform_im( + ThresholdIntensityd, dict(keys=CommonKeys.IMAGE, threshold=0.4, above=False, cval=0.9), data, colorbar=True + ) + create_transform_im(ScaleIntensityRange, dict(a_min=0, a_max=1, b_min=1, b_max=10), data, colorbar=True) + create_transform_im( + ScaleIntensityRanged, dict(keys=CommonKeys.IMAGE, a_min=0, a_max=1, b_min=1, b_max=10), data, colorbar=True + ) + create_transform_im(ScaleIntensityRangePercentiles, dict(lower=5, upper=95, b_min=1, b_max=10), data, colorbar=True) + create_transform_im( + ScaleIntensityRangePercentilesd, + dict(keys=CommonKeys.IMAGE, lower=5, upper=95, b_min=1, b_max=10), + data, + colorbar=True, + ) + create_transform_im(AdjustContrast, dict(gamma=2), data, colorbar=True) + create_transform_im(AdjustContrastd, dict(keys=CommonKeys.IMAGE, gamma=2), data, colorbar=True) + create_transform_im(RandAdjustContrast, dict(prob=1, gamma=(1.5, 2)), data, colorbar=True) + create_transform_im(RandAdjustContrastd, dict(keys=CommonKeys.IMAGE, prob=1, gamma=(1.5, 2)), data, colorbar=True) + create_transform_im(MaskIntensity, dict(mask_data=data[CommonKeys.IMAGE], select_fn=lambda x: x > 0.3), data) + create_transform_im( + MaskIntensityd, dict(keys=CommonKeys.IMAGE, mask_key=CommonKeys.IMAGE, select_fn=lambda x: x > 0.3), data + ) + create_transform_im(ForegroundMask, dict(invert=True), data) + create_transform_im(ForegroundMaskd, dict(keys=CommonKeys.IMAGE, invert=True), data) + create_transform_im(GaussianSmooth, dict(sigma=2), data) + create_transform_im(GaussianSmoothd, dict(keys=CommonKeys.IMAGE, sigma=2), data) + create_transform_im(MedianSmooth, dict(radius=3), data) + create_transform_im(MedianSmoothD, dict(keys=keys, radius=1), data) + create_transform_im(RandGaussianSmooth, dict(prob=1.0, sigma_x=(1, 2)), data) + create_transform_im(RandGaussianSmoothd, dict(keys=CommonKeys.IMAGE, prob=1.0, sigma_x=(1, 2)), data) + create_transform_im(GaussianSharpen, dict(), GaussianSmoothd(CommonKeys.IMAGE, 2)(data)) + create_transform_im(GaussianSharpend, dict(keys=CommonKeys.IMAGE), GaussianSmoothd(CommonKeys.IMAGE, 2)(data)) + create_transform_im(RandGaussianSharpen, dict(prob=1), GaussianSmoothd(CommonKeys.IMAGE, 2)(data)) + create_transform_im( + RandGaussianSharpend, dict(keys=CommonKeys.IMAGE, prob=1), GaussianSmoothd(CommonKeys.IMAGE, 2)(data) + ) + create_transform_im(RandHistogramShift, dict(prob=1, num_control_points=3), data, colorbar=True) + create_transform_im( + RandHistogramShiftd, dict(keys=CommonKeys.IMAGE, prob=1, num_control_points=3), data, colorbar=True + ) + create_transform_im(RandCoarseDropout, dict(prob=1, holes=200, spatial_size=20, fill_value=0), data) + create_transform_im( + RandCoarseDropoutd, dict(keys=CommonKeys.IMAGE, prob=1, holes=200, spatial_size=20, fill_value=0), data + ) + create_transform_im(RandCoarseShuffle, dict(prob=1, holes=200, spatial_size=20), data) + create_transform_im(RandCoarseShuffled, dict(keys=CommonKeys.IMAGE, prob=1, holes=200, spatial_size=20), data) + create_transform_im(HistogramNormalize, dict(num_bins=10), data) + create_transform_im(HistogramNormalized, dict(keys=CommonKeys.IMAGE, num_bins=10), data) + create_transform_im(SpatialPad, dict(spatial_size=(300, 300, 300)), data) + create_transform_im(SpatialPadd, dict(keys=keys, spatial_size=(300, 300, 300)), data) + create_transform_im(BorderPad, dict(spatial_border=10), data) + create_transform_im(BorderPadd, dict(keys=keys, spatial_border=10), data) + create_transform_im(SpatialCrop, dict(roi_center=(75, 75, 75), roi_size=(100, 100, 100)), data) + create_transform_im(SpatialCropd, dict(keys=keys, roi_center=(75, 75, 75), roi_size=(100, 100, 100)), data) + create_transform_im(CenterSpatialCrop, dict(roi_size=(100, 100, 100)), data) + create_transform_im(CenterSpatialCropd, dict(keys=keys, roi_size=(100, 100, 100)), data) + create_transform_im(RandSpatialCrop, dict(roi_size=(100, 100, 100), random_size=False), data) + create_transform_im(RandSpatialCropd, dict(keys=keys, roi_size=(100, 100, 100), random_size=False), data) + create_transform_im(RandSpatialCropSamples, dict(num_samples=4, roi_size=(100, 100, 100), random_size=False), data) + create_transform_im( + RandSpatialCropSamplesd, dict(keys=keys, num_samples=4, roi_size=(100, 100, 100), random_size=False), data + ) + create_transform_im( + RandWeightedCrop, dict(spatial_size=(100, 100, 100), num_samples=4, weight_map=data[CommonKeys.IMAGE] > 0), data + ) + create_transform_im( + RandWeightedCropd, dict(keys=keys, spatial_size=(100, 100, 100), num_samples=4, w_key=CommonKeys.IMAGE), data + ) + create_transform_im( + RandCropByPosNegLabel, + dict(spatial_size=(100, 100, 100), label=data[CommonKeys.LABEL], neg=0, num_samples=4), + data, + ) + create_transform_im( + RandCropByPosNegLabeld, + dict(keys=keys, spatial_size=(100, 100, 100), label_key=CommonKeys.LABEL, neg=0, num_samples=4), + data, + ) + create_transform_im( + RandCropByLabelClasses, + dict( + spatial_size=(100, 100, 100), label=data[CommonKeys.LABEL] > 0, num_classes=2, ratios=[0, 1], num_samples=4 + ), + data, + ) + create_transform_im( + RandCropByLabelClassesd, + dict( + keys=keys, + spatial_size=(100, 100, 100), + label_key=CommonKeys.LABEL, + num_classes=2, + ratios=[0, 1], + num_samples=4, + ), + data, + ) + create_transform_im(ResizeWithPadOrCrop, dict(spatial_size=(100, 100, 100)), data) + create_transform_im(ResizeWithPadOrCropd, dict(keys=keys, spatial_size=(100, 100, 100)), data) + create_transform_im(RandScaleCrop, dict(roi_scale=0.4), data) + create_transform_im(RandScaleCropd, dict(keys=keys, roi_scale=0.4), data) + create_transform_im(CenterScaleCrop, dict(roi_scale=0.4), data) + create_transform_im(CenterScaleCropd, dict(keys=keys, roi_scale=0.4), data) + create_transform_im(AsDiscrete, dict(to_onehot=None, threshold=10), data, is_post=True, colorbar=True) + create_transform_im(AsDiscreted, dict(keys=CommonKeys.LABEL, to_onehot=None, threshold=10), data, is_post=True) + create_transform_im(LabelFilter, dict(applied_labels=(1, 2, 3, 4, 5, 6)), data, is_post=True) + create_transform_im( + LabelFilterd, dict(keys=CommonKeys.LABEL, applied_labels=(1, 2, 3, 4, 5, 6)), data, is_post=True + ) + create_transform_im(LabelToContour, dict(), data, is_post=True) + create_transform_im(LabelToContourd, dict(keys=CommonKeys.LABEL), data, is_post=True) + create_transform_im(Spacing, dict(pixdim=(5, 5, 5)), data) + create_transform_im(Spacingd, dict(keys=keys, pixdim=(5, 5, 5), mode=["bilinear", "nearest"]), data) + create_transform_im(RandAxisFlip, dict(prob=1), data) + create_transform_im(RandAxisFlipd, dict(keys=keys, prob=1), data) + create_transform_im(Resize, dict(spatial_size=(100, 100, 100)), data) + create_transform_im(Resized, dict(keys=keys, spatial_size=(100, 100, 100), mode=["area", "nearest"]), data) + data_binary = deepcopy(data) + data_binary[CommonKeys.LABEL] = (data_binary[CommonKeys.LABEL] > 0).astype(np.float32) + create_transform_im(KeepLargestConnectedComponent, dict(applied_labels=1), data_binary, is_post=True, ndim=2) + create_transform_im( + KeepLargestConnectedComponentd, dict(keys=CommonKeys.LABEL, applied_labels=1), data_binary, is_post=True, ndim=2 + ) + create_transform_im(RemoveSmallObjects, dict(min_size=100), data_binary, is_post=True, ndim=2) + create_transform_im( + RemoveSmallObjectsd, dict(keys=CommonKeys.LABEL, min_size=100), data_binary, is_post=True, ndim=2 + ) + create_transform_im( + GridDistortion, dict(num_cells=3, distort_steps=[(1.5,) * 4] * 3, mode="nearest", padding_mode="zeros"), data + ) + create_transform_im( + GridDistortiond, + dict( + keys=keys, num_cells=3, distort_steps=[(1.5,) * 4] * 3, mode=["bilinear", "nearest"], padding_mode="zeros" + ), + data, + ) + create_transform_im(RandGridDistortion, dict(num_cells=3, prob=1.0, distort_limit=(-0.1, 0.1)), data) + create_transform_im( + RandGridDistortiond, + dict(keys=keys, num_cells=4, prob=1.0, distort_limit=(-0.2, 0.2), mode=["bilinear", "nearest"]), + data, + ) + create_transform_im( + RandSmoothFieldAdjustContrast, dict(spatial_size=(217, 217, 217), rand_size=(10, 10, 10), prob=1.0), data + ) + create_transform_im( + RandSmoothFieldAdjustContrastd, + dict(keys=keys, spatial_size=(217, 217, 217), rand_size=(10, 10, 10), prob=1.0), + data, + ) + create_transform_im( + RandSmoothFieldAdjustIntensity, + dict(spatial_size=(217, 217, 217), rand_size=(10, 10, 10), prob=1.0, gamma=(0.5, 4.5)), + data, + ) + create_transform_im( + RandSmoothFieldAdjustIntensityd, + dict(keys=keys, spatial_size=(217, 217, 217), rand_size=(10, 10, 10), prob=1.0, gamma=(0.5, 4.5)), + data, + ) + + create_transform_im( + RandSmoothDeform, + dict(spatial_size=(217, 217, 217), rand_size=(10, 10, 10), prob=1.0, def_range=0.05, grid_mode="bilinear"), + data, + ) + create_transform_im( + RandSmoothDeformd, + dict( + keys=keys, + spatial_size=(217, 217, 217), + rand_size=(10, 10, 10), + prob=1.0, + def_range=0.05, + grid_mode="bilinear", + ), + data, + ) diff --git a/source_code/SegMamba/monai/transforms/utils_pytorch_numpy_unification.py b/source_code/SegMamba/monai/transforms/utils_pytorch_numpy_unification.py new file mode 100644 index 0000000000000000000000000000000000000000..020d99af1657db5eada41fe1182ce51711cfce36 --- /dev/null +++ b/source_code/SegMamba/monai/transforms/utils_pytorch_numpy_unification.py @@ -0,0 +1,593 @@ +# Copyright (c) MONAI Consortium +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from __future__ import annotations + +from collections.abc import Sequence +from typing import TypeVar + +import numpy as np +import torch + +from monai.config.type_definitions import NdarrayOrTensor, NdarrayTensor +from monai.utils.misc import is_module_ver_at_least +from monai.utils.type_conversion import convert_data_type, convert_to_dst_type + +__all__ = [ + "allclose", + "moveaxis", + "in1d", + "clip", + "percentile", + "where", + "argwhere", + "argsort", + "nonzero", + "floor_divide", + "unravel_index", + "unravel_indices", + "ravel", + "any_np_pt", + "maximum", + "concatenate", + "cumsum", + "isfinite", + "searchsorted", + "repeat", + "isnan", + "ascontiguousarray", + "stack", + "mode", + "unique", + "max", + "min", + "median", + "mean", + "std", + "softplus", +] + + +def softplus(x: NdarrayOrTensor) -> NdarrayOrTensor: + """stable softplus through `np.logaddexp` with equivalent implementation for torch. + + Args: + x: array/tensor. + + Returns: + Softplus of the input. + """ + if isinstance(x, np.ndarray): + return np.logaddexp(np.zeros_like(x), x) + return torch.logaddexp(torch.zeros_like(x), x) + + +def allclose(a: NdarrayTensor, b: NdarrayOrTensor, rtol=1e-5, atol=1e-8, equal_nan=False) -> bool: + """`np.allclose` with equivalent implementation for torch.""" + b, *_ = convert_to_dst_type(b, a, wrap_sequence=True) + if isinstance(a, np.ndarray): + return np.allclose(a, b, rtol=rtol, atol=atol, equal_nan=equal_nan) + return torch.allclose(a, b, rtol=rtol, atol=atol, equal_nan=equal_nan) # type: ignore + + +def moveaxis(x: NdarrayOrTensor, src: int | Sequence[int], dst: int | Sequence[int]) -> NdarrayOrTensor: + """`moveaxis` for pytorch and numpy""" + if isinstance(x, torch.Tensor): + return torch.movedim(x, src, dst) # type: ignore + return np.moveaxis(x, src, dst) + + +def in1d(x, y): + """`np.in1d` with equivalent implementation for torch.""" + if isinstance(x, np.ndarray): + return np.in1d(x, y) + return (x[..., None] == torch.tensor(y, device=x.device)).any(-1).view(-1) + + +def clip(a: NdarrayOrTensor, a_min, a_max) -> NdarrayOrTensor: + """`np.clip` with equivalent implementation for torch.""" + result: NdarrayOrTensor + if isinstance(a, np.ndarray): + result = np.clip(a, a_min, a_max) + else: + result = torch.clamp(a, a_min, a_max) + return result + + +def percentile( + x: NdarrayOrTensor, q, dim: int | None = None, keepdim: bool = False, **kwargs +) -> NdarrayOrTensor | float | int: + """`np.percentile` with equivalent implementation for torch. + + Pytorch uses `quantile`. For more details please refer to: + https://pytorch.org/docs/stable/generated/torch.quantile.html. + https://numpy.org/doc/stable/reference/generated/numpy.percentile.html. + + Args: + x: input data. + q: percentile to compute (should in range 0 <= q <= 100). + dim: the dim along which the percentiles are computed. default is to compute the percentile + along a flattened version of the array. + keepdim: whether the output data has dim retained or not. + kwargs: if `x` is numpy array, additional args for `np.percentile`, more details: + https://numpy.org/doc/stable/reference/generated/numpy.percentile.html. + + Returns: + Resulting value (scalar) + """ + q_np = convert_data_type(q, output_type=np.ndarray, wrap_sequence=True)[0] + if ((q_np < 0) | (q_np > 100)).any(): + raise ValueError(f"q values must be in [0, 100], got values: {q}.") + result: NdarrayOrTensor | float | int + if isinstance(x, np.ndarray) or (isinstance(x, torch.Tensor) and torch.numel(x) > 1_000_000): # pytorch#64947 + _x = convert_data_type(x, output_type=np.ndarray)[0] + result = np.percentile(_x, q_np, axis=dim, keepdims=keepdim, **kwargs) + result = convert_to_dst_type(result, x)[0] + else: + q = convert_to_dst_type(q_np / 100.0, x)[0] + result = torch.quantile(x, q, dim=dim, keepdim=keepdim) + return result + + +def where(condition: NdarrayOrTensor, x=None, y=None) -> NdarrayOrTensor: + """ + Note that `torch.where` may convert y.dtype to x.dtype. + """ + result: NdarrayOrTensor + if isinstance(condition, np.ndarray): + if x is not None: + result = np.where(condition, x, y) + else: + result = np.where(condition) # type: ignore + else: + if x is not None: + x = torch.as_tensor(x, device=condition.device) + y = torch.as_tensor(y, device=condition.device, dtype=x.dtype) + result = torch.where(condition, x, y) + else: + result = torch.where(condition) # type: ignore + return result + + +def argwhere(a: NdarrayTensor) -> NdarrayTensor: + """`np.argwhere` with equivalent implementation for torch. + + Args: + a: input data. + + Returns: + Indices of elements that are non-zero. Indices are grouped by element. + This array will have shape (N, a.ndim) where N is the number of non-zero items. + """ + if isinstance(a, np.ndarray): + return np.argwhere(a) # type: ignore + return torch.argwhere(a) # type: ignore + + +def argsort(a: NdarrayTensor, axis: int | None = -1) -> NdarrayTensor: + """`np.argsort` with equivalent implementation for torch. + + Args: + a: the array/tensor to sort. + axis: axis along which to sort. + + Returns: + Array/Tensor of indices that sort a along the specified axis. + """ + if isinstance(a, np.ndarray): + return np.argsort(a, axis=axis) # type: ignore + return torch.argsort(a, dim=axis) # type: ignore + + +def nonzero(x: NdarrayOrTensor) -> NdarrayOrTensor: + """`np.nonzero` with equivalent implementation for torch. + + Args: + x: array/tensor. + + Returns: + Index unravelled for given shape + """ + if isinstance(x, np.ndarray): + return np.nonzero(x)[0] + return torch.nonzero(x).flatten() + + +def floor_divide(a: NdarrayOrTensor, b) -> NdarrayOrTensor: + """`np.floor_divide` with equivalent implementation for torch. + + As of pt1.8, use `torch.div(..., rounding_mode="floor")`, and + before that, use `torch.floor_divide`. + + Args: + a: first array/tensor + b: scalar to divide by + + Returns: + Element-wise floor division between two arrays/tensors. + """ + if isinstance(a, torch.Tensor): + if is_module_ver_at_least(torch, (1, 8, 0)): + return torch.div(a, b, rounding_mode="floor") + return torch.floor_divide(a, b) + return np.floor_divide(a, b) + + +def unravel_index(idx, shape) -> NdarrayOrTensor: + """`np.unravel_index` with equivalent implementation for torch. + + Args: + idx: index to unravel. + shape: shape of array/tensor. + + Returns: + Index unravelled for given shape + """ + if isinstance(idx, torch.Tensor): + coord = [] + for dim in reversed(shape): + coord.append(idx % dim) + idx = floor_divide(idx, dim) + return torch.stack(coord[::-1]) + return np.asarray(np.unravel_index(idx, shape)) + + +def unravel_indices(idx, shape) -> NdarrayOrTensor: + """Computing unravel coordinates from indices. + + Args: + idx: a sequence of indices to unravel. + shape: shape of array/tensor. + + Returns: + Stacked indices unravelled for given shape + """ + lib_stack = torch.stack if isinstance(idx[0], torch.Tensor) else np.stack + return lib_stack([unravel_index(i, shape) for i in idx]) # type: ignore + + +def ravel(x: NdarrayOrTensor) -> NdarrayOrTensor: + """`np.ravel` with equivalent implementation for torch. + + Args: + x: array/tensor to ravel. + + Returns: + Return a contiguous flattened array/tensor. + """ + if isinstance(x, torch.Tensor): + if hasattr(torch, "ravel"): # `ravel` is new in torch 1.8.0 + return x.ravel() + return x.flatten().contiguous() + return np.ravel(x) + + +def any_np_pt(x: NdarrayOrTensor, axis: int | Sequence[int]) -> NdarrayOrTensor: + """`np.any` with equivalent implementation for torch. + + For pytorch, convert to boolean for compatibility with older versions. + + Args: + x: input array/tensor. + axis: axis to perform `any` over. + + Returns: + Return a contiguous flattened array/tensor. + """ + if isinstance(x, np.ndarray): + return np.any(x, axis) # type: ignore + + # pytorch can't handle multiple dimensions to `any` so loop across them + axis = [axis] if not isinstance(axis, Sequence) else axis + for ax in axis: + try: + x = torch.any(x, ax) + except RuntimeError: + # older versions of pytorch require the input to be cast to boolean + x = torch.any(x.bool(), ax) + return x + + +def maximum(a: NdarrayOrTensor, b: NdarrayOrTensor) -> NdarrayOrTensor: + """`np.maximum` with equivalent implementation for torch. + + Args: + a: first array/tensor. + b: second array/tensor. + + Returns: + Element-wise maximum between two arrays/tensors. + """ + if isinstance(a, torch.Tensor) and isinstance(b, torch.Tensor): + return torch.maximum(a, b) + return np.maximum(a, b) + + +def concatenate(to_cat: Sequence[NdarrayOrTensor], axis: int = 0, out=None) -> NdarrayOrTensor: + """`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 + return torch.cat(to_cat, dim=axis, out=out) # type: ignore + + +def cumsum(a: NdarrayOrTensor, axis=None, **kwargs) -> NdarrayOrTensor: + """ + `np.cumsum` with equivalent implementation for torch. + + Args: + a: input data to compute cumsum. + axis: expected axis to compute cumsum. + kwargs: if `a` is PyTorch Tensor, additional args for `torch.cumsum`, more details: + https://pytorch.org/docs/stable/generated/torch.cumsum.html. + + """ + + if isinstance(a, np.ndarray): + return np.cumsum(a, axis) # type: ignore + if axis is None: + return torch.cumsum(a[:], 0, **kwargs) + return torch.cumsum(a, dim=axis, **kwargs) + + +def isfinite(x: NdarrayOrTensor) -> NdarrayOrTensor: + """`np.isfinite` with equivalent implementation for torch.""" + if not isinstance(x, torch.Tensor): + return np.isfinite(x) # type: ignore + return torch.isfinite(x) + + +def searchsorted(a: NdarrayTensor, v: NdarrayOrTensor, right=False, sorter=None, **kwargs) -> NdarrayTensor: + """ + `np.searchsorted` with equivalent implementation for torch. + + Args: + a: numpy array or tensor, containing monotonically increasing sequence on the innermost dimension. + v: containing the search values. + right: if False, return the first suitable location that is found, if True, return the last such index. + sorter: if `a` is numpy array, optional array of integer indices that sort array `a` into ascending order. + kwargs: if `a` is PyTorch Tensor, additional args for `torch.searchsorted`, more details: + https://pytorch.org/docs/stable/generated/torch.searchsorted.html. + + """ + side = "right" if right else "left" + if isinstance(a, np.ndarray): + return np.searchsorted(a, v, side, sorter) # type: ignore + return torch.searchsorted(a, v, right=right, **kwargs) # type: ignore + + +def repeat(a: NdarrayOrTensor, repeats: int, axis: int | None = None, **kwargs) -> NdarrayOrTensor: + """ + `np.repeat` with equivalent implementation for torch (`repeat_interleave`). + + Args: + a: input data to repeat. + repeats: number of repetitions for each element, repeats is broadcast to fit the shape of the given axis. + axis: axis along which to repeat values. + kwargs: if `a` is PyTorch Tensor, additional args for `torch.repeat_interleave`, more details: + https://pytorch.org/docs/stable/generated/torch.repeat_interleave.html. + + """ + if isinstance(a, np.ndarray): + return np.repeat(a, repeats, axis) + return torch.repeat_interleave(a, repeats, dim=axis, **kwargs) + + +def isnan(x: NdarrayOrTensor) -> NdarrayOrTensor: + """`np.isnan` with equivalent implementation for torch. + + Args: + x: array/tensor. + + """ + if isinstance(x, np.ndarray): + return np.isnan(x) # type: ignore + return torch.isnan(x) + + +T = TypeVar("T") + + +def ascontiguousarray(x: NdarrayTensor | T, **kwargs) -> NdarrayOrTensor | T: + """`np.ascontiguousarray` with equivalent implementation for torch (`contiguous`). + + Args: + x: array/tensor. + kwargs: if `x` is PyTorch Tensor, additional args for `torch.contiguous`, more details: + https://pytorch.org/docs/stable/generated/torch.Tensor.contiguous.html. + + """ + if isinstance(x, np.ndarray): + if x.ndim == 0: + return x + return np.ascontiguousarray(x) + if isinstance(x, torch.Tensor): + return x.contiguous(**kwargs) + return x + + +def stack(x: Sequence[NdarrayTensor], dim: int) -> NdarrayTensor: + """`np.stack` with equivalent implementation for torch. + + Args: + x: array/tensor. + dim: dimension along which to perform the stack (referred to as `axis` by numpy). + """ + if isinstance(x[0], np.ndarray): + return np.stack(x, dim) # type: ignore + return torch.stack(x, dim) # type: ignore + + +def mode(x: NdarrayTensor, dim: int = -1, to_long: bool = True) -> NdarrayTensor: + """`torch.mode` with equivalent implementation for numpy. + + Args: + x: array/tensor. + dim: dimension along which to perform `mode` (referred to as `axis` by numpy). + to_long: convert input to long before performing mode. + """ + dtype = torch.int64 if to_long else None + x_t, *_ = convert_data_type(x, torch.Tensor, dtype=dtype) + o_t = torch.mode(x_t, dim).values + o, *_ = convert_to_dst_type(o_t, x) + return o + + +def unique(x: NdarrayTensor, **kwargs) -> NdarrayTensor: + """`torch.unique` with equivalent implementation for numpy. + + Args: + x: array/tensor. + """ + return np.unique(x, **kwargs) if isinstance(x, (np.ndarray, list)) else torch.unique(x, **kwargs) # type: ignore + + +def linalg_inv(x: NdarrayTensor) -> NdarrayTensor: + """`torch.linalg.inv` with equivalent implementation for numpy. + + Args: + x: array/tensor. + """ + if isinstance(x, torch.Tensor) and hasattr(torch, "inverse"): # pytorch 1.7.0 + return torch.inverse(x) # type: ignore + return torch.linalg.inv(x) if isinstance(x, torch.Tensor) else np.linalg.inv(x) # type: ignore + + +def max(x: NdarrayTensor, dim: int | tuple | None = None, **kwargs) -> NdarrayTensor: + """`torch.max` with equivalent implementation for numpy + + Args: + x: array/tensor. + + Returns: + the maximum of x. + + """ + + ret: NdarrayTensor + if dim is None: + ret = np.max(x, **kwargs) if isinstance(x, (np.ndarray, list)) else torch.max(x, **kwargs) # type: ignore + else: + if isinstance(x, (np.ndarray, list)): + ret = np.max(x, axis=dim, **kwargs) + else: + ret = torch.max(x, int(dim), **kwargs) # type: ignore + + return ret + + +def mean(x: NdarrayTensor, dim: int | tuple | None = None, **kwargs) -> NdarrayTensor: + """`torch.mean` with equivalent implementation for numpy + + Args: + x: array/tensor. + + Returns: + the mean of x + """ + + ret: NdarrayTensor + if dim is None: + ret = np.mean(x, **kwargs) if isinstance(x, (np.ndarray, list)) else torch.mean(x, **kwargs) # type: ignore + else: + if isinstance(x, (np.ndarray, list)): + ret = np.mean(x, axis=dim, **kwargs) + else: + ret = torch.mean(x, int(dim), **kwargs) # type: ignore + + return ret + + +def median(x: NdarrayTensor, dim: int | tuple | None = None, **kwargs) -> NdarrayTensor: + """`torch.median` with equivalent implementation for numpy + + Args: + x: array/tensor. + + Returns + the median of x. + """ + + ret: NdarrayTensor + if dim is None: + ret = np.median(x, **kwargs) if isinstance(x, (np.ndarray, list)) else torch.median(x, **kwargs) # type: ignore + else: + if isinstance(x, (np.ndarray, list)): + ret = np.median(x, axis=dim, **kwargs) + else: + ret = torch.median(x, int(dim), **kwargs) # type: ignore + + return ret + + +def min(x: NdarrayTensor, dim: int | tuple | None = None, **kwargs) -> NdarrayTensor: + """`torch.min` with equivalent implementation for numpy + + Args: + x: array/tensor. + + Returns: + the minimum of x. + """ + + ret: NdarrayTensor + if dim is None: + ret = np.min(x, **kwargs) if isinstance(x, (np.ndarray, list)) else torch.min(x, **kwargs) # type: ignore + else: + if isinstance(x, (np.ndarray, list)): + ret = np.min(x, axis=dim, **kwargs) + else: + ret = torch.min(x, int(dim), **kwargs) # type: ignore + + return ret + + +def std(x: NdarrayTensor, dim: int | tuple | None = None, unbiased: bool = False) -> NdarrayTensor: + """`torch.std` with equivalent implementation for numpy + + Args: + x: array/tensor. + + Returns: + the standard deviation of x. + """ + + ret: NdarrayTensor + if dim is None: + ret = np.std(x) if isinstance(x, (np.ndarray, list)) else torch.std(x, unbiased) # type: ignore + else: + if isinstance(x, (np.ndarray, list)): + ret = np.std(x, axis=dim) + else: + ret = torch.std(x, int(dim), unbiased) # type: ignore + + return ret + + +def sum(x: NdarrayTensor, dim: int | tuple | None = None, **kwargs) -> NdarrayTensor: + """`torch.sum` with equivalent implementation for numpy + + Args: + x: array/tensor. + + Returns: + the sum of x. + """ + + ret: NdarrayTensor + if dim is None: + ret = np.sum(x, **kwargs) if isinstance(x, (np.ndarray, list)) else torch.sum(x, **kwargs) # type: ignore + else: + if isinstance(x, (np.ndarray, list)): + ret = np.sum(x, axis=dim, **kwargs) + else: + ret = torch.sum(x, int(dim), **kwargs) # type: ignore + + return ret diff --git a/source_code/SegMamba/monai/utils/__init__.py b/source_code/SegMamba/monai/utils/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..2c32eb2cf4581a612107515022947e85fef8f1b3 --- /dev/null +++ b/source_code/SegMamba/monai/utils/__init__.py @@ -0,0 +1,153 @@ +# Copyright (c) MONAI Consortium +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from __future__ import annotations + +# have to explicitly bring these in here to resolve circular import issues +from .aliases import alias, resolve_name +from .component_store import ComponentStore +from .decorators import MethodReplacer, RestartGenerator +from .deprecate_utils import DeprecatedError, deprecated, deprecated_arg, deprecated_arg_default +from .dist import RankFilter, evenly_divisible_all_gather, get_dist_device, string_list_all_gather +from .enums import ( + AdversarialIterationEvents, + AdversarialKeys, + AlgoKeys, + Average, + BlendMode, + BoxModeName, + BundleProperty, + BundlePropertyConfig, + ChannelMatching, + ColorOrder, + CommonKeys, + CompInitMode, + DiceCEReduction, + EngineStatsKeys, + FastMRIKeys, + ForwardMode, + GanKeys, + GridPatchSort, + GridSampleMode, + GridSamplePadMode, + HoVerNetBranch, + HoVerNetMode, + InterpolateMode, + JITMetadataKeys, + LazyAttr, + LossReduction, + MetaKeys, + Method, + MetricReduction, + NdimageMode, + NumpyPadMode, + OrderingTransformations, + OrderingType, + PatchKeys, + PostFix, + ProbMapKeys, + PytorchPadMode, + SkipMode, + SpaceKeys, + SplineMode, + StrEnum, + TraceKeys, + TraceStatusKeys, + TransformBackends, + UpsampleMode, + Weight, + WSIPatchKeys, +) +from .jupyter_utils import StatusMembers, ThreadContainer +from .misc import ( + MAX_SEED, + ImageMetaKey, + MONAIEnvVars, + check_kwargs_exist_in_class_init, + check_parent_dir, + copy_to_device, + ensure_tuple, + ensure_tuple_rep, + ensure_tuple_size, + fall_back_tuple, + first, + get_seed, + has_option, + is_immutable, + is_module_ver_at_least, + is_scalar, + is_scalar_tensor, + is_sqrt, + issequenceiterable, + list_to_dict, + path_to_uri, + pprint_edges, + progress_bar, + run_cmd, + sample_slices, + save_obj, + set_determinism, + star_zip_with, + str2bool, + str2list, + to_tuple_of_dictionaries, + unsqueeze_left, + unsqueeze_right, + zip_with, +) +from .module import ( + InvalidPyTorchVersionError, + OptionalImportError, + allow_missing_reference, + damerau_levenshtein_distance, + exact_version, + export, + get_full_type_name, + get_package_version, + get_torch_version_tuple, + instantiate, + load_submodules, + look_up_option, + min_version, + optional_import, + pytorch_after, + require_pkg, + run_debug, + run_eval, + version_geq, + version_leq, +) +from .nvtx import Range +from .profiling import ( + PerfContext, + ProfileHandler, + WorkflowProfiler, + select_transform_call, + torch_profiler_full, + torch_profiler_time_cpu_gpu, + torch_profiler_time_end_to_end, +) +from .state_cacher import StateCacher +from .tf32 import detect_default_tf32, has_ampere_or_later +from .type_conversion import ( + convert_data_type, + convert_to_cupy, + convert_to_dst_type, + convert_to_list, + convert_to_numpy, + convert_to_tensor, + dtype_numpy_to_torch, + dtype_torch_to_numpy, + get_dtype, + get_equivalent_dtype, + get_numpy_dtype_from_string, + get_torch_dtype_from_string, +) diff --git a/source_code/SegMamba/monai/utils/aliases.py b/source_code/SegMamba/monai/utils/aliases.py new file mode 100644 index 0000000000000000000000000000000000000000..2974eec2eb522f4b9331f96a07231316a1fb46e7 --- /dev/null +++ b/source_code/SegMamba/monai/utils/aliases.py @@ -0,0 +1,103 @@ +# Copyright (c) MONAI Consortium +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +""" +This module is written for configurable workflow, not currently in use. +""" + +from __future__ import annotations + +import importlib +import inspect +import sys +import threading + +alias_lock = threading.RLock() +GlobalAliases = {} + +__all__ = ["alias", "resolve_name"] + + +def alias(*names): + """ + Stores the decorated function or class in the global aliases table under the given names and as the `__aliases__` + member of the decorated object. This new member will contain all alias names declared for that object. + """ + + def _outer(obj): + for n in names: + with alias_lock: + GlobalAliases[n] = obj + + # set the member list __aliases__ to contain the alias names defined by the decorator for `obj` + obj.__aliases__ = getattr(obj, "__aliases__", ()) + tuple(names) + + return obj + + return _outer + + +def resolve_name(name): + """ + Search for the declaration (function or class) with the given name. This will first search the list of aliases to + see if it was declared with this aliased name, then search treating `name` as a fully qualified name, then search + the loaded modules for one having a declaration with the given name. If no declaration is found, raise ValueError. + + Raises: + ValueError: When the module is not found. + ValueError: When the module does not have the specified member. + ValueError: When multiple modules with the declaration name are found. + ValueError: When no module with the specified member is found. + + """ + # attempt to resolve an alias + with alias_lock: + obj = GlobalAliases.get(name) + + if name in GlobalAliases and obj is None: + raise AssertionError + + # attempt to resolve a qualified name + if obj is None and "." in name: + modname, declname = name.rsplit(".", 1) + + try: + mod = importlib.import_module(modname) + obj = getattr(mod, declname, None) + except ModuleNotFoundError as not_found_err: + raise ValueError(f"Module {modname!r} not found.") from not_found_err + + if obj is None: + raise ValueError(f"Module {modname!r} does not have member {declname!r}.") + + # attempt to resolve a simple name + if obj is None: + # Get all modules having the declaration/import, need to check here that getattr returns something which doesn't + # equate to False since in places __getattr__ returns 0 incorrectly: + # https://github.com/tensorflow/tensorboard/blob/a22566561d2b4fea408755a951ac9eaf3a156f8e/ + # tensorboard/compat/tensorflow_stub/pywrap_tensorflow.py#L35 + mods = [m for m in list(sys.modules.values()) if getattr(m, name, None)] + + if len(mods) > 0: # found modules with this declaration or import + if len(mods) > 1: # found multiple modules, need to determine if ambiguous or just multiple imports + foundmods = set(filter(None, {inspect.getmodule(getattr(m, name)) for m in mods})) # resolve imports + + if len(foundmods) > 1: # found multiple declarations with the same name + modnames = [m.__name__ for m in foundmods] + msg = f"Multiple modules ({modnames!r}) with declaration name {name!r} found, resolution is ambiguous." + raise ValueError(msg) + mods = list(foundmods) + + obj = getattr(mods[0], name) + + if obj is None: + raise ValueError(f"No module with member {name!r} found.") + + return obj diff --git a/source_code/SegMamba/monai/utils/deprecate_utils.py b/source_code/SegMamba/monai/utils/deprecate_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..d4f239cd23c014c2c98968ef93ff148d2fb1fc66 --- /dev/null +++ b/source_code/SegMamba/monai/utils/deprecate_utils.py @@ -0,0 +1,327 @@ +# Copyright (c) MONAI Consortium +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from __future__ import annotations + +import inspect +import sys +import warnings +from collections.abc import Callable +from functools import wraps +from types import FunctionType +from typing import Any, TypeVar + +from monai.utils.module import version_leq + +from .. import __version__ + +__all__ = ["deprecated", "deprecated_arg", "DeprecatedError", "deprecated_arg_default"] +T = TypeVar("T", type, Callable) + + +class DeprecatedError(Exception): + pass + + +def warn_deprecated(obj, msg, warning_category=FutureWarning): + """ + Issue the warning message `msg`. + """ + warnings.warn(f"{obj}: {msg}", category=warning_category, stacklevel=2) + + +def deprecated( + since: str | None = None, + removed: str | None = None, + msg_suffix: str = "", + version_val: str = __version__, + warning_category: type[FutureWarning] = FutureWarning, +) -> Callable[[T], T]: + """ + Marks a function or class as deprecated. If `since` is given this should be a version at or earlier than the + current version and states at what version of the definition was marked as deprecated. If `removed` is given + this can be any version and marks when the definition was removed. + + When the decorated definition is called, that is when the function is called or the class instantiated, + a `warning_category` is issued if `since` is given and the current version is at or later than that given. + a `DeprecatedError` exception is instead raised if `removed` is given and the current version is at or later + than that, or if neither `since` nor `removed` is provided. + + The relevant docstring of the deprecating function should also be updated accordingly, + using the Sphinx directives such as `.. versionchanged:: version` and `.. deprecated:: version`. + https://www.sphinx-doc.org/en/master/usage/restructuredtext/directives.html#directive-versionadded + + Args: + since: version at which the definition was marked deprecated but not removed. + removed: version at which the definition was/will be removed and no longer usable. + msg_suffix: message appended to warning/exception detailing reasons for deprecation and what to use instead. + version_val: (used for testing) version to compare since and removed against, default is MONAI version. + warning_category: a warning category class, defaults to `FutureWarning`. + + Returns: + Decorated definition which warns or raises exception when used + """ + + if since is not None and removed is not None and not version_leq(since, removed): + raise ValueError(f"since must be less or equal to removed, got since={since}, removed={removed}.") + is_not_yet_deprecated = since is not None and version_val != since and version_leq(version_val, since) + if is_not_yet_deprecated: + # smaller than `since`, do nothing + return lambda obj: obj + + if since is None and removed is None: + # raise a DeprecatedError directly + is_removed = True + is_deprecated = True + else: + # compare the numbers + is_deprecated = since is not None and version_leq(since, version_val) + is_removed = removed is not None and version_leq(removed, version_val) + + def _decorator(obj): + is_func = isinstance(obj, FunctionType) + call_obj = obj if is_func else obj.__init__ + + msg_prefix = f"{'Function' if is_func else 'Class'} `{obj.__qualname__}`" + + if is_removed: + msg_infix = f"was removed in version {removed}." + elif is_deprecated: + msg_infix = f"has been deprecated since version {since}." + if removed is not None: + msg_infix += f" It will be removed in version {removed}." + else: + msg_infix = "has been deprecated." + + msg = f"{msg_prefix} {msg_infix} {msg_suffix}".strip() + + @wraps(call_obj) + def _wrapper(*args, **kwargs): + if is_removed: + raise DeprecatedError(msg) + if is_deprecated: + warn_deprecated(obj, msg, warning_category) + + return call_obj(*args, **kwargs) + + if is_func: + return _wrapper + obj.__init__ = _wrapper + return obj + + return _decorator + + +def deprecated_arg( + name: str, + since: str | None = None, + removed: str | None = None, + msg_suffix: str = "", + version_val: str = __version__, + new_name: str | None = None, + warning_category: type[FutureWarning] = FutureWarning, +) -> Callable[[T], T]: + """ + Marks a particular named argument of a callable as deprecated. The same conditions for `since` and `removed` as + described in the `deprecated` decorator. + + When the decorated definition is called, that is when the function is called or the class instantiated with args, + a `warning_category` is issued if `since` is given and the current version is at or later than that given. + a `DeprecatedError` exception is instead raised if `removed` is given and the current version is at or later + than that, or if neither `since` nor `removed` is provided. + + The relevant docstring of the deprecating function should also be updated accordingly, + using the Sphinx directives such as `.. versionchanged:: version` and `.. deprecated:: version`. + https://www.sphinx-doc.org/en/master/usage/restructuredtext/directives.html#directive-versionadded + + + Args: + name: name of position or keyword argument to mark as deprecated. + since: version at which the argument was marked deprecated but not removed. + removed: version at which the argument was/will be removed and no longer usable. + msg_suffix: message appended to warning/exception detailing reasons for deprecation and what to use instead. + version_val: (used for testing) version to compare since and removed against, default is MONAI version. + new_name: name of position or keyword argument to replace the deprecated argument. + if it is specified and the signature of the decorated function has a `kwargs`, the value to the + deprecated argument `name` will be removed. + warning_category: a warning category class, defaults to `FutureWarning`. + + Returns: + Decorated callable which warns or raises exception when deprecated argument used. + """ + + if version_val.startswith("0+") or not f"{version_val}".strip()[0].isdigit(): + # version unknown, set version_val to a large value (assuming the latest version) + version_val = f"{sys.maxsize}" + if since is not None and removed is not None and not version_leq(since, removed): + raise ValueError(f"since must be less or equal to removed, got since={since}, removed={removed}.") + is_not_yet_deprecated = since is not None and version_val != since and version_leq(version_val, since) + if is_not_yet_deprecated: + # smaller than `since`, do nothing + return lambda obj: obj + if since is None and removed is None: + # raise a DeprecatedError directly + is_removed = True + is_deprecated = True + else: + # compare the numbers + is_deprecated = since is not None and version_leq(since, version_val) + is_removed = removed is not None and version_val != f"{sys.maxsize}" and version_leq(removed, version_val) + + def _decorator(func): + argname = f"{func.__module__} {func.__qualname__}:{name}" + + msg_prefix = f"Argument `{name}`" + + if is_removed: + msg_infix = f"was removed in version {removed}." + elif is_deprecated: + msg_infix = f"has been deprecated since version {since}." + if removed is not None: + msg_infix += f" It will be removed in version {removed}." + else: + msg_infix = "has been deprecated." + + msg = f"{msg_prefix} {msg_infix} {msg_suffix}".strip() + + sig = inspect.signature(func) + + @wraps(func) + def _wrapper(*args, **kwargs): + if new_name is not None and name in kwargs and new_name not in kwargs: + # replace the deprecated arg "name" with "new_name" + # if name is specified and new_name is not specified + kwargs[new_name] = kwargs[name] + try: + sig.bind(*args, **kwargs).arguments + except TypeError: + # multiple values for new_name using both args and kwargs + kwargs.pop(new_name, None) + binding = sig.bind(*args, **kwargs).arguments + positional_found = name in binding + kw_found = False + for k, param in sig.parameters.items(): + if param.kind == inspect.Parameter.VAR_KEYWORD and k in binding and name in binding[k]: + kw_found = True + # if the deprecated arg is found in the **kwargs, it should be removed + kwargs.pop(name, None) + + if positional_found or kw_found: + if is_removed: + raise DeprecatedError(msg) + if is_deprecated: + warn_deprecated(argname, msg, warning_category) + + return func(*args, **kwargs) + + return _wrapper + + return _decorator + + +def deprecated_arg_default( + name: str, + old_default: Any, + new_default: Any, + since: str | None = None, + replaced: str | None = None, + msg_suffix: str = "", + version_val: str = __version__, + warning_category: type[FutureWarning] = FutureWarning, +) -> Callable[[T], T]: + """ + Marks a particular arguments default of a callable as deprecated. It is changed from `old_default` to `new_default` + in version `changed`. + + When the decorated definition is called, a `warning_category` is issued if `since` is given, + the default is not explicitly set by the caller and the current version is at or later than that given. + Another warning with the same category is issued if `changed` is given and the current version is at or later. + + The relevant docstring of the deprecating function should also be updated accordingly, + using the Sphinx directives such as `.. versionchanged:: version` and `.. deprecated:: version`. + https://www.sphinx-doc.org/en/master/usage/restructuredtext/directives.html#directive-versionadded + + + Args: + name: name of position or keyword argument where the default is deprecated/changed. + old_default: name of the old default. This is only for the warning message, it will not be validated. + new_default: name of the new default. + It is validated that this value is not present as the default before version `replaced`. + This means, that you can also use this if the actual default value is `None` and set later in the function. + You can also set this to any string representation, e.g. `"calculate_default_value()"` + if the default is calculated from another function. + since: version at which the argument default was marked deprecated but not replaced. + replaced: version at which the argument default was/will be replaced. + msg_suffix: message appended to warning/exception detailing reasons for deprecation. + version_val: (used for testing) version to compare since and removed against, default is MONAI version. + warning_category: a warning category class, defaults to `FutureWarning`. + + Returns: + Decorated callable which warns when deprecated default argument is not explicitly specified. + """ + + if version_val.startswith("0+") or not f"{version_val}".strip()[0].isdigit(): + # version unknown, set version_val to a large value (assuming the latest version) + version_val = f"{sys.maxsize}" + if since is not None and replaced is not None and not version_leq(since, replaced): + raise ValueError(f"since must be less or equal to replaced, got since={since}, replaced={replaced}.") + is_not_yet_deprecated = since is not None and version_val != since and version_leq(version_val, since) + if is_not_yet_deprecated: + # smaller than `since`, do nothing + return lambda obj: obj + if since is None and replaced is None: + # raise a DeprecatedError directly + is_replaced = True + is_deprecated = True + else: + # compare the numbers + is_deprecated = since is not None and version_leq(since, version_val) + is_replaced = replaced is not None and version_val != f"{sys.maxsize}" and version_leq(replaced, version_val) + + def _decorator(func): + argname = f"{func.__module__} {func.__qualname__}:{name}" + + msg_prefix = f" Current default value of argument `{name}={old_default}`" + + if is_replaced: + msg_infix = f"was changed in version {replaced} from `{name}={old_default}` to `{name}={new_default}`." + elif is_deprecated: + msg_infix = f"has been deprecated since version {since}." + if replaced is not None: + msg_infix += f" It will be changed to `{name}={new_default}` in version {replaced}." + else: + msg_infix = f"has been deprecated from `{name}={old_default}` to `{name}={new_default}`." + + msg = f"{msg_prefix} {msg_infix} {msg_suffix}".strip() + + sig = inspect.signature(func) + if name not in sig.parameters: + raise ValueError(f"Argument `{name}` not found in signature of {func.__qualname__}.") + param = sig.parameters[name] + if param.default is inspect.Parameter.empty: + raise ValueError(f"Argument `{name}` has no default value.") + + if param.default == new_default and not is_replaced: + raise ValueError( + f"Argument `{name}` was replaced to the new default value `{new_default}` before the specified version {replaced}." + ) + + @wraps(func) + def _wrapper(*args, **kwargs): + if name not in sig.bind(*args, **kwargs).arguments and is_deprecated: + # arg was not found so the default value is used + warn_deprecated(argname, msg, warning_category) + + return func(*args, **kwargs) + + return _wrapper + + return _decorator diff --git a/source_code/SegMamba/monai/utils/dist.py b/source_code/SegMamba/monai/utils/dist.py new file mode 100644 index 0000000000000000000000000000000000000000..2418b43591a84f4df5dd07bfb1f84accd7eb1cf2 --- /dev/null +++ b/source_code/SegMamba/monai/utils/dist.py @@ -0,0 +1,206 @@ +# Copyright (c) MONAI Consortium +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from __future__ import annotations + +import sys +import warnings +from collections.abc import Callable +from logging import Filter + +if sys.version_info >= (3, 8): + from typing import Literal + +from typing import overload + +import torch +import torch.distributed as dist + +from monai.config import IgniteInfo +from monai.utils.module import min_version, optional_import + +idist, has_ignite = optional_import("ignite", IgniteInfo.OPT_IMPORT_VERSION, min_version, "distributed") + +__all__ = ["get_dist_device", "evenly_divisible_all_gather", "string_list_all_gather", "RankFilter"] + + +def get_dist_device(): + """ + Get the expected target device in the native PyTorch distributed data parallel. + For NCCL backend, return GPU device of current process. + For GLOO backend, return CPU. + For any other backends, return None as the default, tensor.to(None) will not change the device. + + """ + if dist.is_initialized(): + backend = dist.get_backend() + if backend == "nccl" and torch.cuda.is_available(): + return torch.device(f"cuda:{torch.cuda.current_device()}") + if backend == "gloo": + return torch.device("cpu") + return None + + +@overload +def evenly_divisible_all_gather(data: torch.Tensor, concat: Literal[True]) -> torch.Tensor: ... + + +@overload +def evenly_divisible_all_gather(data: torch.Tensor, concat: Literal[False]) -> list[torch.Tensor]: ... + + +@overload +def evenly_divisible_all_gather(data: torch.Tensor, concat: bool) -> torch.Tensor | list[torch.Tensor]: ... + + +def evenly_divisible_all_gather(data: torch.Tensor, concat: bool = True) -> torch.Tensor | list[torch.Tensor]: + """ + Utility function for distributed data parallel to pad at first dim to make it evenly divisible and all_gather. + The input data of every rank should have the same number of dimensions, only the first dim can be different. + + Note: If has ignite installed, will execute based on ignite distributed APIs, otherwise, if the native + PyTorch distributed group initialized, will execute based on native PyTorch distributed APIs. + + Args: + data: source tensor to pad and execute all_gather in distributed data parallel. + concat: whether to concat the gathered list to be a Tensor, if False, return a list + of Tensors, similar behavior as torch.distributed.all_gather(). default to True. + + Note: + The input data on different ranks must have exactly same `dtype`. + + """ + if not isinstance(data, torch.Tensor): + raise ValueError("input data must be PyTorch Tensor.") + # data of all the ranks must have same number of dimensions + ndims = data.ndimension() + length: int = data.shape[0] if ndims > 0 else 1 + + def _torch_all_gather(data: torch.Tensor) -> list[torch.Tensor]: + """ + Implementation based on native PyTorch distributed data parallel APIs. + + """ + device = get_dist_device() + orig_device = data.device + data = data.to(device) + data = data.unsqueeze(0) if ndims == 0 else data + + # make sure the data is evenly-divisible on multi-GPUs + length_tensor = torch.as_tensor([length], device=device) + all_lens = [torch.zeros_like(length_tensor) for _ in range(dist.get_world_size())] + dist.all_gather(all_lens, length_tensor) + all_lens_: list[int] = [int(i.item()) for i in all_lens] + + max_len: int = max(all_lens_) + if length < max_len: + size = [max_len - length] + list(data.shape[1:]) + data = torch.cat([data, data.new_full(size, 0)], dim=0) + # all gather across all processes + output = [torch.zeros_like(data) for _ in range(dist.get_world_size())] + dist.all_gather(output, data) + # remove the padding items, if all the input data doesn't have batch dim, squeeze the first dim + return [(o.squeeze(0) if ndims == 0 else o[:l, ...]).to(orig_device) for o, l in zip(output, all_lens_)] + + def _ignite_all_gather(data: torch.Tensor) -> list[torch.Tensor]: + """ + Implementation based on PyTorch ignite package, it can support more kinds of backends. + + """ + data = data.unsqueeze(0) if ndims == 0 else data + # make sure the data is evenly-divisible on multi-GPUs + all_lens: list[int] = idist.all_gather(length) + max_len: int = max(all_lens) + if length < max_len: + size = [max_len - length] + list(data.shape[1:]) + data = torch.cat([data, data.new_full(size, 0)], dim=0) + # all gather across all processes + output = idist.all_gather(data) + # delete the padding NaN items + if ndims == 0: + # if all the input data doesn't have batch dim, unbind to a list of 0-dim Tensors + return list(torch.unbind(output, dim=0)) + return [output[i * max_len : i * max_len + l, ...] for i, l in enumerate(all_lens)] + + output: list[torch.Tensor] + if has_ignite: + if idist.get_world_size() <= 1: + return data + output = _ignite_all_gather(data=data) + elif dist.is_available() and dist.is_initialized(): + if dist.get_world_size() <= 1: + return data + output = _torch_all_gather(data=data) + else: + return data + + return torch.cat(output, dim=0) if concat else output + + +def string_list_all_gather(strings: list[str], delimiter: str = "\t") -> list[str]: + """ + Utility function for distributed data parallel to all gather a list of strings. + Refer to the idea of ignite `all_gather(string)`: + https://pytorch.org/ignite/v0.4.5/distributed.html#ignite.distributed.utils.all_gather. + + Note: If has ignite installed, will execute based on ignite distributed APIs, otherwise, if the native + PyTorch distributed group initialized, will execute based on native PyTorch distributed APIs. + + Args: + strings: a list of strings to all gather. + delimiter: use the delimiter to join the string list to be a long string, + then all gather across ranks and split to a list. default to "\t". + + """ + world_size: int = 1 + if has_ignite: + world_size = idist.get_world_size() + elif dist.is_available() and dist.is_initialized(): + world_size = dist.get_world_size() + + if world_size <= 1: + return strings + + joined = delimiter.join(strings) + gathered = evenly_divisible_all_gather(torch.tensor(bytearray(joined, "utf-8"), dtype=torch.long), concat=False) + _gathered = [bytearray(g.tolist()).decode("utf-8").split(delimiter) for g in gathered] + + return [i for k in _gathered for i in k] + + +class RankFilter(Filter): + """ + The RankFilter class is a convenient filter that extends the Filter class in the Python logging module. + The purpose is to control which log records are processed based on the rank in a distributed environment. + + Args: + rank: the rank of the process in the torch.distributed. Default is None and then it will use dist.get_rank(). + filter_fn: an optional lambda function used as the filtering criteria. + The default function logs only if the rank of the process is 0, + but the user can define their own function to implement custom filtering logic. + """ + + def __init__(self, rank: int | None = None, filter_fn: Callable = lambda rank: rank == 0): + super().__init__() + self.filter_fn: Callable = filter_fn + if dist.is_available() and dist.is_initialized(): + self.rank: int = rank if rank is not None else dist.get_rank() + else: + if torch.cuda.is_available() and torch.cuda.device_count() > 1: + warnings.warn( + "The torch.distributed is either unavailable and uninitiated when RankFilter is instantiated.\n" + "If torch.distributed is used, please ensure that the RankFilter() is called\n" + "after torch.distributed.init_process_group() in the script.\n" + ) + self.rank = 0 + + def filter(self, *_args): + return self.filter_fn(self.rank) diff --git a/source_code/SegMamba/monai/utils/enums.py b/source_code/SegMamba/monai/utils/enums.py new file mode 100644 index 0000000000000000000000000000000000000000..b786e921516a07ccfe5bba0a8a5f4fc943e2a29b --- /dev/null +++ b/source_code/SegMamba/monai/utils/enums.py @@ -0,0 +1,759 @@ +# Copyright (c) MONAI Consortium +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from __future__ import annotations + +import random +from enum import Enum +from typing import TYPE_CHECKING + +from monai.config import IgniteInfo +from monai.utils import deprecated +from monai.utils.module import min_version, optional_import + +__all__ = [ + "StrEnum", + "NumpyPadMode", + "GridSampleMode", + "SplineMode", + "InterpolateMode", + "UpsampleMode", + "BlendMode", + "PytorchPadMode", + "NdimageMode", + "GridSamplePadMode", + "Average", + "MetricReduction", + "LossReduction", + "DiceCEReduction", + "Weight", + "ChannelMatching", + "SkipMode", + "Method", + "TraceKeys", + "TraceStatusKeys", + "CommonKeys", + "GanKeys", + "PostFix", + "ForwardMode", + "TransformBackends", + "CompInitMode", + "BoxModeName", + "GridPatchSort", + "FastMRIKeys", + "SpaceKeys", + "MetaKeys", + "ColorOrder", + "EngineStatsKeys", + "DataStatsKeys", + "ImageStatsKeys", + "LabelStatsKeys", + "AlgoEnsembleKeys", + "HoVerNetMode", + "HoVerNetBranch", + "LazyAttr", + "BundleProperty", + "BundlePropertyConfig", + "AlgoKeys", +] + + +class StrEnum(str, Enum): + """ + Enum subclass that converts its value to a string. + + .. code-block:: python + + from monai.utils import StrEnum + + class Example(StrEnum): + MODE_A = "A" + MODE_B = "B" + + assert (list(Example) == ["A", "B"]) + assert Example.MODE_A == "A" + assert str(Example.MODE_A) == "A" + assert monai.utils.look_up_option("A", Example) == "A" + """ + + def __str__(self): + return self.value + + def __repr__(self): + return self.value + + +if TYPE_CHECKING: + from ignite.engine import EventEnum +else: + EventEnum, _ = optional_import( + "ignite.engine", IgniteInfo.OPT_IMPORT_VERSION, min_version, "EventEnum", as_type="base" + ) + + +class NumpyPadMode(StrEnum): + """ + See also: https://numpy.org/doc/1.18/reference/generated/numpy.pad.html + """ + + CONSTANT = "constant" + EDGE = "edge" + LINEAR_RAMP = "linear_ramp" + MAXIMUM = "maximum" + MEAN = "mean" + MEDIAN = "median" + MINIMUM = "minimum" + REFLECT = "reflect" + SYMMETRIC = "symmetric" + WRAP = "wrap" + EMPTY = "empty" + + +class NdimageMode(StrEnum): + """ + The available options determine how the input array is extended beyond its boundaries when interpolating. + See also: https://docs.scipy.org/doc/scipy/reference/generated/scipy.ndimage.map_coordinates.html + """ + + REFLECT = "reflect" + GRID_MIRROR = "grid-mirror" + CONSTANT = "constant" + GRID_CONSTANT = "grid-constant" + NEAREST = "nearest" + MIRROR = "mirror" + GRID_WRAP = "grid-wrap" + WRAP = "wrap" + + +class GridSampleMode(StrEnum): + """ + See also: https://pytorch.org/docs/stable/generated/torch.nn.functional.grid_sample.html + + interpolation mode of `torch.nn.functional.grid_sample` + + Note: + (documentation from `torch.nn.functional.grid_sample`) + `mode='bicubic'` supports only 4-D input. + When `mode='bilinear'` and the input is 5-D, the interpolation mode used internally will actually be trilinear. + However, when the input is 4-D, the interpolation mode will legitimately be bilinear. + """ + + NEAREST = "nearest" + BILINEAR = "bilinear" + BICUBIC = "bicubic" + + +class SplineMode(StrEnum): + """ + Order of spline interpolation. + + See also: https://docs.scipy.org/doc/scipy/reference/generated/scipy.ndimage.map_coordinates.html + """ + + ZERO = 0 + ONE = 1 + TWO = 2 + THREE = 3 + FOUR = 4 + FIVE = 5 + + +class InterpolateMode(StrEnum): + """ + See also: https://pytorch.org/docs/stable/generated/torch.nn.functional.interpolate.html + """ + + NEAREST = "nearest" + NEAREST_EXACT = "nearest-exact" + LINEAR = "linear" + BILINEAR = "bilinear" + BICUBIC = "bicubic" + TRILINEAR = "trilinear" + AREA = "area" + + +class UpsampleMode(StrEnum): + """ + See also: :py:class:`monai.networks.blocks.UpSample` + """ + + DECONV = "deconv" + DECONVGROUP = "deconvgroup" + NONTRAINABLE = "nontrainable" # e.g. using torch.nn.Upsample + PIXELSHUFFLE = "pixelshuffle" + + +class BlendMode(StrEnum): + """ + See also: :py:class:`monai.data.utils.compute_importance_map` + """ + + CONSTANT = "constant" + GAUSSIAN = "gaussian" + + +class PytorchPadMode(StrEnum): + """ + See also: https://pytorch.org/docs/stable/generated/torch.nn.functional.pad.html + """ + + CONSTANT = "constant" + REFLECT = "reflect" + REPLICATE = "replicate" + CIRCULAR = "circular" + + +class GridSamplePadMode(StrEnum): + """ + See also: https://pytorch.org/docs/stable/generated/torch.nn.functional.grid_sample.html + """ + + ZEROS = "zeros" + BORDER = "border" + REFLECTION = "reflection" + + +class Average(StrEnum): + """ + See also: :py:class:`monai.metrics.rocauc.compute_roc_auc` + """ + + MACRO = "macro" + WEIGHTED = "weighted" + MICRO = "micro" + NONE = "none" + + +class MetricReduction(StrEnum): + """ + See also: :py:func:`monai.metrics.utils.do_metric_reduction` + """ + + NONE = "none" + MEAN = "mean" + SUM = "sum" + MEAN_BATCH = "mean_batch" + SUM_BATCH = "sum_batch" + MEAN_CHANNEL = "mean_channel" + SUM_CHANNEL = "sum_channel" + + +class LossReduction(StrEnum): + """ + See also: + - :py:class:`monai.losses.dice.DiceLoss` + - :py:class:`monai.losses.dice.GeneralizedDiceLoss` + - :py:class:`monai.losses.focal_loss.FocalLoss` + - :py:class:`monai.losses.tversky.TverskyLoss` + """ + + NONE = "none" + MEAN = "mean" + SUM = "sum" + + +class DiceCEReduction(StrEnum): + """ + See also: + - :py:class:`monai.losses.dice.DiceCELoss` + """ + + MEAN = "mean" + SUM = "sum" + + +class Weight(StrEnum): + """ + See also: :py:class:`monai.losses.dice.GeneralizedDiceLoss` + """ + + SQUARE = "square" + SIMPLE = "simple" + UNIFORM = "uniform" + + +class ChannelMatching(StrEnum): + """ + See also: :py:class:`monai.networks.nets.HighResBlock` + """ + + PAD = "pad" + PROJECT = "project" + + +class SkipMode(StrEnum): + """ + See also: :py:class:`monai.networks.layers.SkipConnection` + """ + + CAT = "cat" + ADD = "add" + MUL = "mul" + + +class Method(StrEnum): + """ + See also: :py:class:`monai.transforms.croppad.array.SpatialPad` + """ + + SYMMETRIC = "symmetric" + END = "end" + + +class ForwardMode(StrEnum): + """ + See also: :py:class:`monai.transforms.engines.evaluator.Evaluator` + """ + + TRAIN = "train" + EVAL = "eval" + + +class TraceKeys(StrEnum): + """Extra metadata keys used for traceable transforms.""" + + CLASS_NAME: str = "class" + ID: str = "id" + ORIG_SIZE: str = "orig_size" + EXTRA_INFO: str = "extra_info" + DO_TRANSFORM: str = "do_transforms" + KEY_SUFFIX: str = "_transforms" + NONE: str = "none" + TRACING: str = "tracing" + STATUSES: str = "statuses" + LAZY: str = "lazy" + + +class TraceStatusKeys(StrEnum): + """Enumerable status keys for the TraceKeys.STATUS flag""" + + PENDING_DURING_APPLY = "pending_during_apply" + + +class CommonKeys(StrEnum): + """ + A set of common keys for dictionary based supervised training process. + `IMAGE` is the input image data. + `LABEL` is the training or evaluation label of segmentation or classification task. + `PRED` is the prediction data of model output. + `LOSS` is the loss value of current iteration. + `INFO` is some useful information during training or evaluation, like loss value, etc. + + """ + + IMAGE = "image" + LABEL = "label" + PRED = "pred" + LOSS = "loss" + METADATA = "metadata" + + +class GanKeys(StrEnum): + """ + A set of common keys for generative adversarial networks. + + """ + + REALS = "reals" + FAKES = "fakes" + LATENTS = "latents" + GLOSS = "g_loss" + DLOSS = "d_loss" + + +class PostFix(StrEnum): + """Post-fixes.""" + + @staticmethod + def _get_str(prefix: str | None, suffix: str) -> str: + return suffix if prefix is None else f"{prefix}_{suffix}" + + @staticmethod + def meta(key: str | None = None) -> str: + return PostFix._get_str(key, "meta_dict") + + @staticmethod + def orig_meta(key: str | None = None) -> str: + return PostFix._get_str(key, "orig_meta_dict") + + @staticmethod + def transforms(key: str | None = None) -> str: + return PostFix._get_str(key, TraceKeys.KEY_SUFFIX[1:]) + + +class TransformBackends(StrEnum): + """ + Transform backends. Most of `monai.transforms` components first converts the input data into ``torch.Tensor`` or + ``monai.data.MetaTensor``. Internally, some transforms are made by converting the data into ``numpy.array`` or + ``cupy.array`` and use the underlying transform backend API to achieve the actual output array and + converting back to ``Tensor``/``MetaTensor``. Transforms with more than one backend indicate the that they may + convert the input data types to accommodate the underlying API. + """ + + TORCH = "torch" + NUMPY = "numpy" + CUPY = "cupy" + + +class CompInitMode(StrEnum): + """ + Mode names for instantiating a class or calling a callable. + + See also: :py:func:`monai.utils.module.instantiate` + """ + + DEFAULT = "default" + CALLABLE = "callable" + DEBUG = "debug" + + +class JITMetadataKeys(StrEnum): + """ + Keys stored in the metadata file for saved Torchscript models. Some of these are generated by the routines + and others are optionally provided by users. + """ + + NAME = "name" + TIMESTAMP = "timestamp" + VERSION = "version" + DESCRIPTION = "description" + + +class BoxModeName(StrEnum): + """ + Box mode names. + """ + + XYXY = "xyxy" # [xmin, ymin, xmax, ymax] + XYZXYZ = "xyzxyz" # [xmin, ymin, zmin, xmax, ymax, zmax] + XXYY = "xxyy" # [xmin, xmax, ymin, ymax] + XXYYZZ = "xxyyzz" # [xmin, xmax, ymin, ymax, zmin, zmax] + XYXYZZ = "xyxyzz" # [xmin, ymin, xmax, ymax, zmin, zmax] + XYWH = "xywh" # [xmin, ymin, xsize, ysize] + XYZWHD = "xyzwhd" # [xmin, ymin, zmin, xsize, ysize, zsize] + CCWH = "ccwh" # [xcenter, ycenter, xsize, ysize] + CCCWHD = "cccwhd" # [xcenter, ycenter, zcenter, xsize, ysize, zsize] + + +class ProbMapKeys(StrEnum): + """ + The keys to be used for generating the probability maps from patches + """ + + LOCATION = "mask_location" + SIZE = "mask_size" + COUNT = "num_patches" + NAME = "name" + + +class GridPatchSort(StrEnum): + """ + The sorting method for the generated patches in `GridPatch` + """ + + RANDOM = "random" + MIN = "min" + MAX = "max" + + @staticmethod + def min_fn(x): + return x[0].sum() + + @staticmethod + def max_fn(x): + return -x[0].sum() + + @staticmethod + def get_sort_fn(sort_fn): + if sort_fn == GridPatchSort.RANDOM: + return random.random + elif sort_fn == GridPatchSort.MIN: + return GridPatchSort.min_fn + elif sort_fn == GridPatchSort.MAX: + return GridPatchSort.max_fn + else: + raise ValueError( + f'sort_fn should be one of the following values, "{sort_fn}" was given:', + [e.value for e in GridPatchSort], + ) + + +class PatchKeys(StrEnum): + """ + The keys to be used for metadata of patches extracted from any kind of image + """ + + LOCATION = "location" + SIZE = "size" + COUNT = "count" + + +class WSIPatchKeys(StrEnum): + """ + The keys to be used for metadata of patches extracted from whole slide images + """ + + LOCATION = PatchKeys.LOCATION + SIZE = PatchKeys.SIZE + COUNT = PatchKeys.COUNT + LEVEL = "level" + PATH = "path" + + +class FastMRIKeys(StrEnum): + """ + The keys to be used for extracting data from the fastMRI dataset + """ + + KSPACE = "kspace" + MASK = "mask" + FILENAME = "filename" + RECON = "reconstruction_rss" + ACQUISITION = "acquisition" + MAX = "max" + NORM = "norm" + PID = "patient_id" + + +class SpaceKeys(StrEnum): + """ + The coordinate system keys, for example, Nifti1 uses Right-Anterior-Superior or "RAS", + DICOM (0020,0032) uses Left-Posterior-Superior or "LPS". This type does not distinguish spatial 1/2/3D. + """ + + RAS = "RAS" + LPS = "LPS" + + +class MetaKeys(StrEnum): + """ + Typical keys for MetaObj.meta + """ + + AFFINE = "affine" # MetaTensor.affine + ORIGINAL_AFFINE = "original_affine" # the affine after image loading before any data processing + SPATIAL_SHAPE = "spatial_shape" # optional key for the length in each spatial dimension + SPACE = "space" # possible values of space type are defined in `SpaceKeys` + ORIGINAL_CHANNEL_DIM = "original_channel_dim" # an integer or float("nan") + + +class ColorOrder(StrEnum): + """ + Enums for color order. Expand as necessary. + """ + + RGB = "RGB" + BGR = "BGR" + + +class EngineStatsKeys(StrEnum): + """ + Default keys for the statistics of trainer and evaluator engines. + + """ + + RANK = "rank" + CURRENT_ITERATION = "current_iteration" + CURRENT_EPOCH = "current_epoch" + TOTAL_EPOCHS = "total_epochs" + TOTAL_ITERATIONS = "total_iterations" + BEST_VALIDATION_EPOCH = "best_validation_epoch" + BEST_VALIDATION_METRIC = "best_validation_metric" + + +class DataStatsKeys(StrEnum): + """ + Defaults keys for dataset statistical analysis modules + + """ + + SUMMARY = "stats_summary" + BY_CASE = "stats_by_cases" + BY_CASE_IMAGE_PATH = "image_filepath" + BY_CASE_LABEL_PATH = "label_filepath" + IMAGE_STATS = "image_stats" + FG_IMAGE_STATS = "image_foreground_stats" + LABEL_STATS = "label_stats" + IMAGE_HISTOGRAM = "image_histogram" + + +class ImageStatsKeys(StrEnum): + """ + Defaults keys for dataset statistical analysis image modules + + """ + + SHAPE = "shape" + CHANNELS = "channels" + CROPPED_SHAPE = "cropped_shape" + SPACING = "spacing" + SIZEMM = "sizemm" + INTENSITY = "intensity" + HISTOGRAM = "histogram" + + +class LabelStatsKeys(StrEnum): + """ + Defaults keys for dataset statistical analysis label modules + + """ + + LABEL_UID = "labels" + PIXEL_PCT = "foreground_percentage" + IMAGE_INTST = "image_intensity" + LABEL = "label" + LABEL_SHAPE = "shape" + LABEL_NCOMP = "ncomponents" + + +@deprecated(since="1.2", removed="1.4", msg_suffix="please use `AlgoKeys` instead.") +class AlgoEnsembleKeys(StrEnum): + """ + Default keys for Mixed Ensemble + """ + + ID = "identifier" + ALGO = "infer_algo" + SCORE = "best_metric" + + +class HoVerNetMode(StrEnum): + """ + Modes for HoVerNet model: + `FAST`: a faster implementation (than original) + `ORIGINAL`: the original implementation + """ + + FAST = "FAST" + ORIGINAL = "ORIGINAL" + + +class HoVerNetBranch(StrEnum): + """ + Three branches of HoVerNet model, which results in three outputs: + `HV` is horizontal and vertical gradient map of each nucleus (regression), + `NP` is the pixel prediction of all nuclei (segmentation), and + `NC` is the type of each nucleus (classification). + """ + + HV = "horizontal_vertical" + NP = "nucleus_prediction" + NC = "type_prediction" + + +class LazyAttr(StrEnum): + """ + MetaTensor with pending operations requires some key attributes tracked especially when the primary array + is not up-to-date due to lazy evaluation. + This class specifies the set of key attributes to be tracked for each MetaTensor. + See also: :py:func:`monai.transforms.lazy.utils.resample` for more details. + """ + + SHAPE = "lazy_shape" # spatial shape + AFFINE = "lazy_affine" + PADDING_MODE = "lazy_padding_mode" + INTERP_MODE = "lazy_interpolation_mode" + DTYPE = "lazy_dtype" + ALIGN_CORNERS = "lazy_align_corners" + RESAMPLE_MODE = "lazy_resample_mode" + + +class BundleProperty(StrEnum): + """ + Bundle property fields: + `DESC` is the description of the property. + `REQUIRED` is flag to indicate whether the property is required or optional. + """ + + DESC = "description" + REQUIRED = "required" + + +class BundlePropertyConfig(StrEnum): + """ + additional bundle property fields for config based bundle workflow: + `ID` is the config item ID of the property. + `REF_ID` is the ID of config item which is supposed to refer to this property. + For properties that do not have `REF_ID`, `None` should be set. + this field is only useful to check the optional property ID. + """ + + ID = "id" + REF_ID = "refer_id" + + +class AlgoKeys(StrEnum): + """ + Default keys for templated Auto3DSeg Algo. + `ID` is the identifier of the algorithm. The string has the format of __. + `ALGO` is the Auto3DSeg Algo instance. + `IS_TRAINED` is the status that shows if the Algo has been trained. + `SCORE` is the score the Algo has achieved after training. + """ + + ID = "identifier" + ALGO = "algo_instance" + IS_TRAINED = "is_trained" + SCORE = "best_metric" + + +class AdversarialKeys(StrEnum): + """ + Keys used by the AdversarialTrainer. + `REALS` are real images from the batch. + `FAKES` are fake images generated by the generator. Are the same as PRED. + `REAL_LOGITS` are logits of the discriminator for the real images. + `FAKE_LOGIT` are logits of the discriminator for the fake images. + `RECONSTRUCTION_LOSS` is the loss value computed by the reconstruction loss function. + `GENERATOR_LOSS` is the loss value computed by the generator loss function. It is the + discriminator loss for the fake images. That is backpropagated through the generator only. + `DISCRIMINATOR_LOSS` is the loss value computed by the discriminator loss function. It is the + discriminator loss for the real images and the fake images. That is backpropagated through the + discriminator only. + """ + + REALS = "reals" + REAL_LOGITS = "real_logits" + FAKES = "fakes" + FAKE_LOGITS = "fake_logits" + RECONSTRUCTION_LOSS = "reconstruction_loss" + GENERATOR_LOSS = "generator_loss" + DISCRIMINATOR_LOSS = "discriminator_loss" + + +class AdversarialIterationEvents(EventEnum): + """ + Keys used to define events as used in the AdversarialTrainer. + """ + + RECONSTRUCTION_LOSS_COMPLETED = "reconstruction_loss_completed" + GENERATOR_FORWARD_COMPLETED = "generator_forward_completed" + GENERATOR_DISCRIMINATOR_FORWARD_COMPLETED = "generator_discriminator_forward_completed" + GENERATOR_LOSS_COMPLETED = "generator_loss_completed" + GENERATOR_BACKWARD_COMPLETED = "generator_backward_completed" + GENERATOR_MODEL_COMPLETED = "generator_model_completed" + DISCRIMINATOR_REALS_FORWARD_COMPLETED = "discriminator_reals_forward_completed" + DISCRIMINATOR_FAKES_FORWARD_COMPLETED = "discriminator_fakes_forward_completed" + DISCRIMINATOR_LOSS_COMPLETED = "discriminator_loss_completed" + DISCRIMINATOR_BACKWARD_COMPLETED = "discriminator_backward_completed" + DISCRIMINATOR_MODEL_COMPLETED = "discriminator_model_completed" + + +class OrderingType(StrEnum): + RASTER_SCAN = "raster_scan" + S_CURVE = "s_curve" + RANDOM = "random" + + +class OrderingTransformations(StrEnum): + ROTATE_90 = "rotate_90" + TRANSPOSE = "transpose" + REFLECT = "reflect" diff --git a/source_code/SegMamba/monai/utils/jupyter_utils.py b/source_code/SegMamba/monai/utils/jupyter_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..7dcd0e62cda2834b5bfbf8771404c471a92b3e3e --- /dev/null +++ b/source_code/SegMamba/monai/utils/jupyter_utils.py @@ -0,0 +1,372 @@ +# Copyright (c) MONAI Consortium +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +""" +This set of utility function is meant to make using Jupyter notebooks easier with MONAI. Plotting functions using +Matplotlib produce common plots for metrics and images. +""" + +from __future__ import annotations + +import copy +from collections.abc import Callable, Mapping +from enum import Enum +from threading import RLock, Thread +from typing import TYPE_CHECKING, Any + +import numpy as np +import torch + +from monai.config import IgniteInfo +from monai.utils.module import min_version, optional_import + +try: + import matplotlib.pyplot as plt + + has_matplotlib = True +except ImportError: + has_matplotlib = False + +if TYPE_CHECKING: + from ignite.engine import Engine, Events +else: + Engine, _ = optional_import("ignite.engine", IgniteInfo.OPT_IMPORT_VERSION, min_version, "Engine") + Events, _ = optional_import("ignite.engine", IgniteInfo.OPT_IMPORT_VERSION, min_version, "Events") + +LOSS_NAME = "loss" + + +def plot_metric_graph( + ax: plt.Axes, + title: str, + graphmap: Mapping[str, list[float] | tuple[list[float], list[float]]], + yscale: str = "log", + avg_keys: tuple[str] = (LOSS_NAME,), + window_fraction: int = 20, +) -> None: + """ + Plot metrics on a single graph with running averages plotted for selected keys. The values in `graphmap` + should be lists of (timepoint, value) pairs as stored in MetricLogger objects. + + Args: + ax: Axes object to plot into + title: graph title + graphmap: dictionary of named graph values, which are lists of values or (index, value) pairs + yscale: scale for y-axis compatible with `Axes.set_yscale` + avg_keys: tuple of keys in `graphmap` to provide running average plots for + window_fraction: what fraction of the graph value length to use as the running average window + """ + from matplotlib.ticker import MaxNLocator + + for n, v in graphmap.items(): + if len(v) > 0: + if isinstance(v[0], (tuple, list)): # values are (x,y) pairs + inds, vals = zip(*v) # separate values into list of indices in X dimension and values + else: + inds, vals = tuple(range(len(v))), tuple(v) # values are without indices, make indices for them + + ax.plot(inds, vals, label=f"{n} = {vals[-1]:.5g}") + + # if requested compute and plot a running average for the values using a fractional window size + if n in avg_keys and len(v) > window_fraction: + window = len(v) // window_fraction + kernel = np.ones((window,)) / window + ra = np.convolve((vals[0],) * (window - 1) + vals, kernel, mode="valid") + + ax.plot(inds, ra, label=f"{n} Avg = {ra[-1]:.5g}") + + ax.set_title(title) + ax.set_yscale(yscale) + ax.axis("on") + ax.legend(bbox_to_anchor=(1, 1), loc=1, borderaxespad=0.0) + ax.grid(True, "both", "both") + ax.xaxis.set_major_locator(MaxNLocator(integer=True)) + + +def plot_metric_images( + fig: plt.Figure, + title: str, + graphmap: Mapping[str, list[float] | tuple[list[float], list[float]]], + imagemap: dict[str, np.ndarray], + yscale: str = "log", + avg_keys: tuple[str] = (LOSS_NAME,), + window_fraction: int = 20, +) -> list: + """ + Plot metric graph data with images below into figure `fig`. The intended use is for the graph data to be + metrics from a training run and the images to be the batch and output from the last iteration. This uses + `plot_metric_graph` to plot the metric graph. + + Args: + fig: Figure object to plot into, reuse from previous plotting for flicker-free refreshing + title: graph title + graphmap: dictionary of named graph values, which are lists of values or (index, value) pairs + imagemap: dictionary of named images to show with metric plot + yscale: for metric plot, scale for y-axis compatible with `Axes.set_yscale` + avg_keys: for metric plot, tuple of keys in `graphmap` to provide running average plots for + window_fraction: for metric plot, what fraction of the graph value length to use as the running average window + + Returns: + list of Axes objects for graph followed by images + """ + gridshape = (4, max(1, len(imagemap))) + + graph = plt.subplot2grid(gridshape, (0, 0), colspan=gridshape[1], fig=fig) + + plot_metric_graph(graph, title, graphmap, yscale, avg_keys, window_fraction) + + axes = [graph] + for i, n in enumerate(imagemap): + im = plt.subplot2grid(gridshape, (1, i), rowspan=2, fig=fig) + + if imagemap[n].shape[0] == 3: + im.imshow(imagemap[n].transpose([1, 2, 0])) + else: + im.imshow(np.squeeze(imagemap[n]), cmap="gray") + + im.set_title(f"{n}\n{imagemap[n].min():.3g} -> {imagemap[n].max():.3g}") + im.axis("off") + axes.append(im) + + return axes + + +def tensor_to_images(name: str, tensor: torch.Tensor) -> np.ndarray | None: + """ + Return an tuple of images derived from the given tensor. The `name` value indices which key from the + output or batch value the tensor was stored as, or is "Batch" or "Output" if these were single tensors + instead of dictionaries. Returns a tuple of 2D images of shape HW, or 3D images of shape CHW where C is + color channels RGB or RGBA. This allows multiple images to be created from a single tensor, ie. to show + each channel separately. + """ + if tensor.ndim == 3 and tensor.shape[1] > 2 and tensor.shape[2] > 2: + return tensor.cpu().data.numpy() # type: ignore[no-any-return] + if tensor.ndim == 4 and tensor.shape[2] > 2 and tensor.shape[3] > 2: + dmid = tensor.shape[1] // 2 + return tensor[:, dmid].cpu().data.numpy() # type: ignore[no-any-return] + + return None + + +def plot_engine_status( + engine: Engine, + logger: Any, + title: str = "Training Log", + yscale: str = "log", + avg_keys: tuple[str] = (LOSS_NAME,), + window_fraction: int = 20, + image_fn: Callable[[str, torch.Tensor], Any] | None = tensor_to_images, + fig: plt.Figure | None = None, + selected_inst: int = 0, +) -> tuple[plt.Figure, list]: + """ + Plot the status of the given Engine with its logger. The plot will consist of a graph of loss values and metrics + taken from the logger, and images taken from the `output` and `batch` members of `engine.state`. The images are + converted to Numpy arrays suitable for input to `Axes.imshow` using `image_fn`, if this is None then no image + plotting is done. + + Args: + engine: Engine to extract images from + logger: MetricLogger to extract loss and metric data from + title: graph title + yscale: for metric plot, scale for y-axis compatible with `Axes.set_yscale` + avg_keys: for metric plot, tuple of keys in `graphmap` to provide running average plots for + window_fraction: for metric plot, what fraction of the graph value length to use as the running average window + image_fn: callable converting tensors keyed to a name in the Engine to a tuple of images to plot + fig: Figure object to plot into, reuse from previous plotting for flicker-free refreshing + selected_inst: index of the instance to show in the image plot + + Returns: + Figure object (or `fig` if given), list of Axes objects for graph and images + """ + if fig is not None: + fig.clf() + else: + fig = plt.Figure(figsize=(20, 10), tight_layout=True, facecolor="white") + + graphmap: dict[str, list[float]] = {LOSS_NAME: logger.loss} + graphmap.update(logger.metrics) + + imagemap: dict = {} + if image_fn is not None and engine.state is not None and engine.state.batch is not None: + for src in (engine.state.batch, engine.state.output): + label = "Batch" if src is engine.state.batch else "Output" + batch_selected_inst = selected_inst # selected batch index, set to 0 when src is decollated + + # if the src object is a list of elements, ie. a decollated batch, select an element and keep it as + # a dictionary of tensors with a batch dimension added + if isinstance(src, list): + selected_dict = src[selected_inst] # select this element + batch_selected_inst = 0 # set the selection to be the single index in the batch dimension + # store each tensor that is interpretable as an image with an added batch dimension + src = {k: v[None] for k, v in selected_dict.items() if isinstance(v, torch.Tensor) and v.ndim >= 3} + + # images will be generated from the batch item selected above only, or from the single item given as `src` + + if isinstance(src, dict): + for k, v in src.items(): + if isinstance(v, torch.Tensor) and v.ndim >= 4: + image = image_fn(k, v[batch_selected_inst]) + + # if we have images add each one separately to the map + if image is not None: + for i, im in enumerate(image): + imagemap[f"{k}_{i}"] = im + + elif isinstance(src, torch.Tensor): + image = image_fn(label, src) + if image is not None: + imagemap[f"{label}_{i}"] = image + + axes = plot_metric_images(fig, title, graphmap, imagemap, yscale, avg_keys, window_fraction) + + if logger.loss: + axes[0].axhline(logger.loss[-1][1], c="k", ls=":") # draw dotted horizontal line at last loss value + + return fig, axes + + +def _get_loss_from_output( + output: list[torch.Tensor | dict[str, torch.Tensor]] | dict[str, torch.Tensor] | torch.Tensor +) -> torch.Tensor: + """Returns a single value from the network output, which is a dict or tensor.""" + + def _get_loss(data: torch.Tensor | dict[str, torch.Tensor]) -> torch.Tensor: + if isinstance(data, dict): + return data["loss"] + return data + + if isinstance(output, list): + return _get_loss(output[0]) + return _get_loss(output) + + +class StatusMembers(Enum): + """ + Named members of the status dictionary, others may be present for named metric values. + """ + + STATUS = "Status" + EPOCHS = "Epochs" + ITERS = "Iters" + LOSS = "Loss" + + +class ThreadContainer(Thread): + """ + Contains a running `Engine` object within a separate thread from main thread in a Jupyter notebook. This + allows an engine to begin a run in the background and allow the starting notebook cell to complete. A + user can thus start a run and then navigate away from the notebook without concern for loosing connection + with the running cell. All output is acquired through methods which synchronize with the running engine + using an internal `lock` member, acquiring this lock allows the engine to be inspected while it's prevented + from starting the next iteration. + + Args: + engine: wrapped `Engine` object, when the container is started its `run` method is called + loss_transform: callable to convert an output dict into a single numeric value + metric_transform: callable to convert a named metric value into a single numeric value + status_format: format string for status key-value pairs. + """ + + def __init__( + self, + engine: Engine, + loss_transform: Callable = _get_loss_from_output, + metric_transform: Callable = lambda name, value: value, + status_format: str = "{}: {:.4}", + ): + super().__init__() + self.lock = RLock() + self.engine = engine + self._status_dict: dict[str, Any] = {} + self.loss_transform = loss_transform + self.metric_transform = metric_transform + self.fig: plt.Figure | None = None + self.status_format = status_format + + self.engine.add_event_handler(Events.ITERATION_COMPLETED, self._update_status) + + def run(self): + """Calls the `run` method of the wrapped engine.""" + self.engine.run() + + def stop(self): + """Stop the engine and join the thread.""" + self.engine.terminate() + self.join() + + def _update_status(self): + """Called as an event, updates the internal status dict at the end of iterations.""" + with self.lock: + state = self.engine.state + stats: dict[str, Any] = { + StatusMembers.EPOCHS.value: 0, + StatusMembers.ITERS.value: 0, + StatusMembers.LOSS.value: float("nan"), + } + + if state is not None: + if state.max_epochs is not None and state.max_epochs >= 1: + epoch = f"{state.epoch}/{state.max_epochs}" + else: + epoch = str(state.epoch) + + if state.epoch_length is not None: + iters = f"{state.iteration % state.epoch_length}/{state.epoch_length}" + else: + iters = str(state.iteration) + + stats[StatusMembers.EPOCHS.value] = epoch + stats[StatusMembers.ITERS.value] = iters + stats[StatusMembers.LOSS.value] = self.loss_transform(state.output) + + metrics = state.metrics or {} + for m, v in metrics.items(): + v = self.metric_transform(m, v) + if v is not None: + stats[m].append(v) + + self._status_dict.update(stats) + + @property + def status_dict(self) -> dict[str, str]: + """A dictionary containing status information, current loss, and current metric values.""" + with self.lock: + stats = {StatusMembers.STATUS.value: "Running" if self.is_alive() else "Stopped"} + stats.update(self._status_dict) + return stats + + def status(self) -> str: + """Returns a status string for the current state of the engine.""" + stats = copy.deepcopy(self.status_dict) + + msgs = [stats.pop(StatusMembers.STATUS.value), "Iters: " + str(stats.pop(StatusMembers.ITERS.value, 0))] + + for key, val in stats.items(): + if isinstance(val, float): + msg = self.status_format.format(key, val) + else: + msg = f"{key}: {val}" + + msgs.append(msg) + + return ", ".join(msgs) + + def plot_status(self, logger: Any, plot_func: Callable = plot_engine_status) -> plt.Figure | None: + """ + Generate a plot of the current status of the contained engine whose loss and metrics were tracked by `logger`. + The function `plot_func` must accept arguments `title`, `engine`, `logger`, and `fig` which are the plot title, + `self.engine`, `logger`, and `self.fig` respectively. The return value must be a figure object (stored in + `self.fig`) and a list of Axes objects for the plots in the figure. Only the figure is returned by this method, + which holds the internal lock during the plot generation. + """ + with self.lock: + self.fig, _ = plot_func(title=self.status(), engine=self.engine, logger=logger, fig=self.fig) + return self.fig diff --git a/source_code/SegMamba/monai/utils/misc.py b/source_code/SegMamba/monai/utils/misc.py new file mode 100644 index 0000000000000000000000000000000000000000..ab9fe259aa990bcffb5d7bf811b7ff4ba419090b --- /dev/null +++ b/source_code/SegMamba/monai/utils/misc.py @@ -0,0 +1,899 @@ +# Copyright (c) MONAI Consortium +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from __future__ import annotations + +import inspect +import itertools +import math +import os +import pprint +import random +import shutil +import subprocess +import tempfile +import types +import warnings +from ast import literal_eval +from collections.abc import Callable, Iterable, Sequence +from distutils.util import strtobool +from math import log10 +from pathlib import Path +from typing import TYPE_CHECKING, Any, TypeVar, cast, overload + +import numpy as np +import torch + +from monai.config.type_definitions import NdarrayOrTensor, NdarrayTensor, PathLike +from monai.utils.module import optional_import, version_leq + +if TYPE_CHECKING: + from yaml import SafeLoader +else: + SafeLoader, _ = optional_import("yaml", name="SafeLoader", as_type="base") + +__all__ = [ + "zip_with", + "star_zip_with", + "first", + "issequenceiterable", + "is_immutable", + "ensure_tuple", + "ensure_tuple_size", + "ensure_tuple_rep", + "to_tuple_of_dictionaries", + "fall_back_tuple", + "is_scalar_tensor", + "is_scalar", + "progress_bar", + "get_seed", + "set_determinism", + "list_to_dict", + "MAX_SEED", + "copy_to_device", + "str2bool", + "str2list", + "MONAIEnvVars", + "ImageMetaKey", + "is_module_ver_at_least", + "has_option", + "sample_slices", + "check_parent_dir", + "save_obj", + "label_union", + "path_to_uri", + "pprint_edges", + "check_key_duplicates", + "CheckKeyDuplicatesYamlLoader", + "ConvertUnits", + "check_kwargs_exist_in_class_init", + "run_cmd", +] + +_seed = None +_flag_deterministic = torch.backends.cudnn.deterministic +_flag_cudnn_benchmark = torch.backends.cudnn.benchmark +NP_MAX = np.iinfo(np.uint32).max +MAX_SEED = NP_MAX + 1 # 2**32, the actual seed should be in [0, MAX_SEED - 1] for uint32 + + +def zip_with(op, *vals, mapfunc=map): + """ + Map `op`, using `mapfunc`, to each tuple derived from zipping the iterables in `vals`. + """ + return mapfunc(op, zip(*vals)) + + +def star_zip_with(op, *vals): + """ + Use starmap as the mapping function in zipWith. + """ + return zip_with(op, *vals, mapfunc=itertools.starmap) + + +T = TypeVar("T") + + +@overload +def first(iterable: Iterable[T], default: T) -> T: ... + + +@overload +def first(iterable: Iterable[T]) -> T | None: ... + + +def first(iterable: Iterable[T], default: T | None = None) -> T | None: + """ + Returns the first item in the given iterable or `default` if empty, meaningful mostly with 'for' expressions. + """ + for i in iterable: + return i + return default + + +def issequenceiterable(obj: Any) -> bool: + """ + Determine if the object is an iterable sequence and is not a string. + """ + try: + if hasattr(obj, "ndim") and obj.ndim == 0: + return False # a 0-d tensor is not iterable + except Exception: + return False + return isinstance(obj, Iterable) and not isinstance(obj, (str, bytes)) + + +def is_immutable(obj: Any) -> bool: + """ + Determine if the object is an immutable object. + + see also https://github.com/python/cpython/blob/3.11/Lib/copy.py#L109 + """ + return isinstance(obj, (type(None), int, float, bool, complex, str, tuple, bytes, type, range, slice)) + + +def ensure_tuple(vals: Any, wrap_array: bool = False) -> tuple: + """ + Returns a tuple of `vals`. + + Args: + vals: input data to convert to a tuple. + wrap_array: if `True`, treat the input numerical array (ndarray/tensor) as one item of the tuple. + if `False`, try to convert the array with `tuple(vals)`, default to `False`. + + """ + if wrap_array and isinstance(vals, (np.ndarray, torch.Tensor)): + return (vals,) + return tuple(vals) if issequenceiterable(vals) else (vals,) + + +def ensure_tuple_size(vals: Any, dim: int, pad_val: Any = 0, pad_from_start: bool = False) -> tuple: + """ + Returns a copy of `tup` with `dim` values by either shortened or padded with `pad_val` as necessary. + """ + tup = ensure_tuple(vals) + pad_dim = dim - len(tup) + if pad_dim <= 0: + return tup[:dim] + if pad_from_start: + return (pad_val,) * pad_dim + tup + return tup + (pad_val,) * pad_dim + + +def ensure_tuple_rep(tup: Any, dim: int) -> tuple[Any, ...]: + """ + Returns a copy of `tup` with `dim` values by either shortened or duplicated input. + + Raises: + ValueError: When ``tup`` is a sequence and ``tup`` length is not ``dim``. + + Examples:: + + >>> ensure_tuple_rep(1, 3) + (1, 1, 1) + >>> ensure_tuple_rep(None, 3) + (None, None, None) + >>> ensure_tuple_rep('test', 3) + ('test', 'test', 'test') + >>> ensure_tuple_rep([1, 2, 3], 3) + (1, 2, 3) + >>> ensure_tuple_rep(range(3), 3) + (0, 1, 2) + >>> ensure_tuple_rep([1, 2], 3) + ValueError: Sequence must have length 3, got length 2. + + """ + if isinstance(tup, torch.Tensor): + tup = tup.detach().cpu().numpy() + if isinstance(tup, np.ndarray): + tup = tup.tolist() + if not issequenceiterable(tup): + return (tup,) * dim + if len(tup) == dim: + return tuple(tup) + + raise ValueError(f"Sequence must have length {dim}, got {len(tup)}.") + + +def to_tuple_of_dictionaries(dictionary_of_tuples: dict, keys: Any) -> tuple[dict[Any, Any], ...]: + """ + Given a dictionary whose values contain scalars or tuples (with the same length as ``keys``), + Create a dictionary for each key containing the scalar values mapping to that key. + + Args: + dictionary_of_tuples: a dictionary whose values are scalars or tuples whose length is + the length of ``keys`` + keys: a tuple of string values representing the keys in question + + Returns: + a tuple of dictionaries that contain scalar values, one dictionary for each key + + Raises: + ValueError: when values in the dictionary are tuples but not the same length as the length + of ``keys`` + + Examples: + >>> to_tuple_of_dictionaries({'a': 1 'b': (2, 3), 'c': (4, 4)}, ("x", "y")) + ({'a':1, 'b':2, 'c':4}, {'a':1, 'b':3, 'c':4}) + + """ + + keys = ensure_tuple(keys) + if len(keys) == 0: + return tuple({}) + + dict_overrides = {k: ensure_tuple_rep(v, len(keys)) for k, v in dictionary_of_tuples.items()} + return tuple({k: v[ik] for (k, v) in dict_overrides.items()} for ik in range(len(keys))) + + +def fall_back_tuple( + user_provided: Any, default: Sequence | NdarrayTensor, func: Callable = lambda x: x and x > 0 +) -> tuple[Any, ...]: + """ + Refine `user_provided` according to the `default`, and returns as a validated tuple. + + The validation is done for each element in `user_provided` using `func`. + If `func(user_provided[idx])` returns False, the corresponding `default[idx]` will be used + as the fallback. + + Typically used when `user_provided` is a tuple of window size provided by the user, + `default` is defined by data, this function returns an updated `user_provided` with its non-positive + components replaced by the corresponding components from `default`. + + Args: + user_provided: item to be validated. + default: a sequence used to provided the fallbacks. + func: a Callable to validate every components of `user_provided`. + + Examples:: + + >>> fall_back_tuple((1, 2), (32, 32)) + (1, 2) + >>> fall_back_tuple(None, (32, 32)) + (32, 32) + >>> fall_back_tuple((-1, 10), (32, 32)) + (32, 10) + >>> fall_back_tuple((-1, None), (32, 32)) + (32, 32) + >>> fall_back_tuple((1, None), (32, 32)) + (1, 32) + >>> fall_back_tuple(0, (32, 32)) + (32, 32) + >>> fall_back_tuple(range(3), (32, 64, 48)) + (32, 1, 2) + >>> fall_back_tuple([0], (32, 32)) + ValueError: Sequence must have length 2, got length 1. + + """ + ndim = len(default) + user = ensure_tuple_rep(user_provided, ndim) + return tuple( # use the default values if user provided is not valid + user_c if func(user_c) else default_c for default_c, user_c in zip(default, user) + ) + + +def is_scalar_tensor(val: Any) -> bool: + return isinstance(val, torch.Tensor) and val.ndim == 0 + + +def is_scalar(val: Any) -> bool: + if isinstance(val, torch.Tensor) and val.ndim == 0: + return True + return bool(np.isscalar(val)) + + +def progress_bar(index: int, count: int, desc: str | None = None, bar_len: int = 30, newline: bool = False) -> None: + """print a progress bar to track some time consuming task. + + Args: + index: current status in progress. + count: total steps of the progress. + desc: description of the progress bar, if not None, show before the progress bar. + bar_len: the total length of the bar on screen, default is 30 char. + newline: whether to print in a new line for every index. + """ + end = "\r" if not newline else "\r\n" + filled_len = int(bar_len * index // count) + bar = f"{desc} " if desc is not None else "" + bar += "[" + "=" * filled_len + " " * (bar_len - filled_len) + "]" + print(f"{index}/{count} {bar}", end=end) + if index == count: + print("") + + +def get_seed() -> int | None: + return _seed + + +def set_determinism( + seed: int | None = NP_MAX, + use_deterministic_algorithms: bool | None = None, + additional_settings: Sequence[Callable[[int], Any]] | Callable[[int], Any] | None = None, +) -> None: + """ + Set random seed for modules to enable or disable deterministic training. + + Args: + seed: the random seed to use, default is np.iinfo(np.int32).max. + It is recommended to set a large seed, i.e. a number that has a good balance + of 0 and 1 bits. Avoid having many 0 bits in the seed. + if set to None, will disable deterministic training. + use_deterministic_algorithms: Set whether PyTorch operations must use "deterministic" algorithms. + additional_settings: additional settings that need to set random seed. + + Note: + + This function will not affect the randomizable objects in :py:class:`monai.transforms.Randomizable`, which + have independent random states. For those objects, the ``set_random_state()`` method should be used to + ensure the deterministic behavior (alternatively, :py:class:`monai.data.DataLoader` by default sets the seeds + according to the global random state, please see also: :py:class:`monai.data.utils.worker_init_fn` and + :py:class:`monai.data.utils.set_rnd`). + """ + if seed is None: + # cast to 32 bit seed for CUDA + seed_ = torch.default_generator.seed() % MAX_SEED + torch.manual_seed(seed_) + else: + seed = int(seed) % MAX_SEED + torch.manual_seed(seed) + + global _seed + _seed = seed + random.seed(seed) + np.random.seed(seed) + + if additional_settings is not None: + additional_settings = ensure_tuple(additional_settings) + for func in additional_settings: + func(seed) + + if torch.backends.flags_frozen(): + warnings.warn("PyTorch global flag support of backends is disabled, enable it to set global `cudnn` flags.") + torch.backends.__allow_nonbracketed_mutation_flag = True + + if seed is not None: + torch.backends.cudnn.deterministic = True + torch.backends.cudnn.benchmark = False + else: # restore the original flags + torch.backends.cudnn.deterministic = _flag_deterministic + torch.backends.cudnn.benchmark = _flag_cudnn_benchmark + if use_deterministic_algorithms is not None: + if hasattr(torch, "use_deterministic_algorithms"): # `use_deterministic_algorithms` is new in torch 1.8.0 + torch.use_deterministic_algorithms(use_deterministic_algorithms) + elif hasattr(torch, "set_deterministic"): # `set_deterministic` is new in torch 1.7.0 + torch.set_deterministic(use_deterministic_algorithms) + else: + warnings.warn("use_deterministic_algorithms=True, but PyTorch version is too old to set the mode.") + + +def list_to_dict(items): + """ + To convert a list of "key=value" pairs into a dictionary. + For examples: items: `["a=1", "b=2", "c=3"]`, return: {"a": "1", "b": "2", "c": "3"}. + If no "=" in the pair, use None as the value, for example: ["a"], return: {"a": None}. + Note that it will remove the blanks around keys and values. + + """ + + def _parse_var(s): + items = s.split("=", maxsplit=1) + key = items[0].strip(" \n\r\t'") + value = items[1].strip(" \n\r\t'") if len(items) > 1 else None + return key, value + + d = {} + if items: + for item in items: + key, value = _parse_var(item) + + try: + if key in d: + raise KeyError(f"encounter duplicated key {key}.") + d[key] = literal_eval(value) + except ValueError: + try: + d[key] = bool(strtobool(str(value))) + except ValueError: + d[key] = value + return d + + +def copy_to_device( + obj: Any, device: str | torch.device | None, non_blocking: bool = True, verbose: bool = False +) -> Any: + """ + Copy object or tuple/list/dictionary of objects to ``device``. + + Args: + obj: object or tuple/list/dictionary of objects to move to ``device``. + device: move ``obj`` to this device. Can be a string (e.g., ``cpu``, ``cuda``, + ``cuda:0``, etc.) or of type ``torch.device``. + non_blocking: when `True`, moves data to device asynchronously if + possible, e.g., moving CPU Tensors with pinned memory to CUDA devices. + verbose: when `True`, will print a warning for any elements of incompatible type + not copied to ``device``. + Returns: + Same as input, copied to ``device`` where possible. Original input will be + unchanged. + """ + + if hasattr(obj, "to"): + return obj.to(device, non_blocking=non_blocking) + if isinstance(obj, tuple): + return tuple(copy_to_device(o, device, non_blocking) for o in obj) + if isinstance(obj, list): + return [copy_to_device(o, device, non_blocking) for o in obj] + if isinstance(obj, dict): + return {k: copy_to_device(o, device, non_blocking) for k, o in obj.items()} + if verbose: + fn_name = cast(types.FrameType, inspect.currentframe()).f_code.co_name + warnings.warn(f"{fn_name} called with incompatible type: " + f"{type(obj)}. Data will be returned unchanged.") + + return obj + + +def str2bool(value: str | bool, default: bool = False, raise_exc: bool = True) -> bool: + """ + Convert a string to a boolean. Case insensitive. + True: yes, true, t, y, 1. False: no, false, f, n, 0. + + Args: + value: string to be converted to a boolean. If value is a bool already, simply return it. + raise_exc: if value not in tuples of expected true or false inputs, + should we raise an exception? If not, return `default`. + Raises + ValueError: value not in tuples of expected true or false inputs and + `raise_exc` is `True`. + Useful with argparse, for example: + parser.add_argument("--convert", default=False, type=str2bool) + python mycode.py --convert=True + """ + + if isinstance(value, bool): + return value + + true_set = ("yes", "true", "t", "y", "1") + false_set = ("no", "false", "f", "n", "0") + + if isinstance(value, str): + value = value.lower() + if value in true_set: + return True + if value in false_set: + return False + + if raise_exc: + raise ValueError(f"Got \"{value}\", expected a value from: {', '.join(true_set + false_set)}") + return default + + +def str2list(value: str | list | None, raise_exc: bool = True) -> list | None: + """ + Convert a string to a list. Useful with argparse commandline arguments: + parser.add_argument("--blocks", default=[1,2,3], type=str2list) + python mycode.py --blocks=1,2,2,4 + + Args: + value: string (comma separated) to be converted to a list + raise_exc: if not possible to convert to a list, raise an exception + Raises + ValueError: value not a string or list or not possible to convert + """ + + if value is None: + return None + elif isinstance(value, list): + return value + elif isinstance(value, str): + v = value.split(",") + for i in range(len(v)): + try: + a = literal_eval(v[i].strip()) # attempt to convert + v[i] = a + except Exception: + pass + return v + elif raise_exc: + raise ValueError(f'Unable to convert "{value}", expected a comma-separated str, e.g. 1,2,3') + + return None + + +class MONAIEnvVars: + """ + Environment variables used by MONAI. + """ + + @staticmethod + def data_dir() -> str | None: + return os.environ.get("MONAI_DATA_DIRECTORY") + + @staticmethod + def debug() -> bool: + val = os.environ.get("MONAI_DEBUG", False) + return val if isinstance(val, bool) else str2bool(val) + + @staticmethod + def doc_images() -> str | None: + return os.environ.get("MONAI_DOC_IMAGES") + + @staticmethod + def algo_hash() -> str | None: + return os.environ.get("MONAI_ALGO_HASH", "e4cf5a1") + + @staticmethod + def trace_transform() -> str | None: + return os.environ.get("MONAI_TRACE_TRANSFORM", "1") + + @staticmethod + def eval_expr() -> str | None: + return os.environ.get("MONAI_EVAL_EXPR", "1") + + @staticmethod + def allow_missing_reference() -> str | None: + return os.environ.get("MONAI_ALLOW_MISSING_REFERENCE", "1") + + @staticmethod + def extra_test_data() -> str | None: + return os.environ.get("MONAI_EXTRA_TEST_DATA", "1") + + @staticmethod + def testing_algo_template() -> str | None: + return os.environ.get("MONAI_TESTING_ALGO_TEMPLATE", None) + + +class ImageMetaKey: + """ + Common key names in the metadata header of images + """ + + FILENAME_OR_OBJ = "filename_or_obj" + PATCH_INDEX = "patch_index" + SPATIAL_SHAPE = "spatial_shape" + + +def has_option(obj: Callable, keywords: str | Sequence[str]) -> bool: + """ + Return a boolean indicating whether the given callable `obj` has the `keywords` in its signature. + """ + if not callable(obj): + return False + sig = inspect.signature(obj) + return all(key in sig.parameters for key in ensure_tuple(keywords)) + + +def is_module_ver_at_least(module, version): + """Determine if a module's version is at least equal to the given value. + + Args: + module: imported module's name, e.g., `np` or `torch`. + version: required version, given as a tuple, e.g., `(1, 8, 0)`. + Returns: + `True` if module is the given version or newer. + """ + test_ver = ".".join(map(str, version)) + return module.__version__ != test_ver and version_leq(test_ver, module.__version__) + + +def sample_slices(data: NdarrayOrTensor, dim: int = 1, as_indices: bool = True, *slicevals: int) -> NdarrayOrTensor: + """sample several slices of input numpy array or Tensor on specified `dim`. + + Args: + data: input data to sample slices, can be numpy array or PyTorch Tensor. + dim: expected dimension index to sample slices, default to `1`. + as_indices: if `True`, `slicevals` arg will be treated as the expected indices of slice, like: `1, 3, 5` + means `data[..., [1, 3, 5], ...]`, if `False`, `slicevals` arg will be treated as args for `slice` func, + like: `1, None` means `data[..., [1:], ...]`, `1, 5` means `data[..., [1: 5], ...]`. + slicevals: indices of slices or start and end indices of expected slices, depends on `as_indices` flag. + + """ + slices = [slice(None)] * len(data.shape) + slices[dim] = slicevals if as_indices else slice(*slicevals) # type: ignore + + return data[tuple(slices)] + + +def check_parent_dir(path: PathLike, create_dir: bool = True) -> None: + """ + Utility to check whether the parent directory of the `path` exists. + + Args: + path: input path to check the parent directory. + create_dir: if True, when the parent directory doesn't exist, create the directory, + otherwise, raise exception. + + """ + path = Path(path) + path_dir = path.parent + if not path_dir.exists(): + if create_dir: + path_dir.mkdir(parents=True) + else: + raise ValueError(f"the directory of specified path does not exist: `{path_dir}`.") + + +def save_obj( + obj: object, + path: PathLike, + create_dir: bool = True, + atomic: bool = True, + func: Callable | None = None, + **kwargs: Any, +) -> None: + """ + Save an object to file with specified path. + Support to serialize to a temporary file first, then move to final destination, + so that files are guaranteed to not be damaged if exception occurs. + + Args: + obj: input object data to save. + path: target file path to save the input object. + create_dir: whether to create dictionary of the path if not existing, default to `True`. + atomic: if `True`, state is serialized to a temporary file first, then move to final destination. + so that files are guaranteed to not be damaged if exception occurs. default to `True`. + func: the function to save file, if None, default to `torch.save`. + kwargs: other args for the save `func` except for the checkpoint and filename. + default `func` is `torch.save()`, details of other args: + https://pytorch.org/docs/stable/generated/torch.save.html. + + """ + path = Path(path) + check_parent_dir(path=path, create_dir=create_dir) + if path.exists(): + # remove the existing file + os.remove(path) + + if func is None: + func = torch.save + + if not atomic: + func(obj=obj, f=path, **kwargs) + return + try: + # writing to a temporary directory and then using a nearly atomic rename operation + with tempfile.TemporaryDirectory() as tempdir: + temp_path: Path = Path(tempdir) / path.name + func(obj=obj, f=temp_path, **kwargs) + if temp_path.is_file(): + shutil.move(str(temp_path), path) + except PermissionError: # project-monai/monai issue #3613 + pass + + +def label_union(x: list | np.ndarray) -> list: + """ + Compute the union of class IDs in label and generate a list to include all class IDs + Args: + x: a list of numbers (for example, class_IDs) + + Returns + a list showing the union (the union the class IDs) + """ + return list(set.union(set(np.array(x).tolist()))) + + +def prob2class(x: torch.Tensor, sigmoid: bool = False, threshold: float = 0.5, **kwargs: Any) -> torch.Tensor: + """ + Compute the lab from the probability of predicted feature maps + + Args: + sigmoid: If the sigmoid function should be used. + threshold: threshold value to activate the sigmoid function. + """ + return torch.argmax(x, **kwargs) if not sigmoid else (x > threshold).int() + + +def path_to_uri(path: PathLike) -> str: + """ + Convert a file path to URI. if not absolute path, will convert to absolute path first. + + Args: + path: input file path to convert, can be a string or `Path` object. + + """ + return Path(path).absolute().as_uri() + + +def pprint_edges(val: Any, n_lines: int = 20) -> str: + """ + Pretty print the head and tail ``n_lines`` of ``val``, and omit the middle part if the part has more than 3 lines. + + Returns: the formatted string. + """ + val_str = pprint.pformat(val).splitlines(True) + n_lines = max(n_lines, 1) + if len(val_str) > n_lines * 2 + 3: + hidden_n = len(val_str) - n_lines * 2 + val_str = val_str[:n_lines] + [f"\n ... omitted {hidden_n} line(s)\n\n"] + val_str[-n_lines:] + return "".join(val_str) + + +def check_key_duplicates(ordered_pairs: Sequence[tuple[Any, Any]]) -> dict[Any, Any]: + """ + Checks if there is a duplicated key in the sequence of `ordered_pairs`. + If there is - it will log a warning or raise ValueError + (if configured by environmental var `MONAI_FAIL_ON_DUPLICATE_CONFIG==1`) + + Otherwise, it returns the dict made from this sequence. + + Satisfies a format for an `object_pairs_hook` in `json.load` + + Args: + ordered_pairs: sequence of (key, value) + """ + keys = set() + for k, _ in ordered_pairs: + if k in keys: + if os.environ.get("MONAI_FAIL_ON_DUPLICATE_CONFIG", "0") == "1": + raise ValueError(f"Duplicate key: `{k}`") + else: + warnings.warn(f"Duplicate key: `{k}`") + else: + keys.add(k) + return dict(ordered_pairs) + + +class CheckKeyDuplicatesYamlLoader(SafeLoader): + + def construct_mapping(self, node, deep=False): + mapping = set() + for key_node, _ in node.value: + key = self.construct_object(key_node, deep=deep) + if key in mapping: + if os.environ.get("MONAI_FAIL_ON_DUPLICATE_CONFIG", "0") == "1": + raise ValueError(f"Duplicate key: `{key}`") + else: + warnings.warn(f"Duplicate key: `{key}`") + mapping.add(key) + return super().construct_mapping(node, deep) + + +class ConvertUnits: + """ + Convert the values from input unit to the target unit + + Args: + input_unit: the unit of the input quantity + target_unit: the unit of the target quantity + + """ + + imperial_unit_of_length = {"inch": 0.0254, "foot": 0.3048, "yard": 0.9144, "mile": 1609.344} + + unit_prefix = { + "peta": 15, + "tera": 12, + "giga": 9, + "mega": 6, + "kilo": 3, + "hecto": 2, + "deca": 1, + "deci": -1, + "centi": -2, + "milli": -3, + "micro": -6, + "nano": -9, + "pico": -12, + "femto": -15, + } + base_units = ["meter", "byte", "bit"] + + def __init__(self, input_unit: str, target_unit: str) -> None: + self.input_unit, input_base = self._get_valid_unit_and_base(input_unit) + self.target_unit, target_base = self._get_valid_unit_and_base(target_unit) + if input_base == target_base: + self.unit_base = input_base + else: + raise ValueError( + "Both input and target units should be from the same quantity. " + f"Input quantity is {input_base} while target quantity is {target_base}" + ) + self._calculate_conversion_factor() + + def _get_valid_unit_and_base(self, unit): + unit = str(unit).lower() + if unit in self.imperial_unit_of_length: + return unit, "meter" + for base_unit in self.base_units: + if unit.endswith(base_unit): + return unit, base_unit + raise ValueError(f"Currently, it only supports length conversion but `{unit}` is given.") + + def _get_unit_power(self, unit): + """Calculate the power of the unit factor with respect to the base unit""" + if unit in self.imperial_unit_of_length: + return log10(self.imperial_unit_of_length[unit]) + + prefix = unit[: len(self.unit_base)] + if prefix == "": + return 1.0 + return self.unit_prefix[prefix] + + def _calculate_conversion_factor(self): + """Calculate unit conversion factor with respect to the input unit""" + if self.input_unit == self.target_unit: + return 1.0 + input_power = self._get_unit_power(self.input_unit) + target_power = self._get_unit_power(self.target_unit) + self.conversion_factor = 10 ** (input_power - target_power) + + def __call__(self, value: int | float) -> Any: + return float(value) * self.conversion_factor + + +def check_kwargs_exist_in_class_init(cls, kwargs): + """ + Check if the all keys in kwargs exist in the __init__ method of the class. + + Args: + cls: the class to check. + kwargs: kwargs to examine. + + Returns: + a boolean indicating if all keys exist. + a set of extra keys that are not used in the __init__. + """ + init_signature = inspect.signature(cls.__init__) + init_params = set(init_signature.parameters) - {"self"} # Exclude 'self' from the parameter list + input_kwargs = set(kwargs) + extra_kwargs = input_kwargs - init_params + + return extra_kwargs == set(), extra_kwargs + + +def run_cmd(cmd_list: list[str], **kwargs: Any) -> subprocess.CompletedProcess: + """ + Run a command by using ``subprocess.run`` with capture_output=True and stderr=subprocess.STDOUT + so that the raise exception will have that information. The argument `capture_output` can be set explicitly + if desired, but will be overriden with the debug status from the variable. + + Args: + cmd_list: a list of strings describing the command to run. + kwargs: keyword arguments supported by the ``subprocess.run`` method. + + Returns: + a CompletedProcess instance after the command completes. + """ + debug = MONAIEnvVars.debug() + kwargs["capture_output"] = kwargs.get("capture_output", debug) + + if kwargs.pop("run_cmd_verbose", False): + import monai + + monai.apps.utils.get_logger("run_cmd").info(f"{cmd_list}") + try: + return subprocess.run(cmd_list, **kwargs) + except subprocess.CalledProcessError as e: + if not debug: + raise + output = str(e.stdout.decode(errors="replace")) + errors = str(e.stderr.decode(errors="replace")) + raise RuntimeError(f"subprocess call error {e.returncode}: {errors}, {output}.") from e + + +def is_sqrt(num: Sequence[int] | int) -> bool: + """ + Determine if the input is a square number or a squence of square numbers. + """ + num = ensure_tuple(num) + sqrt_num = [int(math.sqrt(_num)) for _num in num] + ret = [_i * _j for _i, _j in zip(sqrt_num, sqrt_num)] + return ensure_tuple(ret) == num + + +def unsqueeze_right(arr: NdarrayOrTensor, ndim: int) -> NdarrayOrTensor: + """Append 1-sized dimensions to `arr` to create a result with `ndim` dimensions.""" + return arr[(...,) + (None,) * (ndim - arr.ndim)] + + +def unsqueeze_left(arr: NdarrayOrTensor, ndim: int) -> NdarrayOrTensor: + """Prepend 1-sized dimensions to `arr` to create a result with `ndim` dimensions.""" + return arr[(None,) * (ndim - arr.ndim)] diff --git a/source_code/SegMamba/monai/utils/module.py b/source_code/SegMamba/monai/utils/module.py new file mode 100644 index 0000000000000000000000000000000000000000..6f301d8067d964b65fa2ebb9623675917b9d242d --- /dev/null +++ b/source_code/SegMamba/monai/utils/module.py @@ -0,0 +1,656 @@ +# Copyright (c) MONAI Consortium +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from __future__ import annotations + +import enum +import functools +import os +import pdb +import re +import sys +import warnings +from collections.abc import Callable, Collection, Hashable, Mapping +from functools import partial, wraps +from importlib import import_module +from pkgutil import walk_packages +from pydoc import locate +from re import match +from types import FunctionType, ModuleType +from typing import Any, Iterable, cast + +import torch + +# bundle config system flags +# set MONAI_EVAL_EXPR=1 to use 'eval', default value: run_eval=True +run_eval = os.environ.get("MONAI_EVAL_EXPR", "1") != "0" +# set MONAI_DEBUG_CONFIG=1 to run in debug mode, default value: run_debug=False +run_debug = os.environ.get("MONAI_DEBUG_CONFIG", "0") != "0" +# set MONAI_ALLOW_MISSING_REFERENCE=1 to allow missing references, default value: allow_missing_reference=False +allow_missing_reference = os.environ.get("MONAI_ALLOW_MISSING_REFERENCE", "0") != "0" + +OPTIONAL_IMPORT_MSG_FMT = "{}" + +__all__ = [ + "InvalidPyTorchVersionError", + "OptionalImportError", + "exact_version", + "export", + "damerau_levenshtein_distance", + "look_up_option", + "min_version", + "optional_import", + "require_pkg", + "load_submodules", + "instantiate", + "get_full_type_name", + "get_package_version", + "get_torch_version_tuple", + "version_leq", + "version_geq", + "pytorch_after", +] + + +def look_up_option( + opt_str: Hashable, + supported: Collection | enum.EnumMeta, + default: Any = "no_default", + print_all_options: bool = True, +) -> Any: + """ + Look up the option in the supported collection and return the matched item. + Raise a value error possibly with a guess of the closest match. + + Args: + opt_str: The option string or Enum to look up. + supported: The collection of supported options, it can be list, tuple, set, dict, or Enum. + default: If it is given, this method will return `default` when `opt_str` is not found, + instead of raising a `ValueError`. Otherwise, it defaults to `"no_default"`, + so that the method may raise a `ValueError`. + print_all_options: whether to print all available options when `opt_str` is not found. Defaults to True + + Examples: + + .. code-block:: python + + from enum import Enum + from monai.utils import look_up_option + class Color(Enum): + RED = "red" + BLUE = "blue" + look_up_option("red", Color) # + look_up_option(Color.RED, Color) # + look_up_option("read", Color) + # ValueError: By 'read', did you mean 'red'? + # 'read' is not a valid option. + # Available options are {'blue', 'red'}. + look_up_option("red", {"red", "blue"}) # "red" + + Adapted from https://github.com/NifTK/NiftyNet/blob/v0.6.0/niftynet/utilities/util_common.py#L249 + """ + if not isinstance(opt_str, Hashable): + raise ValueError(f"Unrecognized option type: {type(opt_str)}:{opt_str}.") + if isinstance(opt_str, str): + opt_str = opt_str.strip() + if isinstance(supported, enum.EnumMeta): + if isinstance(opt_str, str) and opt_str in {item.value for item in supported}: # type: ignore + # such as: "example" in MyEnum + return supported(opt_str) + if isinstance(opt_str, enum.Enum) and opt_str in supported: + # such as: MyEnum.EXAMPLE in MyEnum + return opt_str + elif isinstance(supported, Mapping) and opt_str in supported: + # such as: MyDict[key] + return supported[opt_str] + elif isinstance(supported, Collection) and opt_str in supported: + return opt_str + + if default != "no_default": + return default + + # find a close match + set_to_check: set + if isinstance(supported, enum.EnumMeta): + set_to_check = {item.value for item in supported} # type: ignore + else: + set_to_check = set(supported) if supported is not None else set() + if not set_to_check: + raise ValueError(f"No options available: {supported}.") + edit_dists = {} + opt_str = f"{opt_str}" + for key in set_to_check: + edit_dist = damerau_levenshtein_distance(f"{key}", opt_str) + if edit_dist <= 3: + edit_dists[key] = edit_dist + + supported_msg = f"Available options are {set_to_check}.\n" if print_all_options else "" + if edit_dists: + guess_at_spelling = min(edit_dists, key=edit_dists.get) # type: ignore + raise ValueError( + f"By '{opt_str}', did you mean '{guess_at_spelling}'?\n" + + f"'{opt_str}' is not a valid value.\n" + + supported_msg + ) + raise ValueError(f"Unsupported option '{opt_str}', " + supported_msg) + + +def damerau_levenshtein_distance(s1: str, s2: str) -> int: + """ + Calculates the Damerau–Levenshtein distance between two strings for spelling correction. + https://en.wikipedia.org/wiki/Damerau–Levenshtein_distance + """ + if s1 == s2: + return 0 + string_1_length = len(s1) + string_2_length = len(s2) + if not s1: + return string_2_length + if not s2: + return string_1_length + d = {(i, -1): i + 1 for i in range(-1, string_1_length + 1)} + for j in range(-1, string_2_length + 1): + d[(-1, j)] = j + 1 + + for i, s1i in enumerate(s1): + for j, s2j in enumerate(s2): + cost = 0 if s1i == s2j else 1 + d[(i, j)] = min( + 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 + + return d[string_1_length - 1, string_2_length - 1] + + +def export(modname): + """ + Make the decorated object a member of the named module. This will also add the object under its aliases if it has + a `__aliases__` member, thus this decorator should be before the `alias` decorator to pick up those names. Alias + names which conflict with package names or existing members will be ignored. + """ + + def _inner(obj): + mod = import_module(modname) + if not hasattr(mod, obj.__name__): + setattr(mod, obj.__name__, obj) + + # add the aliases for `obj` to the target module + for alias in getattr(obj, "__aliases__", ()): + if not hasattr(mod, alias): + setattr(mod, alias, obj) + + return obj + + return _inner + + +def load_submodules( + basemod: ModuleType, load_all: bool = True, exclude_pattern: str = "(.*[tT]est.*)|(_.*)" +) -> tuple[list[ModuleType], list[str]]: + """ + Traverse the source of the module structure starting with module `basemod`, loading all packages plus all files if + `load_all` is True, excluding anything whose name matches `exclude_pattern`. + """ + submodules = [] + err_mod: list[str] = [] + for importer, name, is_pkg in walk_packages( + basemod.__path__, prefix=basemod.__name__ + ".", onerror=err_mod.append + ): + if (is_pkg or load_all) and name not in sys.modules and match(exclude_pattern, name) is None: + try: + mod = import_module(name) + importer.find_spec(name).loader.load_module(name) # type: ignore + submodules.append(mod) + except OptionalImportError: + pass # could not import the optional deps., they are ignored + except ImportError as e: + msg = ( + "\nMultiple versions of MONAI may have been installed?\n" + "Please see the installation guide: https://docs.monai.io/en/stable/installation.html\n" + ) # issue project-monai/monai#5193 + raise type(e)(f"{e}\n{msg}").with_traceback(e.__traceback__) from e # raise with modified message + + return submodules, err_mod + + +def instantiate(__path: str, __mode: str, **kwargs: Any) -> Any: + """ + Create an object instance or call a callable object from a class or function represented by ``_path``. + `kwargs` will be part of the input arguments to the class constructor or function. + The target component must be a class or a function, if not, return the component directly. + + Args: + __path: if a string is provided, it's interpreted as the full path of the target class or function component. + If a callable is provided, ``__path(**kwargs)`` will be invoked and returned for ``__mode="default"``. + For ``__mode="callable"``, the callable will be returned as ``__path`` or, if ``kwargs`` are provided, + as ``functools.partial(__path, **kwargs)`` for future invoking. + + __mode: the operating mode for invoking the (callable) ``component`` represented by ``__path``: + + - ``"default"``: returns ``component(**kwargs)`` + - ``"callable"``: returns ``component`` or, if ``kwargs`` are provided, ``functools.partial(component, **kwargs)`` + - ``"debug"``: returns ``pdb.runcall(component, **kwargs)`` + + kwargs: keyword arguments to the callable represented by ``__path``. + + """ + from monai.utils.enums import CompInitMode + + component = locate(__path) if isinstance(__path, str) else __path + if component is None: + raise ModuleNotFoundError(f"Cannot locate class or function path: '{__path}'.") + m = look_up_option(__mode, CompInitMode) + try: + if kwargs.pop("_debug_", False) or run_debug: + warnings.warn( + f"\n\npdb: instantiating component={component}, mode={m}\n" + f"See also Debugger commands documentation: https://docs.python.org/3/library/pdb.html\n" + ) + breakpoint() + if not callable(component): + warnings.warn(f"Component {component} is not callable when mode={m}.") + return component + if m == CompInitMode.DEFAULT: + return component(**kwargs) + if m == CompInitMode.CALLABLE: + return partial(component, **kwargs) if kwargs else component + if m == CompInitMode.DEBUG: + warnings.warn( + f"\n\npdb: instantiating component={component}, mode={m}\n" + f"See also Debugger commands documentation: https://docs.python.org/3/library/pdb.html\n" + ) + return pdb.runcall(component, **kwargs) + except Exception as e: + raise RuntimeError( + f"Failed to instantiate component '{__path}' with keywords: {','.join(kwargs.keys())}" + f"\n set '_mode_={CompInitMode.DEBUG}' to enter the debugging mode." + ) from e + + warnings.warn(f"Component to instantiate must represent a valid class or function, but got {__path}.") + return component + + +def get_full_type_name(typeobj): + """ + Utility to get the full path name of a class or object type. + + """ + module = typeobj.__module__ + if module is None or module == str.__class__.__module__: + return typeobj.__name__ # Avoid reporting __builtin__ + return module + "." + typeobj.__name__ + + +def min_version(the_module: Any, min_version_str: str = "", *_args: Any) -> bool: + """ + Convert version strings into tuples of int and compare them. + + Returns True if the module's version is greater or equal to the 'min_version'. + When min_version_str is not provided, it always returns True. + """ + if not min_version_str or not hasattr(the_module, "__version__"): + return True # always valid version + + mod_version = tuple(int(x) for x in the_module.__version__.split(".")[:2]) + required = tuple(int(x) for x in min_version_str.split(".")[:2]) + return mod_version >= required + + +def exact_version(the_module: Any, version_str: str = "", *_args: Any) -> bool: + """ + Returns True if the module's __version__ matches version_str + """ + if not hasattr(the_module, "__version__"): + warnings.warn(f"{the_module} has no attribute __version__ in exact_version check.") + return False + return bool(the_module.__version__ == version_str) + + +class InvalidPyTorchVersionError(Exception): + """ + Raised when called function or method requires a more recent + PyTorch version than that installed. + """ + + def __init__(self, required_version, name): + message = f"{name} requires PyTorch version {required_version} or later" + super().__init__(message) + + +class OptionalImportError(ImportError): + """ + Could not import APIs from an optional dependency. + """ + + +def optional_import( + module: str, + version: str = "", + version_checker: Callable[..., bool] = min_version, + name: str = "", + descriptor: str = OPTIONAL_IMPORT_MSG_FMT, + version_args: Any = None, + allow_namespace_pkg: bool = False, + as_type: str = "default", +) -> tuple[Any, bool]: + """ + Imports an optional module specified by `module` string. + Any importing related exceptions will be stored, and exceptions raise lazily + when attempting to use the failed-to-import module. + + Args: + module: name of the module to be imported. + version: version string used by the version_checker. + version_checker: a callable to check the module version, Defaults to monai.utils.min_version. + name: a non-module attribute (such as method/class) to import from the imported module. + descriptor: a format string for the final error message when using a not imported module. + version_args: additional parameters to the version checker. + allow_namespace_pkg: whether importing a namespace package is allowed. Defaults to False. + as_type: there are cases where the optionally imported object is used as + a base class, or a decorator, the exceptions should raise accordingly. The current supported values + are "default" (call once to raise), "decorator" (call the constructor and the second call to raise), + and anything else will return a lazy class that can be used as a base class (call the constructor to raise). + + Returns: + The imported module and a boolean flag indicating whether the import is successful. + + Examples:: + + >>> torch, flag = optional_import('torch', '1.1') + >>> print(torch, flag) + True + + >>> the_module, flag = optional_import('unknown_module') + >>> print(flag) + False + >>> the_module.method # trying to access a module which is not imported + OptionalImportError: import unknown_module (No module named 'unknown_module'). + + >>> torch, flag = optional_import('torch', '42', exact_version) + >>> torch.nn # trying to access a module for which there isn't a proper version imported + OptionalImportError: import torch (requires version '42' by 'exact_version'). + + >>> conv, flag = optional_import('torch.nn.functional', '1.0', name='conv1d') + >>> print(conv) + + + >>> conv, flag = optional_import('torch.nn.functional', '42', name='conv1d') + >>> conv() # trying to use a function from the not successfully imported module (due to unmatched version) + OptionalImportError: from torch.nn.functional import conv1d (requires version '42' by 'min_version'). + """ + + tb = None + exception_str = "" + if name: + actual_cmd = f"from {module} import {name}" + else: + actual_cmd = f"import {module}" + try: + pkg = __import__(module) # top level module + the_module = import_module(module) + if not allow_namespace_pkg: + is_namespace = getattr(the_module, "__file__", None) is None and hasattr(the_module, "__path__") + if is_namespace: + raise AssertionError + if name: # user specified to load class/function/... from the module + the_module = getattr(the_module, name) + except Exception as import_exception: # any exceptions during import + tb = import_exception.__traceback__ + exception_str = f"{import_exception}" + else: # found the module + if version_args and version_checker(pkg, f"{version}", version_args): + return the_module, True + if not version_args and version_checker(pkg, f"{version}"): + return the_module, True + + # preparing lazy error message + msg = descriptor.format(actual_cmd) + if version and tb is None: # a pure version issue + msg += f" (requires '{module} {version}' by '{version_checker.__name__}')" + if exception_str: + msg += f" ({exception_str})" + + class _LazyRaise: + + def __init__(self, *_args, **_kwargs): + _default_msg = ( + f"{msg}." + + "\n\nFor details about installing the optional dependencies, please visit:" + + "\n https://docs.monai.io/en/latest/installation.html#installing-the-recommended-dependencies" + ) + if tb is None: + self._exception = OptionalImportError(_default_msg) + else: + self._exception = OptionalImportError(_default_msg).with_traceback(tb) + + def __getattr__(self, name): + """ + Raises: + OptionalImportError: When you call this method. + """ + raise self._exception + + def __call__(self, *_args, **_kwargs): + """ + Raises: + OptionalImportError: When you call this method. + """ + raise self._exception + + def __getitem__(self, item): + raise self._exception + + def __iter__(self): + raise self._exception + + if as_type == "default": + return _LazyRaise(), False + + class _LazyCls(_LazyRaise): + + def __init__(self, *_args, **kwargs): + super().__init__() + if not as_type.startswith("decorator"): + raise self._exception + + return _LazyCls, False + + +def require_pkg( + pkg_name: str, version: str = "", version_checker: Callable[..., bool] = min_version, raise_error: bool = True +) -> Callable: + """ + Decorator function to check the required package installation. + + Args: + pkg_name: required package name, like: "itk", "nibabel", etc. + version: required version string used by the version_checker. + version_checker: a callable to check the module version, defaults to `monai.utils.min_version`. + raise_error: if True, raise `OptionalImportError` error if the required package is not installed + or the version doesn't match requirement, if False, print the error in a warning. + + """ + + def _decorator(obj): + is_func = isinstance(obj, FunctionType) + call_obj = obj if is_func else obj.__init__ + + @wraps(call_obj) + def _wrapper(*args, **kwargs): + _, has = optional_import(module=pkg_name, version=version, version_checker=version_checker) + if not has: + err_msg = f"required package `{pkg_name}` is not installed or the version doesn't match requirement." + if raise_error: + raise OptionalImportError(err_msg) + else: + warnings.warn(err_msg) + + return call_obj(*args, **kwargs) + + if is_func: + return _wrapper + obj.__init__ = _wrapper + return obj + + return _decorator + + +def get_package_version(dep_name, default="NOT INSTALLED or UNKNOWN VERSION."): + """ + Try to load package and get version. If not found, return `default`. + """ + dep, has_dep = optional_import(dep_name) + if has_dep and hasattr(dep, "__version__"): + return dep.__version__ + return default + + +@functools.lru_cache(None) +def get_torch_version_tuple(): + """ + Returns: + tuple of ints represents the pytorch major/minor version. + """ + return tuple(int(x) for x in torch.__version__.split(".")[:2]) + + +def parse_version_strs(lhs: str, rhs: str) -> tuple[Iterable[int | str], Iterable[int | str]]: + """ + Parse the version strings. + """ + + def _try_cast(val: str) -> int | str: + val = val.strip() + try: + m = match("(\\d+)(.*)", val) + if m is not None: + val = m.groups()[0] + return int(val) + return val + except ValueError: + return val + + # remove git version suffixes if present + lhs = lhs.split("+", 1)[0] + rhs = rhs.split("+", 1)[0] + + # parse the version strings in this basic way without `packaging` package + lhs_ = map(_try_cast, lhs.split(".")) + rhs_ = map(_try_cast, rhs.split(".")) + return lhs_, rhs_ + + +def version_leq(lhs: str, rhs: str) -> bool: + """ + Returns True if version `lhs` is earlier or equal to `rhs`. + + Args: + lhs: version name to compare with `rhs`, return True if earlier or equal to `rhs`. + rhs: version name to compare with `lhs`, return True if later or equal to `lhs`. + + """ + + lhs, rhs = str(lhs), str(rhs) + pkging, has_ver = optional_import("pkg_resources", name="packaging") + if has_ver: + try: + return cast(bool, pkging.version.Version(lhs) <= pkging.version.Version(rhs)) + except pkging.version.InvalidVersion: + return True + + lhs_, rhs_ = parse_version_strs(lhs, rhs) + for l, r in zip(lhs_, rhs_): + if l != r: + if isinstance(l, int) and isinstance(r, int): + return l < r + return f"{l}" < f"{r}" + + return True + + +def version_geq(lhs: str, rhs: str) -> bool: + """ + Returns True if version `lhs` is later or equal to `rhs`. + + Args: + lhs: version name to compare with `rhs`, return True if later or equal to `rhs`. + rhs: version name to compare with `lhs`, return True if earlier or equal to `lhs`. + + """ + lhs, rhs = str(lhs), str(rhs) + pkging, has_ver = optional_import("pkg_resources", name="packaging") + if has_ver: + try: + return cast(bool, pkging.version.Version(lhs) >= pkging.version.Version(rhs)) + except pkging.version.InvalidVersion: + return True + + lhs_, rhs_ = parse_version_strs(lhs, rhs) + for l, r in zip(lhs_, rhs_): + if l != r: + if isinstance(l, int) and isinstance(r, int): + return l > r + return f"{l}" > f"{r}" + + return True + + +@functools.lru_cache(None) +def pytorch_after(major: int, minor: int, patch: int = 0, current_ver_string: str | None = None) -> bool: + """ + Compute whether the current pytorch version is after or equal to the specified version. + The current system pytorch version is determined by `torch.__version__` or + via system environment variable `PYTORCH_VER`. + + Args: + major: major version number to be compared with + minor: minor version number to be compared with + patch: patch version number to be compared with + current_ver_string: if None, `torch.__version__` will be used. + + Returns: + True if the current pytorch version is greater than or equal to the specified version. + """ + + try: + if current_ver_string is None: + _env_var = os.environ.get("PYTORCH_VER", "") + current_ver_string = _env_var if _env_var else torch.__version__ + ver, has_ver = optional_import("pkg_resources", name="parse_version") + if has_ver: + return ver(".".join((f"{major}", f"{minor}", f"{patch}"))) <= ver(f"{current_ver_string}") # type: ignore + parts = f"{current_ver_string}".split("+", 1)[0].split(".", 3) + while len(parts) < 3: + parts += ["0"] + c_major, c_minor, c_patch = parts[:3] + except (AttributeError, ValueError, TypeError): + c_major, c_minor = get_torch_version_tuple() + c_patch = "0" + c_mn = int(c_major), int(c_minor) + mn = int(major), int(minor) + if c_mn != mn: + return c_mn > mn + is_prerelease = ("a" in f"{c_patch}".lower()) or ("rc" in f"{c_patch}".lower()) + c_p = 0 + try: + p_reg = re.search(r"\d+", f"{c_patch}") + if p_reg: + c_p = int(p_reg.group()) + except (AttributeError, TypeError, ValueError): + is_prerelease = True + patch = int(patch) + if c_p != patch: + return c_p > patch + if is_prerelease: + return False + return True diff --git a/source_code/SegMamba/monai/utils/nvtx.py b/source_code/SegMamba/monai/utils/nvtx.py new file mode 100644 index 0000000000000000000000000000000000000000..2cea9aabd1b71300fbf679fb94666fd566e80a0b --- /dev/null +++ b/source_code/SegMamba/monai/utils/nvtx.py @@ -0,0 +1,176 @@ +# Copyright (c) MONAI Consortium +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +""" +Decorators and context managers for NVIDIA Tools Extension to profile MONAI components +""" + +from __future__ import annotations + +from collections import defaultdict +from functools import wraps +from typing import Any + +from torch.autograd import Function +from torch.nn import Module +from torch.optim import Optimizer +from torch.utils.data import Dataset + +from monai.utils import ensure_tuple, optional_import + +_nvtx, _ = optional_import("torch._C._nvtx", descriptor="NVTX is not installed. Are you sure you have a CUDA build?") + +__all__ = ["Range"] + + +class Range: + """ + A decorator and context manager for NVIDIA Tools Extension (NVTX) Range for profiling. + When used as a decorator it encloses a specific method of the object with an NVTX Range. + When used as a context manager, it encloses the runtime context (created by with statement) with an NVTX Range. + + Args: + name: the name to be associated to the range + methods: (only when used as decorator) the name of a method (or a list of the name of the methods) + to be wrapped by NVTX range. + If None (default), the method(s) will be inferred based on the object's type for various MONAI components, + such as Networks, Losses, Functions, Transforms, and Datasets. + Otherwise, it look up predefined methods: "forward", "__call__", "__next__", "__getitem__" + append_method_name: if append the name of the methods to be decorated to the range's name + If None (default), it appends the method's name only if we are annotating more than one method. + recursive: if set to True, it will recursively annotate every individual module in a list + or in a chain of modules (chained using Compose). Default to False. + + """ + + name_counter: dict = defaultdict(int) + + def __init__( + self, + name: str | None = None, + methods: str | tuple[str, ...] | None = None, + append_method_name: bool | None = None, + recursive: bool = False, + ) -> None: + self.name = name + self.methods = methods + self.append_method_name = append_method_name + self.recursive = recursive + + def __call__(self, obj: Any) -> Any: + if self.recursive is True: + if isinstance(obj, (list, tuple)): + return type(obj)(Range(recursive=True)(t) for t in obj) + + from monai.transforms.compose import Compose + + if isinstance(obj, Compose): + obj.transforms = Range(recursive=True)(obj.transforms) + + self.recursive = False + + # Define the name to be associated to the range if not provided + if self.name is None: + name = type(obj).__name__ + # If CuCIM or TorchVision transform wrappers are being used, + # append the underlying transform to the name for more clarity + if "CuCIM" in name or "TorchVision" in name: + name = f"{name}_{obj.name}" + self.name_counter[name] += 1 + if self.name_counter[name] > 1: + self.name = f"{name}_{self.name_counter[name]}" + else: + self.name = name + + # Define the methods to be wrapped if not provided + if self.methods is None: + self.methods = self._get_method(obj) + else: + self.methods = ensure_tuple(self.methods) + + # Check if to append method's name to the range's name + if self.append_method_name is None: + if len(self.methods) > 1: + self.append_method_name = True + else: + self.append_method_name = False + + # Decorate the methods + for method in self.methods: + self._decorate_method(obj, method, self.append_method_name) + + return obj + + def _decorate_method(self, obj, method, append_method_name): + # Append the method's name to the range's name + name = f"{self.name}.{method}" if append_method_name else self.name + + # Get the class for special functions + if method.startswith("__"): + owner = type(obj) + else: + owner = obj + + # Get the method to be wrapped + _temp_func = getattr(owner, method) + + # Wrap the method with NVTX range (range push/pop) + @wraps(_temp_func) + def range_wrapper(*args, **kwargs): + _nvtx.rangePushA(name) + output = _temp_func(*args, **kwargs) + _nvtx.rangePop() + return output + + # Replace the method with the wrapped version + if method.startswith("__"): + # If it is a special method, it requires special attention + class NVTXRangeDecoratedClass(owner): # type: ignore + ... + + setattr(NVTXRangeDecoratedClass, method, range_wrapper) + obj.__class__ = NVTXRangeDecoratedClass + + else: + setattr(owner, method, range_wrapper) + + def _get_method(self, obj: Any) -> tuple: + if isinstance(obj, Module): + method_list = ["forward"] + elif isinstance(obj, Optimizer): + method_list = ["step"] + elif isinstance(obj, Function): + method_list = ["forward", "backward"] + elif isinstance(obj, Dataset): + method_list = ["__getitem__"] + else: + default_methods = ["forward", "__call__", "__next__", "__getitem__"] + method_list = [] + for method in default_methods: + if hasattr(obj, method): + method_list.append(method) + if len(method_list) < 1: + raise ValueError( + f"The method to be wrapped for this object [{type(obj)}] is not recognized." + "The name of the method should be provided or the object should have one of these methods:" + f"{default_methods}" + ) + return ensure_tuple(method_list) + + def __enter__(self): + if self.name is None: + # Number the range with class variable counter to avoid duplicate names. + self.name_counter["context"] += 1 + self.name = f"context_{self.name_counter['context']}" + + _nvtx.rangePushA(self.name) + + def __exit__(self, type, value, traceback): + _nvtx.rangePop() diff --git a/source_code/SegMamba/monai/utils/profiling.py b/source_code/SegMamba/monai/utils/profiling.py new file mode 100644 index 0000000000000000000000000000000000000000..5c880bbe1fdce50c9fbbd2bd03c13d238bfc6a19 --- /dev/null +++ b/source_code/SegMamba/monai/utils/profiling.py @@ -0,0 +1,432 @@ +# Copyright (c) MONAI Consortium +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from __future__ import annotations + +import csv +import datetime +import multiprocessing +import os +import sys +import threading +from collections import defaultdict, namedtuple +from contextlib import contextmanager +from functools import wraps +from inspect import getframeinfo, stack +from queue import Empty +from time import perf_counter, perf_counter_ns +from typing import TYPE_CHECKING, Any, cast + +import numpy as np +import torch + +from monai.utils import optional_import + +if TYPE_CHECKING: + from ignite.engine import Events +else: + Events = optional_import("ignite.engine", name="Events") + +pd, has_pandas = optional_import("pandas") + +__all__ = [ + "torch_profiler_full", + "torch_profiler_time_cpu_gpu", + "torch_profiler_time_end_to_end", + "PerfContext", + "WorkflowProfiler", + "ProfileHandler", + "select_transform_call", +] + + +def torch_profiler_full(func): + """ + A decorator which will run the torch profiler for the decorated function, + printing the results in full. + Note: Enforces a gpu sync point which could slow down pipelines. + """ + + @wraps(func) + def wrapper(*args, **kwargs): + with torch.autograd.profiler.profile(use_cuda=True) as prof: + result = func(*args, **kwargs) + + print(prof, flush=True) + + return result + + return wrapper + + +def torch_profiler_time_cpu_gpu(func): + """ + A decorator which measures the execution time of both the CPU and GPU components + of the decorated function, printing both results. + Note: Enforces a gpu sync point which could slow down pipelines. + """ + + @wraps(func) + def wrapper(*args, **kwargs): + with torch.autograd.profiler.profile(use_cuda=True) as prof: + result = func(*args, **kwargs) + + cpu_time = prof.self_cpu_time_total + gpu_time = sum(evt.self_cuda_time_total for evt in prof.function_events) + + cpu_time = torch.autograd.profiler.format_time(cpu_time) # type: ignore + gpu_time = torch.autograd.profiler.format_time(gpu_time) # type: ignore + + print(f"cpu time: {cpu_time}, gpu time: {gpu_time}", flush=True) + + return result + + return wrapper + + +def torch_profiler_time_end_to_end(func): + """ + A decorator which measures the total execution time from when the decorated + function is called to when the last cuda operation finishes, printing the result. + Note: Enforces a gpu sync point which could slow down pipelines. + """ + + @wraps(func) + def wrapper(*args, **kwargs): + torch.cuda.synchronize() + start = perf_counter() + + result = func(*args, **kwargs) + + torch.cuda.synchronize() + end = perf_counter() + + total_time = (end - start) * 1e6 + total_time_str = torch.autograd.profiler.format_time(total_time) # type: ignore + print(f"End-to-end time: {total_time_str}", flush=True) + + return result + + return wrapper + + +class PerfContext: + """ + Context manager for tracking how much time is spent within context blocks. This uses `time.perf_counter` to + accumulate the total amount of time in seconds in the attribute `total_time` over however many context blocks + the object is used in. + """ + + def __init__(self): + self.total_time: float = 0 + self.start_time: float | None = None + + def __enter__(self): + self.start_time = perf_counter() + return self + + def __exit__(self, exc_type, exc_value, exc_traceback): + if self.start_time is not None: + self.total_time += perf_counter() - self.start_time + self.start_time = None + + +# stores the results from profiling with trace or with other helper methods +ProfileResult = namedtuple("ProfileResult", ["name", "time", "filename", "lineno", "pid", "timestamp"]) + + +def select_transform_call(frame): + """Returns True if `frame` is a call to a `Transform` object's `_call__` method.""" + from monai.transforms import Transform # prevents circular import + + self_obj = frame.f_locals.get("self", None) + return frame.f_code.co_name == "__call__" and isinstance(self_obj, Transform) + + +class WorkflowProfiler: + """ + Profiler for timing all aspects of a workflow. This includes using stack tracing to capture call times for + all selected calls (by default calls to `Transform.__call__` methods), times within context blocks, times + to generate items from iterables, and times to execute decorated functions. + + This profiler must be used only within its context because it uses an internal thread to read results from a + multiprocessing queue. This allows the profiler to function across multiple threads and processes, though the + multiprocess tracing is at times unreliable and not available in Windows at all. + + The profiler uses `sys.settrace` and `threading.settrace` to find all calls to profile, this will be set when + the context enters and cleared when it exits so proper use of the context is essential to prevent excessive + tracing. Note that tracing has a high overhead so times will not accurately reflect real world performance + but give an idea of relative share of time spent. + + The tracing functionality uses a selector to choose which calls to trace, since tracing all calls induces + infinite loops and would be terribly slow even if not. This selector is a callable accepting a `call` trace + frame and returns True if the call should be traced. The default is `select_transform_call` which will return + True for `Transform.__call__` calls only. + + Example showing use of all profiling functions: + + .. code-block:: python + + import monai.transform as mt + from monai.utils import WorkflowProfiler + import torch + + comp=mt.Compose([mt.ScaleIntensity(),mt.RandAxisFlip(0.5)]) + + with WorkflowProfiler() as wp: + for _ in wp.profile_iter("range",range(5)): + with wp.profile_ctx("Loop"): + for i in range(10): + comp(torch.rand(1,16,16)) + + @wp.profile_callable() + def foo(): pass + + foo() + foo() + + print(wp.get_times_summary_pd()) # print results + + Args: + call_selector: selector to determine which calls to trace, use None to disable tracing + """ + + def __init__(self, call_selector=select_transform_call): + self.results = defaultdict(list) + self.parent_pid = os.getpid() + self.read_thread: threading.Thread | None = None + self.lock = threading.RLock() + self.queue: multiprocessing.SimpleQueue = multiprocessing.SimpleQueue() + self.queue_timeout = 0.1 + self.call_selector = call_selector + + def _is_parent(self): + """Return True if this is the parent process.""" + return os.getpid() == self.parent_pid + + def _is_thread_active(self): + """Return True if the read thread should be still active.""" + return self.read_thread is not None or not self.queue.empty() + + def _read_thread_func(self): + """Read results from the queue and add to self.results in a thread stared by `__enter__`.""" + while self._is_parent() and self._is_thread_active(): + try: + result = self.queue.get() + + if result is None: + break + + self.add_result(result) + except Empty: + pass + + if not (not self._is_parent() or self.queue.empty()): + raise AssertionError + + def _put_result(self, name, timedelta, filename, lineno): + """Add a ProfileResult object to the queue.""" + ts = str(datetime.datetime.now()) + self.queue.put(ProfileResult(name, timedelta, filename, lineno, os.getpid(), ts)) + + def _trace_call(self, frame, why, arg): + """ + Trace calls, when a call is encountered that is accepted by self.call_selector, create a new function to + trace that call and measure the time from the call to a "return" frame. + """ + if why == "call": + if self.call_selector(frame): + calling_frame = frame + start = perf_counter_ns() + + def _call_profiler(frame, why, arg): + """Defines a new inner trace function just for this call.""" + if why == "return": + diff = perf_counter_ns() - start + f_code = calling_frame.f_code + self_obj = calling_frame.f_locals.get("self", None) + name = f_code.co_name + if self_obj is not None: + name = f"{type(self_obj).__name__}.{name}" + + self._put_result(name, diff, f_code.co_filename, f_code.co_firstlineno) + + # This function will be used to trace this specific call now, however any new functions calls + # within will cause a "call" frame to be sent to `_trace_call` rather than to it, ie. it's not + # actually recursively tracing everything below as the documentation suggests and so cannot + # control whether subsequence calls are traced (see https://bugs.python.org/issue11992). + return _call_profiler + else: + return self._trace_call + + def __enter__(self): + """Enter the context, creating the read thread and setting up tracing if needed.""" + self.read_thread = threading.Thread(target=self._read_thread_func) + self.read_thread.start() + + if self.call_selector is not None: + threading.settrace(self._trace_call) + sys.settrace(self._trace_call) + + return self + + def __exit__(self, exc_type, exc_value, traceback): + """Terminate the read thread cleanly and reset tracing if needed.""" + if not self._is_parent(): + raise AssertionError + + self.queue.put(None) + + read_thread = cast(threading.Thread, self.read_thread) + self.read_thread = None + + read_thread.join() + + if self.call_selector is not None: + threading.settrace(None) # type: ignore + sys.settrace(None) + + def add_result(self, result: ProfileResult) -> None: + """Add a result in a thread-safe manner to the internal results dictionary.""" + with self.lock: + self.results[result.name].append(result) + + def get_results(self): + """Get a fresh results dictionary containing fresh tuples of ProfileResult objects.""" + if not self._is_parent(): + raise RuntimeError("Only parent process can collect results") + + with self.lock: + return {k: tuple(v) for k, v in self.results.items()} + + @contextmanager + def profile_ctx(self, name, caller=None): + """Creates a context to profile, placing a timing result onto the queue when it exits.""" + if caller is None: + caller = getframeinfo(stack()[2][0]) # caller of context, not something in contextlib + + start = perf_counter_ns() + try: + yield + finally: + diff = perf_counter_ns() - start + self._put_result(name, diff, caller.filename, caller.lineno) + + def profile_callable(self, name=None): + """ + Decorator which can be applied to a function which profiles any calls to it. All calls to decorated + callables must be done within the context of the profiler. + """ + + def _outer(func): + _name = func.__name__ if name is None else name + return self.profile_ctx(_name)(func) + + return _outer + + def profile_iter(self, name, iterable): + """Wrapper around anything iterable to profile how long it takes to generate items.""" + + class _Iterable: + + def __iter__(_self): # noqa: B902, N805 pylint: disable=E0213 + do_iter = True + orig_iter = iter(iterable) + caller = getframeinfo(stack()[1][0]) + + while do_iter: + try: + start = perf_counter_ns() + item = next(orig_iter) + diff = perf_counter_ns() - start + # don't put result when StopIteration is hit + self._put_result(name, diff, caller.filename, caller.lineno) + yield item + except StopIteration: + do_iter = False + + return _Iterable() + + def get_times_summary(self, times_in_s=True): + """ + Returns a dictionary mapping results entries to tuples containing the number of items, time sum, time average, + time std dev, time min, and time max. + """ + result = {} + for k, v in self.get_results().items(): + timemult = 1e-9 if times_in_s else 1.0 + all_times = [res.time * timemult for res in v] + + timesum = sum(all_times) + timeavg = timesum / len(all_times) + timestd = np.std(all_times) + timemin = min(all_times) + timemax = max(all_times) + + result[k] = (len(v), timesum, timeavg, timestd, timemin, timemax) + + return result + + def get_times_summary_pd(self, times_in_s=True): + """Returns the same information as `get_times_summary` but in a Pandas DataFrame.""" + import pandas as pd + + summ = self.get_times_summary(times_in_s) + suffix = "s" if times_in_s else "ns" + columns = ["Count", f"Total Time ({suffix})", "Avg", "Std", "Min", "Max"] + + df = pd.DataFrame.from_dict(summ, orient="index", columns=columns) + df = df.sort_values(columns[1], ascending=False) + return df + + def dump_csv(self, stream=sys.stdout): + """Save all results to a csv file.""" + all_results = list(self.get_results().values()) + writer = csv.DictWriter(stream, fieldnames=all_results[0][0]._asdict().keys()) + writer.writeheader() + + for rlist in all_results: + for r in rlist: + writer.writerow(r._asdict()) + + +class ProfileHandler: + """ + Handler for Ignite Engine classes which measures the time from a start event ton an end event. This can be used to + profile epoch, iteration, and other events as defined in `ignite.engine.Events`. This class should be used only + within the context of a profiler object. + + Args: + name: name of event to profile + profiler: instance of WorkflowProfiler used by the handler, should be within the context of this object + start_event: item in `ignite.engine.Events` stating event at which to start timing + end_event: item in `ignite.engine.Events` stating event at which to stop timing + """ + + def __init__(self, name: str, profiler: WorkflowProfiler, start_event: Events, end_event: Events): + self.name = name + self.profiler = profiler + self.start_event = start_event + self.end_event = end_event + self.ctx: Any = None + + def attach(self, engine): + engine.add_event_handler(self.start_event, self.start) + engine.add_event_handler(self.end_event, self.end) + return self + + def start(self, engine): + self.ctx = self.profiler.profile_ctx(self.name) + self.ctx.__enter__() + + def end(self, engine): + self.ctx.__exit__(None, None, None) + self.ctx = None diff --git a/source_code/SegMamba/monai/utils/state_cacher.py b/source_code/SegMamba/monai/utils/state_cacher.py new file mode 100644 index 0000000000000000000000000000000000000000..d37e7abde4d68fa020737b208ce7420c8d322f0b --- /dev/null +++ b/source_code/SegMamba/monai/utils/state_cacher.py @@ -0,0 +1,137 @@ +# Copyright (c) MONAI Consortium +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from __future__ import annotations + +import copy +import os +import pickle +import tempfile +from types import ModuleType +from typing import Any, Hashable + +import torch +from torch.serialization import DEFAULT_PROTOCOL + +from monai.config.type_definitions import PathLike + +__all__ = ["StateCacher"] + + +class StateCacher: + """Class to cache and retrieve the state of an object. + + Objects can either be stored in memory or on disk. If stored on disk, they can be + stored in a given directory, or alternatively a temporary location will be used. + + If necessary/possible, restored objects will be returned to their original device. + + Example: + + >>> state_cacher = StateCacher(memory_cache, cache_dir=cache_dir) + >>> state_cacher.store("model", model.state_dict()) + >>> model.load_state_dict(state_cacher.retrieve("model")) + """ + + def __init__( + self, + in_memory: bool, + cache_dir: PathLike | None = None, + allow_overwrite: bool = True, + pickle_module: ModuleType = pickle, + pickle_protocol: int = DEFAULT_PROTOCOL, + ) -> None: + """Constructor. + + Args: + in_memory: boolean to determine if the object will be cached in memory or on + disk. + cache_dir: directory for data to be cached if `in_memory==False`. Defaults + to using a temporary directory. Any created files will be deleted during + the `StateCacher`'s destructor. + allow_overwrite: allow the cache to be overwritten. If set to `False`, an + error will be thrown if a matching already exists in the list of cached + objects. + pickle_module: module used for pickling metadata and objects, default to `pickle`. + this arg is used by `torch.save`, for more details, please check: + https://pytorch.org/docs/stable/generated/torch.save.html#torch.save. + pickle_protocol: can be specified to override the default protocol, default to `2`. + this arg is used by `torch.save`, for more details, please check: + https://pytorch.org/docs/stable/generated/torch.save.html#torch.save. + + """ + self.in_memory = in_memory + self.cache_dir = tempfile.gettempdir() if cache_dir is None else cache_dir + if not os.path.isdir(self.cache_dir): + raise ValueError("Given `cache_dir` is not a valid directory.") + + self.allow_overwrite = allow_overwrite + self.pickle_module = pickle_module + self.pickle_protocol = pickle_protocol + self.cached: dict = {} + + def store( + self, key: Hashable, data_obj: Any, pickle_module: ModuleType | None = None, pickle_protocol: int | None = None + ) -> None: + """ + Store a given object with the given key name. + + Args: + key: key of the data object to store. + data_obj: data object to store. + pickle_module: module used for pickling metadata and objects, default to `self.pickle_module`. + this arg is used by `torch.save`, for more details, please check: + https://pytorch.org/docs/stable/generated/torch.save.html#torch.save. + pickle_protocol: can be specified to override the default protocol, default to `self.pickle_protocol`. + this arg is used by `torch.save`, for more details, please check: + https://pytorch.org/docs/stable/generated/torch.save.html#torch.save. + + """ + if key in self.cached and not self.allow_overwrite: + raise RuntimeError("Cached key already exists and overwriting is disabled.") + if self.in_memory: + self.cached.update({key: {"obj": copy.deepcopy(data_obj)}}) + else: + fn = os.path.join(self.cache_dir, f"state_{key}_{id(self)}.pt") + self.cached.update({key: {"obj": fn}}) + torch.save( + obj=data_obj, + f=fn, + pickle_module=self.pickle_module if pickle_module is None else pickle_module, + pickle_protocol=self.pickle_protocol if pickle_protocol is None else pickle_protocol, + ) + # store object's device if relevant + if hasattr(data_obj, "device"): + self.cached[key]["device"] = data_obj.device + + def retrieve(self, key: Hashable) -> Any: + """Retrieve the object stored under a given key name.""" + if key not in self.cached: + raise KeyError(f"Target {key} was not cached.") + + if self.in_memory: + return self.cached[key]["obj"] + + fn = self.cached[key]["obj"] # pytype: disable=attribute-error + if not os.path.exists(fn): # pytype: disable=wrong-arg-types + raise RuntimeError(f"Failed to load state in {fn}. File doesn't exist anymore.") + data_obj = torch.load(fn, map_location=lambda storage, location: storage) + # copy back to device if necessary + if "device" in self.cached[key]: + data_obj = data_obj.to(self.cached[key]["device"]) + return data_obj + + def __del__(self): + """If necessary, delete any cached files existing in `cache_dir`.""" + if not self.in_memory: + for k in self.cached: + if os.path.exists(self.cached[k]["obj"]): + os.remove(self.cached[k]["obj"]) diff --git a/source_code/SegMamba/monai/utils/type_conversion.py b/source_code/SegMamba/monai/utils/type_conversion.py new file mode 100644 index 0000000000000000000000000000000000000000..e4f97fc4a6719fe6d9df1a2fbe4ca10d173244b5 --- /dev/null +++ b/source_code/SegMamba/monai/utils/type_conversion.py @@ -0,0 +1,471 @@ +# Copyright (c) MONAI Consortium +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from __future__ import annotations + +import re +from collections.abc import Sequence +from typing import Any + +import numpy as np +import torch + +import monai +from monai.config.type_definitions import DtypeLike, NdarrayTensor +from monai.utils import optional_import + +cp, has_cp = optional_import("cupy") +cp_ndarray, _ = optional_import("cupy", name="ndarray") + +__all__ = [ + "get_numpy_dtype_from_string", + "get_torch_dtype_from_string", + "dtype_torch_to_numpy", + "dtype_numpy_to_torch", + "get_equivalent_dtype", + "convert_data_type", + "get_dtype", + "convert_to_cupy", + "convert_to_numpy", + "convert_to_tensor", + "convert_to_dst_type", +] + +# conversion map for types unsupported by torch.as_tensor +UNSUPPORTED_TYPES = {np.dtype("uint16"): np.int32, np.dtype("uint32"): np.int64, np.dtype("uint64"): np.int64} + + +def get_numpy_dtype_from_string(dtype: str) -> np.dtype: + """Get a numpy dtype (e.g., `np.float32`) from its string (e.g., `"float32"`).""" + return np.empty([], dtype=str(dtype).split(".")[-1]).dtype + + +def get_torch_dtype_from_string(dtype: str) -> torch.dtype: + """Get a torch dtype (e.g., `torch.float32`) from its string (e.g., `"float32"`).""" + return dtype_numpy_to_torch(get_numpy_dtype_from_string(dtype)) + + +def dtype_torch_to_numpy(dtype: torch.dtype) -> np.dtype: + """Convert a torch dtype to its numpy equivalent.""" + return torch.empty([], dtype=dtype).numpy().dtype # type: ignore + + +def dtype_numpy_to_torch(dtype: np.dtype) -> torch.dtype: + """Convert a numpy dtype to its torch equivalent.""" + return torch.from_numpy(np.empty([], dtype=dtype)).dtype + + +def get_equivalent_dtype(dtype, data_type): + """Convert to the `dtype` that corresponds to `data_type`. + + The input dtype can also be a string. e.g., `"float32"` becomes `torch.float32` or + `np.float32` as necessary. + + Example:: + + im = torch.tensor(1) + dtype = get_equivalent_dtype(np.float32, type(im)) + + """ + if dtype is None: + return None + if data_type is torch.Tensor or data_type.__name__ == "MetaTensor": + if isinstance(dtype, torch.dtype): + # already a torch dtype and target `data_type` is torch.Tensor + return dtype + return dtype_numpy_to_torch(dtype) + if not isinstance(dtype, torch.dtype): + # assuming the dtype is ok if it is not a torch dtype and target `data_type` is not torch.Tensor + return dtype + return dtype_torch_to_numpy(dtype) + + +def get_dtype(data: Any) -> DtypeLike | torch.dtype: + """Get the dtype of an image, or if there is a sequence, recursively call the method on the 0th element. + + This therefore assumes that in a `Sequence`, all types are the same. + """ + if hasattr(data, "dtype"): + return data.dtype # type: ignore + # need recursion + if isinstance(data, Sequence): + return get_dtype(data[0]) + # objects like float don't have dtype, so return their type + return type(data) + + +def convert_to_tensor( + data: Any, + dtype: DtypeLike | torch.dtype = None, + device: None | str | torch.device = None, + wrap_sequence: bool = False, + track_meta: bool = False, + safe: bool = False, +) -> Any: + """ + Utility to convert the input data to a PyTorch Tensor, if `track_meta` is True, the output will be a `MetaTensor`, + otherwise, the output will be a regular torch Tensor. + If passing a dictionary, list or tuple, recursively check every item and convert it to PyTorch Tensor. + + Args: + data: input data can be PyTorch Tensor, numpy array, list, dictionary, int, float, bool, str, etc. + will convert Tensor, Numpy array, float, int, bool to Tensor, strings and objects keep the original. + for dictionary, list or tuple, convert every item to a Tensor if applicable. + dtype: target data type to when converting to Tensor. + device: target device to put the converted Tensor data. + wrap_sequence: if `False`, then lists will recursively call this function. + E.g., `[1, 2]` -> `[tensor(1), tensor(2)]`. If `True`, then `[1, 2]` -> `tensor([1, 2])`. + track_meta: whether to track the meta information, if `True`, will convert to `MetaTensor`. + default to `False`. + safe: if `True`, then do safe dtype convert when intensity overflow. default to `False`. + E.g., `[256, -12]` -> `[tensor(0), tensor(244)]`. + If `True`, then `[256, -12]` -> `[tensor(255), tensor(0)]`. + + """ + + def _convert_tensor(tensor: Any, **kwargs: Any) -> Any: + if not isinstance(tensor, torch.Tensor): + # certain numpy types are not supported as being directly convertible to Pytorch tensors + if isinstance(tensor, np.ndarray) and tensor.dtype in UNSUPPORTED_TYPES: + tensor = tensor.astype(UNSUPPORTED_TYPES[tensor.dtype]) + + # if input data is not Tensor, convert it to Tensor first + tensor = torch.as_tensor(tensor, **kwargs) + if track_meta and not isinstance(tensor, monai.data.MetaTensor): + return monai.data.MetaTensor(tensor) + if not track_meta and isinstance(tensor, monai.data.MetaTensor): + return tensor.as_tensor() + return tensor + + if safe: + data = safe_dtype_range(data, dtype) + dtype = get_equivalent_dtype(dtype, torch.Tensor) + if isinstance(data, torch.Tensor): + return _convert_tensor(data).to(dtype=dtype, device=device, memory_format=torch.contiguous_format) + if isinstance(data, np.ndarray): + # skip array of string classes and object, refer to: + # https://github.com/pytorch/pytorch/blob/v1.9.0/torch/utils/data/_utils/collate.py#L13 + if re.search(r"[SaUO]", data.dtype.str) is None: + # numpy array with 0 dims is also sequence iterable, + # `ascontiguousarray` will add 1 dim if img has no dim, so we only apply on data with dims + if data.ndim > 0: + data = np.ascontiguousarray(data) + return _convert_tensor(data, dtype=dtype, device=device) + elif (has_cp and isinstance(data, cp_ndarray)) or isinstance(data, (float, int, bool)): + return _convert_tensor(data, dtype=dtype, device=device) + elif isinstance(data, list): + list_ret = [convert_to_tensor(i, dtype=dtype, device=device, track_meta=track_meta) for i in data] + return _convert_tensor(list_ret, dtype=dtype, device=device) if wrap_sequence else list_ret + elif isinstance(data, tuple): + tuple_ret = tuple(convert_to_tensor(i, dtype=dtype, device=device, track_meta=track_meta) for i in data) + return _convert_tensor(tuple_ret, dtype=dtype, device=device) if wrap_sequence else tuple_ret + elif isinstance(data, dict): + return {k: convert_to_tensor(v, dtype=dtype, device=device, track_meta=track_meta) for k, v in data.items()} + + return data + + +def convert_to_numpy(data: Any, dtype: DtypeLike = None, wrap_sequence: bool = False, safe: bool = False) -> Any: + """ + Utility to convert the input data to a numpy array. If passing a dictionary, list or tuple, + recursively check every item and convert it to numpy array. + + Args: + data: input data can be PyTorch Tensor, numpy array, list, dictionary, int, float, bool, str, etc. + will convert Tensor, Numpy array, float, int, bool to numpy arrays, strings and objects keep the original. + for dictionary, list or tuple, convert every item to a numpy array if applicable. + dtype: target data type when converting to numpy array. + wrap_sequence: if `False`, then lists will recursively call this function. + E.g., `[1, 2]` -> `[array(1), array(2)]`. If `True`, then `[1, 2]` -> `array([1, 2])`. + safe: if `True`, then do safe dtype convert when intensity overflow. default to `False`. + E.g., `[256, -12]` -> `[array(0), array(244)]`. If `True`, then `[256, -12]` -> `[array(255), array(0)]`. + """ + if safe: + data = safe_dtype_range(data, dtype) + if isinstance(data, torch.Tensor): + data = np.asarray(data.detach().to(device="cpu").numpy(), dtype=get_equivalent_dtype(dtype, np.ndarray)) + elif has_cp and isinstance(data, cp_ndarray): + data = cp.asnumpy(data).astype(dtype, copy=False) + elif isinstance(data, (np.ndarray, float, int, bool)): + # Convert into a contiguous array first if the current dtype's size is smaller than the target dtype's size. + # This help improve the performance because (convert to contiguous array) -> (convert dtype) is faster + # than (convert dtype) -> (convert to contiguous array) when src dtype (e.g., uint8) is smaller than + # target dtype(e.g., float32) and we are going to convert it to contiguous array anyway later in this + # method. + if isinstance(data, np.ndarray) and data.ndim > 0 and data.dtype.itemsize < np.dtype(dtype).itemsize: + data = np.ascontiguousarray(data) + data = np.asarray(data, dtype=dtype) + elif isinstance(data, list): + list_ret = [convert_to_numpy(i, dtype=dtype) for i in data] + return np.asarray(list_ret) if wrap_sequence else list_ret + elif isinstance(data, tuple): + tuple_ret = tuple(convert_to_numpy(i, dtype=dtype) for i in data) + return np.asarray(tuple_ret) if wrap_sequence else tuple_ret + elif isinstance(data, dict): + return {k: convert_to_numpy(v, dtype=dtype) for k, v in data.items()} + + if isinstance(data, np.ndarray) and data.ndim > 0: + data = np.ascontiguousarray(data) + + return data + + +def convert_to_cupy(data: Any, dtype: np.dtype | None = None, wrap_sequence: bool = False, safe: bool = False) -> Any: + """ + Utility to convert the input data to a cupy array. If passing a dictionary, list or tuple, + recursively check every item and convert it to cupy array. + + Args: + data: input data can be PyTorch Tensor, numpy array, cupy array, list, dictionary, int, float, bool, str, etc. + Tensor, numpy array, cupy array, float, int, bool are converted to cupy arrays, + for dictionary, list or tuple, convert every item to a numpy array if applicable. + dtype: target data type when converting to Cupy array, tt must be an argument of `numpy.dtype`, + for more details: https://docs.cupy.dev/en/stable/reference/generated/cupy.array.html. + wrap_sequence: if `False`, then lists will recursively call this function. + E.g., `[1, 2]` -> `[array(1), array(2)]`. If `True`, then `[1, 2]` -> `array([1, 2])`. + safe: if `True`, then do safe dtype convert when intensity overflow. default to `False`. + E.g., `[256, -12]` -> `[array(0), array(244)]`. If `True`, then `[256, -12]` -> `[array(255), array(0)]`. + """ + if safe: + data = safe_dtype_range(data, dtype) + # direct calls + if isinstance(data, torch.Tensor) and data.device.type == "cuda": + # This is needed because of https://github.com/cupy/cupy/issues/7874#issuecomment-1727511030 + if data.dtype == torch.bool: + data = data.detach().to(torch.uint8) + if dtype is None: + dtype = bool # type: ignore + data = cp.asarray(data, dtype) + elif isinstance(data, (cp_ndarray, np.ndarray, torch.Tensor, float, int, bool)): + data = cp.asarray(data, dtype) + elif isinstance(data, list): + list_ret = [convert_to_cupy(i, dtype) for i in data] + return cp.asarray(list_ret) if wrap_sequence else list_ret + elif isinstance(data, tuple): + tuple_ret = tuple(convert_to_cupy(i, dtype) for i in data) + return cp.asarray(tuple_ret) if wrap_sequence else tuple_ret + elif isinstance(data, dict): + return {k: convert_to_cupy(v, dtype) for k, v in data.items()} + # make it contiguous + if not isinstance(data, cp.ndarray): + raise ValueError(f"The input data type [{type(data)}] cannot be converted into cupy arrays!") + + if data.ndim > 0: + data = cp.ascontiguousarray(data) + return data + + +def convert_data_type( + data: Any, + output_type: type[NdarrayTensor] | None = None, + device: None | str | torch.device = None, + dtype: DtypeLike | torch.dtype = None, + wrap_sequence: bool = False, + safe: bool = False, +) -> tuple[NdarrayTensor, type, torch.device | None]: + """ + Convert to `MetaTensor`, `torch.Tensor` or `np.ndarray` from `MetaTensor`, `torch.Tensor`, + `np.ndarray`, `float`, `int`, etc. + + Args: + data: data to be converted + output_type: `monai.data.MetaTensor`, `torch.Tensor`, or `np.ndarray` (if `None`, unchanged) + device: if output is `MetaTensor` or `torch.Tensor`, select device (if `None`, unchanged) + dtype: dtype of output data. Converted to correct library type (e.g., + `np.float32` is converted to `torch.float32` if output type is `torch.Tensor`). + If left blank, it remains unchanged. + wrap_sequence: if `False`, then lists will recursively call this function. + E.g., `[1, 2]` -> `[array(1), array(2)]`. If `True`, then `[1, 2]` -> `array([1, 2])`. + safe: if `True`, then do safe dtype convert when intensity overflow. default to `False`. + E.g., `[256, -12]` -> `[array(0), array(244)]`. If `True`, then `[256, -12]` -> `[array(255), array(0)]`. + + Returns: + modified data, orig_type, orig_device + + Note: + When both `output_type` and `dtype` are specified with different backend + (e.g., `torch.Tensor` and `np.float32`), the `output_type` will be used as the primary type, + for example:: + + >>> convert_data_type(1, torch.Tensor, dtype=np.float32) + (1.0, , None) + + """ + orig_type: type + if isinstance(data, monai.data.MetaTensor): + orig_type = monai.data.MetaTensor + elif isinstance(data, torch.Tensor): + orig_type = torch.Tensor + elif isinstance(data, np.ndarray): + orig_type = np.ndarray + elif has_cp and isinstance(data, cp.ndarray): + orig_type = cp.ndarray + else: + orig_type = type(data) + + orig_device = data.device if isinstance(data, torch.Tensor) else None + + output_type = output_type or orig_type + dtype_ = get_equivalent_dtype(dtype, output_type) + + data_: NdarrayTensor + if issubclass(output_type, torch.Tensor): + track_meta = issubclass(output_type, monai.data.MetaTensor) + data_ = convert_to_tensor( + data, dtype=dtype_, device=device, wrap_sequence=wrap_sequence, track_meta=track_meta, safe=safe + ) + return data_, orig_type, orig_device + if issubclass(output_type, np.ndarray): + data_ = convert_to_numpy(data, dtype=dtype_, wrap_sequence=wrap_sequence, safe=safe) + return data_, orig_type, orig_device + elif has_cp and issubclass(output_type, cp.ndarray): + data_ = convert_to_cupy(data, dtype=dtype_, wrap_sequence=wrap_sequence, safe=safe) + return data_, orig_type, orig_device + raise ValueError(f"Unsupported output type: {output_type}") + + +def convert_to_dst_type( + src: Any, + dst: NdarrayTensor, + dtype: DtypeLike | torch.dtype | None = None, + wrap_sequence: bool = False, + device: None | str | torch.device = None, + safe: bool = False, +) -> tuple[NdarrayTensor, type, torch.device | None]: + """ + Convert source data to the same data type and device as the destination data. + If `dst` is an instance of `torch.Tensor` or its subclass, convert `src` to `torch.Tensor` with the same data type as `dst`, + if `dst` is an instance of `numpy.ndarray` or its subclass, convert to `numpy.ndarray` with the same data type as `dst`, + otherwise, convert to the type of `dst` directly. + + Args: + src: source data to convert type. + dst: destination data that convert to the same data type as it. + dtype: an optional argument if the target `dtype` is different from the original `dst`'s data type. + wrap_sequence: if `False`, then lists will recursively call this function. E.g., `[1, 2]` -> `[array(1), array(2)]`. + If `True`, then `[1, 2]` -> `array([1, 2])`. + device: target device to put the converted Tensor data. If unspecified, `dst.device` will be used if possible. + safe: if `True`, then do safe dtype convert when intensity overflow. default to `False`. + E.g., `[256, -12]` -> `[array(0), array(244)]`. If `True`, then `[256, -12]` -> `[array(255), array(0)]`. + + See Also: + :func:`convert_data_type` + """ + + device = dst.device if device is None and isinstance(dst, torch.Tensor) else device + if dtype is None: + dtype = getattr(dst, "dtype", None) # sequence has no dtype + + copy_meta = False + output_type: Any + if isinstance(dst, monai.data.MetaTensor): + output_type = monai.data.MetaTensor + if not isinstance(src, monai.data.MetaTensor): + copy_meta = True # converting a non-meta tensor to a meta tensor, probably take the metadata as well. + elif isinstance(dst, torch.Tensor): + output_type = torch.Tensor + elif isinstance(dst, np.ndarray): + output_type = np.ndarray + else: + output_type = type(dst) + output: NdarrayTensor + output, _type, _device = convert_data_type( + data=src, output_type=output_type, device=device, dtype=dtype, wrap_sequence=wrap_sequence, safe=safe + ) + if copy_meta and isinstance(output, monai.data.MetaTensor): + output.copy_meta_from(dst) + return output, _type, _device + + +def convert_to_list(data: Sequence | torch.Tensor | np.ndarray) -> list: + """ + Convert to list from `torch.Tensor`/`np.ndarray`/`list`/`tuple` etc. + Args: + data: data to be converted + Returns: + a list + + """ + return data.tolist() if isinstance(data, (torch.Tensor, np.ndarray)) else list(data) + + +def get_dtype_bound_value(dtype: DtypeLike | torch.dtype) -> tuple[float, float]: + """ + Get dtype bound value + Args: + dtype: dtype to get bound value + Returns: + (bound_min_value, bound_max_value) + """ + if dtype in UNSUPPORTED_TYPES: + is_floating_point = False + else: + is_floating_point = get_equivalent_dtype(dtype, torch.Tensor).is_floating_point + dtype = get_equivalent_dtype(dtype, np.array) + if is_floating_point: + return (np.finfo(dtype).min, np.finfo(dtype).max) # type: ignore + else: + return (np.iinfo(dtype).min, np.iinfo(dtype).max) + + +def safe_dtype_range(data: Any, dtype: DtypeLike | torch.dtype = None) -> Any: + """ + Utility to safely convert the input data to target dtype. + + Args: + data: input data can be PyTorch Tensor, numpy array, list, dictionary, int, float, bool, str, etc. + will convert to target dtype and keep the original type. + for dictionary, list or tuple, convert every item. + dtype: target data type to convert. + """ + + def _safe_dtype_range(data, dtype): + output_dtype = dtype if dtype is not None else data.dtype + dtype_bound_value = get_dtype_bound_value(output_dtype) + if data.ndim == 0: + data_bound = (data, data) + else: + if isinstance(data, torch.Tensor): + data_bound = (torch.min(data), torch.max(data)) + else: + data_bound = (np.min(data), np.max(data)) + if (data_bound[1] > dtype_bound_value[1]) or (data_bound[0] < dtype_bound_value[0]): + if isinstance(data, torch.Tensor): + return torch.clamp(data, dtype_bound_value[0], dtype_bound_value[1]) + elif isinstance(data, np.ndarray): + return np.clip(data, dtype_bound_value[0], dtype_bound_value[1]) + elif has_cp and isinstance(data, cp_ndarray): + return cp.clip(data, dtype_bound_value[0], dtype_bound_value[1]) + else: + return data + + if has_cp and isinstance(data, cp_ndarray): + return cp.asarray(_safe_dtype_range(data, dtype)) + elif isinstance(data, np.ndarray): + return np.asarray(_safe_dtype_range(data, dtype)) + elif isinstance(data, torch.Tensor): + return _safe_dtype_range(data, dtype) + elif isinstance(data, (float, int, bool)) and dtype is None: + return data + elif isinstance(data, (float, int, bool)) and dtype is not None: + output_dtype = dtype + dtype_bound_value = get_dtype_bound_value(output_dtype) + data = dtype_bound_value[1] if data > dtype_bound_value[1] else data + data = dtype_bound_value[0] if data < dtype_bound_value[0] else data + return data + + elif isinstance(data, list): + return [safe_dtype_range(i, dtype=dtype) for i in data] + elif isinstance(data, tuple): + return tuple(safe_dtype_range(i, dtype=dtype) for i in data) + elif isinstance(data, dict): + return {k: safe_dtype_range(v, dtype=dtype) for k, v in data.items()} + return data diff --git a/source_code/SegMamba/monai/visualize/__init__.py b/source_code/SegMamba/monai/visualize/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..1f2bb7d024ceff478c336b28ad4fe4f1b493463c --- /dev/null +++ b/source_code/SegMamba/monai/visualize/__init__.py @@ -0,0 +1,19 @@ +# Copyright (c) MONAI Consortium +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from __future__ import annotations + +from .class_activation_maps import CAM, GradCAM, GradCAMpp, ModelWithHooks, default_normalizer +from .gradient_based import GuidedBackpropGrad, GuidedBackpropSmoothGrad, SmoothGrad, VanillaGrad +from .img2tensorboard import add_animated_gif, make_animated_gif_summary, plot_2d_or_3d_image +from .occlusion_sensitivity import OcclusionSensitivity +from .utils import blend_images, matshow3d +from .visualizer import default_upsampler diff --git a/source_code/SegMamba/monai/visualize/class_activation_maps.py b/source_code/SegMamba/monai/visualize/class_activation_maps.py new file mode 100644 index 0000000000000000000000000000000000000000..6d1e8dfd034efc44ed2f3fbb61ffb41dfab28e1a --- /dev/null +++ b/source_code/SegMamba/monai/visualize/class_activation_maps.py @@ -0,0 +1,415 @@ +# Copyright (c) MONAI Consortium +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from __future__ import annotations + +import warnings +from collections.abc import Callable, Sequence +from typing import cast + +import numpy as np +import torch +import torch.nn as nn +import torch.nn.functional as F + +from monai.config import NdarrayTensor +from monai.transforms import ScaleIntensity +from monai.utils import ensure_tuple, pytorch_after +from monai.visualize.visualizer import default_upsampler + +__all__ = ["CAM", "GradCAM", "GradCAMpp", "ModelWithHooks", "default_normalizer"] + + +def default_normalizer(x: NdarrayTensor) -> NdarrayTensor: + """ + A linear intensity scaling by mapping the (min, max) to (1, 0). + If the input data is PyTorch Tensor, the output data will be Tensor on the same device, + otherwise, output data will be numpy array. + + Note: This will flip magnitudes (i.e., smallest will become biggest and vice versa). + """ + + def _compute(data: np.ndarray) -> np.ndarray: + scaler = ScaleIntensity(minv=1.0, maxv=0.0) + return np.stack([scaler(i) for i in data], axis=0) + + if isinstance(x, torch.Tensor): + return torch.as_tensor(_compute(x.detach().cpu().numpy()), device=x.device) # type: ignore + + return _compute(x) # type: ignore + + +class ModelWithHooks: + """ + A model wrapper to run model forward/backward steps and storing some intermediate feature/gradient information. + """ + + def __init__( + self, + nn_module: nn.Module, + target_layer_names: str | Sequence[str], + register_forward: bool = False, + register_backward: bool = False, + ): + """ + + Args: + nn_module: the model to be wrapped. + target_layer_names: the names of the layer to cache. + register_forward: whether to cache the forward pass output corresponding to `target_layer_names`. + register_backward: whether to cache the backward pass output corresponding to `target_layer_names`. + """ + self.model = nn_module + self.target_layers = ensure_tuple(target_layer_names) + + self.gradients: dict[str, torch.Tensor] = {} + self.activations: dict[str, torch.Tensor] = {} + self.score: torch.Tensor | None = None + self.class_idx: int | None = None + self.register_backward = register_backward + self.register_forward = register_forward + + _registered = [] + for name, mod in nn_module.named_modules(): + if name not in self.target_layers: + continue + _registered.append(name) + if self.register_backward: + if pytorch_after(1, 8): + if "inplace" in mod.__dict__ and mod.__dict__["inplace"]: + # inplace=True causes errors for register_full_backward_hook + mod.__dict__["inplace"] = False + mod.register_full_backward_hook(self.backward_hook(name)) + else: + mod.register_backward_hook(self.backward_hook(name)) + if self.register_forward: + mod.register_forward_hook(self.forward_hook(name)) + if self.target_layers and (len(_registered) != len(self.target_layers)): + warnings.warn(f"Not all target_layers exist in the network module: targets: {self.target_layers}.") + + def backward_hook(self, name): + + def _hook(_module, _grad_input, grad_output): + self.gradients[name] = grad_output[0] + + return _hook + + def forward_hook(self, name): + + def _hook(_module, _input, output): + self.activations[name] = output + + return _hook + + def get_layer(self, layer_id: str | Callable[[nn.Module], nn.Module]) -> nn.Module: + """ + + Args: + layer_id: a layer name string or a callable. If it is a callable such as `lambda m: m.fc`, + this method will return the module `self.model.fc`. + + Returns: + a submodule from self.model. + """ + if callable(layer_id): + return layer_id(self.model) + if isinstance(layer_id, str): + for name, mod in self.model.named_modules(): + if name == layer_id: + return cast(nn.Module, mod) + raise NotImplementedError(f"Could not find {layer_id}.") + + def class_score(self, logits: torch.Tensor, class_idx: int) -> torch.Tensor: + return logits[:, class_idx].squeeze() + + def __call__(self, x, class_idx=None, retain_graph=False, **kwargs): + train = self.model.training + self.model.eval() + logits = self.model(x, **kwargs) + self.class_idx = logits.max(1)[-1] if class_idx is None else class_idx + acti, grad = None, None + if self.register_forward: + acti = tuple(self.activations[layer] for layer in self.target_layers) + if self.register_backward: + self.score = self.class_score(logits, cast(int, self.class_idx)) + self.model.zero_grad() + self.score.sum().backward(retain_graph=retain_graph) + for layer in self.target_layers: + if layer not in self.gradients: + warnings.warn( + f"Backward hook for {layer} is not triggered; `requires_grad` of {layer} should be `True`." + ) + grad = tuple(self.gradients[layer] for layer in self.target_layers if layer in self.gradients) + if train: + self.model.train() + return logits, acti, grad + + def get_wrapped_net(self): + return self.model + + +class CAMBase: + """ + Base class for CAM methods. + """ + + def __init__( + self, + nn_module: nn.Module, + target_layers: str, + upsampler: Callable = default_upsampler, + postprocessing: Callable = default_normalizer, + register_backward: bool = True, + ) -> None: + self.nn_module: ModelWithHooks + # Convert to model with hooks if necessary + if not isinstance(nn_module, ModelWithHooks): + self.nn_module = ModelWithHooks( + nn_module, target_layers, register_forward=True, register_backward=register_backward + ) + else: + self.nn_module = nn_module + + self.upsampler = upsampler + self.postprocessing = postprocessing + + def feature_map_size(self, input_size, device="cpu", layer_idx=-1, **kwargs): + """ + Computes the actual feature map size given `nn_module` and the target_layer name. + Args: + input_size: shape of the input tensor + device: the device used to initialise the input tensor + layer_idx: index of the target layer if there are multiple target layers. Defaults to -1. + kwargs: any extra arguments to be passed on to the module as part of its `__call__`. + Returns: + shape of the actual feature map. + """ + return self.compute_map(torch.zeros(*input_size, device=device), layer_idx=layer_idx, **kwargs).shape + + def compute_map(self, x, class_idx=None, layer_idx=-1): + """ + Compute the actual feature map with input tensor `x`. + + Args: + x: input to `nn_module`. + class_idx: index of the class to be visualized. Default to `None` (computing `class_idx` from `argmax`) + layer_idx: index of the target layer if there are multiple target layers. Defaults to -1. + + Returns: + activation maps (raw outputs without upsampling/post-processing.) + """ + raise NotImplementedError() + + def _upsample_and_post_process(self, acti_map, x): + # upsampling and postprocessing + img_spatial = x.shape[2:] + acti_map = self.upsampler(img_spatial)(acti_map) + return self.postprocessing(acti_map) + + def __call__(self): + raise NotImplementedError() + + +class CAM(CAMBase): + """ + Compute class activation map from the last fully-connected layers before the spatial pooling. + This implementation is based on: + + Zhou et al., Learning Deep Features for Discriminative Localization. CVPR '16, + https://arxiv.org/abs/1512.04150 + + Examples + + .. code-block:: python + + import torch + + # densenet 2d + from monai.networks.nets import DenseNet121 + from monai.visualize import CAM + + model_2d = DenseNet121(spatial_dims=2, in_channels=1, out_channels=3) + cam = CAM(nn_module=model_2d, target_layers="class_layers.relu", fc_layers="class_layers.out") + result = cam(x=torch.rand((1, 1, 48, 64))) + + # resnet 2d + from monai.networks.nets import seresnet50 + from monai.visualize import CAM + + model_2d = seresnet50(spatial_dims=2, in_channels=3, num_classes=4) + cam = CAM(nn_module=model_2d, target_layers="layer4", fc_layers="last_linear") + result = cam(x=torch.rand((2, 3, 48, 64))) + + N.B.: To help select the target layer, it may be useful to list all layers: + + .. code-block:: python + + for name, _ in model.named_modules(): print(name) + + See Also: + + - :py:class:`monai.visualize.class_activation_maps.GradCAM` + + """ + + def __init__( + self, + nn_module: nn.Module, + target_layers: str, + fc_layers: str | Callable = "fc", + upsampler: Callable = default_upsampler, + postprocessing: Callable = default_normalizer, + ) -> None: + """ + Args: + nn_module: the model to be visualized + target_layers: name of the model layer to generate the feature map. + fc_layers: a string or a callable used to get fully-connected weights to compute activation map + from the target_layers (without pooling). and evaluate it at every spatial location. + upsampler: An upsampling method to upsample the output image. Default is + N dimensional linear (bilinear, trilinear, etc.) depending on num spatial + dimensions of input. + postprocessing: a callable that applies on the upsampled output image. + Default is normalizing between min=1 and max=0 (i.e., largest input will become 0 and + smallest input will become 1). + """ + super().__init__( + nn_module=nn_module, + target_layers=target_layers, + upsampler=upsampler, + postprocessing=postprocessing, + register_backward=False, + ) + self.fc_layers = fc_layers + + def compute_map(self, x, class_idx=None, layer_idx=-1, **kwargs): + logits, acti, _ = self.nn_module(x, **kwargs) + acti = acti[layer_idx] + if class_idx is None: + class_idx = logits.max(1)[-1] + b, c, *spatial = acti.shape + acti = torch.split(acti.reshape(b, c, -1), 1, dim=2) # make the spatial dims 1D + fc_layers = self.nn_module.get_layer(self.fc_layers) + output = torch.stack([fc_layers(a[..., 0]) for a in acti], dim=2) + output = torch.stack([output[i, b : b + 1] for i, b in enumerate(class_idx)], dim=0) + return output.reshape(b, 1, *spatial) # resume the spatial dims on the selected class + + def __call__(self, x, class_idx=None, layer_idx=-1, **kwargs): + """ + Compute the activation map with upsampling and postprocessing. + + Args: + x: input tensor, shape must be compatible with `nn_module`. + class_idx: index of the class to be visualized. Default to argmax(logits) + layer_idx: index of the target layer if there are multiple target layers. Defaults to -1. + kwargs: any extra arguments to be passed on to the module as part of its `__call__`. + + Returns: + activation maps + """ + acti_map = self.compute_map(x, class_idx, layer_idx, **kwargs) + return self._upsample_and_post_process(acti_map, x) + + +class GradCAM(CAMBase): + """ + Computes Gradient-weighted Class Activation Mapping (Grad-CAM). + This implementation is based on: + + Selvaraju et al., Grad-CAM: Visual Explanations from Deep Networks via Gradient-based Localization, + https://arxiv.org/abs/1610.02391 + + Examples + + .. code-block:: python + + import torch + + # densenet 2d + from monai.networks.nets import DenseNet121 + from monai.visualize import GradCAM + + model_2d = DenseNet121(spatial_dims=2, in_channels=1, out_channels=3) + cam = GradCAM(nn_module=model_2d, target_layers="class_layers.relu") + result = cam(x=torch.rand((1, 1, 48, 64))) + + # resnet 2d + from monai.networks.nets import seresnet50 + from monai.visualize import GradCAM + + model_2d = seresnet50(spatial_dims=2, in_channels=3, num_classes=4) + cam = GradCAM(nn_module=model_2d, target_layers="layer4") + result = cam(x=torch.rand((2, 3, 48, 64))) + + N.B.: To help select the target layer, it may be useful to list all layers: + + .. code-block:: python + + for name, _ in model.named_modules(): print(name) + + See Also: + + - :py:class:`monai.visualize.class_activation_maps.CAM` + + """ + + def compute_map(self, x, class_idx=None, retain_graph=False, layer_idx=-1, **kwargs): + _, acti, grad = self.nn_module(x, class_idx=class_idx, retain_graph=retain_graph, **kwargs) + acti, grad = acti[layer_idx], grad[layer_idx] + b, c, *spatial = grad.shape + weights = grad.view(b, c, -1).mean(2).view(b, c, *[1] * len(spatial)) + acti_map = (weights * acti).sum(1, keepdim=True) + return F.relu(acti_map) + + def __call__(self, x, class_idx=None, layer_idx=-1, retain_graph=False, **kwargs): + """ + Compute the activation map with upsampling and postprocessing. + + Args: + x: input tensor, shape must be compatible with `nn_module`. + class_idx: index of the class to be visualized. Default to argmax(logits) + layer_idx: index of the target layer if there are multiple target layers. Defaults to -1. + retain_graph: whether to retain_graph for torch module backward call. + kwargs: any extra arguments to be passed on to the module as part of its `__call__`. + + Returns: + activation maps + """ + acti_map = self.compute_map(x, class_idx=class_idx, retain_graph=retain_graph, layer_idx=layer_idx, **kwargs) + return self._upsample_and_post_process(acti_map, x) + + +class GradCAMpp(GradCAM): + """ + Computes Gradient-weighted Class Activation Mapping (Grad-CAM++). + This implementation is based on: + + Chattopadhyay et al., Grad-CAM++: Improved Visual Explanations for Deep Convolutional Networks, + https://arxiv.org/abs/1710.11063 + + See Also: + + - :py:class:`monai.visualize.class_activation_maps.GradCAM` + + """ + + def compute_map(self, x, class_idx=None, retain_graph=False, layer_idx=-1, **kwargs): + _, acti, grad = self.nn_module(x, class_idx=class_idx, retain_graph=retain_graph, **kwargs) + acti, grad = acti[layer_idx], grad[layer_idx] + b, c, *spatial = grad.shape + alpha_nr = grad.pow(2) + alpha_dr = alpha_nr.mul(2) + acti.mul(grad.pow(3)).view(b, c, -1).sum(-1).view(b, c, *[1] * len(spatial)) + alpha_dr = torch.where(alpha_dr != 0.0, alpha_dr, torch.ones_like(alpha_dr)) + alpha = alpha_nr.div(alpha_dr + 1e-7) + relu_grad = F.relu(cast(torch.Tensor, self.nn_module.score).exp() * grad) + weights = (alpha * relu_grad).view(b, c, -1).sum(-1).view(b, c, *[1] * len(spatial)) + acti_map = (weights * acti).sum(1, keepdim=True) + return F.relu(acti_map) diff --git a/source_code/SegMamba/monai/visualize/occlusion_sensitivity.py b/source_code/SegMamba/monai/visualize/occlusion_sensitivity.py new file mode 100644 index 0000000000000000000000000000000000000000..d8b99ba220fa84407b7fb7b5663dbd7d3f3d0b1c --- /dev/null +++ b/source_code/SegMamba/monai/visualize/occlusion_sensitivity.py @@ -0,0 +1,350 @@ +# Copyright (c) MONAI Consortium +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from __future__ import annotations + +from collections.abc import Callable, Mapping, Sequence +from typing import Any + +import numpy as np +import torch +import torch.nn as nn + +from monai.data.meta_tensor import MetaTensor +from monai.networks.utils import eval_mode +from monai.transforms import Compose, GaussianSmooth, Lambda, ScaleIntensity, SpatialCrop +from monai.utils import ensure_tuple_rep + + +class OcclusionSensitivity: + """ + This class computes the occlusion sensitivity for a model's prediction of a given image. By occlusion sensitivity, + we mean how the probability of a given prediction changes as the occluded section of an image changes. This can be + useful to understand why a network is making certain decisions. + + As important parts of the image are occluded, the probability of classifying the image correctly will decrease. + Hence, more negative values imply the corresponding occluded volume was more important in the decision process. + + Two ``torch.Tensor`` will be returned by the ``__call__`` method: an occlusion map and an image of the most probable + class. Both images will be cropped if a bounding box used, but voxel sizes will always match the input. + + The occlusion map shows the inference probabilities when the corresponding part of the image is occluded. Hence, + more -ve values imply that region was important in the decision process. The map will have shape ``BCHW(D)N``, + where ``N`` is the number of classes to be inferred by the network. Hence, the occlusion for class ``i`` can + be seen with ``map[...,i]``. + + The most probable class is an image of the probable class when the corresponding part of the image is occluded + (equivalent to ``occ_map.argmax(dim=-1)``). + + See: R. R. Selvaraju et al. Grad-CAM: Visual Explanations from Deep Networks via + Gradient-based Localization. https://doi.org/10.1109/ICCV.2017.74. + + Examples: + + .. code-block:: python + + # densenet 2d + from monai.networks.nets import DenseNet121 + from monai.visualize import OcclusionSensitivity + import torch + + model_2d = DenseNet121(spatial_dims=2, in_channels=1, out_channels=3) + occ_sens = OcclusionSensitivity(nn_module=model_2d) + occ_map, most_probable_class = occ_sens(x=torch.rand((1, 1, 48, 64)), b_box=[2, 40, 1, 62]) + + # densenet 3d + from monai.networks.nets import DenseNet + from monai.visualize import OcclusionSensitivity + + model_3d = DenseNet(spatial_dims=3, in_channels=1, out_channels=3, init_features=2, growth_rate=2, block_config=(6,)) + occ_sens = OcclusionSensitivity(nn_module=model_3d, n_batch=10) + occ_map, most_probable_class = occ_sens(torch.rand(1, 1, 6, 6, 6), b_box=[1, 3, -1, -1, -1, -1]) + + See Also: + + - :py:class:`monai.visualize.occlusion_sensitivity.OcclusionSensitivity.` + """ + + def __init__( + self, + nn_module: nn.Module, + mask_size: int | Sequence = 16, + n_batch: int = 16, + verbose: bool = True, + mode: str | float | Callable = "gaussian", + overlap: float = 0.25, + activate: bool | Callable = True, + ) -> None: + """ + Occlusion sensitivity constructor. + + Args: + nn_module: Classification model to use for inference + mask_size: Size of box to be occluded, centred on the central voxel. If a single number + is given, this is used for all dimensions. If a sequence is given, this is used for each dimension + individually. + n_batch: Number of images in a batch for inference. + verbose: Use progress bar (if ``tqdm`` available). + mode: what should the occluded region be replaced with? If a float is given, that value will be used + throughout the occlusion. Else, ``gaussian``, ``mean_img`` and ``mean_patch`` can be supplied: + + * ``gaussian``: occluded region is multiplied by 1 - gaussian kernel. In this fashion, the occlusion + will be 0 at the center and will be unchanged towards the edges, varying smoothly between. When + gaussian is used, a weighted average will be used to combine overlapping regions. This will be + done using the gaussian (not 1-gaussian) as occluded regions count more. + * ``mean_patch``: occluded region will be replaced with the mean of occluded region. + * ``mean_img``: occluded region will be replaced with the mean of the whole image. + + overlap: overlap between inferred regions. Should be in range 0<=x<1. + activate: if ``True``, do softmax activation if num_channels > 1 else do ``sigmoid``. If ``False``, don't do any + activation. If ``callable``, use callable on inferred outputs. + + """ + self.nn_module = nn_module + self.mask_size = mask_size + self.n_batch = n_batch + self.verbose = verbose + self.overlap = overlap + self.activate = activate + # mode + if isinstance(mode, str) and mode not in ("gaussian", "mean_patch", "mean_img"): + raise NotImplementedError + self.mode = mode + + @staticmethod + def constant_occlusion(x: torch.Tensor, val: float, mask_size: Sequence) -> tuple[float, torch.Tensor]: + """Occlude with a constant occlusion. Multiplicative is zero, additive is constant value.""" + ones = torch.ones((*x.shape[:2], *mask_size), device=x.device, dtype=x.dtype) + return 0, ones * val + + @staticmethod + def gaussian_occlusion(x: torch.Tensor, mask_size: Sequence, sigma: float = 0.25) -> tuple[torch.Tensor, float]: + """ + For Gaussian occlusion, Multiplicative is 1-Gaussian, additive is zero. + Default sigma of 0.25 empirically shown to give reasonable kernel, see here: + https://github.com/Project-MONAI/MONAI/pull/5230#discussion_r984520714. + """ + kernel = torch.zeros((x.shape[1], *mask_size), device=x.device, dtype=x.dtype) + spatial_shape = kernel.shape[1:] + # all channels (as occluded shape already takes into account per_channel), center in spatial dimensions + center = [slice(None)] + [slice(s // 2, s // 2 + 1) for s in spatial_shape] + # place value of 1 at center + kernel[center] = 1.0 + # Smooth with sigma equal to quarter of image, flip +ve/-ve so largest values are at edge + # and smallest at center. Scale to [0, 1]. + gaussian = Compose( + [GaussianSmooth(sigma=[b * sigma for b in spatial_shape]), Lambda(lambda x: -x), ScaleIntensity()] + ) + # transform and add batch + mul: torch.Tensor = gaussian(kernel)[None] + + return mul, 0 + + @staticmethod + def predictor( + cropped_grid: torch.Tensor, + nn_module: nn.Module, + x: torch.Tensor, + mul: torch.Tensor | float, + add: torch.Tensor | float, + mask_size: Sequence, + occ_mode: str, + activate: bool | Callable, + module_kwargs: Mapping[str, Any], + ) -> torch.Tensor: + """ + Predictor function to be passed to the sliding window inferer. Takes a cropped meshgrid, + referring to the coordinates in the input image. We use the index of the top-left corner + in combination ``mask_size`` to figure out which region of the image is to be occluded. The + occlusion is performed on the original image, ``x``, using ``cropped_region * mul + add``. ``mul`` + and ``add`` are sometimes pre-computed (e.g., a constant Gaussian blur), or they are + sometimes calculated on the fly (e.g., the mean of the occluded patch). For this reason + ``occ_mode`` is given. Lastly, ``activate`` is used to activate after each call of the model. + + Args: + cropped_grid: subsection of the meshgrid, where each voxel refers to the coordinate of + the input image. The meshgrid is created by the ``OcclusionSensitivity`` class, and + the generation of the subset is determined by ``sliding_window_inference``. + nn_module: module to call on data. + x: the image that was originally passed into ``OcclusionSensitivity.__call__``. + mul: occluded region will be multiplied by this. Can be ``torch.Tensor`` or ``float``. + add: after multiplication, this is added to the occluded region. Can be ``torch.Tensor`` or ``float``. + mask_size: Size of box to be occluded, centred on the central voxel. Should be + a sequence, one value for each spatial dimension. + occ_mode: might be used to calculate ``mul`` and ``add`` on the fly. + activate: if ``True``, do softmax activation if num_channels > 1 else do ``sigmoid``. If ``False``, don't do any + activation. If ``callable``, use callable on inferred outputs. + module_kwargs: kwargs to be passed onto module when inferring + """ + n_batch = cropped_grid.shape[0] + sd = cropped_grid.ndim - 2 + # start with copies of x to infer + im = torch.repeat_interleave(x, n_batch, 0) + # get coordinates of top left corner of occluded region (possible because we use meshgrid) + corner_coord_slices = [slice(None)] * 2 + [slice(1)] * sd + top_corners = cropped_grid[corner_coord_slices] + + # replace occluded regions + for b, t in enumerate(top_corners): + # starting from corner, get the slices to extract the occluded region from the image + slices = [slice(b, b + 1), slice(None)] + [slice(int(j), int(j) + m) for j, m in zip(t, mask_size)] + to_occlude = im[slices] + if occ_mode == "mean_patch": + add, mul = OcclusionSensitivity.constant_occlusion(x, to_occlude.mean().item(), mask_size) + + if callable(occ_mode): + to_occlude = occ_mode(x, to_occlude) + else: + to_occlude = to_occlude * mul + add + if add is None or mul is None: + raise RuntimeError("Shouldn't be here, something's gone wrong...") + im[slices] = to_occlude + # infer + out: torch.Tensor = nn_module(im, **module_kwargs) + + # if activation is callable, call it + if callable(activate): + out = activate(out) + # else if True (should be boolean), sigmoid if n_chan == 1 else softmax + elif activate: + out = out.sigmoid() if x.shape[1] == 1 else out.softmax(1) + + # the output will have shape [B,C] where C is number of channels output by model (inference classes) + # we need to return it to sliding window inference with shape [B,C,H,W,[D]], so add dims and repeat values + for m in mask_size: + out = torch.repeat_interleave(out.unsqueeze(-1), m, dim=-1) + + return out + + @staticmethod + def crop_meshgrid( + grid: MetaTensor, b_box: Sequence, mask_size: Sequence + ) -> tuple[MetaTensor, SpatialCrop, Sequence]: + """Crop the meshgrid so we only perform occlusion sensitivity on a subsection of the image.""" + # distance from center of mask to edge is -1 // 2. + mask_edge = [(m - 1) // 2 for m in mask_size] + bbox_min = [max(b - m, 0) for b, m in zip(b_box[::2], mask_edge)] + bbox_max = [] + for b, m, s in zip(b_box[1::2], mask_edge, grid.shape[2:]): + # if bbox is -ve for that dimension, no cropping so use current image size + if b == -1: + bbox_max.append(s) + # else bounding box plus distance to mask edge. Make sure it's not bigger than the size of the image + else: + bbox_max.append(min(b + m, s)) + # bbox_max = [min(b + m, s) if b >= 0 else s for b, m, s in zip(b_box[1::2], mask_edge, grid.shape[2:])] + # No need for batch and channel slices. Batch will be removed and added back in, and + # SpatialCrop doesn't act on the first dimension anyway. + slices = [slice(s, e) for s, e in zip(bbox_min, bbox_max)] + cropper = SpatialCrop(roi_slices=slices) + cropped: MetaTensor = cropper(grid[0])[None] # type: ignore + mask_size = list(mask_size) + for i, s in enumerate(cropped.shape[2:]): + mask_size[i] = min(s, mask_size[i]) + return cropped, cropper, mask_size + + def __call__( + self, x: torch.Tensor, b_box: Sequence | None = None, **kwargs: Any + ) -> tuple[torch.Tensor, torch.Tensor]: + """ + Args: + x: Image to use for inference. Should be a tensor consisting of 1 batch. + b_box: Bounding box on which to perform the analysis. The output image will be limited to this size. + There should be a minimum and maximum for all spatial dimensions: ``[min1, max1, min2, max2,...]``. + * By default, the whole image will be used. Decreasing the size will speed the analysis up, which might + be useful for larger images. + * Min and max are inclusive, so ``[0, 63, ...]`` will have size ``(64, ...)``. + * Use -ve to use ``min=0`` and ``max=im.shape[x]-1`` for xth dimension. + * N.B.: we add half of the mask size to the bounding box to ensure that the region of interest has a + sufficiently large area surrounding it. + kwargs: any extra arguments to be passed on to the module as part of its `__call__`. + + Returns: + * Occlusion map: + * Shows the inference probabilities when the corresponding part of the image is occluded. + Hence, more -ve values imply that region was important in the decision process. + * The map will have shape ``BCHW(D)N``, where N is the number of classes to be inferred by the + network. Hence, the occlusion for class ``i`` can be seen with ``map[...,i]``. + * If `per_channel==False`, output ``C`` will equal 1: ``B1HW(D)N`` + * Most probable class: + * The most probable class when the corresponding part of the image is occluded (``argmax(dim=-1)``). + Both images will be cropped if a bounding box used, but voxel sizes will always match the input. + """ + if x.shape[0] > 1: + raise ValueError("Expected batch size of 1.") + + sd = x.ndim - 2 + mask_size: Sequence = ensure_tuple_rep(self.mask_size, sd) + + # get the meshgrid (so that sliding_window_inference can tell us which bit to occlude) + grid: MetaTensor = MetaTensor( + np.stack(np.meshgrid(*[np.arange(0, i) for i in x.shape[2:]], indexing="ij"))[None], + device=x.device, + dtype=x.dtype, + ) + # if bounding box given, crop the grid to only infer subsections of the image + if b_box is not None: + grid, cropper, mask_size = self.crop_meshgrid(grid, b_box, mask_size) + + # check that the grid is bigger than the mask size + if any(m > g for g, m in zip(grid.shape[2:], mask_size)): + raise ValueError(f"Image (spatial shape) {grid.shape[2:]} should be bigger than mask {mask_size}.") + + # get additive and multiplicative factors if they are unchanged for all patches (i.e., not mean_patch) + add: float | torch.Tensor | None + mul: float | torch.Tensor | None + # multiply by 0, add value + if isinstance(self.mode, float): + mul, add = self.constant_occlusion(x, self.mode, mask_size) + # multiply by 0, add mean of image + elif self.mode == "mean_img": + mul, add = self.constant_occlusion(x, x.mean().item(), mask_size) + # for gaussian, additive = 0, multiplicative = gaussian + elif self.mode == "gaussian": + mul, add = self.gaussian_occlusion(x, mask_size) + # else will be determined on each patch individually so calculated later + else: + add, mul = None, None + + with eval_mode(self.nn_module): + # needs to go here to avoid circular import + from monai.inferers import sliding_window_inference + + sensitivity_im: MetaTensor = sliding_window_inference( # type: ignore + grid, + roi_size=mask_size, + sw_batch_size=self.n_batch, + predictor=OcclusionSensitivity.predictor, + overlap=self.overlap, + mode="gaussian" if self.mode == "gaussian" else "constant", + progress=self.verbose, + nn_module=self.nn_module, + x=x, + add=add, + mul=mul, + mask_size=mask_size, + occ_mode=self.mode, + activate=self.activate, + module_kwargs=kwargs, + ) + + if b_box is not None: + # undo the cropping that was applied to the meshgrid + sensitivity_im = cropper.inverse(sensitivity_im[0])[None] # type: ignore + # crop using the bounding box (ignoring the mask size this time) + bbox_min = [max(b, 0) for b in b_box[::2]] + bbox_max = [b if b > 0 else s for b, s in zip(b_box[1::2], x.shape[2:])] + cropper = SpatialCrop(roi_start=bbox_min, roi_end=bbox_max) + sensitivity_im = cropper(sensitivity_im[0])[None] # type: ignore + + # The most probable class is the max in the classification dimension (1) + most_probable_class = sensitivity_im.argmax(dim=1, keepdim=True) + return sensitivity_im, most_probable_class diff --git a/source_code/SegMamba/monai/visualize/visualizer.py b/source_code/SegMamba/monai/visualize/visualizer.py new file mode 100644 index 0000000000000000000000000000000000000000..e7f5d9bbbe05ecc531ad5e7078e711ee01a767f3 --- /dev/null +++ b/source_code/SegMamba/monai/visualize/visualizer.py @@ -0,0 +1,36 @@ +# Copyright (c) MONAI Consortium +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from __future__ import annotations + +from collections.abc import Callable, Sized + +import torch +import torch.nn.functional as F + +from monai.utils import InterpolateMode + +__all__ = ["default_upsampler"] + + +def default_upsampler(spatial_size: Sized, align_corners: bool = False) -> Callable[[torch.Tensor], torch.Tensor]: + """ + A linear interpolation method for upsampling the feature map. + The output of this function is a callable `func`, + such that `func(x)` returns an upsampled tensor. + """ + + def up(x): + linear_mode = [InterpolateMode.LINEAR, InterpolateMode.BILINEAR, InterpolateMode.TRILINEAR] + interp_mode = linear_mode[len(spatial_size) - 1] + return F.interpolate(x, size=spatial_size, mode=str(interp_mode.value), align_corners=align_corners) + + return up