U
    Ph\                     @  sh   d dl mZ d dlZd dlmZmZ d dlmZ ddlm	Z	 G dd de	Z
dd
d
ddd
dddZdS )    )annotationsN)do_metric_reductionignore_background)MetricReduction   )CumulativeIterationMetricc                      s^   e Zd ZdZdejddf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 )MeanIoUag  
    Compute average Intersection over Union (IoU) score between two tensors.
    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` should be in one-hot format. You can use suitable transforms
    in ``monai.transforms.post`` first to achieve binarized values.
    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_pred` and `y` can be a list of channel-first Tensor (CHW[D]) or a batch-first Tensor (BCHW[D]).

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

    Args:
        include_background: whether to include IoU 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.

    TFboolzMetricReduction | strNone)include_background	reductionget_not_nansignore_emptyreturnc                   s&   t    || _|| _|| _|| _d S )N)super__init__r   r   r   r   )selfr   r   r   r   	__class__ J/home/dell461/cl/sdc2/HISourceFinder-master-l/src/monai/metrics/meaniou.pyr   3   s
    
zMeanIoU.__init__torch.Tensor)y_predyr   c                 C  s4   |  }|dk r td| dt||| j| 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 IoU metric. It must be one-hot format and first dim is batch.
                The values should be binarized.

        Raises:
            ValueError: when `y_pred` has less than three dimensions.
           zHy_pred should have at least 3 dimensions (batch, channel, spatial), got .)r   r   r   r   )
ndimension
ValueErrorcompute_iour   r   )r   r   r   dimsr   r   r   _compute_tensor@   s       zMeanIoU._compute_tensorNzMetricReduction | str | Nonez0torch.Tensor | tuple[torch.Tensor, torch.Tensor])r   r   c                 C  sB   |   }t|tjstdt||p(| j\}}| jr>||fS |S )a  
        Execute reduction logic for the output of `compute_iou`.

        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.

        z-the data to aggregate must be PyTorch Tensor.)
get_buffer
isinstancetorchTensorr   r   r   r   )r   r   datafnot_nansr   r   r   	aggregateT   s
    zMeanIoU.aggregate)N)
__name__
__module____qualname____doc__r   MEANr   r    r(   __classcell__r   r   r   r   r      s    r   Tr   r	   )r   r   r   r   r   c           
      C  s   |st | |d\} }|j| jkr:td| j d|j dt| j}ttd|}tj||  |d}t||}tj| |d}|| | }	|rt|dk||	 tj	t
d|jd	S t|	dk||	 tj	d
|jd	S )a  Computes Intersection over Union (IoU) score metric from a batch of predictions.

    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 IoU metric. It must be one-hot format and first dim is batch.
            The values should be binarized.
        include_background: whether to include IoU 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.

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

    Raises:
        ValueError: when `y_pred` and `y` have different shapes.

    )r   r   z*y_pred and y should have same shapes, got z and r      )dimr   nan)deviceg      ?)r   shaper   lenlistranger#   sumwheretensorfloatr2   )
r   r   r   r   n_lenreduce_axisintersectiony_oy_pred_ounionr   r   r   r   i   s    
&r   )TT)
__future__r   r#   monai.metrics.utilsr   r   monai.utilsr   metricr   r   r   r   r   r   r   <module>   s   T   