§
    ’©ºjç   ã                   ó¨   — 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sd
gZ G d„ de¦  «        ZdS )é    )ÚSequence)ÚAnyÚOptionalÚUnionN)ÚTensor)ÚLiteral)Ú_generalized_dice_computeÚ_generalized_dice_updateÚ_generalized_dice_validate_args)ÚMetric)Ú_MATPLOTLIB_AVAILABLE)Ú_AX_TYPEÚ_PLOT_OUT_TYPEzGeneralizedDiceScore.plotc                   ó  ‡ — 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dededed         ded         deddfˆ fd„Zdededdfd„Zdefd„Zd"deeee         df         dee         defd „Zˆ xZS )#ÚGeneralizedDiceScorea  Compute `Generalized Dice Score`_.

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

    .. math::
        GDS = \frac{2 \\sum_{i=1}^{N} w_i \\sum_{j} t_{ij} p_{ij}}{
            \\sum_{i=1}^{N} w_i \\sum_{j} t_{ij} + \\sum_{i=1}^{N} w_i \\sum_{j} p_{ij}}

    where :math:`N` is the number of classes, :math:`t_{ij}` is the target tensor, :math:`p_{ij}` is the prediction
    tensor, and :math:`w_i` is the weight for class :math:`i`. The weight can be computed in three different ways:

    - `square`: :math:`w_i = 1 / (\\sum_{j} t_{ij})^2`
    - `simple`: :math:`w_i = 1 / \\sum_{j} t_{ij}`
    - `linear`: :math:`w_i = 1`

    Note that the generalized dice loss can be computed as one minus the generalized dice score.

    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 generalized dice score. If ``per_class`` is set to ``True``, the output
          will be a tensor of shape ``(C,)`` with the generalized dice 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.
        include_background: Whether to include the background class in the computation
        per_class: Whether to compute the metric for each class separately.
        weight_type: The type of weight to apply to each class. Can be one of ``"square"``, ``"simple"``, or
            ``"linear"``.
        input_format: What kind of input the function receives.
            Choose between ``"one-hot"`` for one-hot encoded tensors, ``"index"`` for index tensors
            or ``"mixed"`` for one one-hot encoded and one index tensor
        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 ``per_class`` is not a boolean
        ValueError:
            If ``weight_type`` is not one of ``"square"``, ``"simple"``, or ``"linear"``
        ValueError:
            If ``input_format`` is not one of ``"one-hot"``, ``"index"`` or ``"mixed"``

    Example:
        >>> from torch import randint
        >>> from torchmetrics.segmentation import GeneralizedDiceScore
        >>> gds = GeneralizedDiceScore(num_classes=3)
        >>> preds = randint(0, 2, (10, 3, 128, 128))
        >>> target = randint(0, 2, (10, 3, 128, 128))
        >>> gds(preds, target)
        tensor(0.4992)
        >>> gds = GeneralizedDiceScore(num_classes=3, per_class=True)
        >>> gds(preds, target)
        tensor([0.5001, 0.4993, 0.4982])
        >>> gds = GeneralizedDiceScore(num_classes=3, per_class=True, include_background=False)
        >>> gds(preds, target)
        tensor([0.4993, 0.4982])

    ÚscoreÚsamplesFÚfull_state_updateÚis_differentiableTÚhigher_is_betterg        Úplot_lower_boundg      ð?Úplot_upper_boundÚsquareúone-hotÚnum_classesÚinclude_backgroundÚ	per_classÚweight_type)r   ÚsimpleÚlinearÚinput_format)r   ÚindexÚmixedÚkwargsÚreturnNc                 óh  •—  t          ¦   «         j        di |¤Ž t          |||||¦  «         || _        || _        || _        || _        || _        |s|dz
  n|}|                      dt          j
        |r|nd¦  «        d¬¦  «         |                      dt          j
        d¦  «        d¬¦  «         d S )Né   r   Úsum)ÚdefaultÚdist_reduce_fxr   © )ÚsuperÚ__init__r   r   r   r   r   r!   Ú	add_stateÚtorchÚzeros)Úselfr   r   r   r   r!   r$   Ú	__class__s          €úz/root/private/project/pallet_detection_v2/.venv/lib/python3.11/site-packages/torchmetrics/segmentation/generalized_dice.pyr-   zGeneralizedDiceScore.__init__v   sÇ   ø€ ð 	�‰ŒÔÐ"Ð"˜6Ð"Ð"Ð"Ý'¨Ð5GÈÐT_ÐamÑnÔnÐnØ&ˆÔØ"4ˆÔØ"ˆŒØ&ˆÔØ(ˆÔà-?ÐP�k A‘o�oÀ[ˆØ�Š�w­¬À9Ð4S°K°KÐRSÑ(TÔ(TÐejˆÑkÔkÐkØ�Š�y­%¬+°a©.¬.ÈˆÑOÔOÐOÐOÐOó    ÚpredsÚtargetc                 ó  — t          ||| j        | j        | j        | j        ¦  «        \  }}| xj        t          ||| j        ¦  «                             d¬¦  «        z  c_        | xj	        |j
        d         z  c_	        dS )zUpdate the state with new data.r   )ÚdimN)r
   r   r   r   r!   r   r	   r   r(   r   Úshape)r1   r5   r6   Ú	numeratorÚdenominators        r3   ÚupdatezGeneralizedDiceScore.update‹   s}   € å!9Ø�6˜4Ô+¨TÔ-DÀdÔFVÐX\ÔXiñ"
