U Ph @sNdZddlmZddlZddlmZmZmZddlm Z ddl m Z ddl Z ddlZddlmZddlmZdd lmZdd lmZdd lmZdd lmZmZmZmZmZmZdd l m!Z!m"Z"m#Z#m$Z$m%Z%ee&Z'dddddgZ(d#dddddddddddd ddZ)GdddeeeZ*Gd dde*Z+Gd!dde*Z,Gd"dde*Z-dS)$z: 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_seedComposeOneOf RandomOrderSomeOfexecute_composeTFzKNdarrayOrTensor | Sequence[NdarrayOrTensor] | Mapping[Any, NdarrayOrTensor]z Sequence[Any]boolint int | None bool | None dict | None bool | str) data transforms map_items unpack_itemsstartendlazy overrides threading log_statsreturnc Cs|dkrt|n|} |dkr,td|d|dkrDtd|d|| krbtd|d| d| t|krtd| d t|||kr|S|||D]4} |rt| trt| n| } t| |||||| d }qt|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: 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`. 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 ) r#r$r%r&r'r(r)r*r+r,end_ _transformr5M/home/dell461/cl/sdc2/HISourceFinder-master-l/src/monai/transforms/compose.pyr/s2/ c seZdZdZd*dddddd d d d d ZejjddddZd+ddddfdd Zd,dd dddZ ddZ ddZ ddZ d-dd!d"d#Z d$d%Zed&d'd(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: 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``}. NTF$Sequence[Callable] | Callable | Nonerr"r r!Noner$r%r&r,r)r*r-cCsltj||d|dkrg}t|ts8tdt|dt||_||_||_ ||_ |j t d||_ dS)Nr)z,Argument 'map_items' should be boolean. Got z5.Check brackets when passing a sequence of callables.seed)r __init__r2rr1typerr$r%r&r,set_random_staterr*selfr$r%r&r,r)r*r5r5r6r=s   zCompose.__init__)valcCs ||_dSN)_lazy)rArBr5r5r6r)sz Compose.lazyrznp.random.RandomState | None)r<stater-csDtj||d|jD](}t|ts&q|j|jjtdddq|S)N)r<rEuint32)dtyper;)superr?r$r2rRrandintr)rAr<rEr4 __class__r5r6r?s   zCompose.set_random_statez Any | None)r#r-c Csx|jD]l}t|tsqz||Wqtk rp}z.t|j}td|d|d|dt W5d}~XYqXqdS)Nz Transform 'z' in Compose not randomized .) r$r2r randomize TypeErrorr>__name__warningswarnRuntimeWarning)rAr#r4Z type_errorZtfm_namer5r5r6rN s   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)ranger0r$)rA predicateir5r5r6get_index_of_firsts zCompose.get_index_of_firstcCs>g}|jD]*}t|tkr*||j7}q ||q t|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])`. )r$r>rflattenappend)rAZnew_transformstr5r5r6rX9s    zCompose.flattencCst|jS)z!Return number of transformations.)r0rXr$rAr5r5r6__len__IszCompose.__len__rr:c Cs<|dkr|jn|}t||j|||j|j||j||jd }|S)N) r$r'r(r%r&r)r*r+r,)rDrr$r%r&r*r,)rAinput_r'r(r+r)rDresultr5r5r6__call__Ms zCompose.__call__c Csx||dd|jD}|s,td|jdkrJtd|jdt|D] }t|j||j |j d|j d}qR|S) NcSsg|]}t|tr|qSr5)r2r ).0rZr5r5r6 as z#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_invertiblerXr$rQrRrDreversedrinverser%r&r,)rAr#Zinvertible_transformsrZr5r5r6rd^s$     zCompose.inverser)r#cCsTddlm}||tjd\}}|dkrP|dk rHd|}td|ntddS)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.utilsrerPENDING_DURING_APPLYjoin RuntimeError)r#re invertibleZreasonsZ reason_textr5r5r6rbqs  z Compose._raise_if_not_invertible)NTFFFN)NN)N)rNFN)rP __module__ __qualname____doc__r=r r)setterr?rNrWrXr\r_rd staticmethodrb __classcell__r5r5rKr6rvs&n #c s^eZdZdZddddddd d d d fd d ZddZddZdd dddZddZZ 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: 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``}. NTFr7zSequence[float] | float | Nonerr"r r!r8)r$weightsr%r&r,r)r*r-cst||||||t|jdkr*g}n,|dksq||||qt|||j|jSrC) zipr$rqr2rrXrYr%r&)rAr$rqrZwtrt_w_r5r5r6rXs    z OneOf.flattenrr:c Cs|dkrtd|d|dk r.td|t|jdkr@|S|jd|j}|j|}|dkrl|jn|}t||g|||j |j ||j ||j d }t |tjjr|j|d|idnr rd)rAr#rrr4r5r5r6rds   z OneOf.inverse)NNTFFFN)rNFN) rPrkrlrmr=rsrXr_rdrpr5r5rKr6rs" #c sLeZdZdZddddddd d d fd d ZdddddZddZZS)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``}. NTFr7rr"r r!r8r9cs t||||||||_dSrC)rHr=r,r@rKr5r6r=#s zRandomOrder.__init__rr:c s|dkrtd|d|dk r.td|tjdkr@|Stj}jt|}|dkrhjn|}t|fdd|D||jj ||j d }t |t j jrj|d|id nsz(RandomOrder.__call__..)r'r(r%r&r)r+r, applied_orderr)r1r0r$rI permutationrTrDrr%r&r,r2rr#rrr) rAr]r'r(r+r)numrrDrr5r[r6r_/s6   zRandomOrder.__call__cCst|jdkr|Sd}t|tjjr:||tjd}nRt|t rx|D],}t||tjjrH|||tjd}qHnt dt |d|dkr|St |D]4}t|j|t rt|j|j||j|j|jd}q|SNrrrrM)r,)r0r$r2rr#rrrrrrir>rcr rrdr%r&r,rAr#rror5r5r6rdQs0   zRandomOrder.inverse)NTFFFN)rNFN)rPrkrlrmr=r_rdrpr5r5rKr6r s "c sjeZdZdZdddddddd d d d d fdd ZdddddZddZdd dddZddZZ 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``}. NTFr7rr"zint | tuple[int, int] | Nonezlist[int] | Noner r!r8) r$r%r&r,num_transformsreplacerqr)r*r-c sFtj|||||| d||\|_|_||_|||_||_dS)N)r,r)r*) rHr=_ensure_valid_num_transformsmin_num_transformsmax_num_transformsrrsrqr,) rAr$r%r&r,rrrqr)r*rKr5r6r=s  zSomeOf.__init__tuple)rr-cCs0t|ts8t|ts8t|ts8|dk r8tdt||dkrVt|jt|jg}nt|trztt|j|}||g}npt|dkrtdt|t|dtrt|dtstdt|ddt|dd|d|dg}|ddks |dt|jkr(td |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, r.znum_transforms=z are out of the bounds [0, z].) r2rr{rr1r>r0r$minr)rArr^nr5r5r6rs4     "z#SomeOf._ensure_valid_num_transformscCs|dkst|jdkrdSt|}t|}|t|jkrVtdt|jd|dt|dkrttd|dt|dkrtd|d||}tt |S)NrzExpected len(weights)=z, got: rMrtru) r0r$rvrwr1rxryrzrr{)rArqZ n_weightsr5r5r6rss  zSomeOf._normalize_probabilitiesrr:c s.|dkrtd|d|dk r.td|tjdkr@|Sjjjd}jjtj|jj d }|dkrj n|}t |fdd|D||j j|j|jd }t|tjjrވj|d |id nLt|tr*|D]:} t|| tjjs| |krj|| d |id q|S) Nrz8SomeOf requires 'start' parameter to be 0 (start set to r.z7SomeOf requires 'end' parameter to be None (end set to r)rpcsg|]}j|qSr5r)r`ar[r5r6rasz#SomeOf.__call__..rrr)r1r0r$rIrJrrchoicerrqtolistrDrr%r&r*r,r2rr#rrr trace_key) rAr#r'r(r+r) sample_sizerrDrr5r[r6r_s8"  "zSomeOf.__call__cCst|jdkr|Sd}t|tjjr:||tjd}n`t|t r|D]:}t||tjjsl| ||krH|||tjd}qHnt dt |d|dkr|St |D]4}t|j|trt|j|j||j|j|jd}q|Sr)r0r$r2rr#rrrrrrrir>rcr rrdr%r&r,rr5r5r6rds0    zSomeOf.inverse) NTFFNFNFN)rNFN) rPrkrlrmr=rrsr_rdrpr5r5rKr6rms#& #)TFrNFNFF).rm __future__rrQcollections.abcrrrcopyrtypingrnumpyrvrmonai.apps.utilsr monai.configr Zmonai.transforms.inverser Z monai.transforms.lazy.functionalr Zmonai.transforms.traitsr Zmonai.transforms.transformr rrrrr monai.utilsrrrrrrPlogger__all__rrrrrr5r5r5r6 s@         $G  c