§
    ’©ºj‹3  ã                   óÊ   — d dl mZ d dlmZmZmZmZ d dlZd dlmZ d dl	m
Z
mZ d dlmZmZ d dlmZ d dlmZ d d	lmZmZ d d
lmZmZ esddgZnesdgZ G d„ de¦  «        ZdS )é    )ÚSequence)ÚAnyÚListÚOptionalÚUnionN)ÚTensor)Ú_fix_empty_tensorsÚ_input_validator)Ú_iou_computeÚ_iou_update)ÚMetric)Údim_zero_cat)Ú_MATPLOTLIB_AVAILABLEÚ_TORCHVISION_AVAILABLE)Ú_AX_TYPEÚ_PLOT_OUT_TYPEÚIntersectionOverUnionzIntersectionOverUnion.plotc                   óð  ‡ — e Zd ZU dZdZeed<   dZee         ed<   dZ	eed<   e
e         ed<   e
e         ed<   e
e         ed	<   d
Zeed<   dZeed<   	 	 	 	 d$dedee         dedededdfˆ fd„Zedededefd„¦   «         Zedededefd„¦   «         Zdeeeef                  deeeef                  ddfd„Zdedefd„Zdefd„Zdefd „Z	 d%d!eeeee         f                  d"ee         defd#„Zˆ xZ S )&r   aÍ  Computes Intersection Over Union (IoU).

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

    - ``preds`` (:class:`~List`): A list consisting of dictionaries each containing the key-values
      (each dictionary corresponds to a single image). Parameters that should be provided per dict:

        - ``boxes`` (:class:`~torch.Tensor`): float tensor of shape ``(num_boxes, 4)`` containing ``num_boxes``
          detection boxes of the format specified in the constructor.
          By default, this method expects ``(xmin, ymin, xmax, ymax)`` in absolute image coordinates.
        - labels: ``IntTensor`` of shape ``(num_boxes)`` containing 0-indexed detection classes for
          the boxes.

    - ``target`` (:class:`~List`): A list consisting of dictionaries each containing the key-values
      (each dictionary corresponds to a single image). Parameters that should be provided per dict:

        - ``boxes`` (:class:`~torch.Tensor`): float tensor of shape ``(num_boxes, 4)`` containing ``num_boxes`` ground
          truth boxes of the format specified in the constructor.
          By default, this method expects ``(xmin, ymin, xmax, ymax)`` in absolute image coordinates.
        - ``labels`` (:class:`~torch.Tensor`): integer tensor of shape ``(num_boxes)`` containing 0-indexed ground truth
          classes for the boxes.

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

    - ``iou_dict``: A dictionary containing the following key-values:

        - iou: (:class:`~torch.Tensor`)
        - iou/cl_{cl}: (:class:`~torch.Tensor`), if argument ``class metrics=True``

    Args:
        box_format:
            Input format of given boxes. Supported formats are ``[`xyxy`, `xywh`, `cxcywh`]``.
        iou_thresholds:
            Optional IoU thresholds for evaluation. If set to `None` the threshold is ignored.
        class_metrics:
            Option to enable per-class metrics for IoU. Has a performance impact.
        respect_labels:
            Ignore values from boxes that do not have the same label as the ground truth box. Else will compute Iou
                between all pairs of boxes.
        kwargs:
            Additional keyword arguments, see :ref:`Metric kwargs` for more info.

    Example::

        >>> import torch
        >>> from torchmetrics.detection import IntersectionOverUnion
        >>> preds = [
        ...    {
        ...        "boxes": torch.tensor([
        ...             [296.55, 93.96, 314.97, 152.79],
        ...             [298.55, 98.96, 314.97, 151.79]]),
        ...        "labels": torch.tensor([4, 5]),
        ...    }
        ... ]
        >>> target = [
        ...    {
        ...        "boxes": torch.tensor([[300.00, 100.00, 315.00, 150.00]]),
        ...        "labels": torch.tensor([5]),
        ...    }
        ... ]
        >>> metric = IntersectionOverUnion()
        >>> metric(preds, target)
        {'iou': tensor(0.8614)}

    Example::

        The metric can also return the score per class:

        >>> import torch
        >>> from torchmetrics.detection import IntersectionOverUnion
        >>> preds = [
        ...    {
        ...        "boxes": torch.tensor([
        ...             [296.55, 93.96, 314.97, 152.79],
        ...             [298.55, 98.96, 314.97, 151.79]]),
        ...        "labels": torch.tensor([4, 5]),
        ...    }
        ... ]
        >>> target = [
        ...    {
        ...        "boxes": torch.tensor([
        ...               [300.00, 100.00, 315.00, 150.00],
        ...               [300.00, 100.00, 315.00, 150.00]
        ...        ]),
        ...        "labels": torch.tensor([4, 5]),
        ...    }
        ... ]
        >>> metric = IntersectionOverUnion(class_metrics=True)
        >>> metric(preds, target)
        {'iou': tensor(0.7756), 'iou/cl_4': tensor(0.6898), 'iou/cl_5': tensor(0.8614)}

    Raises:
        ModuleNotFoundError:
            If torchvision is not installed with version 0.8.0 or newer.

    FÚis_differentiableTÚhigher_is_betterÚfull_state_updateÚgroundtruth_labelsÚpred_labelsÚ
