o
    i*=                     @  sb  d dl mZ d dlmZmZ d dlmZ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mZ d dlmZmZ e
rOd d	lmZ ned
ejeddd\ZZg dZG dd deZd?d@ddZ 		dAdBd!d"Z!G d#d$ d$eZ"G d%d& d&e"Z#G d'd( d(e"Z$G d)d* d*e"Z%G d+d, d,e%Z&		dAdCd1d2Z'dDd8d9Z(dEd=d>Z)dS )F    )annotations)ABCabstractmethod)CallableMappingSequence)TYPE_CHECKINGAnycastN)apply_transform)
IgniteInfoensure_tuplemin_versionoptional_import)
CommonKeysGanKeys)	EventEnumzignite.enginer   base)as_type)IterationEventsget_devices_specdefault_prepare_batchPrepareBatchPrepareBatchDefaultPrepareBatchExtraInputDiffusionPrepareBatchVPredictionPrepareBatch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.
    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'   U/home/dell461/cl/sdc2/last_ska_mid/HISourceFinder-master-l/src/monai/engines/utils.pyr   /   s    r   devices#Sequence[torch.device | str] | Nonereturnlist[torch.device]c                 C  sb   | du rdd t tj D } | stdnt| dkr$t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>U   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/   r0   r'   r'   r(   r2   `   s   $ )ranger.   cudadevice_countRuntimeErrorlenr/   list)r)   r'   r'   r(   r   D   s   r   F	batchdata?dict[str, torch.Tensor] | torch.Tensor | Sequence[torch.Tensor]r/   str | torch.device | Nonenon_blockingboolkwargsr	   7tuple[torch.Tensor, torch.Tensor | None] | torch.Tensorc                 K  s
  t | ts<t | tjr| jd||d|dfS t| dkr8| \}}|jd||d||jd||d|fS tdt | tj	tjrb| tj
 jd||d|| tj	 jd||d|fS tj| v ru| tj jd||d|S | tj
 jd||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'   )r4   dictr.   Tensortor:   AssertionErrorgetr   LABELIMAGEr   REALS)r<   r/   r?   rA   imagelabelr'   r'   r(   r   d   s    

 r   c                   @  s$   e Zd ZdZe		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.
    NFr<   dict[str, torch.Tensor]r/   r>   r?   r@   rA   r	   r+   c                 K  s   t d| jj d)Nz	Subclass z must implement this method.)NotImplementedError	__class__r!   selfr<   r/   r?   rA   r'   r'   r(   __call__   s   zPrepareBatch.__call__NF)
