Read the package versions into a dictionary.


Read the optional package versions into a dictionary.


tuple of ints represents the pytorch major/minor version.

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

Print the package versions to file.


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

Module utils

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



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


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.

  • 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]


The imported module and a boolean flag indicating whether the import is successful.


>>> 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)
>>> 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').
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.has_option(obj, keywords)[source]

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

Return type



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


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.


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.

  • 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.


class monai.utils.misc.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.


Convert a numpy dtype to its torch equivalent.


Convert a torch dtype to its numpy equivalent.


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.


ValueError – When tup is a sequence and tup length is not dim.


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

  • user_provided (Any) – item to be validated.

  • default (Sequence) – a sequence used to provided the fallbacks.

  • func (Callable) – a Callable to validate every components of user_provided.


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


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

Return type



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.

  • 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


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

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

  • 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


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.