Utilities

Configurations

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

Read the package versions into a dictionary.

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

Read the optional package versions into a dictionary.

monai.config.deviceconfig.get_torch_version_tuple()[source]
Returns

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.

Parameters

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

Module utils

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.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 loadAll is True, excluding anything whose name matches excludePattern.

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) – 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
AttributeError: Optional import: 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
AttributeError: Optional import: 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)
AttributeError: Optional import: 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

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

Returns a tuple of vals.

Return type

Tuple

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

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 (Sequence) – 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

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.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 satus 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=2147483647, 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], Callable, 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.