iou_matrixÚiouÚ	_iou_typeg      ð¿Ú_invalid_valÚxyxyNÚ
box_formatÚiou_thresholdÚclass_metricsÚrespect_labelsÚkwargsÚreturnc                 ó*  •—  t          ¦   «         j        di |¤Ž t          s*t          d| j                             ¦   «         › d�¦  «        ‚d}||vrt          d|› d|› �¦  «        ‚|| _        || _        t          |t          ¦  «        st          d¦  «        ‚|| _        t          |t          ¦  «        st          d¦  «        ‚|| _        |                      dg d ¬	¦  «         |                      d
g d ¬	¦  «         |                      dg d ¬	¦  «         d S )NzMetric `zf` requires that `torchvision` is installed. Please install with `pip install torchmetrics[detection]`.)r   ÚxywhÚcxcywhz,Expected argument `box_format` to be one of z	 but got z1Expected argument `class_metrics` to be a booleanz2Expected argument `respect_labels` to be a booleanr   )ÚdefaultÚdist_reduce_fxr   r   © )ÚsuperÚ__init__r   ÚModuleNotFoundErrorr   ÚupperÚ
ValueErrorr   r    Ú
isinstanceÚboolr!   r"   Ú	add_state)Úselfr   r    r!   r"   r#   Úallowed_box_formatsÚ	__class__s          €új/root/private/project/pallet_detection_v2/.venv/lib/python3.11/site-packages/torchmetrics/detection/iou.pyr,   zIntersectionOverUnion.__init__�   sK  ø€ ð 	�‰ŒÔÐ"Ð"˜6Ð"Ð"Ð"å%ð 	Ý%ðN˜4œ>×/Ò/Ñ1Ô1ð Nð Nð Nñô ð ð
 9ÐØÐ0Ð0Ð0ÝÐvÐL_ÐvÐvÐjtÐvÐvÑwÔwÐwà$ˆŒØ*ˆÔå˜-­Ñ.Ô.ð 	RÝÐPÑQÔQÐQØ*ˆÔå˜.­$Ñ/Ô/ð 	SÝÐQÑRÔRÐRØ,ˆÔà�ŠÐ+°RÈˆÑMÔMÐMØ�Š�}¨bÀˆÑFÔFÐFØ�Š�|¨RÀˆÑEÔEÐEÐEÐEó    Úargsc                  ó   — t          | i |¤ŽS ©N)r   ©r8   r#   s     r6   Ú_iou_update_fnz$IntersectionOverUnion._iou_update_fn°   s   € å˜DÐ+ FÐ+Ð+Ð+r7   c                  ó   — t          | i |¤ŽS r:   )r   r;   s     r6   Ú_iou_compute_fnz%IntersectionOverUnion._iou_compute_fn´   s   € å˜TÐ, VÐ,Ð,Ð,r7   ÚpredsÚtargetc                 ó  — t          ||d¬¦  «         t          ||¦  «        D �]_\  }}|                      |d         ¦  «        }|                      |d         ¦  «        }| j                             |d         ¦  «         | j                             |d         ¦  «         |                      ||| j        | j        ¦  «        }| j	        r | 
                    ¦   «         dk    rQ| 
                    ¦   «         dk    r9|d                              d¦  «        |d                              d¦  «        k    }n,t          j        |j        d         t          |j        ¬¦  «        }| j        || <   | j                             |¦  «         �ŒadS )	z*Update state with predictions and targets.T)Úignore_scoreÚboxesÚlabelsr   é   )ÚdtypeÚdeviceN)r
   ÚzipÚ_get_safe_item_valuesr   Úappendr   r<   r    r   r"   ÚnumelÚ	unsqueezeÚtorchÚeyeÚshaper1   rG   r   )	r3   r?   r@   Úp_iÚt_iÚ	det_boxesÚgt_boxesr   Úlabel_eqs	            r6   ÚupdatezIntersectionOverUnion.update¸   sq  € å˜ °TÐ:Ñ:Ô:Ð:å˜E 6Ñ*Ô*ð 	/ñ 	/‰HˆC�Ø×2Ò2°3°w´<Ñ@Ô@ˆIØ×1Ò1°#°g´,Ñ?Ô?ˆHØÔ#×*Ò*¨3¨x¬=Ñ9Ô9Ð9ØÔ×#Ò# C¨¤MÑ2Ô2Ð2à×,Ò,¨Y¸À$ÔBTÐVZÔVgÑhÔhˆJØÔ"ð :Ø—?’?Ñ$Ô$ qÒ(Ð(¨X¯^ª^Ñ-=Ô-=ÀÒ-AÐ-AØ" 8œ}×6Ò6°qÑ9Ô9¸SÀ¼]×=TÒ=TÐUVÑ=WÔ=WÒW�H�Hå$œy¨Ô)9¸!Ô)<ÅDÐQ[ÔQbÐcÑcÔc�HØ(,Ô(9�
˜H˜9Ñ%ØŒO×"Ò" :Ñ.Ô.Ð.Ñ.ð	/ð 	/r7   rC   c                 ó†   — ddl m} t          |¦  «        }|                     ¦   «         dk    r ||| j        d¬¦  «        }|S )Nr   )Úbox_convertr   )Úin_fmtÚout_fmt)Útorchvision.opsrW   r	   rK   r   )r3   rC   rW   s      r6   rI   z+IntersectionOverUnion._get_safe_item_valuesË   sQ   € Ø/Ð/Ð/Ð/Ð/Ð/å" 5Ñ)Ô)ˆØ�;Š;‰=Œ=˜1ÒÐØ�K ¨d¬oÀvÐNÑNÔNˆEØˆr7   c                 ó°   — t          | j        ¦  «        dk    r=t          j        | j        ¦  «                             ¦   «                              ¦   «         S g S )zJReturns a list of unique classes found in ground truth and detection data.r   )Úlenr   rM   ÚcatÚuniqueÚtolist)r3   s    r6   Ú_get_gt_classesz%IntersectionOverUnion._get_gt_classesÓ   sH   € åˆtÔ&Ñ'Ô'¨!Ò+Ð+Ý”9˜TÔ4Ñ5Ô5×<Ò<Ñ>Ô>×EÒEÑGÔGÐGØˆ	r7   c                 ó^  ‡ — ˆ fd„‰ j         D ¦   «         }|r't          j        |d¦  «                             ¦   «         nt          j        d‰ j        ¬¦  «        }‰ j        › |i}t          j        |¦  «        r$t          j        d|j        ¬¦  «        |‰ j        › <   ‰ j        �rŠt          t          ‰ j
        ¦  «        t          ‰ j        ¦  «        g¦  «        }|                     ¦   «         dk    r&|                     ¦   «                              ¦   «         ng }|D �]}t          j        |¦  «        }t          j        |¦  «        }t!          ‰ j         ‰ j
        ¦  «        D ]T\  }	}
