a
    dmD                     @   s   d dl mZmZmZmZmZ d dlZd dlmZ d dlm	Z	m
Z
mZ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 esdd	gZG d
d deZG dd deZdS )    )Any
CollectionOptionalSequenceUnionN)Tensor)!_get_category_id_to_continuous_id_get_void_color_panoptic_quality_compute_panoptic_quality_update_parse_categories_prepocess_inputs_validate_inputs)Metric)_MATPLOTLIB_AVAILABLE)_AX_TYPE_PLOT_OUT_TYPEPanopticQuality.plotModifiedPanopticQuality.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d< eed< eed< eed< dee ee eedd fddZeeddddZedddZdeeeee f  ee edddZ  ZS )PanopticQualitya(  Compute the `Panoptic Quality`_ for panoptic segmentations.

    .. math::
        PQ = \frac{IOU}{TP + 0.5 FP + 0.5 FN}

    where IOU, TP, FP and FN are respectively the sum of the intersection over union for true positives,
    the number of true postitives, false positives and false negatives. This metric is inspired by the PQ
    implementation of panopticapi, a standard implementation for the PQ metric for panoptic segmentation.

    .. note:
        Points in the target tensor that do not map to a known category ID are automatically ignored in the metric
        computation.

    Args:
        things:
            Set of ``category_id`` for countable things.
        stuffs:
            Set of ``category_id`` for uncountable stuffs.
        allow_unknown_preds_category:
            Boolean flag to specify if unknown categories in the predictions are to be ignored in the metric
            computation or raise an exception when found.


    Raises:
        ValueError:
            If ``things``, ``stuffs`` have at least one common ``category_id``.
        TypeError:
            If ``things``, ``stuffs`` contain non-integer ``category_id``.

    Example:
        >>> from torch import tensor
        >>> from torchmetrics.detection import PanopticQuality
        >>> preds = tensor([[[[6, 0], [0, 0], [6, 0], [6, 0]],
        ...                  [[0, 0], [0, 0], [6, 0], [0, 1]],
        ...                  [[0, 0], [0, 0], [6, 0], [0, 1]],
        ...                  [[0, 0], [7, 0], [6, 0], [1, 0]],
        ...                  [[0, 0], [7, 0], [7, 0], [7, 0]]]])
        >>> target = tensor([[[[6, 0], [0, 1], [6, 0], [0, 1]],
        ...                   [[0, 1], [0, 1], [6, 0], [0, 1]],
        ...                   [[0, 1], [0, 1], [6, 0], [1, 0]],
        ...                   [[0, 1], [7, 0], [1, 0], [1, 0]],
        ...                   [[0, 1], [7, 0], [7, 0], [7, 0]]]])
        >>> panoptic_quality = PanopticQuality(things = {0, 1}, stuffs = {6, 7})
        >>> panoptic_quality(preds, target)
        tensor(0.5463, dtype=torch.float64)

    Fis_differentiableThigher_is_betterfull_state_update        plot_lower_bound      ?plot_upper_boundiou_sumtrue_positivesfalse_positivesfalse_negativesNthingsstuffsallow_unknown_preds_categorykwargsreturnc                    s   t  jf i | t||\}}|| _|| _t||| _t||| _|| _	t
|t
| }| jdtj|tjddd | jdtj|tjddd | jdtj|tjddd | jdtj|tjddd d S Nr   )Zdtypesum)defaultZdist_reduce_fxr   r   r    super__init__r   r"   r#   r	   
void_colorr   cat_id_to_continuous_idr$   lenZ	add_statetorchzerosdoubleintselfr"   r#   r$   r%   Zn_categories	__class__ r/var/www/html/stable-diffusion-webui/venv/lib/python3.9/site-packages/torchmetrics/detection/panoptic_qualities.pyr,   _   s    zPanopticQuality.__init__predstargetr&   c           	      C   s   t || t| j| j|| j| j}t| j| j|| jd}t||| j| j\}}}}|  j|7  _|  j	|7  _	|  j
|7  _
|  j|7  _dS )  Update state with predictions and targets.

        Args:
            preds: panoptic detection of shape ``[batch, *spatial_dims, 2]`` containing
                the pair ``(category_id, instance_id)`` for each point.
                If the ``category_id`` refer to a stuff, the instance_id is ignored.

            target: ground truth of shape ``[batch, *spatial_dims, 2]`` containing
                the pair ``(category_id, instance_id)`` for each pixel of the image.
                If the ``category_id`` refer to a stuff, the instance_id is ignored.

        Raises:
            TypeError:
                If ``preds`` or ``target`` is not an ``torch.Tensor``.
            ValueError:
                If ``preds`` and ``target`` have different shape.
            ValueError:
                If ``preds`` has less than 3 dimensions.
            ValueError:
                If the final dimension of ``preds`` has size != 2.

        TNr   r   r"   r#   r-   r$   r   r.   r   r   r   r    	r5   r;   r<   Zflatten_predsZflatten_targetr   r   r   r    r8   r8   r9   updatev   s    
