U
    Ph                     @  sN  d Z ddlmZ ddlZddlmZmZmZ ddlm	Z	 ddl
mZ ddlZddlZddlmZ ddlmZ dd	lmZ dd
lmZ ddlmZ ddlmZmZmZmZmZmZ ddl m!Z!m"Z"m#Z#m$Z$m%Z% ee&Z'dddddgZ(d#ddddddddddddddZ)G dd deeeZ*G d d de*Z+G d!d de*Z,G d"d de*Z-dS )$z:
A collection of generic interfaces for MONAI transforms.
    )annotationsN)CallableMappingSequence)deepcopy)Any)
get_logger)NdarrayOrTensor)InvertibleTransform)apply_pending_transforms)ThreadUnsafe)LazyTransformMapTransformRandomizableRandomizableTransform	Transformapply_transform)MAX_SEED	TraceKeysTraceStatusKeysensure_tupleget_seedComposeOneOfRandomOrderSomeOfexecute_composeTFzKNdarrayOrTensor | Sequence[NdarrayOrTensor] | Mapping[Any, NdarrayOrTensor]zSequence[Any]boolint
int | Nonebool | Nonedict | None
bool | str)data
transforms	map_itemsunpack_itemsstartendlazy	overrides	threading	log_statsreturnc
              
   C  s   |dkrt |n|}
|dkr,td| d|dk rDtd| d||
krbtd| d|
 d|
t |krtd|
 d	t | ||kr| S ||| D ]4}|rt|trt|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<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.
        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<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``}.
        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 Noner   z) 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   r   r   r   )r#   r$   r%   r&   r'   r(   r)   r*   r+   r,   end_
_transform r5   M/home/dell461/cl/sdc2/HISourceFinder-master-l/src/monai/transforms/compose.pyr   /   s2    /      c                	      s   e Zd ZdZd*dddddd	d
dddZejjddddZd+ddd d fddZd,dd
dddZ	dd Z
dd Zdd Zd-dd!d"d#Zd$d% Zed&d'd(d)Z  ZS ).r   a   
    ``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<lazy_resampling>` 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<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<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 | Noner   r"   r    r!   Noner$   r%   r&   r,   r)   r*   r-   c                 C  sl   t j| |d |d krg }t|ts8tdt| dt|| _|| _|| _	|| _
| jt d || _d S )Nr)   z,Argument 'map_items' should be boolean. Got z5.Check brackets when passing a sequence of callables.seed)r   __init__r2   r   r1   typer   r$   r%   r&   r,   set_random_stater   r*   selfr$   r%   r&   r,   r)   r*   r5   r5   r6   r=      s    	

zCompose.__init__)valc                 C  s
   || _ d S N)_lazy)rA   rB   r5   r5   r6   r)      s    zCompose.lazyr   znp.random.RandomState | None)r<   stater-   c                   sD   t  j||d | jD ](}t|ts&q|j| jjtddd q| S )N)r<   rE   uint32)dtyper;   )superr?   r$   r2   r   Rrandintr   )rA   r<   rE   r4   	__class__r5   r6   r?     s    

zCompose.set_random_statez
Any | None)r#   r-   c                 C  sx   | j D ]l}t|tsqz|| W q tk
rp } z.t|j}td| d| d| dt	 W 5 d }~X Y qX qd S )NzTransform 'z' in Compose not randomized
.)
r$   r2   r   	randomize	TypeErrorr>   __name__warningswarnRuntimeWarning)rA   r#   r4   Z
type_errorZtfm_namer5   r5   r6   rN   
  s    


 zCompose.randomizec                 C  s.   t t| jD ]}|| j| r|  S qdS )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)ranger0   r$   )rA   	predicateir5   r5   r6   get_index_of_first  s    
zCompose.get_index_of_firstc                 C  s>   g }| j D ]*}t|tkr*|| j 7 }q
|| q
t|S )a  Return 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>   r   flattenappend)rA   Znew_transformstr5   r5   r6   rX   9  s    
zCompose.flattenc                 C  s   t |  jS )z!Return number of transformations.)r0   rX   r$   rA   r5   r5   r6   __len__I  s    zCompose.__len__r   r:   c                 C  s<   |d kr| j n|}t|| j||| j| j|| j|| jd
}|S )N)	r$   r'   r(   r%   r&   r)   r*   r+   r,   )rD   r   r$   r%   r&   r*   r,   )rA   input_r'   r(   r+   r)   rD   resultr5   r5   r6   __call__M  s    zCompose.__call__c              	   C  sx   |  | dd |  jD }|s,td | jdkrJtd| j d t|D ] }t|j|| j	| j
d| jd}qR|S )	Nc                 S  s   g | ]}t |tr|qS r5   )r2   r
   ).0rZ   r5   r5   r6   
<listcomp>a  s     
 z#Compose.inverse.<locals>.<listcomp>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_invertiblerX   r$   rQ   rR   rD   reversedr   inverser%   r&   r,   )rA   r#   Zinvertible_transformsrZ   r5   r5   r6   rd   ^  s$    


     zCompose.inverser   )r#   c                 C  sT   ddl m} || tjd\}}|dkrP|d k	rHd|}td| ntdd S )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)Zmonai.transforms.utilsre   r   PENDING_DURING_APPLYjoinRuntimeError)r#   re   
invertibleZreasonsZreason_textr5   r5   r6   rb   q  s      
z Compose._raise_if_not_invertible)NTFFFN)NN)N)r   NFN)rP   
__module____qualname____doc__r=   r   r)   setterr?   rN   rW   rX   r\   r_   rd   staticmethodrb   __classcell__r5   r5   rK   r6   r   v   s&   n      #c                
      s^   e Zd ZdZddddddd	d
dd fddZdd Zdd Zdd	dddZdd Z  Z	S )r   a  
    ``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<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<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``}.
    NTFr7   zSequence[float] | float | Noner   r"   r    r!   r8   )r$   weightsr%   r&   r,   r)   r*   r-   c                   s   t  |||||| t| jdkr*g }n,|d ks<t|trVdt| j gt| j }t|t| jkrtdt| dt| j dt| || _	|| _
d S )Nr   g      ?zOtransforms and weights should be same size if both specified as sequences, got z and rM   )rH   r=   r0   r$   r2   floatr1   r   _normalize_probabilitiesrq   r,   )rA   r$   rq   r%   r&   r,   r)   r*   rK   r5   r6   r=     s    
zOneOf.__init__c                 C  sj   t |dkr|S t|}t|dk r8td| dt|dkrVtd| d||  }t|S )Nr   9Probabilities must be greater than or equal to zero, got rM   8At least one probability must be greater than zero, got )r0   nparrayanyr1   allsumlist)rA   rq   r5   r5   r6   rs     s    
zOneOf._normalize_probabilitiesc                 C  s   g }g }t | j| jD ]`\}}t|trb| }t |j|jD ] \}}|| |||  q>q|| || qt||| j| jS rC   )	zipr$   rq   r2   r   rX   rY   r%   r&   )rA   r$   rq   rZ   wtrt_w_r5   r5   r6   rX     s    