ô "
Ñˆ	�;ð 	ˆ
Œ
Õ/°	¸;ÈÌÑWÔW×[Ò[Ð`aÐ[ÑbÔbÑbˆ
Œ
ØˆŒ˜œ AœÑ&ˆŒˆˆr4   c                 ó    — | j         | j        z  S )z)Compute the final generalized dice score.)r   r   )r1   s    r3   ÚcomputezGeneralizedDiceScore.compute“   s   € àŒz˜DœLÑ(Ð(r4   ÚvalÚaxc                 ó.   — |                       ||¦  «        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 GeneralizedDiceScore
            >>> metric = GeneralizedDiceScore(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 GeneralizedDiceScore
            >>> metric = GeneralizedDiceScore(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)r1   r?   r@   s      r3   ÚplotzGeneralizedDiceScore.plot—   s   € ðP �zŠz˜#˜rÑ"Ô"Ð"r4   )TFr   r   )NN)Ú__name__Ú
__module__Ú__qualname__Ú__doc__r   Ú__annotations__r   Úboolr   r   r   Úfloatr   Úintr   r   r-   r<   r>   r   r   r   r   r   rC   Ú__classcell__)r2   s   @r3   r   r   "   s°  ø€ € € € € € ðIð IðV €M€M�MØ€O€O�OØ#Ð�tÐ#Ð#Ñ#Ø#Ð�tÐ#Ð#Ñ#Ø!Ð�dÐ!Ð!Ñ!Ø!Ð�eÐ!Ð!Ñ!Ø!Ð�eÐ!Ð!Ñ!ð
 $(ØØ=EØ=FðPð PàðPð !ðPð ð	Pð
 Ð9Ô:ðPð Ð9Ô:ðPð ðPð 
ðPð Pð Pð Pð Pð Pð*'˜Fð '¨Fð '°tð 'ð 'ð 'ð 'ð)˜ð )ð )ð )ð )ð(#ð (#˜˜f h¨vÔ&6¸Ð<Ô=ð (#È(ÐS[ÔJ\ð (#Ðhvð (#ð (#ð (#ð (#ð (#ð (#ð (#ð (#r4   r   )Úcollections.abcr   Útypingr   r   r   r/   r   Útyping_extensionsr   Ú5torchmetrics.functional.segmentation.generalized_dicer	   r
   r   Útorchmetrics.metricr   Útorchmetrics.utilities.importsr   Útorchmetrics.utilities.plotr   r   Ú__doctest_skip__r   r+   r4   r3   ú<module>rU      s#  ðð %Ð $Ð $Ð $Ð $Ð $Ø 'Ð 'Ð 'Ð 'Ð 'Ð 'Ð 'Ð 'Ð 'Ð 'à €€€Ø Ð Ð Ð Ð Ð Ø %Ð %Ð %Ð %Ð %Ð %ðð ð ð ð ð ð ð ð ð ð
 'Ð &Ð &Ð &Ð &Ð &Ø @Ð @Ð @Ð @Ð @Ð @Ø @Ð @Ð @Ð @Ð @Ð @Ð @Ð @àð 5Ø3Ð4Ðð]#ð ]#ð ]#ð ]#ð ]#˜6ñ ]#ô ]#ð ]#ð ]#ð ]#r4   