U
    Ph4                     @  s~   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d	gZ	G d
d deZ
ddddddddddZG dd	 d	ZdS )    )annotationsN)do_metric_reduction)MetricReduction   )CumulativeIterationMetric
DiceMetriccompute_dice
DiceHelperc                	      sf   e Zd ZdZdejddddfddddddd	d
 fddZddddddZddddddZ  Z	S )r   a
  
    Compute average Dice score for a set of pairs of prediction-groundtruth segmentations.

    It supports both multi-classes and multi-labels tasks.
    Input `y_pred` is compared with ground truth `y`.
    `y_pred` is expected to have binarized predictions and `y` can be single-channel class indices or in the
    one-hot format. The `include_background` parameter can be set to ``False`` to exclude
    the first category (channel index 0) which is by convention assumed to be background. If the non-background
    segmentations are small compared to the total image size they can get overwhelmed by the signal from the
    background. `y_preds` and `y` can be a list of channel-first Tensor (CHW[D]) or a batch-first Tensor (BCHW[D]),
    `y` can also be in the format of `B1HW[D]`.

    Example of the typical execution steps of this metric class follows :py:class:`monai.metrics.metric.Cumulative`.

    Args:
        include_background: whether to include Dice computation on the first channel of
            the predicted output. Defaults to ``True``.
        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.
        ignore_empty: whether to ignore empty ground truth cases during calculation.
            If `True`, NaN value will be set for empty ground truth cases.
            If `False`, 1 will be set if the predictions of empty ground truth cases are also empty.
        num_classes: number of input channels (always including the background). When this is None,
            ``y_pred.shape[1]`` will be used. This option is useful when both ``y_pred`` and ``y`` are
            single-channel class indices and the number of classes is not automatically inferred from data.
        return_with_label: whether to return the metrics with label, only works when reduction is "mean_batch".
            If `True`, use "label_{index}" as the key corresponding to C channels; if 'include_background' is True,
            the index begins at "0", otherwise at "1". It can also take a list of label names.
            The outcome will then be returned as a dictionary.

    TFNboolMetricReduction | str
int | Nonezbool | list[str]None)include_background	reductionget_not_nansignore_emptynum_classesreturn_with_labelreturnc                   sP   t    || _|| _|| _|| _|| _|| _t| jt	j
dd| j| jd| _d S )NFr   r   r   softmaxr   r   )super__init__r   r   r   r   r   r   r	   r   NONEdice_helper)selfr   r   r   r   r   r   	__class__ K/home/dell461/cl/sdc2/HISourceFinder-master-l/src/monai/metrics/meandice.pyr   <   s    	
zDiceMetric.__init__torch.Tensory_predyr   c                 C  s.   |  }|dk r td| d| j||dS )a  
        Args:
            y_pred: input data to compute, typical segmentation model output.
                It must be one-hot format and first dim is batch, example shape: [16, 3, 32, 32]. The values
                should be binarized.
            y: ground truth to compute mean Dice metric. `y` can be single-channel class indices or
                in the one-hot format.

        Raises:
            ValueError: when `y_pred` has less than three dimensions.
           zHy_pred should have at least 3 dimensions (batch, channel, spatial), got .r"   r#   )
ndimension
ValueErrorr   )r   r"   r#   dimsr   r   r   _compute_tensorU   s    zDiceMetric._compute_tensorzMetricReduction | str | None0torch.Tensor | tuple[torch.Tensor, torch.Tensor])r   r   c           
      C  s   |   }t|tjs(tdt| dt||p4| j\}}| jtj	kr| j
ri }t| j
trt|D ]8\}}| jsd|d  nd| }t| d||< qfn(t| j
|D ]\}	}t| d||	< q|}| jr||fS |S )a  
        Execute reduction and aggregation logic for the output of `compute_dice`.

        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.

        z2the data to aggregate must be PyTorch Tensor, got r%   label_r      )
get_buffer
isinstancetorchTensorr(   typer   r   r   
MEAN_BATCHr   r
   	enumerater   rounditemzipr   )
