### Install MONAI Source: https://github.com/project-monai/monai/blob/dev/tests/profile_subclass/README.md Build MONAI from source using the provided script or follow the official installation guide. This step is necessary before running profiling commands. ```bash ./runtests.sh --build # from monai's root directory ``` -------------------------------- ### Install Documentation Dependencies Source: https://github.com/project-monai/monai/blob/dev/CONTRIBUTING.md Install the necessary Python packages required for building MONAI's documentation. Ensure pip is up-to-date before installing. ```bash pip install --upgrade pip pip install -r docs/requirements.txt ``` -------------------------------- ### Install MONAI with All Optional Dependencies (PyPI) Source: https://github.com/project-monai/monai/blob/dev/docs/source/installation.md Install MONAI from PyPI with all available optional dependencies. ```bash pip install 'monai[all]' ``` -------------------------------- ### Install MONAI with All Optional Dependencies Source: https://github.com/project-monai/monai/blob/dev/docs/source/installation.md Install MONAI from source with all optional dependencies using pip. ```bash git clone https://github.com/Project-MONAI/MONAI.git cd MONAI/ pip install -e ".[all]" ``` -------------------------------- ### Install MONAI using pip Source: https://github.com/project-monai/monai/blob/dev/README.md Install the current release of MONAI using pip. This is the simplest installation method. ```bash pip install monai ``` -------------------------------- ### Install MONAI Weekly Preview Release from PyPI Source: https://github.com/project-monai/monai/blob/dev/docs/source/installation.md Install the weekly preview release of MONAI from PyPI for the latest features. Be aware of potential namespace conflicts if the milestone release is also installed. ```bash pip install monai-weekly ``` -------------------------------- ### Install MONAI from GitHub with C++/CUDA Extensions Source: https://github.com/project-monai/monai/blob/dev/docs/source/installation.md Install MONAI from GitHub, building C++/CUDA extensions. Ensure PyTorch is installed and CUDA_PATH is set if needed. ```bash BUILD_MONAI=1 pip install git+https://github.com/Project-MONAI/MONAI ``` -------------------------------- ### Install MONAI with Nibabel and Skimage Source: https://github.com/project-monai/monai/blob/dev/docs/source/installation.md Install MONAI from source with optional Nibabel and Scikit-image support using pip. ```bash git clone https://github.com/Project-MONAI/MONAI.git cd MONAI/ pip install -e '.[nibabel,skimage]' ``` -------------------------------- ### Install MONAI from GitHub with C++/CUDA Extensions (No Build Isolation) Source: https://github.com/project-monai/monai/blob/dev/docs/source/installation.md Install MONAI from GitHub with C++/CUDA extensions, using `--no-build-isolation` which might be preferred if PyTorch is already installed. ```bash BUILD_MONAI=1 pip install --no-build-isolation git+https://github.com/Project-MONAI/MONAI ``` -------------------------------- ### Install MONAI with Specific Optional Dependencies (PyPI) Source: https://github.com/project-monai/monai/blob/dev/docs/source/installation.md Install MONAI from PyPI with specific optional dependencies like Nibabel. ```bash pip install 'monai[nibabel]' ``` -------------------------------- ### Install Profiling Tools Source: https://github.com/project-monai/monai/blob/dev/tests/profile_subclass/README.md Install `py-spy` for live profiling and `snakeviz` for visualizing `cProfile` results. These tools are essential for analyzing performance. ```bash pip install py-spy pip install snakeviz # for viewing the cProfile results ``` -------------------------------- ### Install MONAI from GitHub (System-wide Module) Source: https://github.com/project-monai/monai/blob/dev/docs/source/installation.md Install the latest development version of MONAI directly from GitHub as a system-wide module. ```bash pip install git+https://github.com/Project-MONAI/MONAI ``` -------------------------------- ### Editable Install MONAI from Local Clone Source: https://github.com/project-monai/monai/blob/dev/docs/source/installation.md Install MONAI in editable mode from a local clone of the repository. ```bash cd MONAI/ pip install -e . ``` -------------------------------- ### Get MONAI Version Source: https://github.com/project-monai/monai/blob/dev/docs/source/installation.md Run this command to retrieve the installed MONAI version, useful for reporting issues with the weekly preview release. ```python python -c "import monai; print(monai.__version__)" ``` -------------------------------- ### Editable Install MONAI with C++/CUDA Extensions Source: https://github.com/project-monai/monai/blob/dev/docs/source/installation.md Perform an editable installation of MONAI from a local clone, building C++/CUDA extensions. ```bash cd MONAI/ BUILD_MONAI=1 pip install -e . ``` -------------------------------- ### Run Latest MONAI Docker Image Source: https://github.com/project-monai/monai/blob/dev/README.md Launches the latest MONAI Docker image interactively with GPU support. This is useful for getting started quickly with the most recent development version. ```bash docker run -ti --rm --gpus all projectmonai/monai:latest /bin/bash ``` -------------------------------- ### Install Development Dependencies and Run Linting Source: https://github.com/project-monai/monai/blob/dev/CONTRIBUTING.md Installs development tools and runs code formatting and linting checks. Use `--autofix` to attempt automatic correction of style issues. ```bash # optionally update the dependencies and dev tools python -m pip install -U pip python -m pip install -U -r requirements-dev.txt # run the linting and type checking tools ./runtests.sh --codeformat # try to fix the coding style errors automatically ./runtests.sh --autofix ``` -------------------------------- ### Install MONAI Dev Dependencies with Pip Source: https://github.com/project-monai/monai/blob/dev/docs/source/installation.md Install all optional dependencies for MONAI development using pip and the requirements-dev.txt file. ```bash git clone https://github.com/Project-MONAI/MONAI.git cd MONAI/ pip install -r requirements-dev.txt ``` -------------------------------- ### Clone MONAI Repository for Editable Installation Source: https://github.com/project-monai/monai/blob/dev/docs/source/installation.md Clone the MONAI repository to your local machine to perform an editable installation. ```bash git clone https://github.com/Project-MONAI/MONAI.git ``` -------------------------------- ### Install MONAI Dev Dependencies with Conda Source: https://github.com/project-monai/monai/blob/dev/docs/source/installation.md Install all optional dependencies for MONAI development using conda and the environment-dev.yml file. This also installs PyTorch. ```bash git clone https://github.com/Project-MONAI/MONAI.git cd MONAI/ conda create -n python= # eg 3.10 conda env update -n -f environment-dev.yml ``` -------------------------------- ### Install MONAI Requirements Source: https://github.com/project-monai/monai/wiki/Frequently-asked-questions-and-answers Ensure a compatible Numpy version by installing MONAI's requirements. This command fetches the `requirements.txt` file from the MONAI master branch. ```bash pip install -r https://raw.githubusercontent.com/Project-MONAI/MONAI/master/requirements.txt ``` -------------------------------- ### Bundle Structure Example Source: https://github.com/project-monai/monai/blob/dev/docs/source/modules.md Illustrates the typical directory structure of a MONAI bundle, which includes configuration files, model weights, and documentation. ```plaintext ModelName ┣━ configs ┃ ┗━ metadata.json ┣━ models ┃ ┣━ model.pt ┃ ┣━ *model.ts ┃ ┗━ *model.onnx ┗━ docs ┣━ *README.md ┗━ *license.txt ``` -------------------------------- ### Editable Install MONAI with C++/CUDA Extensions on MacOS Source: https://github.com/project-monai/monai/blob/dev/docs/source/installation.md Perform an editable installation of MONAI from a local clone on MacOS, building C++/CUDA extensions with specified compilers. ```bash cd MONAI/ BUILD_MONAI=1 CC=clang CXX=clang++ pip install -e . ``` -------------------------------- ### Run Latest MONAI Docker Container Source: https://github.com/project-monai/monai/blob/dev/docs/source/installation.md Download and start a Docker container with the latest MONAI version. Requires NVIDIA driver and Docker 19.03+. ```bash docker run --gpus all --rm -ti --ipc=host projectmonai/monai:latest ``` -------------------------------- ### Install MONAI Milestone Release from conda-forge Source: https://github.com/project-monai/monai/blob/dev/docs/source/installation.md Install the current milestone release of MONAI using conda-forge. ```bash conda install -c conda-forge monai ``` -------------------------------- ### Validate MONAI Installation Source: https://github.com/project-monai/monai/blob/dev/docs/source/installation.md Verify your MONAI installation by running this Python command. It prints MONAI version information upon success. ```python python -c "import monai; monai.config.print_config()" ``` -------------------------------- ### Example metadata.json File Source: https://github.com/project-monai/monai/wiki/MONAI-Archive-Specification This JSON file contains metadata for a MONAI archive, detailing model version, dependencies, task, description, data sources, and network input/output formats. ```json { "version": "0.1.0", "changelog": { "0.1.0": "complete the model package", "0.0.1": "initialize the model package structure" }, "monai_version": "0.8.0", "pytorch_version": "1.10.0", "numpy_version": "1.21.2", "optional_packages_version": {"nibabel": "3.2.1"}, "task": "Decathlon spleen segmentation", "description": "A pre-trained model for volumetric (3D) segmentation of the spleen from CT image", "authorship": "MONAI team", "copyright": "Copyright (c) MONAI Consortium", "data_source": "Task09_Spleen.tar from http://medicaldecathlon.com/", "data_type": "dicom", "dataset_dir": "/workspace/data/Task09_Spleen", "image_classes": "single channel data, intensity scaled to [0, 1]", "label_classes": "single channel data, 1 is spleen, 0 is everything else", "pred_classes": "2 channels OneHot data, channel 1 is spleen, channel 0 is background", "eval_metrics": { "mean_dice": 0.96 }, "intended_use": "This is an example, not to be used for diagnostic purposes", "references": [ "Xia, Yingda, et al. '3D Semi-Supervised Learning with Uncertainty-Aware Multi-View Co-Training.' arXiv preprint arXiv:1811.12506 (2018). https://arxiv.org/abs/1811.12506.", "Kerfoot E., Clough J., Oksuz I., Lee J., King A.P., Schnabel J.A. (2019) Left-Ventricle Quantification Using Residual U-Net. In: Pop M. et al. (eds) Statistical Atlases and Computational Models of the Heart. Atrial Segmentation and LV Quantification Challenges. STACOM 2018. Lecture Notes in Computer Science, vol 11395. Springer, Cham. https://doi.org/10.1007/978-3-030-12029-0_40" ], "network_data_format":{ "inputs": { "image": { "type": "image", "format": "magnitude", "num_channels": 1, "spatial_shape": [160, 160, 160], "dtype": "float32", "value_range": [0, 1], "is_patch_data": false, ``` -------------------------------- ### Example Usage of Vanilla RandRotate90 Transform Source: https://github.com/project-monai/monai/wiki/Developer-Guide-Transforms Demonstrates how a vanilla `RandRotate90` transform is applied to a NumPy array, showing the input and output. ```python img = np.array((1, 2, 3, 4)).reshape((1, 2, 2)) rotator = RandRotate90(prob=0.0, max_k=3, axes=(1, 2)) img_result = rotator(img) print(type(img_result)) print(img_result) ``` -------------------------------- ### Adjust metrics APIs for data parallel support (v0.5) Source: https://github.com/project-monai/monai/wiki/v0.5-to-v0.6-migration-guide Example of computing metrics in v0.5, where manual aggregation of metric sum and count is required. ```python dice_metric = DiceMetric(include_background=True, reduction="mean") metric_sum = 0.0 metric_count = 0 for val_data in val_loader: images, labels = val_data["img"].to(device), val_data["seg"].to(device) preds = val_post_tran(sliding_window_inference(images, (96, 96, 96), 4, model)) value, not_nans = dice_metric(y_pred=preds, y=labels) metric_count += not_nans.item() metric_sum += value.item() * not_nans.item() metric = metric_sum / metric_count ``` -------------------------------- ### Compose Transforms with Explicit Seeds Source: https://github.com/project-monai/monai/wiki/MONAI_Preprocessors_and_Transforms_Design_Discussion This example shows how to create separate transform pipelines for images and segmentations while ensuring consistent randomness by initializing transforms with the same seed. This approach allows for different preprocessing stages. ```python imtrans=transforms.Compose([ Rescale(), AddChannel(), AddGaussianNoise(sigma=.5, seed=1234), UniformRandomPatch((64, 64, 64), seed=5678), ToTensor() ]) segtrans=transforms.Compose([ AddChannel(), UniformRandomPatch((64, 64, 64), seed=5678), ToTensor() ]) ``` -------------------------------- ### Define Network Architecture in YAML Source: https://github.com/project-monai/monai/blob/dev/docs/source/config_syntax.md Example of defining a network architecture using YAML format for MONAI bundle configuration. ```yaml demo_net: _target_: monai.networks.nets.BasicUNet spatial_dims: 3 in_channels: 1 out_channels: 2 features: [16, 16, 32, 32, 64, 64] ``` -------------------------------- ### Adjust metrics APIs for data parallel support (v0.6) Source: https://github.com/project-monai/monai/wiki/v0.5-to-v0.6-migration-guide Example of computing metrics in v0.6, utilizing decollate_batch and aggregate for automatic calculation and reset for subsequent computations. ```python dice_metric = DiceMetric(include_background=True, reduction="mean", get_not_nans=False) for val_data in val_loader: images, labels = val_data["img"].to(device), val_data["seg"].to(device) preds = sliding_window_inference(val_images, (96, 96, 96), 4, model) # decollate prediction into a list and execute post processing for every item preds = [postprocessing(i) for i in decollate_batch(preds)] # compute metric for current iteration dice_metric(y_pred=val_outputs, y=val_labels) # aggregate and compute the final result of metric metric = dice_metric.aggregate().item() dice_metric.reset() ``` -------------------------------- ### Define Network Architecture in JSON Source: https://github.com/project-monai/monai/blob/dev/docs/source/config_syntax.md Example of defining a network architecture using JSON format for MONAI bundle configuration. ```json { "demo_net": { "_target_": "monai.networks.nets.BasicUNet", "spatial_dims": 3, "in_channels": 1, "out_channels": 2, "features": [16, 16, 32, 32, 64, 64] } } ``` -------------------------------- ### Uninstall MONAI from Local Clone Source: https://github.com/project-monai/monai/blob/dev/docs/source/installation.md Uninstall MONAI when installed from a local clone. ```bash cd MONAI/ pip uninstall -y monai ``` -------------------------------- ### Get All Bundle Lists Source: https://github.com/project-monai/monai/blob/dev/docs/source/bundle.rst Retrieves a list of all available model bundles. ```APIDOC ## get_all_bundles_list ### Description Gets a list of all available bundles. ### Usage ```python get_all_bundles_list() ``` ``` -------------------------------- ### Get Activation Layer Source: https://github.com/project-monai/monai/wiki/Developer-Guide-Networks Shows how to retrieve activation layers like 'swish' or 'prelu' using the get_act_layer utility. For 'prelu', configuration options like 'num_parameters' and 'init' can be provided. ```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})) ``` -------------------------------- ### Lazy Import of Optional Dependencies Source: https://github.com/project-monai/monai/blob/dev/CONTRIBUTING.md Demonstrates how to lazily import optional dependencies using `optional_import` to ensure MONAI core modules function even if external packages are not installed. ```python from monai.utils import optional_import itk, _ = optional_import("itk", ...) class ITKReader(ImageReader): ... def read(self, ...): return itk.imread(...) ``` -------------------------------- ### View Documentation Build Help Source: https://github.com/project-monai/monai/blob/dev/CONTRIBUTING.md Display all available options and commands for building documentation. This command lists supported formats and other build-related utilities. ```bash make help ``` -------------------------------- ### MetaTensor with Metadata Source: https://github.com/project-monai/monai/wiki/MetaTensor-guide Shows how to initialize a MetaTensor with associated metadata. Metadata can include information like affine transformations, spacing, and origin. ```python import torch from monai.data.meta_tensor import MetaTensor import numpy as np torch_tensor = torch.randn(1, 3, 256, 256) metadata = {"affine": np.eye(4), "spacing": [1.0, 1.0, 1.0]} meta_tensor = MetaTensor(torch_tensor, metadata=metadata) ``` -------------------------------- ### Vista3d Sample Prompt Pairs Source: https://github.com/project-monai/monai/blob/dev/docs/source/apps.rst Samples prompt pairs for Vista3D. ```APIDOC ## Vista3d Sample Prompt Pairs ### Description Function to sample prompt pairs for Vista3D. ### Function `monai.apps.vista3d.sampler.sample_prompt_pairs` ``` -------------------------------- ### Tune Parameters and Instantiate Component Source: https://github.com/project-monai/monai/blob/dev/docs/source/config_syntax.md Modify configuration parameters and then instantiate a Python object. ```python config["demo_net"]["features"] = [32, 32, 32, 64, 64, 64] net = config.get_parsed_content("demo_net", instantiate=True) ``` -------------------------------- ### Build HTML Documentation Source: https://github.com/project-monai/monai/blob/dev/CONTRIBUTING.md Build the HTML version of the MONAI documentation locally. This allows for previewing changes before they are deployed. ```bash cd docs/ make html ``` -------------------------------- ### Initialize Bundle Source: https://github.com/project-monai/monai/blob/dev/docs/source/bundle.rst Initializes a model bundle, potentially setting up necessary configurations or files. ```APIDOC ## init_bundle ### Description Initializes a bundle. ### Parameters * **bundle_dir** (str) - The directory for the bundle. * **config_files** (list[str], optional) - Configuration files to include. ### Usage ```python init_bundle(bundle_dir, config_files=None) ``` ``` -------------------------------- ### Get nnUNet Trainer Source: https://github.com/project-monai/monai/blob/dev/docs/source/apps.rst Retrieves an nnUNet trainer instance. ```APIDOC ## Get nnUNet Trainer ### Description Retrieves an nnUNet trainer instance. ### Function `monai.apps.nnunet.get_nnunet_trainer` ``` -------------------------------- ### MONAI Bundle CLI Usage Source: https://github.com/project-monai/monai/blob/dev/docs/source/config_syntax.md Shows the basic command-line interface for MONAI bundles. Use 'python -m monai.bundle COMMANDS' for various operations like 'run' or 'verify_metadata'. Use '-- --help' after a command for specific usage details. ```bash python -m monai.bundle COMMANDS ``` ```bash python -m monai.bundle run -- --help ``` -------------------------------- ### Run Quick Unit Tests Source: https://github.com/project-monai/monai/blob/dev/CONTRIBUTING.md Execute a subset of unit tests for new features that are not expected to break existing functionality. This is a faster alternative for testing new additions. ```bash ./runtests.sh --quick --unittests ``` -------------------------------- ### Get Network from nnUNet Plans Source: https://github.com/project-monai/monai/blob/dev/docs/source/apps.rst Retrieves a network architecture from nnUNet plans. ```APIDOC ## Get Network from nnUNet Plans ### Description Retrieves a network architecture based on nnUNet plans. ### Function `monai.apps.nnunet.get_network_from_nnunet_plans` ``` -------------------------------- ### BasicUNetPlusPlus Source: https://github.com/project-monai/monai/blob/dev/docs/source/networks.rst Implementation of a UNet++ architecture. ```APIDOC ## BasicUNetPlusPlus ### Description Provides a UNet++ implementation. ### Class `monai.networks.nets.BasicUNetPlusPlus` ``` -------------------------------- ### Get Bundle Info Source: https://github.com/project-monai/monai/blob/dev/docs/source/bundle.rst Retrieves detailed information about a specific model bundle. ```APIDOC ## get_bundle_info ### Description Gets information about a specific bundle. ### Parameters * **bundle_name** (str) - The name of the bundle. * **version** (str, optional) - The specific version of the bundle. ### Usage ```python get_bundle_info(bundle_name, version=None) ``` ``` -------------------------------- ### Get nnUNet MONAI Predictor Source: https://github.com/project-monai/monai/blob/dev/docs/source/apps.rst Retrieves an nnUNet predictor instance compatible with MONAI. ```APIDOC ## Get nnUNet MONAI Predictor ### Description Retrieves an nnUNet predictor instance that is compatible with MONAI. ### Function `monai.apps.nnunet.get_nnunet_monai_predictor` ``` -------------------------------- ### Get Bundle Versions Source: https://github.com/project-monai/monai/blob/dev/docs/source/bundle.rst Retrieves a list of available versions for a specific model bundle. ```APIDOC ## get_bundle_versions ### Description Gets a list of available versions for a bundle. ### Parameters * **bundle_name** (str) - The name of the bundle. ### Usage ```python get_bundle_versions(bundle_name) ``` ``` -------------------------------- ### Instantiate Python Object with Optional Keys Source: https://github.com/project-monai/monai/blob/dev/docs/source/config_syntax.md Includes optional keys like '_requires_', '_disabled_', '_desc_', and '_mode_' for advanced configuration. '_requires_' specifies dependencies, '_disabled_' skips instantiation, '_desc_' provides descriptions, and '_mode_' controls instantiation behavior (default, callable, debug). ```json { "component_name": { "_target_": "my.module.Class", "_desc_": "this is a customized class which also triggers 'cudnn_opt' reference", "_requires_": "@cudnn_opt", "_disabled_": "true", "_mode_": "default"} } ``` -------------------------------- ### Basic MetaTensor Creation Source: https://github.com/project-monai/monai/wiki/MetaTensor-guide Demonstrates how to create a MetaTensor from a PyTorch tensor. This is the fundamental step to leverage MetaTensor's capabilities. ```python import torch from monai.data.meta_tensor import MetaTensor torch_tensor = torch.randn(1, 3, 256, 256) meta_tensor = MetaTensor(torch_tensor) ``` -------------------------------- ### AdversarialTrainer Source: https://github.com/project-monai/monai/blob/dev/docs/source/engines.rst A general trainer for adversarial learning setups, which may include GANs or other adversarial models. ```APIDOC ## AdversarialTrainer ### Description A general trainer for adversarial learning setups, which may include GANs or other adversarial models. ### Members This class offers a flexible framework for training models in adversarial settings. Refer to the source code for a complete list of available methods and attributes. ``` -------------------------------- ### DiceFocalLoss Source: https://github.com/project-monai/monai/blob/dev/docs/source/losses.rst Combines Dice Loss with Focal Loss, designed to handle class imbalance and hard-to-classify examples effectively. ```APIDOC ## DiceFocalLoss ### Description Implements the Dice Focal Loss. ### Class `monai.losses.DiceFocalLoss` ### Members (Members are documented in the source code) ``` -------------------------------- ### Uninstall MONAI Packages Source: https://github.com/project-monai/monai/blob/dev/docs/source/installation.md Use these commands to remove MONAI and MONAI weekly preview packages installed via pip. ```bash pip uninstall -y monai pip uninstall -y monai-weekly ``` -------------------------------- ### FocalLoss Source: https://github.com/project-monai/monai/blob/dev/docs/source/losses.rst Implements Focal Loss, a modification of Cross-Entropy loss that down-weights easy examples and focuses training on hard negatives. ```APIDOC ## FocalLoss ### Description Implements the Focal Loss. ### Class `monai.losses.FocalLoss` ### Members (Members are documented in the source code) ``` -------------------------------- ### Create Convolution Layer using Factory Source: https://github.com/project-monai/monai/wiki/Developer-Guide-Networks Demonstrates how to create a convolutional layer using the Conv factory, specifying dimension and layer name. ```python dimension = 3 name = Conv.CONVTRANS conv = Conv[name, dimension] ``` -------------------------------- ### Profile with cProfile and SNAKEVIZ Source: https://github.com/project-monai/monai/blob/dev/tests/profile_subclass/README.md Utilize Python's built-in `cProfile` module for detailed profiling and `snakeviz` to visualize the results. This method offers in-depth performance analysis. ```bash python cprofile_profiling.py snakeviz out_200.prof ``` -------------------------------- ### Example Usage of Dictionary-Based RandRotate90d Transform Source: https://github.com/project-monai/monai/wiki/Developer-Guide-Transforms Illustrates the application of a dictionary-based `RandRotate90d` transform to a dictionary containing image and segmentation data. ```python data = { 'img': np.array((1, 2, 3, 4)).reshape((1, 2, 2)), 'seg': np.array((1, 2, 3, 4)).reshape((1, 2, 2)), 'unused': 5, } rotator = RandRotate90d(keys=('img', 'seg'), prob=0.8) data_result = rotator(data) print(data_result) ``` -------------------------------- ### Quicknat Source: https://github.com/project-monai/monai/blob/dev/docs/source/networks.rst QuickNAT network architecture. ```APIDOC ## Quicknat ### Description Implementation of the QuickNAT network architecture. ### Class `monai.networks.nets.Quicknat` ``` -------------------------------- ### License Header for Source Files Source: https://github.com/project-monai/monai/blob/dev/CONTRIBUTING.md All source code files must begin with this Apache 2.0 license header. ```python # Copyright (c) MONAI Consortium # Licensed under the Apache License, Version 2.0 (the "License"); ``` -------------------------------- ### Using adaptor with Compose Source: https://github.com/project-monai/monai/wiki/MONAI_Preprocessors_and_Transforms_Design Demonstrates how to use the `adaptor` function to wrap simple and complex transforms for use within a `Compose` pipeline. Specify the output name when wrapping simple transforms to ensure correct dictionary key handling. ```python def load_data(path): def _inner(): dictionary = {'image': get_images(path), 'labels': get_labels(path)} return dictionary return _inner def simple_tx(image): # do something to image and return a copy return image def complex_tx(dictionary): # do something to the 'image' entry in the dictionary and return a copy of the # modified dictionary new_image = work_on(dictionary['image']) dictionary = dict(dictionary) dictionary['image'] = new_image return dictionary Compose([ load_data(path), adaptor(simple_tx, 'image') complex_tx ]) ``` -------------------------------- ### TopologyInstance Source: https://github.com/project-monai/monai/blob/dev/docs/source/networks.rst Component for topology instance handling within DiNTS. ```APIDOC ## TopologyInstance ### Description Component for managing topology instances, used in DiNTS. ### Class `monai.apps.reconstruction.networks.nets.topology_instance.TopologyInstance` ``` -------------------------------- ### Instantiate Component from JSON Config Source: https://github.com/project-monai/monai/blob/dev/docs/source/config_syntax.md Instantiate a Python object from a JSON configuration file using ConfigParser. ```python from monai.bundle import ConfigParser config = ConfigParser() config.read_config("demo_config.json") net = config.get_parsed_content("demo_net", instantiate=True) print(type(net)) ``` -------------------------------- ### Instantiate a Python Object Source: https://github.com/project-monai/monai/blob/dev/docs/source/config_syntax.md Defines an object with a reference name, an instantiable type specified at '_target_', and input arguments. '_target_' is a required key for MONAI bundle syntax. Arguments should be compatible with the Python object to instantiate. ```json { "demo_name":{ "_target_": "my.python.module.Class", "args1": "string", "args2": 42} } ``` -------------------------------- ### FHIR Observation Resource Example Source: https://github.com/project-monai/monai/wiki/Exploring-FHIR This snippet demonstrates a FHIR Observation resource, commonly used to record measurements or findings. It includes details like code, display, and a value. ```json { "code": "(MDC code for intensity)", "display": "(MDC description for intensity)" } ] }, "valueInteger": 5 } } } ] } ``` -------------------------------- ### BasicUNet Source: https://github.com/project-monai/monai/blob/dev/docs/source/networks.rst Implementation of a basic UNet architecture. ```APIDOC ## BasicUNet ### Description Provides a basic UNet implementation. ### Class `monai.networks.nets.BasicUNet` ``` -------------------------------- ### Example Annotation Structure for FHIR Source: https://github.com/project-monai/monai/wiki/Minutes-Data-Working-Group-26-Oct-2020 This structure illustrates a potential way to represent annotations within a FHIR context, using nested objects for original studies and their associated annotations with classification labels. ```json [ { "original study" = nifti } { "annotation 1" } { "annotation 1" = nifti } { "classification label" } { "annotation 2" } { "annotation 2" = nifti } { "classification label" } { "annotation 3" } { "annotation 3" = nifti } { "classification label" } ] ``` -------------------------------- ### Merge Configuration Files Source: https://github.com/project-monai/monai/blob/dev/docs/source/config_syntax.md Demonstrates merging multiple configuration files. Keys specified in later files override earlier ones. Prefixing a key with '+' merges values (dict update, list concatenation) instead of overriding. Type consistency (dict or list) is required for merging. ```json { "amp": "$True" "imports": [ "$import torch" ], "preprocessing": { "_target_": "Compose", "transforms": [ "$@t1", "$@t2" ] }, } ``` ```json { "amp": "$False" "+imports": [ "$from monai.networks import trt_compile" ], "+preprocessing#transforms": [ "$@t3" ] } ``` -------------------------------- ### Example metadata.json Output Specification Source: https://github.com/project-monai/monai/wiki/MONAI-Archive-Specification Defines the 'pred' output in a metadata.json file, specifying it as a segmentation image with 2 channels, a spatial shape of [160, 160, 160], float32 data type, a value range of [0, 1], and channel definitions for background and spleen. ```json { "pred": { "type": "image", "format": "segmentation", "num_channels": 2, "spatial_shape": [160, 160, 160], "dtype": "float32", "value_range": [0, 1], "is_patch_data": false, "channel_def": {0: "background", 1: "spleen"} } } } } ``` -------------------------------- ### Textual Replacement in Configuration Source: https://github.com/project-monai/monai/blob/dev/docs/source/config_syntax.md Use the '%' symbol for textual replacement of configuration elements from other files. ```json "%demo_config.json::demo_net::in_channels" ``` -------------------------------- ### Applying a MONAI Transform Instance Source: https://github.com/project-monai/monai/wiki/Developer-Guide-Transforms Shows the typical usage pattern for applying a constructed MONAI transform instance to input data. ```python transform = Transform(system_params) # construct a transform instance output_data = transform(input_data, data_params) # apply the transform ``` -------------------------------- ### Load Bundle Source: https://github.com/project-monai/monai/blob/dev/docs/source/bundle.rst Loads a model bundle configuration from a specified path. ```APIDOC ## load ### Description Loads a model bundle configuration. ### Parameters * **bundle_dir** (str) - The directory containing the bundle. * **config_files** (list[str], optional) - A list of configuration file names to load. Defaults to ['bundle.json']. * **kwargs** - Additional keyword arguments to pass to the configuration parser. ### Usage ```python load(bundle_dir, config_files=None, **kwargs) ``` ``` -------------------------------- ### ToDevice Source: https://github.com/project-monai/monai/blob/dev/docs/source/transforms.rst Moves the data to a specified device (e.g., CPU, GPU). ```APIDOC ## ToDevice ### Description Moves the data to a specified device (e.g., CPU, GPU). ### Class monai.transforms.ToDevice ### Usage .. autoclass:: ToDevice :members: :special-members: __call__ ``` -------------------------------- ### HoVerNetInstanceMapPostProcessing Source: https://github.com/project-monai/monai/blob/dev/docs/source/apps.rst Post-processing for HoVerNet instance map. ```APIDOC ## HoVerNetInstanceMapPostProcessing ### Description Post-processing steps for generating instance maps from HoVerNet outputs. ### Class `monai.apps.pathology.transforms.post.array.HoVerNetInstanceMapPostProcessing` ``` -------------------------------- ### Skipping Tests for Unavailable Optional Dependencies Source: https://github.com/project-monai/monai/blob/dev/CONTRIBUTING.md Shows how to use `optional_import` and `skipUnless` to conditionally skip test cases when optional dependencies like Matplotlib are not available. ```python from monai.utils import optional_import plt, has_matplotlib = optional_import("matplotlib.pyplot") @skipUnless(has_matplotlib, "Matplotlib required") class TestBlendImages(unittest.TestCase): ``` -------------------------------- ### Profile Task of Adding Two MetaTensors Source: https://github.com/project-monai/monai/blob/dev/tests/profile_subclass/README.md Execute the main profiling script to measure the performance of adding two MetaTensors. This provides a baseline for comparison. ```bash python profiling.py ``` -------------------------------- ### DynUNet Source: https://github.com/project-monai/monai/blob/dev/docs/source/networks.rst Dynamic UNet architecture. ```APIDOC ## DynUNet ### Description Implementation of the Dynamic UNet architecture. ### Class `monai.networks.nets.DynUNet` ### Members Refer to the class documentation for available methods and parameters. ``` -------------------------------- ### MetaTensor with Attached Transforms Source: https://github.com/project-monai/monai/wiki/MetaTensor-guide Shows how to attach transformation functions to a MetaTensor, which can be applied later. ```python import torch from monai.data.meta_tensor import MetaTensor import numpy as np torch_tensor = torch.randn(1, 3, 256, 256) metadata = {"affine": np.eye(4), "spacing": [1.0, 1.0, 1.0]} meta_tensor = MetaTensor(torch_tensor, metadata=metadata) def simple_transform(x): return x * 2 meta_tensor.attach_transform(simple_transform) # The transform is not applied yet, but is stored print(meta_tensor.transforms) ``` -------------------------------- ### Run Bundle Source: https://github.com/project-monai/monai/blob/dev/docs/source/bundle.rst Executes a script or workflow defined within a model bundle. ```APIDOC ## run ### Description Runs a bundle script. ### Parameters * **bundle_dir** (str) - The directory containing the bundle. * **script_name** (str) - The name of the script to run within the bundle. * **args** (list[str], optional) - Command-line arguments to pass to the script. ### Usage ```python run(bundle_dir, script_name, args=None) ``` ``` -------------------------------- ### Import DynUNet from dynunet_v1 for backward compatibility Source: https://github.com/project-monai/monai/wiki/v0.5-to-v0.6-migration-guide In v0.6, 'DynUNet' has been updated. To maintain compatibility with previous versions, import 'DynUNet' from 'monai.networks.nets.dynunet_v1'. This import will be removed in future releases. ```python from monai.networks.nets.dynunet_v1 import DynUNetV1 as DynUNet ``` -------------------------------- ### utils Source: https://github.com/project-monai/monai/blob/dev/docs/source/handlers.rst General utility functions for handlers. ```APIDOC ## Utilities ### Description Contains various utility functions that can be used in conjunction with MONAI handlers. ### Usage Import and use functions from `monai.handlers.utils` to enhance handler functionality. ``` -------------------------------- ### Run All Tests Locally Source: https://github.com/project-monai/monai/blob/dev/CONTRIBUTING.md Execute all linting and unit tests locally before submitting a pull request. This ensures code quality and adherence to project standards. ```bash ./runtests.sh -f -u --net --coverage ``` -------------------------------- ### Applying Attached Transforms Source: https://github.com/project-monai/monai/wiki/MetaTensor-guide Demonstrates how to apply the transforms that have been attached to a MetaTensor. ```python import torch from monai.data.meta_tensor import MetaTensor import numpy as np torch_tensor = torch.randn(1, 3, 256, 256) metadata = {"affine": np.eye(4), "spacing": [1.0, 1.0, 1.0]} meta_tensor = MetaTensor(torch_tensor, metadata=metadata) def simple_transform(x): return x * 2 meta_tensor.attach_transform(simple_transform) # Apply the attached transforms transformed_tensor = meta_tensor.apply_transforms() # The data is now transformed print(transformed_tensor.data == meta_tensor.data * 2) ``` -------------------------------- ### Composing Dictionary-Based Transforms with Compose Source: https://github.com/project-monai/monai/wiki/Developer-Guide-Transforms Demonstrates how to chain multiple dictionary-based transforms together using MONAI's `Compose` utility for sequential data processing. ```python composed = monai.transforms.Compose([ Transform1d(system_params), Transform2d(system_params), ... ]) output_data = composed(input_data) # input_data is a dictionary ``` -------------------------------- ### Basic Transform Structure in MONAI Source: https://github.com/project-monai/monai/wiki/Developer-Guide-Transforms Illustrates the general pattern for defining a MONAI transform class, including initialization with system parameters and the callable method for processing input data. ```python class Transform: def __init__(self, system_params): # set states using system parameters self.some_states = ... # from system_params def __call__(self, input_data, data_params): # using self.some_states and data_params # process data and return output_data ``` -------------------------------- ### ComponentStore Source: https://github.com/project-monai/monai/blob/dev/docs/source/utils.rst Manages components within the MONAI framework, allowing for registration, retrieval, and management of various components. ```APIDOC ## class monai.utils.component_store.ComponentStore ### Description Manages components within the MONAI framework. ### Methods * **register(component: Any, name: Optional[str] = None, overwrite: bool = False)**: Registers a component with an optional name. * **get(name: str, default: Optional[Any] = None)**: Retrieves a registered component by name. * **unregister(name: str)**: Removes a registered component. * **clear()**: Clears all registered components. ``` -------------------------------- ### MONAI Bundle Reference Implementations Source: https://github.com/project-monai/monai/blob/dev/docs/source/fl.rst Reference implementations for MONAI bundles in Federated Learning. ```APIDOC ## MonaiAlgo ### Description Reference implementation of a client algorithm using MONAI bundles. ### Members (Members are documented via autoclass directive) ``` ```APIDOC ## MonaiAlgoStats ### Description Reference implementation for client algorithm statistics using MONAI bundles. ### Members (Members are documented via autoclass directive) ``` -------------------------------- ### Configure NumpyReader to Allow Pickle Loading Source: https://github.com/project-monai/monai/blob/dev/docs/source/whatsnew_1_6.md Illustrates how to explicitly enable or disable pickle loading from .npy/.npz files in NumpyReader using the `allow_pickle` argument. It is disabled by default for security. ```python reader = NumpyReader(allow_pickle=True) ``` -------------------------------- ### ResizeGuidanced Source: https://github.com/project-monai/monai/blob/dev/docs/source/apps.rst Resizes guidance in the data dictionary. ```APIDOC ## ResizeGuidanced ### Description A dictionary transform that resizes the guidance information in the data. ### Class `monai.apps.deepgrow.transforms.ResizeGuidanced` ``` -------------------------------- ### HoVerNetInstanceMapPostProcessingd Source: https://github.com/project-monai/monai/blob/dev/docs/source/apps.rst Post-processing for HoVerNet instance map in data dictionary. ```APIDOC ## HoVerNetInstanceMapPostProcessingd ### Description A dictionary transform for generating instance maps from HoVerNet outputs. ### Class `monai.apps.pathology.transforms.post.dictionary.HoVerNetInstanceMapPostProcessingd` ``` -------------------------------- ### Experiment-Specific IO Overrides in MONAI Source: https://github.com/project-monai/monai/wiki/Image-IO-Proposal This configuration illustrates how to specify alternative loaders for particular file types within an experiment's configuration. This allows for fine-grained control over I/O behavior to ensure reproducibility. ```plaintext Experiment.IO { PNG ITK/5.2/LoadITK TIF LoadTIF } ``` -------------------------------- ### Data-Agnostic Image Loading in MONAI Source: https://github.com/project-monai/monai/wiki/Image-IO-Proposal This demonstrates how MONAI's ImageDataset can abstract away file format specifics, allowing for a consistent API regardless of the underlying image storage. This approach simplifies data loading for developers. ```python train_ds = ImageDataset(images, segs, transform=train_imtrans, seg_transform=train_segtrans) ``` -------------------------------- ### create_dataset Source: https://github.com/project-monai/monai/blob/dev/docs/source/apps.rst Creates a dataset for deepgrow. ```APIDOC ## create_dataset ### Description Function to create a dataset specifically for the deepgrow interaction module. ### Function `monai.apps.deepgrow.dataset.create_dataset` ``` -------------------------------- ### SEResNext101 Source: https://github.com/project-monai/monai/blob/dev/docs/source/networks.rst SE-ResNeXt with 101 layers. ```APIDOC ## SEResNext101 ### Description Squeeze-and-Excitation Residual NeXt (SEResNeXt) with 101 layers. ### Class `monai.networks.nets.SEResNext101` ### Members Refer to the class documentation for available methods and parameters. ``` -------------------------------- ### Dictionary-based Data Flow without Compose Source: https://github.com/project-monai/monai/wiki/MONAI_Preprocessors_and_Transforms_Design_Discussion Demonstrates how to manage data transformations when the loader returns a dictionary. This pattern is useful when transforms operate on specific keys within the dictionary, offering more explicit data handling. ```python # 4. load returns dict, normalise takes single arg; deform takes image and matrix and returns dict d = load(f) d['image'] = normalise(d['image']) d = deform(d) ``` ```python # 5. load returns dict, normalise takes **kwargs, deform takes **kwargs and returns dict# d = load(f) d = normalise(d) d = deform(d) ``` ```python # 6. load returns dict, all methods take and return dicts d = load(f) d = normalise(d) d = image(d) d = matrix(d) ```