r<   rO   r/   r>   r?   r@   rA   r	   r+   r	   )r!   r"   r#   r$   r   rT   r'   r'   r'   r(   r      s    r   c                   @  s    e Zd ZdZ		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.
    NFr<   r=   r/   r>   r?   r@   rA   r	   r+   rB   c                 K  s   t |||fi |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   rR   r'   r'   r(   rT      s   zPrepareBatchDefault.__call__rU   
r<   r=   r/   r>   r?   r@   rA   r	   r+   rB   )r!   r"   r#   r$   rT   r'   r'   r'   r(   r      s
    r   c                   @  s*   e Zd ZdZdddZ			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`.
    
extra_keys$str | Sequence[str] | dict[str, str]r+   Nonec                 C  s
   || _ d S N)rW   )rS   rW   r'   r'   r(   __init__   s   
zPrepareBatchExtraInput.__init__NFr<   rO   r/   r>   r?   r@   rA   r	   .tuple[torch.Tensor, torch.Tensor, tuple, dict]c                   s   t  fi \}}t }t }d fdd}	t| jtttfr5t| jD ]	}
||	|
 q*nt| jtrN| j	 D ]\}
}|
|
|	|i q@t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.
        keyr5   r+   torch.Tensorc                   s.    |  }t |tjr|jdd}|S NrC   r'   )r4   r.   rF   rG   )r]   datar<   r/   rA   r?   r'   r(   	_get_data   s   z2PrepareBatchExtraInput.__call__.<locals>._get_dataN)r]   r5   r+   r^   )r   r;   rE   r4   rW   r5   tupler   appenditemsupdater
   r.   rF   )rS   r<   r/   r?   rA   rM   rN   args_kwargs_rb   kvr'   ra   r(   rT      s    zPrepareBatchExtraInput.__call__)rW   rX   r+   rY   rU   
r<   rO   r/   r>   r?   r@   rA   r	   r+   r\   )r!   r"   r#   r$   r[   rT   r'   r'   r'   r(   r      s    
r   c                   @  sJ   e Zd ZdZd!d"d	d
Zd#ddZd#ddZd$ddZ		d%d&dd ZdS )'r   a  
    This class is used as a callable for the `prepare_batch` parameter of engine classes for diffusion training.

    Assuming a supervised training process, it will generate a noise field using `get_noise` for an input image, and
    return the image and noise field as the image/target pair plus the noise field the kwargs under the key "noise".
    This assumes the inferer being used in conjunction with this class expects a "noise" parameter to be provided.

    If the `condition_name` is provided, this must refer to a key in the input dictionary containing the condition
    field to be passed to the inferer. This will appear in the keyword arguments under the key "condition".

    Nnum_train_timestepsintcondition_name
str | Noner+   rY   c                 C  s   || _ || _d S rZ   )rn   rl   )rS   rl   rn   r'   r'   r(   r[      s   
zDiffusionPrepareBatch.__init__imagesr^   c                 C  s
   t |S )zdReturns the noise tensor for input tensor `images`, override this for different noise distributions.)r.   
randn_likerS   rp   r'   r'   r(   	get_noise  s   
zDiffusionPrepareBatch.get_noisec                 C  s"   t jd| j|jd f|jd S )z]Get a timestep, by default this is a random integer between 0 and `self.num_train_timesteps`.r   )r/   )r.   randintrl   shaper/   longrr   r'   r'   r(   get_timesteps  s   "z#DiffusionPrepareBatch.get_timestepsnoise	timestepsc                 C  s   |S )zNReturn the target for the loss function, this is the `noise` value by default.r'   rS   rp   rx   ry   r'   r'   r(   
get_target  s   z DiffusionPrepareBatch.get_targetFr<   rO   r/   r>   r?   r@   rA   r	   r\   c                 K  s   t |||fi |\}}| |j|fd|i|}| |j|fd|i|}| |||j|fd|i|}	||d}
| jd urWt|trW|| j j|fd|i||
d< ||	d|
fS )Nr?   )rx   ry   	conditionr'   )r   rs   rG   rw   r{   rn   r4   r   )rS   r<   r/   r?   rA   rp   _rx   ry   targetZinfer_kwargsr'   r'   r(   rT     s    
 zDiffusionPrepareBatch.__call__rZ   )rl   rm   rn   ro   r+   rY   )rp   r^   r+   r^   )rp   r^   rx   r^   ry   r^   r+   r^   rU   rk   )	r!   r"   r#   r$   r[   rs   rw   r{   rT   r'   r'   r'   r(   r      s    


r   c                      s,   e Zd ZdZdd fddZdd Z  ZS )r   a  
    This class is used as a callable for the `prepare_batch` parameter of engine classes for diffusion training.

    Assuming a supervised training process, it will generate a noise field using `get_noise` for an input image, and
    from this compute the velocity using the provided scheduler. This value is used as the target in place of the
    noise field itself although the noise is field is in the kwargs under the key "noise". This assumes the inferer
    being used in conjunction with this class expects a "noise" parameter to be provided.

    If the `condition_name` is provided, this must refer to a key in the input dictionary containing the condition
    field to be passed to the inferer. This will appear in the keyword arguments under the key "condition".

    N	scheduler	nn.Modulerl   rm   rn   ro   r+   rY   c                   s   t  j||d || _d S )N)rl   rn   )superr[   r   )rS   r   rl   rn   rQ   r'   r(   r[   3  s   
z VPredictionPrepareBatch.__init__c                 C  s   | j |||S rZ   )r   Zget_velocityrz   r'   r'   r(   r{   7  s   z"VPredictionPrepareBatch.get_targetrZ   )r   r   rl   rm   rn   ro   r+   rY   )r!   r"   r#   r$   r[   r{   __classcell__r'   r'   r   r(   r   %  s    r   num_latentsrm   latent_sizer^   c                 K  s   t | |jd||d|S r_   )r.   randnrG   )r   r   r/   r?   rA   r'   r'   r(   r   ;  s   r   batchoutput	transformCallable[..., dict]tuple[Any, Any]c                 C  s   t | tr?t |tr?t| }|| t||}t |ts!td| D ]\}}||v s1|| vr6|||< q%|| |< q%| |fS 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.)r4   rE   rf   r   rH   re   )r   r   r   r`   Ztransformed_datari   rj   r'   r'   r(   r   E  s   





r   current_metricfloat	prev_bestc                 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'   )r   r   r'   r'   r(   r   a  s   	r   rZ   )r)   r*   r+   r,   rU   rV   )r   rm   r   rm   r/   r>   r?   r@   rA   r	   r+   r^   )r   r	   r   r	   r   r   r+   r   )r   r   r   r   r+   r@   )*
__future__r   abcr   r   collections.abcr   r   r   typingr   r	   r
   r.   torch.nnnnmonai.transformsr   monai.utilsr   r   r   r   monai.utils.enumsr   r   ignite.enginer   OPT_IMPORT_VERSIONr}   __all__r   r   r   r   r   r   r   r   r   r   r   r'   r'   r'   r(   <module>   s<   
"422