zPanopticQuality.updater&   c                 C   s   t | j| j| j| jS zLCompute panoptic quality based on inputs passed in to ``update`` previously.r
   r   r   r   r    r5   r8   r8   r9   compute   s    zPanopticQuality.computevalaxr&   c                 C   s   |  ||S )aX
  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 object and Axes object

        Raises:
            ModuleNotFoundError:
                If `matplotlib` is not installed

        .. plot::
            :scale: 75

            >>> from torch import tensor
            >>> from torchmetrics.detection import PanopticQuality
            >>> preds = tensor([[[[6, 0], [0, 0], [6, 0], [6, 0]],
            ...                  [[0, 0], [0, 0], [6, 0], [0, 1]],
            ...                  [[0, 0], [0, 0], [6, 0], [0, 1]],
            ...                  [[0, 0], [7, 0], [6, 0], [1, 0]],
            ...                  [[0, 0], [7, 0], [7, 0], [7, 0]]]])
            >>> target = tensor([[[[6, 0], [0, 1], [6, 0], [0, 1]],
            ...                   [[0, 1], [0, 1], [6, 0], [0, 1]],
            ...                   [[0, 1], [0, 1], [6, 0], [1, 0]],
            ...                   [[0, 1], [7, 0], [1, 0], [1, 0]],
            ...                   [[0, 1], [7, 0], [7, 0], [7, 0]]]])
            >>> metric = PanopticQuality(things = {0, 1}, stuffs = {6, 7})
            >>> metric.update(preds, target)
            >>> fig_, ax_ = metric.plot()

        .. plot::
            :scale: 75

            >>> # Example plotting multiple values
            >>> from torch import tensor
            >>> from torchmetrics.detection import PanopticQuality
            >>> preds = tensor([[[[6, 0], [0, 0], [6, 0], [6, 0]],
            ...                  [[0, 0], [0, 0], [6, 0], [0, 1]],
            ...                  [[0, 0], [0, 0], [6, 0], [0, 1]],
            ...                  [[0, 0], [7, 0], [6, 0], [1, 0]],
            ...                  [[0, 0], [7, 0], [7, 0], [7, 0]]]])
            >>> target = tensor([[[[6, 0], [0, 1], [6, 0], [0, 1]],
            ...                   [[0, 1], [0, 1], [6, 0], [0, 1]],
            ...                   [[0, 1], [0, 1], [6, 0], [1, 0]],
            ...                   [[0, 1], [7, 0], [1, 0], [1, 0]],
            ...                   [[0, 1], [7, 0], [7, 0], [7, 0]]]])
            >>> metric = PanopticQuality(things = {0, 1}, stuffs = {6, 7})
            >>> vals = []
            >>> for _ in range(20):
            ...     vals.append(metric(preds, target))
            >>> fig_, ax_ = metric.plot(vals)

        Z_plotr5   rG   rH   r8   r8   r9   plot   s    ;r   )F)NN__name__
__module____qualname____doc__r   bool__annotations__r   r   r   floatr   r   r   r3   r   r,   r@   rE   r   r   r   r   r   rK   __classcell__r8   r8   r6   r9   r   $   s2   
/ $ r   c                       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d< eed< eed< eed< dee ee eedd fddZeeddddZedddZdeeeee f  ee edddZ  ZS )ModifiedPanopticQualitya  Compute `Modified Panoptic Quality`_ for panoptic segmentations.

    The metric was introduced in `Seamless Scene Segmentation paper`_, and is an adaptation of the original
    `Panoptic Quality`_ where the metric for a stuff class is computed as

    .. math::
        PQ^{\dagger}_c = \frac{IOU_c}{|S_c|}

    where :math:`IOU_c` is the sum of the intersection over union of all matching segments for a given class, and
    :math:`|S_c|` is the overall number of segments in the ground truth for that class.

    .. note:
        Points in the target tensor that do not map to a known category ID are automatically ignored in the metric
        computation.

    Args:
        things:
            Set of ``category_id`` for countable things.
        stuffs:
            Set of ``category_id`` for uncountable stuffs.
        allow_unknown_preds_category:
            Boolean flag to specify if unknown categories in the predictions are to be ignored in the metric
            computation or raise an exception when found.


    Raises:
        ValueError:
            If ``things``, ``stuffs`` have at least one common ``category_id``.
        TypeError:
            If ``things``, ``stuffs`` contain non-integer ``category_id``.

    Example:
        >>> from torch import tensor
        >>> from torchmetrics.detection import ModifiedPanopticQuality
        >>> preds = tensor([[[0, 0], [0, 1], [6, 0], [7, 0], [0, 2], [1, 0]]])
        >>> target = tensor([[[0, 1], [0, 0], [6, 0], [7, 0], [6, 0], [255, 0]]])
        >>> pq_modified = ModifiedPanopticQuality(things = {0, 1}, stuffs = {6, 7})
        >>> pq_modified(preds, target)
        tensor(0.7667, dtype=torch.float64)

    Fr   Tr   r   r   r   r   r   r   r   r   r    Nr!   c                    s   t  jf i | t||\}}|| _|| _t||| _t||| _|| _	t
