### TopologySearch usage example
Source: https://monai.readthedocs.io/en/stable/networks.html
Shows how to create a TopologySearch instance, get RAM cost usage, and run a forward pass with multi-resolution inputs. The output shapes are printed as comments.
```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])
```
--------------------------------
### Install MONAI with all optional dependencies
Source: https://monai.readthedocs.io/en/stable/installation.html
Clones the MONAI repository and installs it with all optional dependencies using pip.
```bash
git clone https://github.com/Project-MONAI/MONAI.git
cd MONAI/
pip install -e ".[all]"
```
--------------------------------
### Install MONAI with CuPy extra
Source: https://monai.readthedocs.io/en/stable/installation.html
Use this command to install MONAI with the 'cupy' extra, which installs a compatible CuPy build for GPU-accelerated array operations. If CuPy is not installed, transforms that use it will raise OptionalImportError.
```bash
pip install 'monai[cupy]'
```
--------------------------------
### BasicUNet usage examples for 2D and 3D
Source: https://monai.readthedocs.io/en/stable/networks.html
Shows how to instantiate BasicUNet for spatial 2D, spatial 2D with group norm, and spatial 3D. The examples are from the documentation's Examples section.
```python
# for spatial 2D
>>> net = BasicUNet(spatial_dims=2, features=(64, 128, 256, 512, 1024, 128))
# for spatial 2D, with group norm
>>> net = BasicUNet(spatial_dims=2, features=(64, 128, 256, 512, 1024, 128), norm=("group", {"num_groups": 4}))
# for spatial 3D
>>> net = BasicUNet(spatial_dims=3, features=(32, 32, 64, 128, 256, 32))
```
--------------------------------
### Install MONAI with Nibabel and Scikit-image support
Source: https://monai.readthedocs.io/en/stable/installation.html
Clones the MONAI repository and installs it with the 'nibabel' and 'skimage' extras using pip.
```bash
git clone https://github.com/Project-MONAI/MONAI.git
cd MONAI/
pip install -e '.[nibabel,skimage]'
```
--------------------------------
### Run init_bundle script
Source: https://monai.readthedocs.io/en/stable/bundle.html
Typical usage example for the init_bundle script. It initializes a new bundle directory with default configuration files and optionally copies network weights.
```bash
python -m monai.bundle init_bundle /path/to/bundle_dir network_ckpt.pt
```
--------------------------------
### AlgoEnsemble.get_algo_ensemble
Source: https://monai.readthedocs.io/en/stable/apps.html
Gets the algo ensemble after ranking or an empty list if ranking was not started.
```APIDOC
## AlgoEnsemble.get_algo_ensemble
### Description
Get the algo ensemble after ranking or a empty list if ranking was not started.
### Method
get_algo_ensemble
### Signature
get_algo_ensemble()
### Returns
- **list** - A list of Algo.
```
--------------------------------
### config.json: Example configuration with imports and preprocessing
Source: https://monai.readthedocs.io/en/stable/config_syntax.html
Example config file showing the use of '$True', '$import torch', and references to transforms. Used with extra_config.json to demonstrate merging behavior.
```json
{
"amp": "$True"
"imports": [
"$import torch"
],
"preprocessing": {
"_target_": "Compose",
"transforms": [
"$@t1",
"$@t2"
]
},
}
```
--------------------------------
### CornerCornerModeTypeA.get_name example
Source: https://monai.readthedocs.io/en/stable/data.html
Shows how to get the mode name for 2D and 3D spatial dimensions using CornerCornerModeTypeA.get_name.
```python
CornerCornerModeTypeA.get_name(spatial_dims=2) # will return "xyxy"
CornerCornerModeTypeA.get_name(spatial_dims=3) # will return "xyzxyz"
```
--------------------------------
### BundleAlgo usage example
Source: https://monai.readthedocs.io/en/stable/apps.html
Shows how to create a BundleAlgo instance, set data stats from a YAML file, and export the algorithm to disk. The template_path is required if not loaded via load_state_dict.
```python
from monai.apps.auto3dseg import BundleAlgo
data_stats_yaml = "../datastats.yaml"
algo = BundleAlgo(template_path="../algorithm_templates")
algo.set_data_stats(data_stats_yaml)
# algo.set_data_src("../data_src.json")
algo.export_to_disk(".", algo_name="segresnet2d_1")
```
--------------------------------
### CenterSizeMode.get_name example
Source: https://monai.readthedocs.io/en/stable/data.html
Shows how to get the mode name for 2D and 3D spatial dimensions using CenterSizeMode.get_name.
```python
CenterSizeMode.get_name(spatial_dims=2) # will return "ccwh"
CenterSizeMode.get_name(spatial_dims=3) # will return "cccwhd"
```
--------------------------------
### partition_dataset examples with various parameters
Source: https://monai.readthedocs.io/en/stable/data.html
Demonstrates partition_dataset behavior with different parameter combinations: ratios, num_partitions, even_divisible, and drop_last, showing the resulting partitions.
```python
>>> data = [1, 2, 3, 4, 5]
>>> partition_dataset(data, ratios=[0.6, 0.2, 0.2], shuffle=False)
[[1, 2, 3], [4], [5]]
>>> partition_dataset(data, num_partitions=2, shuffle=False)
[[1, 3, 5], [2, 4]]
>>> partition_dataset(data, num_partitions=2, shuffle=False, even_divisible=True, drop_last=True)
[[1, 3], [2, 4]]
>>> partition_dataset(data, num_partitions=2, shuffle=False, even_divisible=True, drop_last=False)
[[1, 3, 5], [2, 4, 1]]
>>> partition_dataset(data, num_partitions=2, shuffle=False, even_divisible=False, drop_last=False)
[[1, 3, 5], [2, 4]]
```
--------------------------------
### CornerSizeMode.get_name example
Source: https://monai.readthedocs.io/en/stable/data.html
Shows how to get the name of the CornerSizeMode mode for 2D and 3D spatial dimensions, returning 'xywh' and 'xyzwhd' respectively.
```python
CornerSizeMode.get_name(spatial_dims=2) # will return "xywh"
CornerSizeMode.get_name(spatial_dims=3) # will return "xyzwhd"
```
--------------------------------
### SwinUNETR instantiation examples
Source: https://monai.readthedocs.io/en/stable/networks.html
Three examples of creating SwinUNETR instances for different input/output configurations, including 3D single-channel, 3D 4-channel, and 2D with gradient checkpointing.
```python
# for 3D single channel input with size (96,96,96), 4-channel output and feature size of 48.
>>> net = SwinUNETR(in_channels=1, out_channels=4, feature_size=48)
```
```python
# for 3D 4-channel input with size (128,128,128), 3-channel output and (2,4,2,2) layers in each stage.
>>> net = SwinUNETR(in_channels=4, out_channels=3, depths=(2,4,2,2))
```
```python
# for 2D single channel input with size (96,96), 2-channel output and gradient checkpointing.
>>> net = SwinUNETR(in_channels=3, out_channels=2, use_checkpoint=True, spatial_dims=2)
```
--------------------------------
### CornerCornerModeTypeC.get_name example
Source: https://monai.readthedocs.io/en/stable/data.html
Shows how to get the name of the CornerCornerModeTypeC mode for 2D and 3D spatial dimensions, returning 'xyxy' and 'xyxyzz' respectively.
```python
CornerCornerModeTypeC.get_name(spatial_dims=2) # will return "xyxy"
CornerCornerModeTypeC.get_name(spatial_dims=3) # will return "xyxyzz"
```
--------------------------------
### CornerCornerModeTypeB.get_name example
Source: https://monai.readthedocs.io/en/stable/data.html
Shows how to get the name of the CornerCornerModeTypeB mode for 2D and 3D spatial dimensions, returning 'xxyy' and 'xxyyzz' respectively.
```python
CornerCornerModeTypeB.get_name(spatial_dims=2) # will return "xxyy"
CornerCornerModeTypeB.get_name(spatial_dims=3) # will return "xxyyzz"
```
--------------------------------
### EnsembleRunner instantiation and run example
Source: https://monai.readthedocs.io/en/stable/apps.html
Example showing how to create an EnsembleRunner with data source config, working directory, ensemble method, and multi-GPU setting, then call run with device settings.
```python
ensemble_runner = EnsembleRunner(data_src_cfg_name,
work_dir,
ensemble_method_name,
mgpu=device_setting['n_devices']>1,
**kwargs,
**pred_params)
ensemble_runner.run(device_setting)
```
--------------------------------
### ConfigParser usage example
Source: https://monai.readthedocs.io/en/stable/bundle.html
Shows how to create a ConfigParser from a config dictionary, access and modify configuration values, parse the config, and instantiate a network component. The example uses a config with expressions and references.
```python
from monai.bundle import ConfigParser
config = {
"my_dims": 2,
"dims_1": "$@my_dims + 1",
"my_xform": {"_target_": "LoadImage"},
"my_net": {"_target_": "BasicUNet", "spatial_dims": "@dims_1", "in_channels": 1, "out_channels": 4},
"trainer": {"_target_": "SupervisedTrainer", "network": "@my_net", "preprocessing": "@my_xform"}
}
# in the example $@my_dims + 1 is an expression, which adds 1 to the value of @my_dims
parser = ConfigParser(config)
# get/set configuration content, the set method should happen before calling parse()
print(parser["my_net"]["in_channels"]) # original input channels 1
parser["my_net"]["in_channels"] = 4 # change input channels to 4
print(parser["my_net"]["in_channels"])
# instantiate the network component
parser.parse(True)
net = parser.get_parsed_content("my_net", instantiate=True)
print(net)
# also support to get the configuration content of parsed `ConfigItem`
trainer = parser.get_parsed_content("trainer", instantiate=False)
print(trainer)
```
--------------------------------
### get_package_version(dep_name, default='NOT INSTALLED or UNKNOWN VERSION.')
Source: https://monai.readthedocs.io/en/stable/utils.html
Try to load a package and get its version. If not found, returns the default value.
```APIDOC
## get_package_version(dep_name, default='NOT INSTALLED or UNKNOWN VERSION.')
### Description
Try to load package and get version. If not found, return default.
### Method
Function
### Signature
`monai.utils.module.get_package_version(dep_name, default='NOT INSTALLED or UNKNOWN VERSION.')`
### Parameters
- **dep_name** (str) - Required - The name of the package.
- **default** (str) - Optional - The default value to return if the package is not found. Defaults to 'NOT INSTALLED or UNKNOWN VERSION.'.
### Returns
- **str** - The version of the package, or the default value if not found.
```
--------------------------------
### Get box mode with get_boxmode
Source: https://monai.readthedocs.io/en/stable/data.html
Example showing how to use get_boxmode with a string mode 'xyzxyz' to obtain the corresponding BoxMode object, which returns CornerCornerModeTypeA().
```python
mode = "xyzxyz"
get_boxmode(mode) # will return CornerCornerModeTypeA()
```
--------------------------------
### QuickNAT network instantiation example
Source: https://monai.readthedocs.io/en/stable/networks.html
Creates a QuickNAT network with max pooling by a factor of 2 at each layer and no se_block. Requires importing QuickNAT from monai.networks.nets.
```python
from monai.networks.nets import QuickNAT
# network with max pooling by a factor of 2 at each layer with no se_block.
net = QuickNAT(
num_classes=3,
num_channels=1,
num_filters=64,
pool = 2,
se_block = "None"
)
```
--------------------------------
### non_max_suppression usage example
Source: https://monai.readthedocs.io/en/stable/data.html
Demonstrates calling non_max_suppression with boxes and scores tensors, then indexing the original boxes with the returned keep indices to get the boxes after NMS.
```python
boxes = torch.ones(10,6)
scores = torch.ones(10)
keep = non_max_suppression(boxes, scores, num_thresh=0.1)
boxes_after_nms = boxes[keep]
```
--------------------------------
### ViT instantiation examples
Source: https://monai.readthedocs.io/en/stable/networks.html
Examples showing how to create ViT instances for different input configurations: single channel 3D, 3-channel 3D with classification, and 3-channel 2D with classification.
```python
# for single channel input with image size of (96,96,96), conv position embedding and segmentation backbone
>>> net = ViT(in_channels=1, img_size=(96,96,96), proj_type='conv', pos_embed_type='sincos')
```
```python
# for 3-channel with image size of (128,128,128), 24 layers and classification backbone
>>> net = ViT(in_channels=3, img_size=(128,128,128), proj_type='conv', pos_embed_type='sincos', classification=True)
```
```python
# for 3-channel with image size of (224,224), 12 layers and classification backbone
>>> net = ViT(in_channels=3, img_size=(224,224), proj_type='conv', pos_embed_type='sincos', classification=True,
>>> spatial_dims=2)
```
--------------------------------
### monai.bundle.init_bundle
Source: https://monai.readthedocs.io/en/stable/bundle.html
Initialises a new bundle directory with some default configuration files and optionally network weights.
```APIDOC
## monai.bundle.init_bundle
### Description
Initialises a new bundle directory with some default configuration files and optionally network weights.
### Method
CLI
### Endpoint
python -m monai.bundle init_bundle /path/to/bundle_dir network_ckpt.pt
### Parameters
- **bundle_dir** (UnionType[str, PathLike]) - Required - Directory name to create, must not exist but parent direct must exist.
- **ckpt_file** (Union[str, PathLike, None]) - Optional - Optional checkpoint file to copy into bundle.
- **network** (Optional[Module, None]) - Optional - If given instead of ckpt_file this network's weights will be stored in bundle.
- **dataset_license** (bool) - Optional - If True, a default license file called "data_license.txt" will be produced. This file is required if there are any license conditions stated for data your bundle uses.
- **metadata_str** (Union[str, dict, None]) - Optional - Optional metadata string to write to bundle, if not given a default will be used.
```
--------------------------------
### LossMetric usage example
Source: https://monai.readthedocs.io/en/stable/metrics.html
Shows how to wrap DiceLoss with LossMetric, accumulate loss over two iterations, aggregate with reduction='none' to get per-batch values, then reset and aggregate with default reduction.
```python
import torch
from monai.losses import DiceLoss
from monai.metrics import LossMetric
dice_loss = DiceLoss(include_background=True)
loss_metric = LossMetric(loss_fn=dice_loss)
# first iteration
y_pred = torch.tensor([[[[1.0, 0.0], [0.0, 1.0]]]]) # shape [batch=1, channel=1, 2, 2]
y = torch.tensor([[[[1.0, 0.0], [1.0, 1.0]]]]) # shape [batch=1, channel=1, 2, 2]
loss_metric(y_pred, y)
# second iteration
y_pred = torch.tensor([[[[1.0, 0.0], [0.0, 0.0]]]]) # shape [batch=1, channel=1, 2, 2]
y = torch.tensor([[[[1.0, 0.0], [1.0, 1.0]]]]) # shape [batch=1, channel=1, 2, 2]
loss_metric(y_pred, y)
# aggregate
print(loss_metric.aggregate(reduction="none")) # tensor([[0.2000], [0.5000]]) (shape [batch=2, channel=1])
# reset
loss_metric.reset()
print(loss_metric.aggregate())
```
--------------------------------
### CutMix usage example
Source: https://monai.readthedocs.io/en/stable/transforms.html
Shows the typical usage of the CutMix transform: instantiate with batch_size and alpha, then apply it to each batch from a data loader to get augmented images and labels for model training.
```python
cm = CutMix(batch_size=8, alpha=0.5)
for batch in loader:
images, labels = batch
augimg, auglabels = cm(images, labels)
output = model(augimg)
loss = loss_function(output, auglabels)
...
```
--------------------------------
### CheckpointLoader usage example
Source: https://monai.readthedocs.io/en/stable/handlers.html
Shows how to create a CheckpointLoader handler with a save_dict containing trainer, network, optimizer, and lr_scheduler, then invoke it to resume training. Requires a checkpoint file with matching keys.
```python
trainer = SupervisedTrainer(...)
save_dict = {
"trainer": trainer,
"net": network,
"opt": optimizer,
"lr": lr_scheduler,
}
map_location = "cuda:0"
# checkpoint needs to have same save_dict for this to work
handler = CheckpointLoader(load_path="/test/checkpoint.pt", load_dict=save_dict, map_location=map_location, strict=True)
handler(trainer)
# Trainer now has the same state as stored, including the number of epochs and iterations completed
# so you can resume an interrupted training at the place where it left
```
--------------------------------
### ZipDataset example: zipping datasets and iterating
Source: https://monai.readthedocs.io/en/stable/data.html
Shows how to create a ZipDataset from two lists, print its length (minimum length of inputs), and iterate over it to get zipped tuples. The output shows the zipped items.
```python
>>> zip_data = ZipDataset([[1, 2, 3], [4, 5]])
>>> print(len(zip_data))
2
>>> for item in zip_data:
>>> print(item)
[1, 4]
[2, 5]
```
--------------------------------
### SegSummarizer usage example
Source: https://monai.readthedocs.io/en/stable/auto3dseg.html
Shows how to instantiate SegSummarizer with image and label keys, build a transform list including the summarizer, and process a dataset to generate a report.
```python
# imports
summarizer = SegSummarizer("image", "label")
transform_list = [
LoadImaged(keys=keys),
EnsureChannelFirstd(keys=keys), # this creates label to be (1,H,W,D)
ToDeviced(keys=keys, device=device, non_blocking=True),
Orientationd(keys=keys, axcodes="RAS"),
EnsureTyped(keys=keys, data_type="tensor"),
Lambdad(keys="label", func=lambda x: torch.argmax(x, dim=0, keepdim=True) if x.shape[0] > 1 else x),
SqueezeDimd(keys=["label"], dim=0),
summarizer,
]
...
# skip some steps to set up data loader
dataset = data.DataLoader(ds, batch_size=1, shuffle=False, num_workers=n_workers, collate_fn=no_collation)
transform = Compose(transform_list)
stats = []
for batch_data in dataset:
d = transform(batch_data[0])
stats.append(d)
report = summarizer.summarize(stats)
```
--------------------------------
### MONAI bundle run CLI usage examples
Source: https://monai.readthedocs.io/en/stable/bundle.html
Shows various ways to invoke the `monai.bundle run` CLI, including specifying run IDs, overriding config values with component IDs or other config files, and using an args file for default arguments.
```bash
# Execute this module as a CLI entry:
python -m monai.bundle run --meta_file --config_file
# Execute with specified `run_id=training`:
python -m monai.bundle run training --meta_file --config_file
# Execute with all specified `run_id=runtest`, `init_id=inittest`, `final_id=finaltest`:
python -m monai.bundle run --run_id runtest --init_id inittest --final_id finaltest ...
# Override config values at runtime by specifying the component id and its new value:
python -m monai.bundle run --net#input_chns 1 ...
# Override config values with another config file `/path/to/another.json`:
python -m monai.bundle run --net %/path/to/another.json ...
# Override config values with part content of another config file:
python -m monai.bundle run --net %/data/other.json#net_arg ...
# Set default args of `run` in a JSON / YAML file, help to record and simplify the command line.
# Other args still can override the default args at runtime:
python -m monai.bundle run --args_file "/workspace/data/args.json" --config_file
```
--------------------------------
### TestTimeAugmentation usage example
Source: https://monai.readthedocs.io/en/stable/data.html
Shows how to instantiate TestTimeAugmentation with a UNet model, a composed transform with random affine, and then run it on test data to get mode, mean, std, and vvc metrics. The transform's random state is set for deterministic evaluation.
```python
model = UNet(...).to(device)
transform = Compose([RandAffined(keys, ...), ...])
transform.set_random_state(seed=123) # ensure deterministic evaluation
tt_aug = TestTimeAugmentation(
transform, batch_size=5, num_workers=0, inferrer_fn=model, device=device
)
mode, mean, std, vvc = tt_aug(test_data)
```
--------------------------------
### BundleAlgo.__init__
Source: https://monai.readthedocs.io/en/stable/apps.html
Creates an Algo instance based on a predefined algorithm template path.
```APIDOC
## BundleAlgo.__init__
### Description
Creates an Algo instance based on the predefined Algo template.
### Method
Constructor
### Signature
`__init__(template_path=None)`
### Parameters
- **template_path** (Union[str, PathLike, None]) - Optional - Path to a folder that contains the algorithm templates. If not provided, its value must be loaded with load_state_dict.
```
--------------------------------
### Compute Absolute Volume Difference with AbsoluteVolumeDifferenceMetric
Source: https://monai.readthedocs.io/en/stable/metrics.html
Example usage of AbsoluteVolumeDifferenceMetric: create random binarized tensors, instantiate the metric with include_background=False, accumulate predictions and ground truth, then aggregate to get the mean AVD per class. The result shape is (n_classes - 1,) after mean reduction.
```python
import torch
from monai.metrics import AbsoluteVolumeDifferenceMetric
batch_size, n_classes = 4, 3
y_pred = torch.randint(0, 2, (batch_size, n_classes, 64, 64, 32)).float()
y = torch.randint(0, 2, (batch_size, n_classes, 64, 64, 32)).float()
metric = AbsoluteVolumeDifferenceMetric(include_background=False)
metric(y_pred, y) # accumulate
result = metric.aggregate() # shape: (n_classes - 1,) after mean reduction
metric.reset()
```
--------------------------------
### start() (monai.handlers.MLFlowHandler method)
Source: https://monai.readthedocs.io/en/stable/genindex.html
Method to start the MLFlowHandler.
```APIDOC
## start()
### Description
Method to start the MLFlowHandler.
### Class
monai.handlers.MLFlowHandler
### Reference
[monai.handlers.MLFlowHandler.start](https://monai.readthedocs.io/en/stable/handlers.html#monai.handlers.MLFlowHandler.start)
```
--------------------------------
### Create and use a MetaTensor with metadata and affine
Source: https://monai.readthedocs.io/en/stable/data.html
Example from the MetaTensor documentation showing how to create a MetaTensor with an affine matrix and metadata, then perform addition and verify metadata and affine are preserved.
```python
import torch
from monai.data import MetaTensor
t = torch.tensor([1,2,3])
affine = torch.as_tensor([[2,0,0,0],
[0,2,0,0],
[0,0,2,0],
[0,0,0,1]], dtype=torch.float64)
meta = {"some": "info"}
m = MetaTensor(t, affine=affine, meta=meta)
m2 = m + m
assert isinstance(m2, MetaTensor)
assert m2.meta["some"] == "info"
assert torch.all(m2.affine == affine)
```
--------------------------------
### BasicUNetPlusPlus usage examples
Source: https://monai.readthedocs.io/en/stable/networks.html
Examples for creating BasicUNetPlusPlus instances for spatial 2D and 3D, with options for deep supervision and group normalization.
```python
# for spatial 2D
>>> net = BasicUNetPlusPlus(spatial_dims=2, features=(64, 128, 256, 512, 1024, 128))
# for spatial 2D, with deep supervision enabled
>>> net = BasicUNetPlusPlus(spatial_dims=2, features=(64, 128, 256, 512, 1024, 128), deep_supervision=True)
# for spatial 2D, with group norm
>>> net = BasicUNetPlusPlus(spatial_dims=2, features=(64, 128, 256, 512, 1024, 128), norm=("group", {"num_groups": 4}))
# for spatial 3D
>>> net = BasicUNetPlusPlus(spatial_dims=3, features=(32, 32, 64, 128, 256, 32))
```