o
    .wi"                     @   s   d dl mZ d dlmZmZmZm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 d dlmZ d dlmZ d d	lmZ d d
lmZmZ esMdgZG dd deZdS )    )Sequence)AnyListOptionalUnion)Tensor)Literal)_dice_score_compute_dice_score_update_dice_score_validate_args)Metric)rank_zero_warn)dim_zero_cat)_MATPLOTLIB_AVAILABLE)_AX_TYPE_PLOT_OUT_TYPEDiceScore.plotc                       s  e Zd ZU dZdZeed< dZeed< dZeed< dZ	e
ed< d	Ze
ed
< ee ed< ee ed< ee ed< 				d'dededeed  ded dee
ed f deddf fddZdededdfdd Zdefd!d"Zd(d#eeee df d$ee defd%d&Z  ZS ))	DiceScoreaX  Compute `Dice Score`_.

    The metric can be used to evaluate the performance of image segmentation models. The Dice Score is defined as:

    ..math::
        DS = \frac{2 \sum_{i=1}^{N} t_i p_i}{\sum_{i=1}^{N} t_i + \sum_{i=1}^{N} p_i}

    where :math:`N` is the number of classes, :math:`t_i` is the target tensor, and :math:`p_i` is the prediction
    tensor. In general the Dice Score can be interpreted as the overlap between the prediction and target tensors
    divided by the total number of elements in the tensors.

    As input to ``forward`` and ``update`` the metric accepts the following input:

        - ``preds`` (:class:`~torch.Tensor`): An one-hot boolean tensor of shape ``(N, C, ...)`` with ``N`` being
          the number of samples and ``C`` the number of classes. Alternatively, an integer tensor of shape ``(N, ...)``
          can be provided, where the integer values correspond to the class index. The input type can be controlled
          with the ``input_format`` argument.
        - ``target`` (:class:`~torch.Tensor`): An one-hot boolean tensor of shape ``(N, C, ...)`` with ``N`` being
          the number of samples and ``C`` the number of classes. Alternatively, an integer tensor of shape ``(N, ...)``
          can be provided, where the integer values correspond to the class index. The input type can be controlled
          with the ``input_format`` argument.

    As output to ``forward`` and ``compute`` the metric returns the following output:

        - ``gds`` (:class:`~torch.Tensor`): The dice score. If ``average`` is set to ``None`` or ``"none"`` the output
          will be a tensor of shape ``(C,)`` with the dice score for each class. If ``average`` is set to
          ``"micro"``, ``"macro"``, or ``"weighted"`` the output will be a scalar tensor. The score is an average over
          all samples.

    Args:
        num_classes: The number of classes in the segmentation problem.
        include_background: Whether to include the background class in the computation.
        average: The method to average the dice score. Options are ``"micro"``, ``"macro"``, ``"weighted"``, ``"none"``
            or ``None``. This determines how to average the dice score across different classes.
        input_format: What kind of input the function receives. Choose between ``"one-hot"`` for one-hot encoded tensors
            or ``"index"`` for index tensors
        zero_division: The value to return when there is a division by zero. Options are 1.0, 0.0, "warn" or "nan".
            Setting it to "warn" behaves like 0.0 but will also create a warning.
        kwargs: Additional keyword arguments, see :ref:`Metric kwargs` for more info.

    Raises:
        ValueError:
            If ``num_classes`` is not a positive integer
        ValueError:
            If ``include_background`` is not a boolean
        ValueError:
            If ``average`` is not one of ``"micro"``, ``"macro"``, ``"weighted"``, ``"none"`` or ``None``
        ValueError:
            If ``input_format`` is not one of ``"one-hot"`` or ``"index"``

    Example:
        >>> from torch import randint
        >>> from torchmetrics.segmentation import DiceScore
        >>> preds = randint(0, 2, (4, 5, 16, 16))  # 4 samples, 5 classes, 16x16 prediction
        >>> target = randint(0, 2, (4, 5, 16, 16))  # 4 samples, 5 classes, 16x16 target
        >>> dice_score = DiceScore(num_classes=5, average="micro")
        >>> dice_score(preds, target)
        tensor(0.4941)
        >>> dice_score = DiceScore(num_classes=5, average="none")
        >>> dice_score(preds, target)
        tensor([0.4860, 0.4999, 0.5014, 0.4885, 0.4915])

    Ffull_state_updateis_differentiableThigher_is_better        plot_lower_boundg      ?plot_upper_bound	numeratordenominatorsupportmicroone-hotnum_classesinclude_backgroundaverage)r   macroweightednoneinput_format)r   indexzero_division)warnnankwargsreturnNc                    s   t  jd	i | |dkrtdt t||||| || _|| _|| _|| _|| _	|s/|d n|}| j
