o
    .wi%                     @   s   d dl 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 d dlmZ d dlmZ d d	lmZmZ esCd
gZG dd deZdS )    )Sequence)AnyOptionalUnionN)Tensor)Literal)_mean_iou_compute_mean_iou_update_mean_iou_validate_args)Metric)_MATPLOTLIB_AVAILABLE)_AX_TYPE_PLOT_OUT_TYPEMeanIoU.plotc                       s   e Zd ZU dZeed< eed< 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< 				d"dee dededed 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 )$MeanIoUa  Computes Mean Intersection over Union (mIoU) for semantic segmentation.

    The metric is defined by the overlap between the predicted segmentation and the ground truth, divided by the
    total area covered by the union of the two. The metric can be computed for each class separately or for all
    classes at once. The metric is optimal at a value of 1 and worst at a value of 0, -1 is returned if class
    is completely absent both from prediction and the ground truth labels.

    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:

        - ``miou`` (:class:`~torch.Tensor`): The mean Intersection over Union (mIoU) score. If ``per_class`` is set to
          ``True``, the output will be a tensor of shape ``(C,)`` with the IoU score for each class. If ``per_class`` is
          set to ``False``, the output will be a scalar tensor.

    Args:
        num_classes: The number of classes in the segmentation problem. Required when input_format="index",
            optional when input_format="one-hot".
        include_background: Whether to include the background class in the computation
        per_class: Whether to compute the IoU for each class separately. If set to ``False``, the metric will
            compute the mean IoU over all classes.
        input_format: What kind of input the function receives. Choose between ``"one-hot"`` for one-hot encoded tensors
            or ``"index"`` for index tensors
        kwargs: Additional keyword arguments, see :ref:`Metric kwargs` for more info.

    Raises:
        ValueError:
            If ``num_classes`` is not ``None`` or a positive integer
        ValueError:
            If ``num_classes`` is not provided when ``input_format="index"``
        ValueError:
            If ``include_background`` is not a boolean
        ValueError:
            If ``per_class`` is not a boolean
        ValueError:
            If ``input_format`` is not one of ``"one-hot"`` or ``"index"``

    Example:
        >>> import torch
        >>> from torch import randint
        >>> from torchmetrics.segmentation import MeanIoU
        >>> miou = MeanIoU()
        >>> preds = randint(0, 2, (10, 3, 128, 128), generator=torch.Generator().manual_seed(42))
        >>> target = randint(0, 2, (10, 3, 128, 128), generator=torch.Generator().manual_seed(43))
        >>> miou(preds, target)
        tensor(0.3336)
        >>> miou = MeanIoU(num_classes=3, per_class=True)
        >>> miou(preds, target)
        tensor([0.3361, 0.3340, 0.3308])
        >>> miou = MeanIoU(per_class=True, include_background=False)
        >>> miou(preds, target)
        tensor([0.3340, 0.3308])
        >>> miou = MeanIoU(num_classes=3, per_class=True, include_background=True, input_format="index")
        >>> miou(preds, target)
        tensor([ 0.3334,  0.3336, -1.0000])

    scorenum_batchesFfull_state_updateis_differentiableThigher_is_better        plot_lower_boundg      ?plot_upper_boundNone-hotnum_classesinclude_background	per_classinput_format)r   indexkwargsreturnc                    s   t  jdi | t|||| || _|| _|| _|| _d| _|d urJ|s)|d n|}| jdt	
|r4|nddd | jdt	
|dd d| _d S | jdt	
ddd | jdt	
ddd d S )	NF   r   sumdefaultdist_reduce_fxr   T )super__init__r
   r   r   r   r   _is_initialized	add_statetorchzeros)selfr   r   r   r   r   	__class__r&   _/home/ubuntu/sommelier/.venv/lib/python3.10/site-packages/torchmetrics/segmentation/mean_iou.pyr(   j   s   
zMeanIoU.__init__predstargetc           	   
   C   sP  | j s]z|jd | _W n ty  } z	td| d|d}~ww | jdkr/td| j d| js7| jd n| j}| jdtj|| j	| j
dd	d
 | jdtj|| j	tjdd	d
 d| _ t||| j| j| j\}}t||dd}|dk}| jr|  j|| jdd7  _|  j|jdd7  _dS |  j||  7  _|  j| 7  _dS )z#Update the state with the new data.r!   z4Cannot determine `num_classes` from `preds` tensor: .Nr   zBExpected argument `num_classes` to be a positive integer, but got r   )devicedtyper"   r#   r   Tr   )zero_division)dim)r)   shaper   
IndexError
ValueErrorr   r*   r+   r,   r4   r5   int32r	   r   r   r   r   r"   r   )	r-   r1   r2   errnum_out_classesintersectionunionr   valid_classesr&   r&   r0   update   sB   
zMeanIoU.updatec                 C   s$   | j | j }| jr|dS | S )z6Compute the final Mean Intersection over Union (mIoU).g      )r   r   r   
nan_to_numnanmean)r-   output_scorer&   r&   r0   compute   s   zMeanIoU.computevalaxc                 C   s   |  ||S )ab  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.audio import PerceptualEvaluationSpeechQuality
            >>> metric = PerceptualEvaluationSpeechQuality(8000, 'nb')
            >>> metric.update(torch.rand(8000), torch.rand(8000))
            >>> fig_, ax_ = metric.plot()

        .. plot::
            :scale: 75

            >>> # Example plotting multiple values
            >>> import torch
            >>> from torchmetrics.audio import PerceptualEvaluationSpeechQuality
            >>> metric = PerceptualEvaluationSpeechQuality(8000, 'nb')
            >>> values = [ ]
            >>> for _ in range(10):
            ...     values.append(metric(torch.rand(8000), torch.rand(8000)))
            >>> fig_, ax_ = metric.plot(values)

        )_plot)r-   rF   rG   r&   r&   r0   plot   s   &r   )NTFr   )NN)__name__
__module____qualname____doc__r   __annotations__r   boolr   r   r   floatr   r   intr   r   r(   rA   rE   r   r   r   r   rI   __classcell__r&   r&   r.   r0   r      s:   
 C'2r   )collections.abcr   typingr   r   r   r+   r   typing_extensionsr   -torchmetrics.functional.segmentation.mean_iour   r	   r
   torchmetrics.metricr   torchmetrics.utilities.importsr   torchmetrics.utilities.plotr   r   __doctest_skip__r   r&   r&   r&   r0   <module>   s   