o  i@s@dZddlmZddlZddlmZmZmZddlm Z ddl m Z ddl Z ddlZddlmZddlmZdd lmZdd lmZdd lmZdd lmZmZmZmZmZmZdd l m!Z!m"Z"m#Z#m$Z$m%Z%ee&Z'gdZ(        d/d0d%d&Z)Gd'd(d(eeeZ*Gd)d*d*e*Z+Gd+d,d,e*Z,Gd-d.d.e*Z-dS)1z: A collection of generic interfaces for MONAI transforms. ) annotationsN)CallableMappingSequence)deepcopy)Any) get_logger)NdarrayOrTensor)InvertibleTransform)apply_pending_transforms) ThreadUnsafe) LazyTransform MapTransform RandomizableRandomizableTransform Transformapply_transform)MAX_SEED TraceKeysTraceStatusKeys ensure_tupleget_seed)ComposeOneOf RandomOrderSomeOfexecute_composeTFdataKNdarrayOrTensor | Sequence[NdarrayOrTensor] | Mapping[Any, NdarrayOrTensor] transforms Sequence[Any] map_items bool | int unpack_itemsboolstartintend int | Nonelazy bool | None overrides dict | None threading log_stats bool | strreturnc Cs|durt|n|} |durtd|d|dkr"td|d|| kr1td|d| d| t|krCtd| d t|||krI|S|||D]} |r^t| tr\t| n| } t| |||||| d }qOt|d|| d }|S) a ``execute_compose`` provides the implementation that the ``Compose`` class uses to execute a sequence of transforms. As well as being used by Compose, it can be used by subclasses of Compose and by code that doesn't have a Compose instance but needs to execute a sequence of transforms is if it were executed by Compose. It should only be used directly when it is not possible to use ``Compose.__call__`` to achieve the same goal. Args: data: a tensor-like object to be transformed transforms: a sequence of transforms to be carried out map_items: controls whether to apply a transformation to each item in `data`. If `data` is a list or tuple, it can behave as follows: - Defaults to True, which is equivalent to `map_items=1`, meaning the transformation will be applied to the first level of items in `data`. - If an integer is provided, it specifies the maximum level of nesting to which the transformation should be recursively applied. This allows treating multi-sample transforms applied after another multi-sample transform while controlling how deep the mapping goes. unpack_items: whether to unpack input `data` with `*` as parameters for the callable function of transform. defaults to `False`. start: the index of the first transform to be executed. If not set, this defaults to 0 end: the index after the last transform to be executed. If set, the transform at index-1 is the last transform that is executed. If this is not set, it defaults to len(transforms) lazy: whether to enable :ref:`lazy evaluation` for lazy transforms. If False, transforms will be carried out on a transform by transform basis. If True, all lazy transforms will be executed by accumulating changes and resampling as few times as possible. overrides: this optional parameter allows you to specify a dictionary of parameters that should be overridden when executing a pipeline. These each parameter that is compatible with a given transform is then applied to that transform before it is executed. Note that overrides are currently only applied when :ref:`lazy evaluation` is enabled for the pipeline or a given transform. If lazy is False they are ignored. Currently supported args are: {``"mode"``, ``"padding_mode"``, ``"dtype"``, ``"align_corners"``, ``"resample_mode"``, ``device``}. threading: whether executing is happening in a threaded environment. If set, copies are made of transforms that have the ``RandomizedTrait`` interface. log_stats: this optional parameter allows you to specify a logger by name for logging of pipeline execution. Setting this to False disables logging. Setting it to True enables logging to the default loggers. Setting a string overrides the logger name to which logging is performed. Returns: A tensorlike, sequence of tensorlikes or dict of tensorlists containing the result of running `data`` through the sequence of ``transforms``. Nz 'start' (z) cannot be Nonerz) cannot be less than 0z) must be less than 'end' ()z'end' (z5) must be less than or equal to the transform count ()r)r+r.) logger_name)len ValueError isinstancer rrr ) rrr!r#r%r'r)r+r-r.end_ _transformr8Z/home/dell461/cl/sdc2/last_ska_mid/HISourceFinder-master-l/src/monai/transforms/compose.pyr/s&4 rcseZdZdZ      d0d1ddZejjd2ddZd3d4fdd Zd5d6d d!Z d"d#Z d$d%Z d&d'Z d7d8d)d*Z d+d,Zed9d.d/ZZS):ra ``Compose`` provides the ability to chain a series of callables together in a sequential manner. Each transform in the sequence must take a single argument and return a single value. ``Compose`` can be used in two ways: #. With a series of transforms that accept and return a single ndarray / tensor / tensor-like parameter. #. With a series of transforms that accept and return a dictionary that contains one or more parameters. Such transforms must have pass-through semantics that unused values in the dictionary must be copied to the return dictionary. It is required that the dictionary is copied between input and output of each transform. If some transform takes a data item dictionary as input, and returns a sequence of data items in the transform chain, all following transforms will be applied to each item of this list if `map_items` is `True` (the default). If `map_items` is `False`, the returned sequence is passed whole to the next callable in the chain. For example: A `Compose([transformA, transformB, transformC], map_items=True)(data_dict)` could achieve the following patch-based transformation on the `data_dict` input: #. transformA normalizes the intensity of 'img' field in the `data_dict`. #. transformB crops out image patches from the 'img' and 'seg' of `data_dict`, and return a list of three patch samples:: {'img': 3x100x100 data, 'seg': 1x100x100 data, 'shape': (100, 100)} applying transformB ----------> [{'img': 3x20x20 data, 'seg': 1x20x20 data, 'shape': (20, 20)}, {'img': 3x20x20 data, 'seg': 1x20x20 data, 'shape': (20, 20)}, {'img': 3x20x20 data, 'seg': 1x20x20 data, 'shape': (20, 20)},] #. transformC then randomly rotates or flips 'img' and 'seg' of each dictionary item in the list returned by transformB. The composed transforms will be set the same global random seed if user called `set_determinism()`. When using the pass-through dictionary operation, you can make use of :class:`monai.transforms.adaptors.adaptor` to wrap transforms that don't conform to the requirements. This approach allows you to use transforms from otherwise incompatible libraries with minimal additional work. Note: In many cases, Compose is not the best way to create pre-processing pipelines. Pre-processing is often not a strictly sequential series of operations, and much of the complexity arises when a not-sequential set of functions must be called as if it were a sequence. Example: images and labels Images typically require some kind of normalization that labels do not. Both are then typically augmented through the use of random rotations, flips, and deformations. Compose can be used with a series of transforms that take a dictionary that contains 'image' and 'label' entries. This might require wrapping `torchvision` transforms before passing them to compose. Alternatively, one can create a class with a `__call__` function that calls your pre-processing functions taking into account that not all of them are called on the labels. Lazy resampling: Lazy resampling is an experimental feature introduced in 1.2. Its purpose is to reduce the number of resample operations that must be carried out when executing a pipeline of transforms. This can provide significant performance improvements in terms of pipeline executing speed and memory usage, and can also significantly reduce the loss of information that occurs when performing a number of spatial resamples in succession. Lazy resampling can be enabled or disabled through the ``lazy`` parameter, either by specifying it at initialisation time or overriding it at call time. * False (default): Don't perform any lazy resampling * None: Perform lazy resampling based on the 'lazy' properties of the transform instances. * True: Always perform lazy resampling if possible. This will ignore the ``lazy`` properties of the transform instances Please see the :ref:`Lazy Resampling topic` for more details of this feature and examples of its use. Args: transforms: sequence of callables. map_items: controls whether to apply a transformation to each item in `data`. If `data` is a list or tuple, it can behave as follows: - Defaults to True, which is equivalent to `map_items=1`, meaning the transformation will be applied to the first level of items in `data`. - If an integer is provided, it specifies the maximum level of nesting to which the transformation should be recursively applied. This allows treating multi-sample transforms applied after another multi-sample transform while controlling how deep the mapping goes. unpack_items: whether to unpack input `data` with `*` as parameters for the callable function of transform. defaults to `False`. log_stats: this optional parameter allows you to specify a logger by name for logging of pipeline execution. Setting this to False disables logging. Setting it to True enables logging to the default loggers. Setting a string overrides the logger name to which logging is performed. lazy: whether to enable :ref:`Lazy Resampling` for lazy transforms. If False, transforms will be carried out on a transform by transform basis. If True, all lazy transforms will be executed by accumulating changes and resampling as few times as possible. If lazy is None, `Compose` will perform lazy execution on lazy transforms that have their `lazy` property set to True. overrides: this optional parameter allows you to specify a dictionary of parameters that should be overridden when executing a pipeline. These each parameter that is compatible with a given transform is then applied to that transform before it is executed. Note that overrides are currently only applied when :ref:`Lazy Resampling` is enabled for the pipeline or a given transform. If lazy is False they are ignored. Currently supported args are: {``"mode"``, ``"padding_mode"``, ``"dtype"``, ``"align_corners"``, ``"resample_mode"``, ``device``}. NTFr$Sequence[Callable] | Callable | Noner!r"r#r$r.r/r)r*r+r,r0NonecCsptj||d|dur g}t|ttfstdt|dt||_||_ ||_ ||_ |j t d||_dS)N)r)z3Argument 'map_items' should be boolean or int. Got z5.Check brackets when passing a sequence of callables.seed)r __init__r5r$r&r4typerrr!r#r.set_random_staterr+selfrr!r#r.r)r+r8r8r9r>s   zCompose.__init__valcCs ||_dSN)_lazy)rBrCr8r8r9r) s z Compose.lazyr=r(statenp.random.RandomState | NonecsHtj||d|jD]}t|tsq |jt|jjtdddq |S)N)r=rFuint32)dtyper<) superr@rr5rr&Rrandintr)rBr=rFr7 __class__r8r9r@ s   zCompose.set_random_stater Any | Nonec Csx|jD]6}t|ts qz||Wqty9}zt|j}td|d|d|dt WYd}~qd}~wwdS)Nz Transform 'z' in Compose not randomized .) rr5r randomize TypeErrorr?__name__warningswarnRuntimeWarning)rBrr7Z type_errorZtfm_namer8r8r9rQs   zCompose.randomizecCs.tt|jD] }||j|r|SqdS)a get_index_of_first takes a ``predicate`` and returns the index of the first transform that satisfies the predicate (ie. makes the predicate return True). If it is unable to find a transform that satisfies the ``predicate``, it returns None. Example: c = Compose([Flip(...), Rotate90(...), Zoom(...), RandRotate(...), Resize(...)]) print(c.get_index_of_first(lambda t: isinstance(t, RandomTrait))) >>> 3 print(c.get_index_of_first(lambda t: isinstance(t, Compose))) >>> None Note: This is only performed on the transforms directly held by this instance. If this instance has nested ``Compose`` transforms or other transforms that contain transforms, it does not iterate into them. Args: predicate: a callable that takes a single argument and returns a bool. When called it is passed a transform from the sequence of transforms contained by this compose instance. Returns: The index of the first transform in the sequence for which ``predicate`` returns True. None if no transform satisfies the ``predicate`` N)ranger3r)rB predicateir8r8r9get_index_of_first!s zCompose.get_index_of_firstcCs>g}|jD]}t|tur||j7}q||qt|S)aReturn a Composition with a simple list of transforms, as opposed to any nested Compositions. e.g., `t1 = Compose([x, x, x, x, Compose([Compose([x, x]), x, x])]).flatten()` will result in the equivalent of `t1 = Compose([x, x, x, x, x, x, x, x])`. )rr?rflattenappend)rBZnew_transformstr8r8r9r[Ds    zCompose.flattencCst|jS)z!Return number of transformations.)r3r[rrBr8r8r9__len__TszCompose.__len__rc Cs<|dur|jn|}t||j|||j|j||j||jd }|S)N) rr%r'r!r#r)r+r-r.)rErrr!r#r+r.)rBinput_r%r'r-r)rEresultr8r8r9__call__Xs zCompose.__call__c Csx||dd|jD}|std|jdur%td|jdt|D]}t|j||j |j d|j d}q)|S) NcSsg|] }t|tr|qSr8)r5r ).0r]r8r8r9 lsz#Compose.inverse..zGinverse has been called but no invertible transforms have been suppliedTz'lazy' is set to zp but lazy execution is not supported when inverting. 'lazy' has been overridden to False for the call to inverseF)r)r.) _raise_if_not_invertibler[rrTrUrEreversedrinverser!r#r.)rBrZinvertible_transformsr]r8r8r9rgis     zCompose.inversercCsRddlm}||tjd\}}|dur'|dur#d|}td|tddS)Nr)has_status_keysz.Pending operations while applying an operationF z;Unable to run inverse on 'data' for the following reasons: z?Unable to run inverse on 'data'; no reason logged in trace data)Zmonai.transforms.utilsrhrPENDING_DURING_APPLYjoin RuntimeError)rrhZ invertibleZreasonsZ reason_textr8r8r9re|s  z Compose._raise_if_not_invertibleNTFFFN)rr:r!r"r#r$r.r/r)r*r+r,r0r;)rCr$)NN)r=r(rFrGr0rrD)rrOr0r;rNFNr)r*)rr)rS __module__ __qualname____doc__r>r r)setterr@rQrZr[r_rbrg staticmethodre __classcell__r8r8rMr9r{s(t    # rcsVeZdZdZ       d d!fdd ZddZddZd"d#ddZddZZ S)$ra ``OneOf`` provides the ability to randomly choose one transform out of a list of callables with pre-defined probabilities for each. Args: transforms: sequence of callables. weights: probabilities corresponding to each callable in transforms. Probabilities are normalized to sum to one. map_items: controls whether to apply a transformation to each item in `data`. If `data` is a list or tuple, it can behave as follows: - Defaults to True, which is equivalent to `map_items=1`, meaning the transformation will be applied to the first level of items in `data`. - If an integer is provided, it specifies the maximum level of nesting to which the transformation should be recursively applied. This allows treating multi-sample transforms applied after another multi-sample transform while controlling how deep the mapping goes. unpack_items: whether to unpack input `data` with `*` as parameters for the callable function of transform. defaults to `False`. log_stats: this optional parameter allows you to specify a logger by name for logging of pipeline execution. Setting this to False disables logging. Setting it to True enables logging to the default loggers. Setting a string overrides the logger name to which logging is performed. lazy: whether to enable :ref:`Lazy Resampling` for lazy transforms. If False, transforms will be carried out on a transform by transform basis. If True, all lazy transforms will be executed by accumulating changes and resampling as few times as possible. If lazy is None, `Compose` will perform lazy execution on lazy transforms that have their `lazy` property set to True. overrides: this optional parameter allows you to specify a dictionary of parameters that should be overridden when executing a pipeline. These each parameter that is compatible with a given transform is then applied to that transform before it is executed. Note that overrides are currently only applied when :ref:`Lazy Resampling` is enabled for the pipeline or a given transform. If lazy is False they are ignored. Currently supported args are: {``"mode"``, ``"padding_mode"``, ``"dtype"``, ``"align_corners"``, ``"resample_mode"``, ``device``}. NTFrr:weightsSequence[float] | float | Noner!r"r#r$r.r/r)r*r+r,r0r;cst||||||t|jdkrg}n|dust|tr+dt|jgt|j}t|t|jkrDtdt|dt|jdt|||_ ||_ dS)Nrg?zOtransforms and weights should be same size if both specified as sequences, got z and rP) rJr>r3rr5floatr4r_normalize_probabilitiesrvr.)rBrrvr!r#r.r)r+rMr8r9r>s  zOneOf.__init__cCsjt|dkr|St|}t|dkrtd|dt|dkr+td|d||}t|S)Nr9Probabilities must be greater than or equal to zero, got rP8At least one probability must be greater than zero, got )r3nparrayanyr4allsumlist)rBrvr8r8r9rys   zOneOf._normalize_probabilitiescCsg}g}t|j|jD]0\}}t|tr1|}t|j|jD]\}}|||||qq ||||q t|||j|jSrD) ziprrvr5rr[r\r!r#)rBrrvr]wtrt_w_r8r8r9r[s    z OneOf.flattenrc Cs|dkr td|d|durtd|t|jdkr |S|jd|j}|j|}|dur6|jn|}t||g|||j |j ||j ||j d }t |tjjr]|j|d|id|St |tr{|D]} t || tjjrz|j|| d|idqd|S) Nrz7OneOf requires 'start' parameter to be 0 (start set to r1z6OneOf requires 'end' parameter to be None (end set to r%r'r!r#r)r+r-r.index extra_info)r4r3rrK multinomialrvargmaxrErr!r#r+r.r5monair MetaTensorpush_transformr) rBrr%r'r-r)rr7rEkeyr8r8r9rbs<  zOneOf.__call__cCst|jdkr |Sd}t|tjjr||tjd}n)t|t r<|D]}t||tjjr:|||tjd}q$n t dt |d|durL|S|j|}t|t r[| |S|S)NrrOInverse only implemented for Mapping (dictionary) or MetaTensor data, got type rP)r3rr5rrr pop_transformr EXTRA_INFOrrlr?r rg)rBrrrr7r8r8r9rgs$  z OneOf.inverse)NNTFFFN)rr:rvrwr!r"r#r$r.r/r)r*r+r,r0r;rnro) rSrprqrrr>ryr[rbrgrur8r8rMr9rs# #rcsDeZdZdZ      ddfdd ZddddZddZZS)ra  ``RandomOrder`` provides the ability to apply a list of transformations in random order. Args: transforms: sequence of callables. map_items: whether to apply transform to each item in the input `data` if `data` is a list or tuple. defaults to `True`. unpack_items: whether to unpack input `data` with `*` as parameters for the callable function of transform. defaults to `False`. log_stats: this optional parameter allows you to specify a logger by name for logging of pipeline execution. Setting this to False disables logging. Setting it to True enables logging to the default loggers. Setting a string overrides the logger name to which logging is performed. lazy: whether to enable :ref:`Lazy Resampling` for lazy transforms. If False, transforms will be carried out on a transform by transform basis. If True, all lazy transforms will be executed by accumulating changes and resampling as few times as possible. If lazy is None, `Compose` will perform lazy execution on lazy transforms that have their `lazy` property set to True. overrides: this optional parameter allows you to specify a dictionary of parameters that should be overridden when executing a pipeline. These each parameter that is compatible with a given transform is then applied to that transform before it is executed. Note that overrides are currently only applied when :ref:`Lazy Resampling` is enabled for the pipeline or a given transform. If lazy is False they are ignored. Currently supported args are: {``"mode"``, ``"padding_mode"``, ``"dtype"``, ``"align_corners"``, ``"resample_mode"``, ``device``}. NTFrr:r!r$r#r.r/r)r*r+r,r0r;cs t||||||||_dSrD)rJr>r.rArMr8r9r>4s zRandomOrder.__init__rc s|dkr td|d|durtd|tjdkr |Stj}jt|}|dur4jn|}t|fdd|D||jj ||j d }t |t j jr_j|d|id |St |tr}|D]} t || t j jr|j|| d|id qf|S) Nrz=RandomOrder requires 'start' parameter to be 0 (start set to r1z.)r%r'r!r#r)r-r. applied_orderr)r4r3rrK permutationrWrErr!r#r.r5rrrrr) rBr`r%r'r-r)numrrErr8r^r9rb@s:   zRandomOrder.__call__cCst|jdkr |Sd}t|tjjr||tjd}n)t|t r<|D]}t||tjjr:|||tjd}q$n t dt |d|durL|St |D]}t|j|t rjt|j|j||j|j|jd}qP|SNrrrrP)r.)r3rr5rrrrrrrrlr?rfr rrgr!r#r.rBrrror8r8r9rgbs.  zRandomOrder.inverserm)rr:r!r$r#r$r.r/r)r*r+r,r0r;rnro)rSrprqrrr>rbrgrur8r8rMr9rs "rcs\eZdZdZ         d#d$fdd Zd%ddZddZd&d'dd Zd!d"ZZ S)(raH ``SomeOf`` samples a different sequence of transforms to apply each time it is called. It can be configured to sample a fixed or varying number of transforms each time its called. Samples are drawn uniformly, or from user supplied transform weights. When varying the number of transforms sampled per call, the number of transforms to sample that call is sampled uniformly from a range supplied by the user. Args: transforms: list of callables. map_items: whether to apply transform to each item in the input `data` if `data` is a list or tuple. Defaults to `True`. unpack_items: whether to unpack input `data` with `*` as parameters for the callable function of transform. Defaults to `False`. log_stats: this optional parameter allows you to specify a logger by name for logging of pipeline execution. Setting this to False disables logging. Setting it to True enables logging to the default loggers. Setting a string overrides the logger name to which logging is performed. num_transforms: a 2-tuple, int, or None. The 2-tuple specifies the minimum and maximum (inclusive) number of transforms to sample at each iteration. If an int is given, the lower and upper bounds are set equal. None sets it to `len(transforms)`. Default to `None`. replace: whether to sample with replacement. Defaults to `False`. weights: weights to use in for sampling transforms. Will be normalized to 1. Default: None (uniform). lazy: whether to enable :ref:`Lazy Resampling` for lazy transforms. If False, transforms will be carried out on a transform by transform basis. If True, all lazy transforms will be executed by accumulating changes and resampling as few times as possible. If lazy is None, `Compose` will perform lazy execution on lazy transforms that have their `lazy` property set to True. overrides: this optional parameter allows you to specify a dictionary of parameters that should be overridden when executing a pipeline. These each parameter that is compatible with a given transform is then applied to that transform before it is executed. Note that overrides are currently only applied when :ref:`Lazy Resampling` is enabled for the pipeline or a given transform. If lazy is False they are ignored. Currently supported args are: {``"mode"``, ``"padding_mode"``, ``"dtype"``, ``"align_corners"``, ``"resample_mode"``, ``device``}. NTFrr:r!r$r#r.r/num_transformsint | tuple[int, int] | Nonereplacervlist[int] | Noner)r*r+r,r0r;c sFtj|||||| d||\|_|_||_|||_||_dS)N)r.r)r+) rJr>_ensure_valid_num_transformsmin_num_transformsmax_num_transformsrryrvr.) rBrr!r#r.rrrvr)r+rMr8r9r>s    zSomeOf.__init__tuplecCs,t|tst|tst|ts|durtdt||dur+t|jt|jg}nJt|tr=tt|j|}||g}n8t|dkrLtdt|t|dtrZt|dtsmtdt|ddt|dd|d|dg}|ddks|dt|jkrtd |d t|jd t |S) NzIExpected num_transforms to be of type int, list, tuple or None, but it's z+Expected len(num_transforms)=2, but it was rrz"Expected (int,int), but received (z, r1znum_transforms=z are out of the bounds [0, z].) r5rrr&r4r?r3rminr)rBrranr8r8r9rs2     z#SomeOf._ensure_valid_num_transformscCs|dus t|jdkr dSt|}t|}|t|jkr+tdt|jd|dt|dkr:td|dt|dkrItd|d||}tt |S)NrzExpected len(weights)=z, got: rPrzr{) r3rr|r}r4r~rrrr)rBrvZ n_weightsr8r8r9rys   zSomeOf._normalize_probabilitiesrc s,|dkr td|d|durtd|tjdkr |Sjjjd}jjtj|jj d }|durCj n|}t |fdd|D||j j|j|jd }t|tjjrpj|d |id |St|tr|D]} t|| tjjs| |vrj|| d |id qw|S) Nrz8SomeOf requires 'start' parameter to be 0 (start set to r1z7SomeOf requires 'end' parameter to be None (end set to r)rpcrr8r)rcar^r8r9rdrz#SomeOf.__call__..rrr)r4r3rrKrLrrchoicerrvtolistrErr!r#r+r.r5rrrrr trace_key) rBrr%r'r-r) sample_sizerrErr8r^r9rbs<"   zSomeOf.__call__cCst|jdkr |Sd}t|tjjr||tjd}n0t|t rC|D]}t||tjjs6| ||vrA|||tjd}q$n t dt |d|durS|St |D]}t|j|trqt|j|j||j|j|jd}qW|Sr)r3rr5rrrrrrrrrlr?rfr rrgr!r#r.rr8r8r9rg s.   zSomeOf.inverse) NTFFNFNFN)rr:r!r$r#r$r.r/rrrr$rvrr)r*r+r,r0r;)rrr0rrnro) rSrprqrrr>rryrbrgrur8r8rMr9r~s #  #r)TFrNFNFF)rrrr r!r"r#r$r%r&r'r(r)r*r+r,r-r$r.r/r0r).rr __future__rrTcollections.abcrrrcopyrtypingrnumpyr|rmonai.apps.utilsrZ monai.configr Zmonai.transforms.inverser Z monai.transforms.lazy.functionalr Zmonai.transforms.traitsr Zmonai.transforms.transformr rrrrr monai.utilsrrrrrrSlogger__all__rrrrrr8r8r8r9sB          Lc