U
    vPho-                  	   @  sr  d dl mZ d dlmZmZ d dlmZmZ d dlm	Z	m
Z
mZ d dlZd dlmZ d dlmZ d dlmZmZmZ d d	lmZmZ e	rd d
lmZ nedejeddd\ZZdddddddddg	ZG dd deZd3dddddZd4ddd d!d"d#d$dZG d%d deZ G d&d de Z!G d'd de Z"d5d(d(dd d!d)d*d+dZ#d!d!d,d-d.d/dZ$d0d0d d1d2dZ%dS )6    )annotations)ABCabstractmethod)CallableSequence)TYPE_CHECKINGAnycastN)
IgniteInfo)apply_transform)ensure_tuplemin_versionoptional_import)
CommonKeysGanKeys)	EventEnumzignite.enginer   base)as_typeIterationEventsget_devices_specdefault_prepare_batchPrepareBatchPrepareBatchDefaultPrepareBatchExtraInputdefault_make_latentengine_apply_transformdefault_metric_cmp_fnc                   @  s(   e Zd ZdZdZdZdZdZdZdZ	dS )	r   a  
    Additional Events engine can register and trigger in the iteration process.
    Refer to the example in ignite: https://pytorch.org/ignite/generated/ignite.engine.events.EventEnum.html.
    These Events can be triggered during training iteration:
    `FORWARD_COMPLETED` is the Event when `network(image, label)` completed.
    `LOSS_COMPLETED` is the Event when `loss(pred, label)` completed.
    `BACKWARD_COMPLETED` is the Event when `loss.backward()` completed.
    `MODEL_COMPLETED` is the Event when all the model related operations completed.
    `INNER_ITERATION_STARTED` is the Event when the iteration has an inner loop and the loop is started.
    `INNER_ITERATION_COMPLETED` is the Event when the iteration has an inner loop and the loop is completed.
    Zforward_completedZloss_completedZbackward_completedZmodel_completedZinner_iteration_startedZinner_iteration_completedN)
__name__
__module____qualname____doc__FORWARD_COMPLETEDZLOSS_COMPLETEDZBACKWARD_COMPLETEDMODEL_COMPLETEDZINNER_ITERATION_STARTEDZINNER_ITERATION_COMPLETED r#   r#   H/home/dell461/cl/sdc2/HISourceFinder-master-l/src/monai/engines/utils.pyr   -   s   z#Sequence[torch.device | str] | Nonezlist[torch.device])devicesreturnc                 C  sb   | dkr.dd t tj D } | sPtdn"t| dkrHtdg} nt| } dd | D } | S )a  
    Get a valid specification for one or more devices. If `devices` is None get devices for all CUDA devices available.
    If `devices` is and zero-length structure a single CPU compute device is returned. In any other cases `devices` is
    returned unchanged.

    Args:
        devices: list of devices to request, None for all GPU devices, [] for CPU.

    Raises:
        RuntimeError: When all GPUs are selected (``devices=None``) but no GPUs are available.

    Returns:
        list of torch.device: list of devices.

    Nc                 S  s   g | ]}t d |dqS )zcuda:d)torchdevice.0r'   r#   r#   r$   
<listcomp>S   s     z$get_devices_spec.<locals>.<listcomp>zNo GPU devices available.r   cpuc                 S  s$   g | ]}t |trt|n|qS r#   )
isinstancestrr(   r)   r*   r#   r#   r$   r,   ^   s     )ranger(   cudadevice_countRuntimeErrorlenr)   list)r%   r#   r#   r$   r   B   s    
F?dict[str, torch.Tensor] | torch.Tensor | Sequence[torch.Tensor]str | torch.device | Noneboolr   7tuple[torch.Tensor, torch.Tensor | None] | torch.Tensor	batchdatar)   non_blockingkwargsr&   c                 K  s
  t | tsxt | tjr0| jf ||d|dfS t| dkrp| \}}|jf ||d||jf ||d|fS tdt | tj	tjr| tj
 jf ||d|| tj	 jf ||d|fS tj| kr| tj jf ||d|S | tj
 jf ||d|dfS )a  
    Default function to prepare the data for current iteration.

    The input `batchdata` is either a single tensor, a pair of tensors, or a dictionary of data. In the first case the
    return value is the tensor and None, in the second case the return value is the two tensors, and in the dictionary
    case the return value depends on what keys are present. if `CommonKeys.IMAGE` and `CommonKeys.LABEL` are present
    then the tensors they key to are returned, if only `CommonKeys.IMAGE` is present that tensor and None is returned.
    If `CommonKeys.REALS` is present this is returned with None. All returned tensors are moved to the given device
    using the given non-blocking argument before being returned.

    This function implements the expected API for a `prepare_batch` callable in Ignite:
    https://pytorch.org/ignite/v0.4.8/generated/ignite.engine.create_supervised_trainer.html

    Args:
        batchdata: input batch data which is either a single tensor, a pair, or a dictionary
        device: device to move every returned tensor to
        non_blocking: equivalent argument for `Tensor.to`
        kwargs: further arguments for `Tensor.to`

    Returns:
        image, label(optional).
    r)   r<   N   zWDefault prepare_batch expects a single tensor, a tensor pair, or dictionary input data.)r.   dictr(   Tensortor4   AssertionErrorgetr   LABELIMAGEr   REALS)r;   r)   r<   r=   imagelabelr#   r#   r$   r   b   s     