|	dd…|
|k    f         }||‰ j        k             }||                     ¦   «         z  }||                     ¦   «         z  }ŒU|                     ¦   «         dk    r;|                     ‰ j        › d|› �t          j        d|j        ¬¦  «        i¦  «         Œí|                     ‰ j        › d|› �||z  i¦  «         �Œ|S )z@Computes IoU based on inputs passed in to ``update`` previously.c                 ól   •— g | ]0}t          j        |‰j        k    ¦  «        ¯||‰j        k             ‘Œ1S r*   )rM   Úanyr   )Ú.0Úmatr3   s     €r6   ú
<listcomp>z1IntersectionOverUnion.compute.<locals>.<listcomp>Ü   sO   ø€ ð 
ð 
ð 
Ø.1ÍÌ	ÐRUÐY]ÔYjÒRjÑHkÔHkð
Ø��tÔ(Ò(Ô)ð
ð 
ð 
r7   r   g        )rG   Nz/cl_)r   rM   r]   ÚmeanÚtensorrG   r   Úisnanr!   r   r   r   rK   r^   r_   Ú
zeros_likerH   r   ÚsumÚitemrU   )r3   Úvalid_matricesÚscoreÚresultsÚ
all_labelsÚclassesÚclÚ
masked_iouÚobservedre   Úgt_labÚscoresÚvalid_scoress   `            r6   ÚcomputezIntersectionOverUnion.computeÙ   sH  ø€ ð
ð 
ð 
ð 
Ø59´_ð
ñ 
ô 
ˆð 8FÐp•”	˜.¨!Ñ,Ô,×1Ò1Ñ3Ô3Ð3Í5Ì<ÐX[ÐdhÔdoÐKpÑKpÔKpˆØ)-¬Ð&9¸5Ð%AˆÝŒ;�uÑÔð 	RÝ+0¬<¸ÀEÄLÐ+QÑ+QÔ+QˆG�t”~Ð'Ñ(ØÔñ 	Yå%¥|°DÔ4KÑ'LÔ'LÍlÐ[_Ô[kÑNlÔNlÐ&mÑnÔnˆJØ6@×6FÒ6FÑ6HÔ6HÈ1Ò6LÐ6L�j×'Ò'Ñ)Ô)×0Ò0Ñ2Ô2Ð2ÐRTˆGØð Yñ Y�Ý"Ô-¨eÑ4Ô4�
Ý Ô+¨EÑ2Ô2�å#& t¤¸Ô8OÑ#PÔ#Pð 5ð 5‘K�C˜Ø     F¨b¢L Ô1�FØ#)¨&°DÔ4EÒ*EÔ#F�LØ ,×"2Ò"2Ñ"4Ô"4Ñ4�JØ × 2Ò 2Ñ 4Ô 4Ñ4�H�Hà—=’=‘?”? aÒ'Ð'Ø—N’N t¤~Ð$?Ð$?¸2Ð$?Ð$?ÅÄÈcÐZ_ÔZfÐAgÑAgÔAgÐ#hÑiÔiÐiÐià—N’N t¤~Ð$?Ð$?¸2Ð$?Ð$?ÀÈhÑAVÐ#WÑXÔXÐXÑXØˆr7   Ú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 object and Axes object

        Raises:
            ModuleNotFoundError:
                If `matplotlib` is not installed

        .. plot::
            :scale: 75

            >>> import torch
            >>> from torchmetrics.detection import IntersectionOverUnion
            >>> preds = [
            ...    {
            ...        "boxes": torch.tensor([[296.55, 93.96, 314.97, 152.79], [298.55, 98.96, 314.97, 151.79]]),
            ...        "scores": torch.tensor([0.236, 0.56]),
            ...        "labels": torch.tensor([4, 5]),
            ...    }
            ... ]
            >>> target = [
            ...    {
            ...        "boxes": torch.tensor([[300.00, 100.00, 315.00, 150.00]]),
            ...        "labels": torch.tensor([5]),
            ...    }
            ... ]
            >>> metric = IntersectionOverUnion()
            >>> metric.update(preds, target)
            >>> fig_, ax_ = metric.plot()

        .. plot::
            :scale: 75

            >>> # Example plotting multiple values
            >>> import torch
            >>> from torchmetrics.detection import IntersectionOverUnion
            >>> preds = [
            ...    {
            ...        "boxes": torch.tensor([[296.55, 93.96, 314.97, 152.79], [298.55, 98.96, 314.97, 151.79]]),
            ...        "scores": torch.tensor([0.236, 0.56]),
            ...        "labels": torch.tensor([4, 5]),
            ...    }
            ... ]
            >>> target = lambda : [
            ...    {
            ...        "boxes": torch.tensor([[300.00, 100.00, 315.00, 150.00]]) + torch.randint(-10, 10, (1, 4)),
            ...        "labels": torch.tensor([5]),
            ...    }
            ... ]
            >>> metric = IntersectionOverUnion()
            >>> vals = []
            >>> for _ in range(20):
            ...     vals.append(metric(preds, target()))
            >>> fig_, ax_ = metric.plot(vals)

        )Ú_plot)r3   ry   rz   s      r6   ÚplotzIntersectionOverUnion.plot÷   s   € ðB �zŠz˜#˜rÑ"Ô"Ð"r7   )r   NFT)NN)!Ú__name__Ú
__module__Ú__qualname__Ú__doc__r   r1   Ú__annotations__r   r   r   r   r   r   Ústrr   Úfloatr   r,   Ústaticmethodr<   r>   ÚlistÚdictrU   rI   r`   rx   r   r   r   r   r}   Ú__classcell__)r5   s   @r6   r   r   !   sš  ø€ € € € € € ð_ð _ðB $Ð�tÐ#Ð#Ñ#Ø'+Ð�h˜t”nÐ+Ð+Ñ+Ø"Ð�tÐ"Ð"Ñ"à˜VœÐ$Ð$Ñ$Ø�f”ÐÐÑØ�V”ÐÐÑØ€IˆsÐÐÑØ€L�%ÐÐÑð !Ø)-Ø#Ø#ð!Fð !Fàð!Fð   ”ð!Fð ð	!Fð
 ð!Fð ð!Fð 
