U
    žPÓh+  ã                   @  sp   d dl mZ d dlm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 G dd„ deƒZdS )é    )Úannotations)ÚAnyN)Ú_Loss)Údo_metric_reduction)ÚMetricReductioné   )ÚTensorOrListé   )ÚCumulativeIterationMetricc                      s\   e Zd ZdZejdfdddddœ‡ fdd	„Zddddœdd„Zddddddœdd„Z‡  Z	S )Ú
LossMetrica¯  
    A wrapper to make ``loss_fn`` available as a cumulative metric. That is, the loss values computed from
    mini-batches can be combined in the ``reduction`` mode across multiple iterations, as a quantitative measurement
    of a model.

    Example:

    .. code-block:: python

        import torch
        from monai.losses import DiceLoss
        from monai.metrics import LossMetric

        dice_loss = DiceLoss(include_background=True)
        loss_metric = LossMetric(loss_fn=dice_loss)

        # first iteration
        y_pred = torch.tensor([[[[1.0, 0.0], [0.0, 1.0]]]])  # shape [batch=1, channel=1, 2, 2]
        y = torch.tensor([[[[1.0, 0.0], [1.0, 1.0]]]])  # shape [batch=1, channel=1, 2, 2]
        loss_metric(y_pred, y)

        # second iteration
        y_pred = torch.tensor([[[[1.0, 0.0], [0.0, 0.0]]]])  # shape [batch=1, channel=1, 2, 2]
        y = torch.tensor([[[[1.0, 0.0], [1.0, 1.0]]]])  # shape [batch=1, channel=1, 2, 2]
        loss_metric(y_pred, y)

        # aggregate
        print(loss_metric.aggregate(reduction="none"))  # tensor([[0.2000], [0.5000]]) (shape [batch=2, channel=1])

        # reset
        loss_metric.reset()
        print(loss_metric.aggregate())


    Args:
        loss_fn: a callable function that takes ``y_pred`` and optionally ``y`` as input (in the "batch-first" format),
            returns a "batch-first" tensor of loss values.
        reduction: define mode of reduction to the metrics, will only apply reduction on `not-nan` values,
            available reduction modes: {``"none"``, ``"mean"``, ``"sum"``, ``"mean_batch"``, ``"sum_batch"``,
            ``"mean_channel"``, ``"sum_channel"``}, default to ``"mean"``. if "none", will not do reduction.
        get_not_nans: whether to return the `not_nans` count, if True, aggregate() returns (metric, not_nans).
            Here `not_nans` count the number of not nans for the metric, thus its shape equals to the shape of the metric.

    Fr   zMetricReduction | strÚboolÚNone)Úloss_fnÚ	reductionÚget_not_nansÚreturnc                   s    t ƒ  ¡  || _|| _|| _d S )N)ÚsuperÚ__init__r   r   r   )Úselfr   r   r   ©Ú	__class__© úN/home/dell461/cl/sdc2/HISourceFinder-master-l/src/monai/metrics/loss_metric.pyr   H   s    
zLossMetric.__init__NzMetricReduction | str | Nonez0torch.Tensor | tuple[torch.Tensor, torch.Tensor])r   r   c                 C  sZ   |   ¡ }|dkr4| jr*t d¡t d¡fS t d¡S t||p@| jƒ\}}| jrV||fS |S )a¶  
        Returns the aggregated loss value across multiple iterations.

        Args:
            reduction: define mode of reduction to the metrics, will only apply reduction on `not-nan` values,
                available reduction modes: {``"none"``, ``"mean"``, ``"sum"``, ``"mean_batch"``, ``"sum_batch"``,
                ``"mean_channel"``, ``"sum_channel"``}, default to `self.reduction`. if "none", will not do reduction.
        Ng        )Ú
get_bufferr   ÚtorchÚtensorr   r   )r   r   ÚdataÚfÚnot_nansr   r   r   Ú	aggregateP   s
    $zLossMetric.aggregateztorch.Tensorztorch.Tensor | Noner   r   )Úy_predÚyÚkwargsr   c                 K  sD   |dkr|   |¡n
|   ||¡}t|tjƒr@| ¡ dk r@|d }q*|S )a	  
        Input `y_pred` is compared with ground truth `y`.
        Both `y_pred` and `y` are expected to be a batch-first Tensor (BC[HWD]).

        Returns:
             a tensor with shape (BC[HWD]), or a list of tensors, each tensor with shape (C[HWD]).
        Nr   )r   Ú
isinstancer   ÚTensorÚdim)r   r    r!   r"   Z	iter_lossr   r   r   Ú_compute_tensora   s
    
zLossMetric._compute_tensor)N)N)
Ú__name__Ú
__module__Ú__qualname__Ú__doc__r   ÚMEANr   r   r&   Ú__classcell__r   r   r   r   r      s   . ÿ	 ÿr   )Ú
__future__r   Útypingr   r   Útorch.nn.modules.lossr   Úmonai.metrics.utilsr   Úmonai.utilsr   Úconfigr   Úmetricr
   r   r   r   r   r   Ú<module>   s   