r   r   datafnot_nans_fivZ
_label_keykeyr   r   r   	aggregateg   s    zDiceMetric.aggregate)N)
__name__
__module____qualname____doc__r   MEANr   r*   r?   __classcell__r   r   r   r   r      s   %  Tr    r
   r   )r"   r#   r   r   r   r   c                 C  s   t |tjdd||d| |dS )a  Computes Dice score metric for a batch of predictions.

    Args:
        y_pred: input data to compute, typical segmentation model output.
            `y_pred` can be single-channel class indices or in the one-hot format.
        y: ground truth to compute mean dice metric. `y` can be single-channel class indices or in the one-hot format.
        include_background: whether to include Dice computation on the first channel of
            the predicted output. Defaults to True.
        ignore_empty: whether to ignore empty ground truth cases during calculation.
            If `True`, NaN value will be set for empty ground truth cases.
            If `False`, 1 will be set if the predictions of empty ground truth cases are also empty.
        num_classes: number of input channels (always including the background). When this is None,
            ``y_pred.shape[1]`` will be used. This option is useful when both ``y_pred`` and ``y`` are
            single-channel class indices and the number of classes is not automatically inferred from data.

    Returns:
        Dice scores per batch and per class, (shape: [batch_size, num_classes]).

    Fr   r&   )r	   r   r   )r"   r#   r   r   r   r   r   r   r      s     c                   @  sf   e Zd ZdZdddddejddfddddddddd	d
	ddZddddddZddddddZdS )r	   a  
    Compute Dice score between two tensors `y_pred` and `y`.
    `y_pred` and `y` can be single-channel class indices or in the one-hot format.

    Example:

    .. code-block:: python

        import torch
        from monai.metrics import DiceHelper

        n_classes, batch_size = 5, 16
        spatial_shape = (128, 128, 128)

        y_pred = torch.rand(batch_size, n_classes, *spatial_shape).float()  # predictions
        y = torch.randint(0, n_classes, size=(batch_size, 1, *spatial_shape)).long()  # ground truth

        score, not_nans = DiceHelper(include_background=False, sigmoid=True, softmax=True)(y_pred, y)
        print(score, not_nans)

    NFTzbool | Noner
   r   r   r   )	r   sigmoidr   activater   r   r   r   r   c	           	      C  sN   || _ || _|| _|dkr|n|| _|dkr2| n|| _|| _|| _|| _dS )aV  

        Args:
            include_background: whether to include the score on the first channel
                (default to the value of `sigmoid`, False).
            sigmoid: whether ``y_pred`` are/will be sigmoid activated outputs. If True, thresholding at 0.5
                will be performed to get the discrete prediction. Defaults to False.
            softmax: whether ``y_pred`` are softmax activated outputs. If True, `argmax` will be performed to
                get the discrete prediction. Defaults to the value of ``not sigmoid``.
            activate: whether to apply sigmoid to ``y_pred`` if ``sigmoid`` is True. Defaults to False.
                This option is only valid when ``sigmoid`` is True.
            get_not_nans: whether to return the number of not-nan values.
            reduction: define mode of reduction to the metrics
            ignore_empty: if `True`, NaN value will be set for empty ground truth cases.
                If `False`, 1 will be set if the Union of ``y_pred`` and ``y`` is empty.
            num_classes: number of input channels (always including the background). When this is None,
                ``y_pred.shape[1]`` will be used. This option is useful when both ``y_pred`` and ``y`` are
                single-channel class indices and the number of classes is not automatically inferred from data.
        N)rF   r   r   r   r   rG   r   r   )	r   r   rF   r   rG   r   r   r   r   r   r   r   r      s    zDiceHelper.__init__r    r!   c                 C  s   t |}|dkr6dt t || |t |  S | jrPt jtd|jdS |t | }|dkrvt jd|jdS t jd|jdS ) r   g       @nan)deviceg      ?g        )r0   summasked_selectr   tensorfloatrJ   )r   r"   r#   y_oZdenormr   r   r   compute_channel   s    
$zDiceHelper.compute_channelr+   c                 C  s~  | j | j }}| jdkr$|jd }n&| j}|jd dkrJ| jdkrJd }}|rh|dkrtj|ddd}n|r| jr|t|}|dk}| jrdnd}g }t|jd D ]}g }	|dkrt||ndgD ]p}
|jd dkr||df |
kn|||
f 	 }|jd dkr||df |
kn
|||
f }|	
| || q|
t|	 qtj|dd }t|| j\}}| jrz||fS |S )	a<  

        Args:
            y_pred: input predictions with shape (batch_size, num_classes or 1, spatial_dims...).
                the number of channels is inferred from ``y_pred.shape[1]`` when ``num_classes is None``.
            y: ground truth with shape (batch_size, num_classes or 1, spatial_dims...).
        Nr   FT)dimkeepdimg      ?r   )rQ   )r   rF   r   shaper0   argmaxrG   r   ranger
   appendrP   stack
contiguousr   r   r   )r   r"   r#   _softmaxZ_sigmoid	n_pred_chZfirst_chr8   bZc_listcZx_predxr9   r:   r   r   r   __call__   s2    

.,zDiceHelper.__call__)	r@   rA   rB   rC   r   r3   r   rP   r^   r   r   r   r   r	      s    ')TTN)
__future__r   r0   monai.metrics.utilsr   monai.utilsr   metricr   __all__r   r   r	   r   r   r   r   <module>   s   
q   $