ð!Fð !Fð !Fð !Fð !Fð !FðF ð,˜cð ,¨Sð ,°Vð ,ð ,ð ,ñ „\ð,ð ð-˜sð -¨cð -°fð -ð -ð -ñ „\ð-ð/˜D  c¨6 kÔ!2Ô3ð /¸TÀ$ÀsÈFÀ{ÔBSÔ=Tð /ÐY]ð /ð /ð /ð /ð&¨6ð °fð ð ð ð ð ð ð ð ð ð˜ð ð ð ð ð> _cðA#ð A#Ø˜E &¨(°6Ô*:Ð":Ô;Ô<ðA#ØIQÐRZÔI[ðA#à	ðA#ð A#ð A#ð A#ð A#ð A#ð A#ð A#r7   )Úcollections.abcr   Útypingr   r   r   r   rM   r   Útorchmetrics.detection.helpersr	   r
   Ú%torchmetrics.functional.detection.iour   r   Útorchmetrics.metricr   Útorchmetrics.utilities.datar   Útorchmetrics.utilities.importsr   r   Útorchmetrics.utilities.plotr   r   Ú__doctest_skip__r   r*   r7   r6   ú<module>r’      sB  ðð %Ð $Ð $Ð $Ð $Ð $Ø -Ð -Ð -Ð -Ð -Ð -Ð -Ð -Ð -Ð -Ð -Ð -à €€€Ø Ð Ð Ð Ð Ð à OÐ OÐ OÐ OÐ OÐ OÐ OÐ OØ KÐ KÐ KÐ KÐ KÐ KÐ KÐ KØ &Ð &Ð &Ð &Ð &Ð &Ø 4Ð 4Ð 4Ð 4Ð 4Ð 4Ø XÐ XÐ XÐ XÐ XÐ XÐ XÐ XØ @Ð @Ð @Ð @Ð @Ð @Ð @Ð @àð 6Ø/Ð1MÐNÐÐØ	ð 6Ø4Ð5ÐðW#ð W#ð W#ð W#ð W#˜Fñ W#ô W#ð W#ð W#ð W#r7   