o  ie@sddlmZddlZddlZddlZddlZddlZddlZddlZddl m Z m Z m Z m Z mZddlmZmZddlmZddlmZddlmZddlmZdd lmZmZdd lmZmZddlZej d d d kZ!ej dd d kZ"ej dd d kZ#dZ$gdZ%  djdkddZ&dld#d$Z' %dmdnd+d,Z(dod0d1Z)d2d3Z*dpdqd8d9Z+dpdrd;d<Z,Gd=d>d>e-Z.Gd?d@d@e/Z0d4e+d4e$ddAdfdsdLdMZ1d4e+dfdtdQdRZ2dudTdUZ3e4ddVdWZ5dvd[d\Z6dwd]d^Z7dwd_d`Z8e4ddxdydfdgZ9e4ddxdzdhdiZ:dS){) annotationsN)Callable CollectionHashableIterableMapping)partialwraps) import_module) walk_packages)locate)match) FunctionType ModuleType)AnycastZMONAI_EVAL_EXPR10ZMONAI_DEBUG_CONFIGZMONAI_ALLOW_MISSING_REFERENCEz{})InvalidPyTorchVersionErrorOptionalImportError exact_versiondamerau_levenshtein_distancelook_up_option min_versionoptional_import require_pkg instantiateget_full_type_nameget_package_versionget_torch_version_tuple version_leq version_geq pytorch_after no_defaultTopt_strr supportedCollection | enum.EnumMetadefaultrprint_all_optionsboolreturnc Cst|tstdt|d|dt|tr|}t|tjr@t|tr3|dd|Dvr3||St|tjr?||vr?|Snt|t rM||vrM||St|t rX||vrX|S|dkr^|St|tjrldd|D}n |durtt |nt }|std |di}|}|D]}t ||}|d kr|||<q|rd |d nd }|rt ||jd} td|d| dd|d|td|d|)a3 Look up the option in the supported collection and return the matched item. Raise a value error possibly with a guess of the closest match. Args: opt_str: The option string or Enum to look up. supported: The collection of supported options, it can be list, tuple, set, dict, or Enum. default: If it is given, this method will return `default` when `opt_str` is not found, instead of raising a `ValueError`. Otherwise, it defaults to `"no_default"`, so that the method may raise a `ValueError`. print_all_options: whether to print all available options when `opt_str` is not found. Defaults to True Examples: .. code-block:: python from enum import Enum from monai.utils import look_up_option class Color(Enum): RED = "red" BLUE = "blue" look_up_option("red", Color) # look_up_option(Color.RED, Color) # look_up_option("read", Color) # ValueError: By 'read', did you mean 'red'? # 'read' is not a valid option. # Available options are {'blue', 'red'}. look_up_option("red", {"red", "blue"}) # "red" Adapted from https://github.com/NifTK/NiftyNet/blob/v0.6.0/niftynet/utilities/util_common.py#L249 zUnrecognized option type: :.cSh|]}|jqSvalue.0itemr.r.T/home/dell461/cl/sdc2/last_ska_mid/HISourceFinder-master-l/src/monai/utils/module.py gz!look_up_option..r#cSr-r.r/r1r.r.r4r5yr6NzNo options available: zAvailable options are z. )keyzBy 'z', did you mean 'z'? 'z' is not a valid value. zUnsupported option 'z', ) isinstancer ValueErrortypestrstripenumEnumMetaEnumrrsetrminget) r$r%r'r(Z set_to_checkZ edit_distsr9Z edit_distZ supported_msgZguess_at_spellingr.r.r4r=sN %     rs1r>s2intc CsN||krdSt|}t|}|s|S|s|Sddtd|dD}td|dD] }|d|d|f<q)t|D]d\}}t|D][\}}||krJdnd} t||d|fd|||dfd||d|df| |||f<|r|r|||dkr||d|krt|||f||d|df| |||f<q@q8||d|dfS)u Calculates the Damerau–Levenshtein distance between two strings for spelling correction. https://en.wikipedia.org/wiki/Damerau–Levenshtein_distance rcSsi|] }|df|dqS)r.)r2ir.r.r4 sz0damerau_levenshtein_distance..rIrJ)lenrange enumeraterD) rFrGZstring_1_lengthZstring_2_lengthdjrKZs1iZs2jcostr.r.r4rs,: (.r(.*[tT]est.*)|(_.*)basemodrload_allexclude_pattern"tuple[list[ModuleType], list[str]]c Csg}g}t|j|jd|jdD]Y\}}}|s|ri|tjvrit||durizt|}||} | rA| j rA| j } | |||Wqt yKYqt yh} zd} t | | d| | j| d} ~ wwq||fS)z 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`. r,)prefixonerrorNz Multiple versions of MONAI may have been installed? Please see the installation guide: https://docs.monai.io/en/stable/installation.html  )r __path____name__appendsysmodulesr r find_specloader exec_moduler ImportErrorr=with_traceback __traceback__) rUrVrW submodulesZerr_modimporternameZis_pkgmodmod_specrbemsgr.r.r4load_submoduless0       rn__path__modekwargsc Kslddlm}t|trt|n|}|durtd|dt||}zg|dds+tr:t d|d |d t t |sMt d |d |d |WS||j krZ|di|WS||jkrm|rjt|fi|WS|WS||jkrt d|d |d tj|fi|WSWn!ty}ztd|dd|d|jd|d}~wwt d|d |S)a Create an object instance or call a callable object from a class or function represented by ``_path``. `kwargs` will be part of the input arguments to the class constructor or function. The target component must be a class or a function, if not, return the component directly. Args: __path: if a string is provided, it's interpreted as the full path of the target class or function component. If a callable is provided, ``__path(**kwargs)`` will be invoked and returned for ``__mode="default"``. For ``__mode="callable"``, the callable will be returned as ``__path`` or, if ``kwargs`` are provided, as ``functools.partial(__path, **kwargs)`` for future invoking. __mode: the operating mode for invoking the (callable) ``component`` represented by ``__path``: - ``"default"``: returns ``component(**kwargs)`` - ``"callable"``: returns ``component`` or, if ``kwargs`` are provided, ``functools.partial(component, **kwargs)`` - ``"debug"``: returns ``pdb.runcall(component, **kwargs)`` kwargs: keyword arguments to the callable represented by ``__path``. r) CompInitModeNz'Cannot locate class or function path: 'z'.Z_debug_Fz pdb: instantiating component=z, mode=zV See also Debugger commands documentation: https://docs.python.org/3/library/pdb.html z Component z is not callable when mode=r,z!Failed to instantiate component 'z' with keywords: ,z set '_mode_=z' to enter the debugging mode.zKComponent to instantiate must represent a valid class or function, but got r.)monai.utils.enumsrrr;r>r ModuleNotFoundErrorrpop run_debugwarningswarn breakpointcallableDEFAULTZCALLABLErDEBUGpdbruncall Exception RuntimeErrorjoinkeys)rorprqrr componentmrlr.r.r4rsH     rcCs.|j}|dus |tjjkr|jS|d|jS)zG Utility to get the full path name of a class or object type. Nr,) __module__r> __class__r])typeobjmoduler.r.r4rsrr8 the_modulemin_version_str_argscGs\|rt|ds dStdd|jdddD}tdd|dddD}||kS) z 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. __version__Tcs|]}t|VqdSNrHr2xr.r.r4 zmin_version..r,NrMcsrrrrr.r.r4rr)hasattrtuplersplit)rrrZ mod_versionrequiredr.r.r4rs " r version_strcGs,t|dst|ddSt|j|kS)zF Returns True if the module's __version__ matches version_str rz5 has no attribute __version__ in exact_version check.F)rrxryr)r)rrrr.r.r4r s rcs eZdZdZfddZZS)rzo Raised when called function or method requires a more recent PyTorch version than that installed. cs |d|d}t|dS)Nz requires PyTorch version z or later)super__init__)selfZrequired_versionrimessagerr.r4r0sz#InvalidPyTorchVersionError.__init__)r]r __qualname____doc__r __classcell__r.r.rr4r*src@seZdZdZdS)rz< Could not import APIs from an optional dependency. N)r]rrrr.r.r.r4r5srFrversionversion_checkerCallable[..., bool]ri descriptor version_argsallow_namespace_pkgas_typetuple[Any, bool]c s^dd}|rd|d|} nd|} z$t|} t|} |s0t| ddduo+t| d} | r0t|r7t| |} WntyP} z | j| }WYd} ~ nd} ~ ww|r^|| ||r^| dfS|sj|| |rj| dfS|| |rdurd |d |d |jd 7|rd |d7Gfddd}dkr|dfSGfddd|}|dfS)a 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. Args: module: name of the module to be imported. version: version string used by the version_checker. version_checker: a callable to check the module version, Defaults to monai.utils.min_version. name: a non-module attribute (such as method/class) to import from the imported module. descriptor: 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: whether importing a namespace package is allowed. Defaults to False. as_type: there are cases where the optionally imported object is used as a base class, or a decorator, the exceptions should raise accordingly. The current supported values are "default" (call once to raise), "decorator" (call the constructor and the second call to raise), and anything else will return a lazy class that can be used as a base class (call the constructor to raise). 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) 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) >>> 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'). Nr8zfrom z import zimport __file__r\Tz (requires ' z' by 'z')z ()cs:eZdZfddZddZddZddZd d Zd S) z#optional_import.._LazyRaisecs<ddd}durt||_dSt||_dS)Nr,zG For details about installing the optional dependencies, please visit:z^ https://docs.monai.io/en/latest/installation.html#installing-the-recommended-dependencies)r _exceptionre)rr_kwargsZ _default_msgrmtbr.r4rsz,optional_import.._LazyRaise.__init__cS|jza Raises: OptionalImportError: When you call this method. r)rrir.r.r4 __getattr__z/optional_import.._LazyRaise.__getattr__c_rrr)rrrr.r.r4__call__rz,optional_import.._LazyRaise.__call__cSrrr)rr3r.r.r4 __getitem__z/optional_import.._LazyRaise.__getitem__cSrrr)rr.r.r4__iter__rz,optional_import.._LazyRaise.__iter__N)r]rrrrrrrr.rr.r4 _LazyRaises   rr'FcseZdZfddZZS)z!optional_import.._LazyClscstds |jdS)N decorator)rr startswithr)rrrq)rrr.r4rs  z*optional_import.._LazyCls.__init__)r]rrrrr.)rrr4_LazyClssr) __import__r getattrrAssertionErrorrrfformatr])rrrrirrrrZ exception_strZ actual_cmdpkgr is_namespaceZimport_exceptionrrr.)rrmrr4r;sD8    ! rpkg_name raise_errorrcsfdd}|S)a Decorator function to check the required package installation. Args: pkg_name: required package name, like: "itk", "nibabel", etc. version: required version string used by the version_checker. version_checker: a callable to check the module version, defaults to `monai.utils.min_version`. raise_error: if True, raise `OptionalImportError` error if the required package is not installed or the version doesn't match requirement, if False, print the error in a warning. csFt|t}|r |n|jtfdd}|r|S||_|S)NcsFtd\}}|sdd}rt|t||i|S)N)rrrzrequired package `z<` is not installed or the version doesn't match requirement.)rrrxry)argsrq_haserr_msg)call_objrrrrr.r4_wrappers  z1require_pkg.._decorator.._wrapper)r;rrr )objis_funcrrrrr)rr4 _decorators  zrequire_pkg.._decoratorr.)rrrrrr.rr4rsr!NOT INSTALLED or UNKNOWN VERSION.cCs$t|\}}|rt|dr|jS|S)zN Try to load package and get version. If not found, return `default`. r)rrr)Zdep_namer'depZhas_depr.r.r4rs rcCs"tddtjdddDS)zT Returns: tuple of ints represents the pytorch major/minor version. csrrrrr.r.r4rrz*get_torch_version_tuple..r,NrM)rtorchrrr.r.r.r4rs"rlhsrhs/tuple[Iterable[int | str], Iterable[int | str]]cCsRd dd}|ddd }|ddd }t||d }t||d }||fS) z$ Parse the version strings. valr>r* int | strcSsN|}ztd|}|dur|d}t|WS|WSty&|YSw)Nz (\d+)(.*)r)r?r groupsrHr<)rrr.r.r4 _try_casts    z%parse_version_strs.._try_cast+rJrr,N)rr>r*r)rmap)rrrlhs_rhs_r.r.r4parse_version_strss  rcCst|t|}}td\}}|r+ztt||||kWS|jy*YdSwt||\}}t||D] \}}||krWt|t rOt|t rO||kS||kSq7dS)a Returns True if version `lhs` is earlier or equal to `rhs`. Args: lhs: version name to compare with `rhs`, return True if earlier or equal to `rhs`. rhs: version name to compare with `lhs`, return True if later or equal to `lhs`. packaging.versionT r>rrr)VersionInvalidVersionrzipr;rHrrZpkginghas_verrrlrr.r.r4r s   r cCst|t|}}td\}}|r+ztt||||kWS|jy*YdSwt||\}}t||D] \}}||krWt|t rOt|t rO||kS||kSq7dS)a Returns True if version `lhs` is later or equal to `rhs`. Args: lhs: version name to compare with `rhs`, return True if later or equal to `rhs`. rhs: version name to compare with `lhs`, return True if earlier or equal to `lhs`. rTrrr.r.r4r!0s   r!majorminorpatchcurrent_ver_string str | Nonec CszX|durtjdd}|r|ntj}tddd\}}|r0|d|||f||kWS|dd d dd }t|d krN|d g7}t|d ksC|dd \}} } Wnt t t fykt \}} d } Ynwt |t | f} t |t |f} | | kr| | kSd | vpd| v} d }ztd| }|rt |}Wnt t t fyd} Ynwt |}||kr||kS| rdSdS)aJ Compute whether the current pytorch version is after or equal to the specified version. The current system pytorch version is determined by `torch.__version__` or via system environment variable `PYTORCH_VER`. Args: major: major version number to be compared with minor: minor version number to be compared with patch: patch version number to be compared with current_ver_string: if None, `torch.__version__` will be used. Returns: True if the current pytorch version is greater than or equal to the specified version. NZ PYTORCH_VERr8rparserir,rrJrr7rarcz\d+TF)osenvironrErrrrrrNAttributeErrorr< TypeErrorrrHlowerresearchgroup)rrrrZ_env_varverrpartsc_majorc_minorZc_patchc_mnmn is_prereleaseZc_pZp_regr.r.r4r"LsH&     r"cCs |dur2tj}td\}}|sdS|sdS||d}||\}}|d|}|tddd \} } | rL| d||f| |kS| d d d dd } t | d krj| d g7} t | d ks_| dd \} } t | t | f}t |t |f}||kS)a Compute whether the current system GPU CUDA compute capability is after or equal to the specified version. The current system GPU CUDA compute capability is determined by the first GPU in the system. The compared version is a string in the form of "major.minor". Args: major: major version number to be compared with. minor: minor version number to be compared with. Defaults to 0. current_ver_string: if None, the current system GPU CUDA compute capability will be used. Returns: True if the current system GPU CUDA compute capability is greater than or equal to the specified version. NpynvmlTFrr,rrrrrJrMr) rcuda is_availablernvmlInitnvmlDeviceGetHandleByIndexZ"nvmlDeviceGetCudaComputeCapabilityZ nvmlShutdownrrrNrH)rrrZcuda_availablerZ has_pynvmlhandleZmajor_cZminor_crrrrrrrr.r.r4compute_capabilities_afters.       r)r#T) r$rr%r&r'rr(r)r*r)rFr>rGr>r*rH)TrT)rUrrVr)rWr>r*rX)ror>rpr>rqrr*r)r8)rrrr>rrr*r))rrrr>rrr*r))rr>rr>rrrir>rr>rrrr)rr>r*r) rr>rr>rrrr)r*r)r)rr>rr>r*r)rr>rr>r*r))rN) rrHrrHrrHrrr*r))rrHrrHrrr*r)); __future__rr@ functoolsrr~rr_rxcollections.abcrrrrrrr importlibr pkgutilr pydocr r typesrrtypingrrrrrErun_evalrwallow_missing_referenceZOPTIONAL_IMPORT_MSG_FMT__all__rrrnrrrrrrrdrrrr lru_cacherrr r!r"rr.r.r.r4sn      S 9     '    2