c                   @  s,   e Zd ZdZedddddddd	d
ZdS )r   a  
    Interface of customized prepare_batch in the trainer or evaluator workflows.
    It takes the data of current batch, target device and non_blocking flag as input.
    Args `batchdata`, `device`, `non_blocking` refer to the ignite API:
    https://pytorch.org/ignite/v0.4.8/generated/ignite.engine.create_supervised_trainer.html.
    `kwargs` supports other args for `Tensor.to()` API.
    NFdict[str, torch.Tensor]r7   r8   r   r:   c                 K  s   t d| jj dd S )Nz	Subclass z must implement this method.)NotImplementedError	__class__r   selfr;   r)   r<   r=   r#   r#   r$   __call__   s    zPrepareBatch.__call__)NF)r   r   r   r    r   rO   r#   r#   r#   r$   r      s
     c                   @  s(   e Zd ZdZddddddd	d
dZdS )r   zo
    This wraps `default_prepare_batch` to return `image` and `label` only, so is consistent with its API.
    NFr6   r7   r8   r   r9   r:   c                 K  s   t |||f|S )z
        Args `batchdata`, `device`, `non_blocking` refer to the ignite API:
        https://pytorch.org/ignite/v0.4.8/generated/ignite.engine.create_supervised_trainer.html.
        `kwargs` supports other args for `Tensor.to()` API.

        )r   rM   r#   r#   r$   rO      s    zPrepareBatchDefault.__call__)NF)r   r   r   r    rO   r#   r#   r#   r$   r      s     c                   @  s8   e Zd ZdZdddddZdd	d
ddddddZdS )r   a  
    Customized prepare batch callable for trainers or evaluators which support extra input data for the network.
    Extra items are specified by the `extra_keys` parameter and are extracted from the input dictionary (ie. the batch).
    This uses `default_prepare_batch` but requires dictionary inputs.

    Args:
        extra_keys: If a string or sequence of strings is provided, values from the input dictionary are extracted from
            those keys and passed to the network as extra positional arguments. If a dictionary is provided, every pair
            `(k, v)` in that dictionary will become a new keyword argument assigning to `k` the value in the input
            dictionary keyed to `v`.
    z$str | Sequence[str] | dict[str, str]None)
extra_keysr&   c                 C  s
   || _ d S )N)rQ   )rN   rQ   r#   r#   r$   __init__   s    zPrepareBatchExtraInput.__init__NFrJ   r7   r8   r   z.tuple[torch.Tensor, torch.Tensor, tuple, dict]r:   c                   s   t  f\}}t }t }ddd fdd}	t| jtttfrlt| jD ]}
||	|
 qVn2t| jtr| j	 D ]\}
}|
|
|	|i qttj|ttj|t||fS )z
        Args `batchdata`, `device`, `non_blocking` refer to the ignite API:
        https://pytorch.org/ignite/v0.4.8/generated/ignite.engine.create_supervised_trainer.html.
        `kwargs` supports other args for `Tensor.to()` API.
        r/   torch.Tensor)keyr&   c                   s.    |  }t |tjr*|jf d}|S Nr>   )r.   r(   rA   rB   )rT   datar;   r)   r=   r<   r#   r$   	_get_data   s    z2PrepareBatchExtraInput.__call__.<locals>._get_data)r   r5   r@   r.   rQ   r/   tupler   appenditemsupdater	   r(   rA   )rN   r;   r)   r<   r=   rH   rI   args_kwargs_rX   kvr#   rW   r$   rO      s    zPrepareBatchExtraInput.__call__)NF)r   r   r   r    rR   rO   r#   r#   r#   r$   r      s
     intrS   )num_latentslatent_sizer)   r<   r=   r&   c                 K  s   t | |jf ||d|S rU   )r(   randnrB   )rb   rc   r)   r<   r=   r#   r#   r$   r      s    zCallable[..., dict]ztuple[Any, Any])batchoutput	transformr&   c                 C  s   t | trxt |trxt| }|| t||}t |tsBtd| D ]*\}}||ksb|| krl|||< qJ|| |< qJn
t||}| |fS )z
    Apply transform on `batch` and `output`.
    If `batch` and `output` are dictionaries, temporarily combine them for the transform,
    otherwise, apply the transform for `output` data only.

    zIWith a dict supplied to apply_transform a single dict return is expected.)r.   r@   r\   r   rC   r[   )re   rf   rg   rV   Ztransformed_datar_   r`   r#   r#   r$   r      s    




float)current_metric	prev_bestr&   c                 C  s   | |kS )a  
    The default function to compare metric values between current metric and previous best metric.

    Args:
        current_metric: metric value of current round computation.
        prev_best: the best metric value of previous rounds to compare with.

    r#   )ri   rj   r#   r#   r$   r     s    	)N)NF)NF)&
__future__r   abcr   r   collections.abcr   r   typingr   r   r	   r(   monai.configr
   monai.transformsr   monai.utilsr   r   r   monai.utils.enumsr   r   ignite.enginer   OPT_IMPORT_VERSION___all__r   r   r   r   r   r   r   r   r   r#   r#   r#   r$   <module>   sP       
"  45  
