Utilities

Configurations

monai.config.deviceconfig.get_system_info()[source]

Get system info as an ordered dictionary.

Return type

OrderedDict

monai.config.deviceconfig.print_config(file=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='UTF-8'>)[source]

Print the package versions to file.

Parameters

fileprint() text stream file. Defaults to sys.stdout.

monai.config.deviceconfig.print_debug_info(file=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='UTF-8'>)[source]

Print config (installed dependencies, etc.) and system info for debugging.

Parameters

fileprint() text stream file. Defaults to sys.stdout.

Return type

None

monai.config.deviceconfig.print_gpu_info(file=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='UTF-8'>)[source]

Print GPU info to file.

Parameters

fileprint() text stream file. Defaults to sys.stdout.

Return type

None

monai.config.deviceconfig.print_system_info(file=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='UTF-8'>)[source]

Print system info to file. Requires the optional library, psutil.

Parameters

fileprint() text stream file. Defaults to sys.stdout.

Return type

None

Module utils

exception monai.utils.module.InvalidPyTorchVersionError(required_version, name)[source]

Raised when called function or method requires a more recent PyTorch version than that installed.

exception monai.utils.module.OptionalImportError[source]

Could not import APIs from an optional dependency.

monai.utils.module.exact_version(the_module, version_str='')[source]

Returns True if the module’s __version__ matches version_str

Return type

bool

monai.utils.module.export(modname)[source]

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.

monai.utils.module.get_package_version(dep_name, default='NOT INSTALLED or UNKNOWN VERSION.')[source]

Try to load package and get version. If not found, return default.

monai.utils.module.get_torch_version_tuple()[source]
Returns

tuple of ints represents the pytorch major/minor version.

monai.utils.module.has_option(obj, keywords)[source]

Return a boolean indicating whether the given callable obj has the keywords in its signature.

Return type

bool

monai.utils.module.load_submodules(basemod, load_all=True, exclude_pattern='(.*[tT]est.*)|(_.*)')[source]

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.

monai.utils.module.min_version(the_module, min_version_str='')[source]

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.

Return type

bool

monai.utils.module.optional_import(module, version='', version_checker=<function min_version>, name='', descriptor='{}', version_args=None, allow_namespace_pkg=False)[source]

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.

Parameters
  • module (str) – name of the module to be imported.

  • version (str) – version string used by the version_checker.

  • version_checker (Callable[…, bool]) – a callable to check the module version, Defaults to monai.utils.min_version.

  • name (str) – a non-module attribute (such as method/class) to import from the imported module.

  • descriptor (str) – 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 (bool) – whether importing a namespace package is allowed. Defaults to False.

Return type

Tuple[Any, bool]

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)
<module 'torch' from 'python/lib/python3.6/site-packages/torch/__init__.py'> 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)
<built-in method conv1d of type object at 0x11a49eac0>

>>> 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').

Aliases

This module is written for configurable workflow, not currently in use.

monai.utils.aliases.alias(*names)[source]

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.

monai.utils.aliases.resolve_name(name)[source]

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.

Misc

class monai.utils.misc.ImageMetaKey[source]

Common key names in the meta data header of images

monai.utils.misc.copy_to_device(obj, device, non_blocking=True, verbose=False)[source]

Copy object or tuple/list/dictionary of objects to device.

Parameters
  • obj (Any) – object or tuple/list/dictionary of objects to move to device.

  • device (Union[str, device, None]) – move obj to this device. Can be a string (e.g., cpu, cuda, cuda:0, etc.) or of type torch.device.

  • non_blocking_transfer – when True, moves data to device asynchronously if possible, e.g., moving CPU Tensors with pinned memory to CUDA devices.

  • verbose (bool) – when True, will print a warning for any elements of incompatible type not copied to device.

Return type

Any

Returns

Same as input, copied to device where possible. Original input will be

unchanged.

monai.utils.misc.dtype_numpy_to_torch(dtype)[source]

Convert a numpy dtype to its torch equivalent.

monai.utils.misc.dtype_torch_to_numpy(dtype)[source]

Convert a torch dtype to its numpy equivalent.

monai.utils.misc.ensure_tuple(vals)[source]

Returns a tuple of vals.

Return type

Tuple[Any, …]

monai.utils.misc.ensure_tuple_rep(tup, dim)[source]

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.
Return type

Tuple[Any, …]

monai.utils.misc.ensure_tuple_size(tup, dim, pad_val=0)[source]

Returns a copy of tup with dim values by either shortened or padded with pad_val as necessary.

Return type

Tuple[Any, …]

monai.utils.misc.fall_back_tuple(user_provided, default, func=<function <lambda>>)[source]

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.

Parameters
  • user_provided (Any) – item to be validated.

  • default (Union[Sequence, ndarray]) – a sequence used to provided the fallbacks.

  • func (Callable) – 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.
Return type

Tuple[Any, …]

monai.utils.misc.first(iterable, default=None)[source]

Returns the first item in the given iterable or default if empty, meaningful mostly with ‘for’ expressions.

monai.utils.misc.issequenceiterable(obj)[source]

Determine if the object is an iterable sequence and is not a string.

Return type

bool

monai.utils.misc.list_to_dict(items)[source]

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.

monai.utils.misc.progress_bar(index, count, desc=None, bar_len=30, newline=False)[source]

print a progress bar to track some time consuming task.

Parameters
  • index (int) – current status in progress.

  • count (int) – total steps of the progress.

  • desc (Optional[str]) – description of the progress bar, if not None, show before the progress bar.

  • bar_len (int) – the total length of the bar on screen, default is 30 char.

  • newline (bool) – whether to print in a new line for every index.

Return type

None

monai.utils.misc.set_determinism(seed=4294967295, additional_settings=None)[source]

Set random seed for modules to enable or disable deterministic training.

Parameters
  • seed (Optional[int]) – 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.

  • additional_settings (Union[Sequence[Callable[[int], Any]], Callable[[int], Any], None]) – additional settings that need to set random seed.

Return type

None

monai.utils.misc.star_zip_with(op, *vals)[source]

Use starmap as the mapping function in zipWith.

monai.utils.misc.zip_with(op, *vals, mapfunc=<class 'map'>)[source]

Map op, using mapfunc, to each tuple derived from zipping the iterables in vals.

Profiling

class monai.utils.profiling.PerfContext[source]

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.

monai.utils.profiling.torch_profiler_full(func)[source]

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.

monai.utils.profiling.torch_profiler_time_cpu_gpu(func)[source]

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.

monai.utils.profiling.torch_profiler_time_end_to_end(func)[source]

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.