dg dd | j
dg dd | j
dg dd d S )
Nr   zDiceScore metric currently defaults to `average=micro`, but will change to`average=macro` in the v1.9 release. If you've explicitly set this parameter, you can ignore this warning.   r   cat)dist_reduce_fxr   r    )super__init__r   UserWarningr   r   r    r!   r%   r'   	add_state)selfr   r    r!   r%   r'   r*   	__class__r/   [/home/ubuntu/sommelier/.venv/lib/python3.10/site-packages/torchmetrics/segmentation/dice.pyr1   n   s    	zDiceScore.__init__predstargetc                 C   sD   t ||| j| j| j\}}}| j| | j| | j| dS )zUpdate the state with new data.N)r
   r   r    r%   r   appendr   r   )r4   r8   r9   r   r   r   r/   r/   r7   update   s   
zDiceScore.updatec                 C   s>   t t| jt| j| j| jdkrt| jnd| jdjddS )zComputes the Dice Score.r#   N)r   r'   r   )dim)r	   r   r   r   r!   r   r'   nanmean)r4   r/   r/   r7   compute   s   zDiceScore.computevalaxc                 C   s   |  ||S )a  Plot a single or multiple values from the metric.

        Args:
            val: Either a single result from calling `metric.forward` or `metric.compute` or a list of these results.
                If no value is provided, will automatically call `metric.compute` and plot that result.
            ax: An matplotlib axis object. If provided will add plot to that axis

        Returns:
            Figure and Axes object

        Raises:
            ModuleNotFoundError:
                If `matplotlib` is not installed

        .. plot::
            :scale: 75

            >>> # Example plotting a single value
            >>> import torch
            >>> from torchmetrics.segmentation import DiceScore
            >>> metric = DiceScore(num_classes=3)
            >>> metric.update(torch.randint(0, 2, (10, 3, 128, 128)), torch.randint(0, 2, (10, 3, 128, 128)))
            >>> fig_, ax_ = metric.plot()

        .. plot::
            :scale: 75

            >>> # Example plotting multiple values
            >>> import torch
            >>> from torchmetrics.segmentation import DiceScore
            >>> metric = DiceScore(num_classes=3)
            >>> values = [ ]
            >>> for _ in range(10):
            ...     values.append(
            ...        metric(torch.randint(0, 2, (10, 3, 128, 128)), torch.randint(0, 2, (10, 3, 128, 128)))
            ...     )
            >>> fig_, ax_ = metric.plot(values)

        )_plot)r4   r?   r@   r/   r/   r7   plot   s   (r   )Tr   r   r   )NN)__name__
__module____qualname____doc__r   bool__annotations__r   r   r   floatr   r   r   intr   r   r   r   r1   r;   r>   r   r   r   rB   __classcell__r/   r/   r5   r7   r   #   s@   
 @
	2
r   N)collections.abcr   typingr   r   r   r   torchr   typing_extensionsr   )torchmetrics.functional.segmentation.dicer	   r
   r   torchmetrics.metricr   torchmetrics.utilitiesr   torchmetrics.utilities.datar   torchmetrics.utilities.importsr   torchmetrics.utilities.plotr   r   __doctest_skip__r   r/   r/   r/   r7   <module>   s   