zOneOf.flattenr   r:   c           
      C  s   |dkrt d| d|d k	r.t d| t| jdkr@|S | jd| j }| j| }|d krl| jn|}t||g||| j	| j
|| j|| jd
}t|tjjr| j|d|id n<t|tr|D ],}	t||	 tjjr| j||	 d|id q|S )	Nr   z7OneOf requires 'start' parameter to be 0 (start set to r.   z6OneOf requires 'end' parameter to be None (end set to    r'   r(   r%   r&   r)   r*   r+   r,   index
extra_info)r1   r0   r$   rI   multinomialrq   argmaxrD   r   r%   r&   r*   r,   r2   monair#   
MetaTensorpush_transformr   )
rA   r#   r'   r(   r+   r)   r   r4   rD   keyr5   r5   r6   r_     s8    

zOneOf.__call__c                 C  s   t | jdkr|S d }t|tjjr:| |tj d }nRt|t	rx|D ],}t|| tjjrH| ||tj d }qHnt
dt| d|d kr|S | j| }t|tr||S |S )Nr   r   OInverse only implemented for Mapping (dictionary) or MetaTensor data, got type rM   )r0   r$   r2   r   r#   r   pop_transformr   
EXTRA_INFOr   ri   r>   r
   rd   )rA   r#   r   r   r4   r5   r5   r6   rd     s     

zOneOf.inverse)NNTFFFN)r   NFN)
rP   rk   rl   rm   r=   rs   rX   r_   rd   rp   r5   r5   rK   r6   r     s          "#c                	      sL   e Zd ZdZddddddd	d
d fddZdddddZdd Z  ZS )r   a   
    ``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<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<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``}.
    NTFr7   r   r"   r    r!   r8   r9   c                   s    t  |||||| || _d S rC   )rH   r=   r,   r@   rK   r5   r6   r=   #  s    	zRandomOrder.__init__r   r:   c           
        s   |dkrt d| d|d k	r.t d| t jdkr@|S t j} jt|}|d krh jn|}t| fdd|D || j j	|| j