|t
| }| jdtj|tjddd | jdtj|tjddd | jdtj|tjddd | jdtj|tjddd d S r'   r*   r4   r6   r8   r9   r,     s    z ModifiedPanopticQuality.__init__r:   c           	      C   s   t || t| j| j|| j| j}t| j| j|| jd}t||| j| j| jd\}}}}|  j|7  _|  j	|7  _	|  j
|7  _
|  j|7  _dS )r=   T)Zmodified_metric_stuffsNr>   r?   r8   r8   r9   r@   (  s     
zModifiedPanopticQuality.updaterA   c                 C   s   t | j| j| j| jS rB   rC   rD   r8   r8   r9   rE   P  s    zModifiedPanopticQuality.computerF   c                 C   s   |  ||S )ax
  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 object and Axes object

        Raises:
            ModuleNotFoundError:
                If `matplotlib` is not installed

        .. plot::
            :scale: 75

            >>> from torch import tensor
            >>> from torchmetrics.detection import ModifiedPanopticQuality
            >>> preds = tensor([[[[6, 0], [0, 0], [6, 0], [6, 0]],
            ...                  [[0, 0], [0, 0], [6, 0], [0, 1]],
            ...                  [[0, 0], [0, 0], [6, 0], [0, 1]],
            ...                  [[0, 0], [7, 0], [6, 0], [1, 0]],
            ...                  [[0, 0], [7, 0], [7, 0], [7, 0]]]])
            >>> target = tensor([[[[6, 0], [0, 1], [6, 0], [0, 1]],
            ...                   [[0, 1], [0, 1], [6, 0], [0, 1]],
            ...                   [[0, 1], [0, 1], [6, 0], [1, 0]],
            ...                   [[0, 1], [7, 0], [1, 0], [1, 0]],
            ...                   [[0, 1], [7, 0], [7, 0], [7, 0]]]])
            >>> metric = ModifiedPanopticQuality(things = {0, 1}, stuffs = {6, 7})
            >>> metric.update(preds, target)
            >>> fig_, ax_ = metric.plot()

        .. plot::
            :scale: 75

            >>> # Example plotting multiple values
            >>> from torch import tensor
            >>> from torchmetrics.detection import ModifiedPanopticQuality
            >>> preds = tensor([[[[6, 0], [0, 0], [6, 0], [6, 0]],
            ...                  [[0, 0], [0, 0], [6, 0], [0, 1]],
            ...                  [[0, 0], [0, 0], [6, 0], [0, 1]],
            ...                  [[0, 0], [7, 0], [6, 0], [1, 0]],
            ...                  [[0, 0], [7, 0], [7, 0], [7, 0]]]])
            >>> target = tensor([[[[6, 0], [0, 1], [6, 0], [0, 1]],
            ...                   [[0, 1], [0, 1], [6, 0], [0, 1]],
            ...                   [[0, 1], [0, 1], [6, 0], [1, 0]],
            ...                   [[0, 1], [7, 0], [1, 0], [1, 0]],
            ...                   [[0, 1], [7, 0], [7, 0], [7, 0]]]])
            >>> metric = ModifiedPanopticQuality(things = {0, 1}, stuffs = {6, 7})
            >>> vals = []
            >>> for _ in range(20):
            ...     vals.append(metric(preds, target))
            >>> fig_, ax_ = metric.plot(vals)

        rI   rJ   r8   r8   r9   rK   T  s    ;r   )F)NNrL   r8   r8   r6   r9   rU      s2   
) ( rU   )typingr   r   r   r   r   r0   r   Z:torchmetrics.functional.detection._panoptic_quality_commonr   r	   r
   r   r   r   r   Ztorchmetrics.metricr   Ztorchmetrics.utilities.importsr   Ztorchmetrics.utilities.plotr   r   Z__doctest_skip__r   rU   r8   r8   r8   r9   <module>   s   $	 9