d	}t|tjjr j|d|id	 n<t|tr|D ],}	t||	 tjjrʈ j||	 d|id	 q|S )
Nr   z=RandomOrder requires 'start' parameter to be 0 (start set to r.   z<RandomOrder requires 'end' parameter to be None (end set to c                   s   g | ]} j | qS r5   r$   )r`   indr[   r5   r6   ra   >  s     z(RandomOrder.__call__.<locals>.<listcomp>)r'   r(   r%   r&   r)   r+   r,   applied_orderr   )r1   r0   r$   rI   permutationrT   rD   r   r%   r&   r,   r2   r   r#   r   r   r   )
rA   r]   r'   r(   r+   r)   numr   rD   r   r5   r[   r6   r_   /  s6    

zRandomOrder.__call__c                 C  s   t | jdkr|S d }t|tjjr:| |tj d }nRt|t	rx|D ],}t|| tjjrH| ||tj d }qHnt
dt| d|d kr|S t|D ]4}t| j| trt| j| j|| j| j| jd}q|S Nr   r   r   rM   )r,   )r0   r$   r2   r   r#   r   r   r   r   r   ri   r>   rc   r
   r   rd   r%   r&   r,   rA   r#   r   r   or5   r5   r6   rd   Q  s0    

    zRandomOrder.inverse)NTFFFN)r   NFN)rP   rk   rl   rm   r=   r_   rd   rp   r5   r5   rK   r6   r   
  s          "c                      sj   e Zd ZdZdddddddd	d
ddd
 fddZdddddZdd Zdd
dddZdd Z  Z	S )r   aH
  
    ``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<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<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``}.
    NTFr7   r   r"   zint | tuple[int, int] | Nonezlist[int] | Noner    r!   r8   )
r$   r%   r&   r,   num_transformsreplacerq   r)   r*   r-   c
           
        sF   t  j||||||	d | |\| _| _|| _| || _|| _d S )N)r,   r)   r*   )	rH   r=   _ensure_valid_num_transformsmin_num_transformsmax_num_transformsr   rs   rq   r,   )
rA   r$   r%   r&   r,   r   r   rq   r)   r*   rK   r5   r6   r=     s
    zSomeOf.__init__tuple)r   r-   c                 C  s0  t |ts8t |ts8t |ts8|d k	r8tdt| |d krVt| jt| jg}nt |trztt| j|}||g}npt|dkrtdt| t |d trt |d tstdt|d  dt|d  d|d |d g}|d dk s|d t| jkr(td	| d
t| j d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 r   r   z"Expected (int,int), but received (z, r.   znum_transforms=z are out of the bounds [0, z].)
r2   r   r{   r   r1   r>   r0   r$   minr   )rA   r   r^   nr5   r5   r6   r     s4    

 "z#SomeOf._ensure_valid_num_transformsc                 C  s   |d kst | jdkrd S t|}t |}|t | jkrVtdt | j d| dt|dk rttd| dt|dkrtd| d||  }tt	|S )Nr   zExpected len(weights)=z, got: rM   rt   ru   )
r0   r$   rv   rw   r1   rx   ry   rz   r   r{   )rA   rq   Z	n_weightsr5   r5   r6   rs     s    
zSomeOf._normalize_probabilitiesr   r:   c           
        s.  |dkrt d| d|d k	r.t d| t jdkr@|S  j j jd } jjt j| j j	d
 }|d kr jn|}t| fdd|D || j j| j| jd	
}t|tjjrވ j|d
|id nLt|tr*|D ]:}	t||	 tjjs |	|kr j||	d
|id q|S )Nr   z8SomeOf requires 'start' parameter to be 0 (start set to r.   z7SomeOf requires 'end' parameter to be None (end set to r   )r   pc                   s   g | ]} j | qS r5   r   )r`   ar[   r5   r6   ra     s     z#SomeOf.__call__.<locals>.<listcomp>r   r   r   )r1   r0   r$   rI   rJ   r   r   choicer   rq   tolistrD   r   r%   r&   r*   r,   r2   r   r#   r   r   r   	trace_key)
rA   r#   r'   r(   r+   r)   sample_sizer   rD   r   r5   r[   r6   r_     s8    ""zSomeOf.__call__c                 C  s   t | jdkr|S d }t|tjjr:| |tj d }n`t|t	r|D ]:}t|| tjjsl| 
||krH| ||tj d }qHntdt| d|d kr|S t|D ]4}t| j| trt| j| j|| j| j| jd}q|S r   )r0   r$   r2   r   r#   r   r   r   r   r   r   ri   r>   rc   r
   r   rd   r%   r&   r,   r   r5   r5   r6   rd     s0    
 
    zSomeOf.inverse)	NTFFNFNFN)r   NFN)
rP   rk   rl   rm   r=   r   rs   r_   rd   rp   r5   r5   rK   r6   r   m  s   #         & #)TFr   NFNFF).rm   
__future__r   rQ   collections.abcr   r   r   copyr   typingr   numpyrv   r   monai.apps.utilsr   monai.configr	   Zmonai.transforms.inverser
   Z monai.transforms.lazy.functionalr   Zmonai.transforms.traitsr   Zmonai.transforms.transformr   r   r   r   r   r   monai.utilsr   r   r   r   r   rP   logger__all__r   r   r   r   r   r5   r5   r5   r6   <module>   s@            $G   
c