
    /j                      d Z ddlmZ ddlZddlZddlmZ ddlmZ ddl	m
Z
 ddlZddlZddlmZmZmZmZmZmZ  ej        g dej        	          d
z  Z ej        g d          ZdbdcdZdddedZ	 	 	 	 	 dfdgdZdddhd!Z	 dddid'Zdjd*Zdbdkd-Zdddld/Z dmdnd2Z! G d3 d4e          Z"dodpd8Z# e             ed9          i dfdqdA            Z$ e             edB          i dCdDdfdrdH            Z%dsdLZ&dd e            i dMdNfdtdVZ' G dW dDe          Z( G dX dYee          Z) G dZ d[e)          Z* G d\ d]e)          Z+ G d^ d_ee          Z, G d` dae)          Z-dS )uzModel validation metrics.    )annotationsN)defaultdict)Path)Any)LOGGERDataExportMixinSimpleClass	TryExceptchecksplt_settings)gp=
ף?      ?r   ffffff?r   HzG?r   
ףp=
?r   ףp=
?r   Q?r   ףp=
?r   {Gz?r   )dtypeg      $@)      ?r   r   r   r   r   r   333333?r         ?r   r   r   r   r   r   r   FHz>box1
np.ndarraybox2iouboolepsfloatreturnc                   | j         \  }}}}|j         \  }}	}
}t          j        |dddf         |
          t          j        |dddf         |          z
                      d          t          j        |dddf         |          t          j        |dddf         |	          z
                      d          z  }|
|z
  ||	z
  z  }|r||z
  ||z
  z  }||dddf         z   |z
  }|||z   z  S )a?  Calculate the intersection over box2 area given box1 and box2.

    Args:
        box1 (np.ndarray): A numpy array of shape (N, 4) representing N bounding boxes in x1y1x2y2 format.
        box2 (np.ndarray): A numpy array of shape (M, 4) representing M bounding boxes in x1y1x2y2 format.
        iou (bool, optional): Calculate the standard IoU if True else return inter_area/box2_area.
        eps (float, optional): A small value to avoid division by zero.

    Returns:
        (np.ndarray): A numpy array of shape (N, M) representing the intersection over box2 area.
    Nr   )Tnpminimummaximumclip)r   r   r   r   b1_x1b1_y1b1_x2b1_y2b2_x1b2_y1b2_x2b2_y2
inter_areaarea	box1_areas                  ^/home/longshao/multi-rider-rag/.venv/lib/python3.11/site-packages/ultralytics/utils/metrics.pybbox_ioar4      s    "&E5%!%E5% *U111d7^U33bjqqq$wQV6W6WW]]^_``

5D>5))BJuQQQW~u,M,MM
d1ggJ
 EMeem,D
 6U]uu}5	i4((:5 $$    torch.Tensorc                   |                                                      d                              dd          |                                                     d                              dd          c\  }}\  }}t          j        ||          t          j        ||          z
                      d                              d          }|||z
                      d          ||z
                      d          z   |z
  |z   z  S )aB  Calculate intersection-over-union (IoU) of boxes.

    Args:
        box1 (torch.Tensor): A tensor of shape (N, 4) representing N bounding boxes in (x1, y1, x2, y2) format.
        box2 (torch.Tensor): A tensor of shape (M, 4) representing M bounding boxes in (x1, y1, x2, y2) format.
        eps (float, optional): A small value to avoid division by zero.

    Returns:
        (torch.Tensor): An NxM tensor containing the pairwise IoU values for every element in box1 and box2.

    References:
        https://github.com/pytorch/vision/blob/main/torchvision/ops/boxes.py
          r   )r    	unsqueezechunktorchminmaxclamp_prod)r   r   r   a1a2b1b2inters           r3   box_iourF   :   s      //2288A>>

@V@VWX@Y@Y@_@_`acd@e@eHRhr2Yr22r!2!22::1==BB1EEE R"WNN1%%bq(9(99EACGHHr5   TxywhGIoUDIoUCIoUc                   |r}|                      dd          |                     dd          c\  }}}	}
\  }}}}|	dz  |
dz  |dz  |dz  f\  }}}}||z
  ||z   ||z
  ||z   f\  }}}}||z
  ||z   ||z
  ||z   f\  }}}}nP|                      dd          \  }}}}|                     dd          \  }}}}||z
  ||z
  |z   }
}	||z
  ||z
  |z   }}|                    |          |                    |          z
                      d          |                    |          |                    |          z
                      d          z  }|	|
z  ||z  z   |z
  |z   }||z  }|s|s|r|                    |          |                    |          z
  }|                    |          |                    |          z
  }|s|r|                    d          |                    d          z   |z   } ||z   |z
  |z
                      d          ||z   |z
  |z
                      d          z   dz  }!|rdt
          j        dz  z  ||z                                  |	|
z                                  z
                      d          z  }"t          j	                    5  |"|"|z
  d|z   z   z  }#ddd           n# 1 swxY w Y   ||!| z  |"|#z  z   z
  S ||!| z  z
  S ||z  |z   }$||$|z
  |$z  z
  S |S )ax  Calculate the Intersection over Union (IoU) between bounding boxes.

    This function supports various shapes for `box1` and `box2` as long as the last dimension is 4. For instance, you
    may pass tensors shaped like (4,), (N, 4), (B, N, 4), or (B, N, 1, 4). Internally, the code will split the last
    dimension into (x, y, w, h) if `xywh=True`, or (x1, y1, x2, y2) if `xywh=False`.

    Args:
        box1 (torch.Tensor): A tensor representing one or more bounding boxes, with the last dimension being 4.
        box2 (torch.Tensor): A tensor representing one or more bounding boxes, with the last dimension being 4.
        xywh (bool, optional): If True, input boxes are in (x, y, w, h) format. If False, input boxes are in (x1, y1,
            x2, y2) format.
        GIoU (bool, optional): If True, calculate Generalized IoU.
        DIoU (bool, optional): If True, calculate Distance IoU.
        CIoU (bool, optional): If True, calculate Complete IoU.
        eps (float, optional): A small value to avoid division by zero.

    Returns:
        (torch.Tensor): IoU, GIoU, DIoU, or CIoU values depending on the specified flags.
       r9   r   r8   N)
r;   r%   r&   r?   powmathpiatanr<   no_grad)%r   r   rG   rH   rI   rJ   r   x1y1w1h1x2y2w2h2w1_h1_w2_h2_r(   r*   r)   r+   r,   r.   r-   r/   rE   unionr   cwchc2rho2valphac_areas%                                        r3   bbox_iourg   Q   s   :  	4-1ZZ2->->

1b@Q@Q*RR*2r2r!VR!VR!VR!V;S#s%'#XrCxc28%K"ueU%'#XrCxc28%K"ueUU%)ZZ2%6%6"ueU%)ZZ2%6%6"ueU 3B 3B ]]5!!EMM%$8$88@@CCeu}}U333fQiiE
 Gb2g%+E %-C /t /t /]]5!!EMM%$8$88]]5!!EMM%$8$88 
	#4 
	#RVVAYY&,B&.33A66%%-%:ORW:W9\9\]^9_9__D  5!^b(8(8BG>>;K;K(K'P'PQR'S'SS]__ 6 6SAG!45E6 6 6 6 6 6 6 6 6 6 6 6 6 6 6dRi!e)344?"b3fun...Js   J88J<?J<mask1mask2c                    t          j        | |j                                      d          }|                     d          dddf         |                    d          d         z   |z
  }|||z   z  S )a  Calculate masks IoU.

    Args:
        mask1 (torch.Tensor): A tensor of shape (N, n) where N is the number of ground truth objects and n is the
            product of image width and height.
        mask2 (torch.Tensor): A tensor of shape (M, n) where M is the number of predicted objects and n is the product
            of image width and height.
        eps (float, optional): A small value to avoid division by zero.

    Returns:
        (torch.Tensor): A tensor of shape (N, M) representing masks IoU.
    r   r8   N)r<   matmulr#   r?   sum)rh   ri   r   intersectionr_   s        r3   mask_iourn      si     <uw//66q99LYYq\\!!!T'"UYYq\\$%77<GE53;''r5   kpt1kpt2r1   sigmalist[float]c                   | ddddddf         |d         z
                       d          | ddddddf         |d         z
                       d          z   }t          j        || j        | j                  }| d         dk    }|d|z                       d          |ddddf         |z   z  dz  z  }|                                 |dddf         z                      d	          |                    d	          dddf         |z   z  S )
aR  Calculate Object Keypoint Similarity (OKS).

    Args:
        kpt1 (torch.Tensor): A tensor of shape (N, 17, 3) representing ground truth keypoints.
        kpt2 (torch.Tensor): A tensor of shape (M, 17, 3) representing predicted keypoints.
        area (torch.Tensor): A tensor of shape (N,) representing areas from ground truth.
        sigma (list[float]): A list containing 17 values representing keypoint scales.
        eps (float, optional): A small value to avoid division by zero.

    Returns:
        (torch.Tensor): A tensor of shape (N, M) representing keypoint similarities.
    Nr   ).r   r9   r8   ).r8   )devicer   ).r9   rM   )rN   r<   tensorrt   r   exprl   )ro   rp   r1   rq   r   dkpt_maskes           r3   kpt_iourz      s    
aaaqqq!m	tF|	+0033tAAAtQQQM7JTRX\7Y6^6^_`6a6aaALt{$*EEEEF|q H	a%i__Q44#6#<=ABARHHJJ!!!T'**//33x||B7G7G47PSV7VWWr5   boxes/tuple[torch.Tensor, torch.Tensor, torch.Tensor]c                   t          j        | ddddf                             d          dz  | ddddf         fd          }|                    dd          \  }}}|                                }|                                }|                    d          }|                    d          }||z  ||z  z   ||z  ||z  z   ||z
  |z  |z  fS )az  Generate covariance matrix from oriented bounding boxes.

    Args:
        boxes (torch.Tensor): A tensor of shape (N, 5) representing rotated bounding boxes, with xywhr format.

    Returns:
        (tuple[torch.Tensor, torch.Tensor, torch.Tensor]): Covariance matrix components (a, b, c) where the covariance
            matrix is [[a, c], [c, b]], each of shape (N, 1).
    Nr9   rL      rM   dimr8   )r<   catrN   splitcossin)	r{   gbbsabcr   r   cos2sin2s	            r3   _get_covariance_matrixr      s     9eAAAqsFm''**R/qqq!""u>BGGGDjjj##GAq!
%%''C
%%''C771::D771::Dt8a$hD1t8 3a!es]S5HHHr5   obb1obb2c                   | dddf                              dd          \  }}|dddf                              dd          \  }}t          |           \  }}	}
t          |          \  }}}||z   ||z
                      d          z  |	|z   ||z
                      d          z  z   ||z   |	|z   z  |
|z                       d          z
  |z   z  dz  }|
|z   ||z
  z  ||z
  z  ||z   |	|z   z  |
|z                       d          z
  |z   z  dz  }||z   |	|z   z  |
|z                       d          z
  d	||	z  |
                    d          z
                      d
          ||z  |                    d          z
                      d
          z                                  z  |z   z  |z                                   dz  }||z   |z                       |d          }d|                                 z
  |z                                   }d|z
  }|r| ddd	f                              dd          \  }}|ddd	f                              dd          \  }}d	t          j	        dz  z  ||z  
                                ||z  
                                z
                      d          z  }t          j                    5  |||z
  d|z   z   z  }ddd           n# 1 swxY w Y   |||z  z
  S |S )a8  Calculate probabilistic IoU between oriented bounding boxes.

    Args:
        obb1 (torch.Tensor): Ground truth OBBs, shape (N, 5), format xywhr.
        obb2 (torch.Tensor): Predicted OBBs, shape (N, 5), format xywhr.
        CIoU (bool, optional): If True, calculate CIoU.
        eps (float, optional): Small value to avoid division by zero.

    Returns:
        (torch.Tensor): OBB similarities, shape (N,).

    Notes:
        OBB format: [center_x, center_y, width, height, rotation_angle].

    References:
        https://arxiv.org/pdf/2106.06072v1.pdf
    .Nr9   r8   rM   r   r         ?rL   r         Y@r   )r   r   rN   r?   sqrtlogclamprv   rO   rP   rQ   r<   rR   )r   r   rJ   r   rS   rT   rW   rX   rA   rC   c1rB   rD   rb   t1t2t3bdhdr   rU   rV   rY   rZ   rd   re   s                             r3   probiour      sb   $ #rr']   ++FB#rr']   ++FB'--JBB'--JBB r'b2g]]1%%	%bR"WMM!4D4D(D	D"r'VX[]V]I^bdgibiananopaqaqIqtwIwx
B GR BG,"r'b2g1F"r'WXIYIY1Y\_1_
`dg	gB
r'b2g	"r'q!1!1	1b266!99$,,Q//27RVVAYY3F2N2Nq2Q2QQWWYYY\__	a
	 
ceec	
B
 r'B,		c5	)	)B
"		
c
!	'	'	)	)B
b&C c1Q3h%%aR%00Bc1Q3h%%aR%00B!^b 0 0BG>>3C3C CHHKKK]__ 	. 	.SAG,-E	. 	. 	. 	. 	. 	. 	. 	. 	. 	. 	. 	. 	. 	. 	.QYJs   K  K$'K$torch.Tensor | np.ndarrayc                   t          | t          j                  rt          j        |           n| } t          |t          j                  rt          j        |          n|}| dddf                             dd          \  }}d |dddf                             dd          D             \  }}t          |           \  }}}	d t          |          D             \  }
}}||
z   ||z
                      d          z  ||z   ||z
                      d          z  z   ||
z   ||z   z  |	|z                       d          z
  |z   z  d	z  }|	|z   ||z
  z  ||z
  z  ||
z   ||z   z  |	|z                       d          z
  |z   z  d
z  }||
z   ||z   z  |	|z                       d          z
  d||z  |	                    d          z
                      d          |
|z  |                    d          z
                      d          z  	                                z  |z   z  |z   
                                d
z  }||z   |z                       |d          }d|                                 z
  |z   	                                }d|z
  S )a  Calculate the probabilistic IoU between oriented bounding boxes.

    Args:
        obb1 (torch.Tensor | np.ndarray): A tensor of shape (N, 5) representing ground truth obbs, with xywhr format.
        obb2 (torch.Tensor | np.ndarray): A tensor of shape (M, 5) representing predicted obbs, with xywhr format.
        eps (float, optional): A small value to avoid division by zero.

    Returns:
        (torch.Tensor): A tensor of shape (N, M) representing obb similarities.

    References:
        https://arxiv.org/pdf/2106.06072v1.pdf
    .Nr9   r8   rM   r   c              3  L   K   | ]}|                     d           d         V   dS rM   Nsqueeze.0xs     r3   	<genexpr>z batch_probiou.<locals>.<genexpr>  s1      JJaaiimmD!JJJJJJr5   c              3  L   K   | ]}|                     d           d         V   dS r   r   r   s     r3   r   z batch_probiou.<locals>.<genexpr>  s1      LL!!))B--%LLLLLLr5   r   r   rL   r   r   r   )
isinstancer$   ndarrayr<   
from_numpyr   r   rN   r?   r   r   r   rv   )r   r   r   rS   rT   rW   rX   rA   rC   r   rB   rD   rb   r   r   r   r   r   s                     r3   batch_probiour      s    &0bj%A%AK5D!!!tD%/bj%A%AK5D!!!tD#rr']   ++FBJJ4RaR=+>+>qb+>+I+IJJJFB'--JBBLL/Ed/K/KLLLJBB r'b2g]]1%%	%bR"WMM!4D4D(D	D"r'VX[]V]I^bdgibiananopaqaqIqtwIwx
B GR BG,"r'b2g1F"r'WXIYIY1Y\_1_
`dg	gB
r'b2g	"r'q!1!1	1b266!99$,,Q//27RVVAYY3F2N2Nq2Q2QQWWYYY\__	a
	 
ceec	
B
 r'B,		c5	)	)B
"		
c
!	'	'	)	)Br6Mr5   皙?tuple[float, float]c                    dd| z  z
  d| z  fS )a}  Compute smoothed positive and negative Binary Cross-Entropy targets.

    Args:
        eps (float, optional): The epsilon value for label smoothing.

    Returns:
        pos (float): Positive label smoothing BCE target.
        neg (float): Negative label smoothing BCE target.

    References:
        https://github.com/ultralytics/yolov3/issues/238#issuecomment-598028441
    r   r    )r   s    r3   
smooth_bcer   $  s     s?C#I%%r5   c                      e Zd ZdZi ddfd4d
Zd5dZd6dZ	 	 d7d8dZd Zd9d!Z	d:d'Z
 ed()           e            d;d<d.                        Zd/ Zd=d>d3Zd,S )?ConfusionMatrixa  A class for calculating and updating a confusion matrix for object detection and classification tasks.

    Attributes:
        task (str): The type of task, either 'detect' or 'classify'.
        matrix (np.ndarray): The confusion matrix, with dimensions depending on the task.
        nc (int): The number of classes.
        names (dict[int, str]): The names of the classes, used as labels on the plot.
        matches (dict | None): Contains the indices of ground truths and predictions categorized into TP, FP and FN.
    detectFnamesdict[int, str]taskstrsave_matchesr   c                   || _         t          |          | _        | j         dk    r t          j        | j        | j        f          n%t          j        | j        dz   | j        dz   f          | _        || _        |ri nd| _        dS )aN  Initialize a ConfusionMatrix instance.

        Args:
            names (dict[int, str], optional): Names of classes, used as labels on the plot.
            task (str, optional): Type of task, either 'detect' or 'classify'.
            save_matches (bool, optional): Save the indices of GTs, TPs, FPs, FNs for visualization.
        classifyr8   N)r   lenncr$   zerosmatrixr   matches)selfr   r   r   s       r3   __init__zConfusionMatrix.__init__?  s     	e**6:i:6M6Mbh1222SUS[]a]dgh]hjnjqtuju\vSwSw
)3rrtr5   mtypebatchdict[str, Any]idxintr!   Nonec                :   | j         dS |                                D ]|\  }}|dv r#| j         |         |xx         ||g         z  cc<   ,|dk    rJ| j         |         |xx         |                                dk    r|d         |dz   k    gn||         gz  cc<   }dS )a  Append the matches to TP, FP, FN or GT list for the last batch.

        This method updates the matches dictionary by appending specific batch data to the appropriate match type (True
        Positive, False Positive, or False Negative).

        Args:
            mtype (str): Match type identifier ('TP', 'FP', 'FN' or 'GT').
            batch (dict[str, Any]): Batch data containing detection results with keys like 'bboxes', 'cls', 'conf',
                'keypoints', 'masks'.
            idx (int): Index of the specific detection to append from the batch.

        Notes:
            For masks, handles both overlap and non-overlap cases. When masks.max() > 1.0, it indicates
            overlap_mask=True with shape (1, H, W), otherwise uses direct indexing.
        N>   clsconfbboxes	keypointsmasksr   r   r8   )r   itemsr>   )r   r   r   r   krd   s         r3   _append_matcheszConfusionMatrix._append_matchesM  s      <FKKMM 	[ 	[DAq:::U#A&&&!SE(2&&&&gU#A&&&quuww}}1Q437?*;*;STUXSYRZZ&&&	[ 	[r5   predslist[torch.Tensor]targetsc                \   t          j        |          dddf         t          j        |          }}t          |                                                                |                                                                          D ] \  }}| j        |         |xx         dz  cc<   !dS )zUpdate confusion matrix for classification task.

        Args:
            preds (list[torch.Tensor]): Predicted class labels.
            targets (list[torch.Tensor]): Ground truth class labels.
        Nr   r8   )r<   r   zipcpunumpyr   )r   r   r   pts        r3   process_cls_predsz!ConfusionMatrix.process_cls_predsf  s     5))!!!Q$/71C1Cw		))++W[[]]-@-@-B-BCC 	# 	#DAqKN1"	# 	#r5   r   ?
detectionsdict[str, torch.Tensor]r   r    	iou_thresc                
   |d         |d         }}| j         Ed dD             | _         t          |j        d                   D ]}|                     d||           |j        d         d	k    }d|rd
ndhv rdnd         j        d         dk    }	|j        d         dk    r|	sfdD             d                                                                         }
t          |
          D ]8\  }}| j        || j        fxx         dz  cc<   |                     d|           9dS |	rp|                                                                }t          |          D ]8\  }}| j        | j        |fxx         dz  cc<   |                     d||           9dS fdD             |                                                                }d                                                                         }
d         }|rt          ||          nt          ||          }t          j        ||k              }|d         j        d         r6t          j        t          j        |d          ||d         |d         f         dddf         fd                                                                          }|d         j        d         dk    r||dddf                                         ddd                  }|t%          j        |dddf         d          d                  }||dddf                                         ddd                  }|t%          j        |dddf         d          d                  }nt%          j        d          }|j        d         dk    }|                                                    t                    \  }}}t          |          D ]\  }}||k    }|rt/          |          dk    r|
||                                                  }| j        ||fxx         dz  cc<   ||k    r0|                     d||                                                    |                     d||                                                    |                     d||           | j        | j        |fxx         dz  cc<   |                     d||           
t          |
          D ]K\  }}t3          ||k              s3| j        || j        fxx         dz  cc<   |                     d|           LdS )a  Update confusion matrix for object detection task.

        Args:
            detections (dict[str, torch.Tensor]): Dictionary containing detected bounding boxes and their associated
                information. Should contain 'cls', 'conf', and 'bboxes' keys, where 'bboxes' can be Array[N, 4] for
                regular boxes or Array[N, 5] for OBB with angle.
            batch (dict[str, Any]): Batch dictionary containing ground truth data with 'bboxes' (Array[M, 4]| Array[M,
                5]) and 'cls' (Array[M]) keys, where M is the number of ground truth objects.
            conf (float, optional): Confidence threshold for detections.
            iou_thres (float, optional): IoU threshold for matching detections to ground truth.
        r   r   Nc                8    i | ]}|t          t                    S r   )r   list)r   r   s     r3   
<dictcomp>z1ConfusionMatrix.process_batch.<locals>.<dictcomp>  s"    SSSQA{400SSSr5   >   FNFPGTTPr   r   r8      g{Gz?MbP?r   c                B    i | ]}||         d          k             S r   r   r   r   r   r   s     r3   r   z1ConfusionMatrix.process_batch.<locals>.<dictcomp>  s.    ^^^aaAz&/AD/H!I^^^r5   r   r   c                B    i | ]}||         d          k             S r   r   r   s     r3   r   z1ConfusionMatrix.process_batch.<locals>.<dictcomp>  s.    VVVaaAz&'9D'@AVVVr5   r9   rM   T)return_index)r      r   )r   rangeshaper   r   tolist	enumerater   r   r   rF   r<   wherer   stackr   r   argsortr$   uniquer   	transposeastyperl   itemany)r   r   r   r   r   gt_cls	gt_bboxesiis_obbno_preddetection_classesdc
gt_classesgcr   r   r   r   nm0m1_js    ` `                   r3   process_batchzConfusionMatrix.process_batchq  s   $ "%L%/	<#SS:RSSSDL6<?++ 5 5$$T5!4444#q(f&?dd%@@@ttdU#)!,1<?a >^^^^^S]^^^
$.u$5$9$9$;$;$B$B$D$D!&'899 > >EArKDG,,,1,,,((z1====F 	,,..J":.. 5 52DGRK(((A-((($$T5!4444FVVVVV:VVV
ZZ\\((**
&u-1133::<<H%28XmIv...giQW>X>XKi((Q4:a= 	'iQ!2!2C!ad
OAAAtG4L MqQQUUWW]]__Gtz!}q  !'!!!Q$-"7"7"9"9$$B$"?@!")GAAAqDM"M"M"Ma"PQ!'!!!Q$-"7"7"9"9$$B$"?@!")GAAAqDM"M"M"Ma"PQhv&&GM!q %%''..s33	Bz** 	5 	5EAraA 
5SVVq[[&r!uzz||4BF###q(###88((z2a5::<<HHHH((z2a5::<<HHH((ua8888DGRK(((A-((($$T5!4444011 	: 	:EArrQw<< :BK(((A-((($$T:q999	: 	:r5   c                    | j         S )zReturn the confusion matrix.)r   r   s    r3   r   zConfusionMatrix.matrix  s
    {r5   tuple[np.ndarray, np.ndarray]c                    | j                                         }| j                             d          |z
  }| j        dk    r||fn|dd         |dd         fS )zReturn true positives and false positives.

        Returns:
            tp (np.ndarray): True positives.
            fp (np.ndarray): False positives.
        r8   r   NrM   )r   diagonalrl   r   )r   tpfps      r3   tp_fpzConfusionMatrix.tp_fp  s^     [!!##[__Q"$9
22BxxCRC"SbS'8JJr5   imgr6   im_filesave_dirr   c           	     6   | j         sdS ddlm} ddlm} t          t                    }t          g d          D ]\  }}| j         |         }	d|	vr5t          j	        dgt          |	d                   z  |j        	          |	d<   t          j        t          |	d                   |j        	          |z  |	d
<   |	                                D ]}
||
xx         |	|
         z  cc<   d |                                D             }| j        dk    r'|d         j        d         r ||d                   |d<   |dz                      dd            |||                    dddd          g d|dz  t'          |          j        z  | j        dd           dS )zPlot grid of GT, TP, FP, FN for each image.

        Args:
            img (torch.Tensor): Image to plot onto.
            im_file (str): Image filename to save visualizations.
            save_dir (Path): Location to save the visualizations to.
        Nr8   )	xyxy2xywh)plot_images)r   r   r   r   r   r   r   )rt   	batch_idxc                    i | ]>\  }}|t          |          rt          j        |d           nt          j        d           ?S r   )r   r<   r   emptyr   r   rd   s      r3   r   z0ConfusionMatrix.plot_matches.<locals>.<dictcomp>  sB    ```A!#a&&DU[A&&&ek!nn```r5   obbr   visualizationsT)parentsexist_okrL   )zGround TruthzFalse PositiveszTrue PositiveszFalse Negativesr   )pathsfnamer   max_subplots
conf_thres)r   opsr  plottingr  r   r   r   r<   ru   r   rt   oneskeysr   r   r   mkdirrepeatr   namer   )r   r  r  r  r  r  labelsr   r   mbatchr   s              r3   plot_matcheszConfusionMatrix.plot_matches  s    | 	F"""""")))))) T""!":":":;; 	' 	'HAu\%(FV##!&sec&:J6K6K.KTWT^!_!_!_v"'*S1A-B-B3:"V"V"VYZ"ZF;[[]] ' 'q			VAY&				' a`QWQ]Q]Q_Q_```9&"2"8";(y)9::F8	$	$++D4+HHHJJq!Q""ZZZ--W0BB*	
 	
 	
 	
 	
 	
r5   zConfusionMatrix plot failure)msgT N	normalizec                	   ddl m} | j        |r1| j                            d                              dd          dz   ndz  }t
          j        ||dk     <   |                    ddd          \  }}t          | j	        
                                          | j        }	}| j        d	k    rWt          d
| j        dz            }
t          dd|
          }||         }||ddf         dd|f         }| j        |
z   dz
  |
z  }	| j        dk    r|	n|	dz   }d}d|cxk     rdk     rn n| j        dk    r|ng |d}|dk    r!t          j        t!          |                    nt          j        |          }t          ddd|z  z
            }t          ddd|z  z
            }t          ddd|z  z
            }t          ddd|z  z
            }t#          j                    5  t#          j        d           |                    |ddd          }|j                            d           |dk     rd|rdnt          j        |          z  }t1          |d|                   D ]y\  }}t1          |d|                   D ]\\  }}|||f         }t          j        |          r$|                    |||r|dnt7          |           ddd ||k    rd!nd"#           ]z|                    ||d$d%&          }ddd           n# 1 swxY w Y   d'd(|z  z   }|                    d)|d *           |                    d+|d *           |                    ||d,-           |                     |           |!                    |           |"                    d.d/d0d/d01           |"                    d2d/d0d/d03           |dk    r0|#                    ||d4d5           |$                    ||6           d7D ]M}|d8k    r |j%        |         &                    d0           |j'        j%        |         &                    d0           N|(                    dd9d:|;           tS          |          |*                                +                    d<d=           d>z  }|,                    |d?@           |-                    |           |r( ||dA| j        .                                dB           dS dS )Cam  Plot the confusion matrix using matplotlib and save it to a file.

        Args:
            normalize (bool, optional): Whether to normalize the confusion matrix.
            save_dir (str, optional): Directory where the plot will be saved.
            on_plot (callable, optional): An optional callback to pass plots path and data when they are rendered.
        r   Nr8   rM   &.>g{Gzt?)r~   	   )figsized   r9   <   r   autoc   
background      r   r~   r   r   ignoreBlues        none)cmapvmininterpolationbottom   r   .2fcenter
   whiteblack)havafontsizecolorgZd;O?皙?)axfractionpadzConfusion Matrixz NormalizedTrue)rK  labelpad	Predicted   )rK  rP  r   TF)axisrB  toplabelbottomlabeltopy)rU  leftright	labelleft
labelrightZ   )rK  rotationrI  )rK  >   rV  rZ  r[  rB  outliner`  gzG?gGz?)rZ  r[  rV  rB   r  z.png   dpiconfusion_matrix)typer   )/matplotlib.pyplotpyplotr   rl   reshaper$   nansubplotsr   r   valuesr   r>   slicer   aranger   warningscatch_warningssimplefilterimshowxaxisset_label_positionnanmaxr   isnantextr   colorbar
set_xlabel
set_ylabel	set_title
set_xticks
set_ytickstick_paramsset_xticklabelsset_yticklabelsspinesset_visiblerN  subplots_adjustr   lowerreplacesavefigcloser   )r   r/  r  on_plotpltarrayfigrN  r   r  r   keep_idxr   
ticklabelsxy_tickstick_fontsizelabel_fontsizetitle_fontsizebtmimcolor_thresholdr   rowr  valcbartitles
plot_fnames                                r3   plotzConfusionMatrix.plot  s    	('''''Y] 2 2 : :1b A AD H H\]^!veem,,q!W,55R
))++,,dgq7c>>Atw"}%%AT4++H(OE(AAA+&qqq({3E1qQ&A)z))QQq1u
r;;;;B;;;;;"&)z"9"9?U?U?UJ1;v1E1E29S__---29UW==ArC"H}--QS2X..QS2X..#tebj())$&& 	E 	E!(+++5wSOOBH''111Bww"&y*N!!bi>N>N"O'crc
33  FAs"+CH"5"5  3#AqDk8C== %$,5HsLLLc#hh=''%'-0?-B-B''      	 <<rEt<DDD)	E 	E 	E 	E 	E 	E 	E 	E 	E 	E 	E 	E 	E 	E 	E* #]Y%>>
f~CCC
kNRHHH
U^<<<
h
h
C%TTYZZZ
Cd%4TYZZZzMBS[\\\zMBBB> 	1 	1AI~~	!((///GN1))%0000$DEEE(^^)>)>sC)H)H&N&N&NN
JC(((		# 	^GJ);t{GYGYG[G[ \ \]]]]]	^ 	^s   DK==LLc           
         t          | j        j        d                   D ]G}t          j        d                    t          t          | j        |                                        HdS )z*Print the confusion matrix to the console.r   ra  N)r   r   r   r   infojoinmapr   r   r   s     r3   printzConfusionMatrix.print@  s\    t{(+,, 	< 	<AKS$+a.!9!9::;;;;	< 	<r5   r   decimalslist[dict[str, float]]c                   
 ddl }| j        dk    r&t          | j                                                  n)g t          | j                                                  d}g t                      c}|D ]}|                    dd|          }|}d}	|                                |v r"| d|	 }|	dz  }	|                                |v "|                    |                                           	                    |           | j
        |r1| j
                            d                              dd          d	z   ndz                      |          

fd
t          t                              D             S )a%  Generate a summarized representation of the confusion matrix as a list of dictionaries, with optional
        normalization. This is useful for exporting the matrix to various formats such as CSV, XML, HTML, JSON,
        or SQL.

        Args:
            normalize (bool): Whether to normalize the confusion matrix values.
            decimals (int): Number of decimal places to round the output values to.

        Returns:
            (list[dict[str, float]]): A list of dictionaries, each representing one predicted class with corresponding
                values for all actual classes.

        Examples:
            >>> results = model.val(data="coco8.yaml", plots=True)
            >>> cm_dict = results.confusion_matrix.summary(normalize=True, decimals=5)
            >>> print(cm_dict)
        r   Nr   r8  z[^a-zA-Z0-9_]r  r8   rM   r1  c                    g | ]?t          d          ifi fdt          t                              D             @S )rS  c                2    i | ]}|         |f         S r   r   )r   r  r  clean_namesr   s     r3   r   z6ConfusionMatrix.summary.<locals>.<listcomp>.<dictcomp>f  s(    2p2p2pST;q>5A;2p2p2pr5   )dictr   r   )r   r   r  r  s    @r3   
<listcomp>z+ConfusionMatrix.summary.<locals>.<listcomp>e  sq     
 
 
 +{1~.qq2p2p2p2p2p2pX]^abm^n^nXoXo2p2p2pqq
 
 
r5   )rer   r   r   rl  setsubr  addappendr   rl   ri  roundr   r   )r   r/  r  r  r   seenr)  
clean_nameoriginal_cleancounterr  r  s             @@r3   summaryzConfusionMatrix.summaryE  s   $ 				-1Y*-D-DTZ&&(()))JtDQUQ[QbQbQdQdLeLeJtgsJtT 	+ 	+D 0#t<<J'NG""$$,, .::::
1 ""$$,, HHZ%%''(((z****i ^!3!3!;!;Ar!B!BT!I!I]^_ffgopp
 
 
 
 
3{++,,
 
 
 	
r5   )r   r   r   r   r   r   )r   r   r   r   r   r   r!   r   )r   r   r   r   r!   r   )r   r   )
r   r   r   r   r   r    r   r    r!   r   )r!   r
  )r  r6   r  r   r  r   r!   r   )Tr.  N)r/  r   r  r   )Fr   r/  r   r  r   r!   r  )__name__
__module____qualname____doc__r   r   r   r  r   r  r,  r
   r   r  r  r  r   r5   r3   r   r   4  sG         02x^c 4 4 4 4 4[ [ [ [2	# 	# 	# 	# M: M: M: M: M:^  
K 
K 
K 
K#
 #
 #
 #
J Y1222\^^G^ G^ G^ G^ ^ 32G^R< < <
#
 #
 #
 #
 #
 #
 #
r5   r   rM  rY  fc                ,   t          t          |           |z  dz            dz  dz   }t          j        |dz            }t          j        || d         z  | || d         z  fd          }t          j        |t          j        |          |z  d          S )zBox filter of fraction f.r9   r8   r   rM   valid)mode)r  r   r$   r%  concatenateconvolve)rY  r  nfr   yps        r3   smoothr  k  s    	s1vvzA~		!	#a	'B
aA	QqT1a!B%i0!	4	4B;r272;;+'::::r5   zpr_curve.pngpxpyapr  r   r   r   c                
   ddl m} |                    dddd          \  }}t          j        |d          }dt          |          cxk     rdk     rKn nHt          |j                  D ]2\  }	}
|                    | |
d||	          d	||	df         d
           3n|                    | |dd           |                    | |	                    d          ddd|dddf         	                                d
d           |
                    d           |                    d           |                    dd           |                    dd           |                    dd           |                    d           |                    |d           |                    |           |rN ||d|                                 |j                                        |                                d           dS dS )a  Plot precision-recall curve.

    Args:
        px (np.ndarray): X values for the PR curve.
        py (np.ndarray): Y values for the PR curve.
        ap (np.ndarray): Average precision values.
        save_dir (Path, optional): Path to save the plot.
        names (dict[int, str], optional): Dictionary mapping class indices to class names.
        on_plot (callable, optional): Function to call after plot is saved.
    r   Nr8   r2  r9  Tr3  tight_layout)rU     ra  .3f	linewidthlabelgrayr  rL  r   blueall classes z mAP@0.5r  rL  r  Recall	Precisiongp=
ף?r8   
upper leftbbox_to_anchorloczPrecision-Recall Curverb  rc  pr_curve)rf  r   rY  r  )rg  rh  rk  r$   r   r   r   r#   r  meanry  rz  set_xlimset_ylimlegendr{  r  r  r   )r  r  r  r  r   r  r  r  rN  r   rY  s              r3   plot_pr_curver  s  s&   & $#####ll1adlCCGC	"1			B3u::bdOO 	L 	LDAqGGBQq.J.JBq!tH.J.J.JGKKKK	L 	B!6222GGB

av=iBqqqRStHMMOO=i=i=i=iGjjjMM(MM+KK1KK1IIYLI999LL)***KKcK"""IIcNNN i 	:BIIKKbdkkmm[][d[d[f[fgghhhhhi ir5   zmc_curve.png
ConfidenceMetricxlabelr   ylabelc                   ddl m} |                    dddd          \  }}	dt          |          cxk     rdk     r9n n6t	          |          D ]%\  }
}|	                    | |d||
                     &n|	                    | |j        dd	
           t          |                    d          d          }|	                    | |ddd|	                                dd| |
                                         d           |	                    |           |	                    |           |	                    dd           |	                    dd           |	                    dd           |	                    | d           |                    |d           |                    |           |rK |||                                 d|                                 |                                d           dS dS )a  Plot metric-confidence curve.

    Args:
        px (np.ndarray): X values for the metric-confidence curve.
        py (np.ndarray): Y values for the metric-confidence curve.
        save_dir (Path, optional): Path to save the plot.
        names (dict[int, str], optional): Dictionary mapping class indices to class names.
        xlabel (str, optional): X-axis label.
        ylabel (str, optional): Y-axis label.
        on_plot (callable, optional): Function to call after plot is saved.
    r   Nr8   r  Tr  r  r  r  r  r   r   r  r  rD  z at r  r  r  r  r  z-Confidence Curverb  rc  _curve)rf  r   rY  )rg  rh  rk  r   r   r  r#   r  r  r>   argmaxry  rz  r  r  r  r{  r  r  r  r   )r  r  r  r   r  r  r  r  r  rN  r   rY  s               r3   plot_mc_curver    s    * $#####ll1adlCCGC3u::bMM 	= 	=DAqGGBQqmG<<<<	= 	BDAV444rwwqzz3AGGBQf4h155774h4h4hTVWXW_W_WaWaTb4h4h4hGiiiMM&MM&KK1KK1IIYLI999LLF---...KKcK"""IIcNNN cfllnn#<#<#<299;;UWU^U^U`U`aabbbbbc cr5   recall	precision$tuple[float, np.ndarray, np.ndarray]c                   t          j        dg| dgf          }t          j        dg|dgf          }t          j        t           j                            t          j        |                              }d}|dk    rnt          j        ddd          }t          j        t           j        d          rt           j	        nt           j
        } |t          j        |||          |          }n`t          j        |dd         |dd	         k              d         }t          j        ||dz            ||         z
  ||dz            z            }|||fS )
a  Compute the average precision (AP) given the recall and precision curves.

    Args:
        recall (list[float]): The recall curve.
        precision (list[float]): The precision curve.

    Returns:
        ap (float): Average precision.
        mpre (np.ndarray): Precision envelope curve.
        mrec (np.ndarray): Modified recall curve with sentinel values added at the beginning and end.
    r=  r   interpr   r8   e   z>=2.0NrM   )r$   r  flipr&   
accumulatelinspacer   check_version__version__	trapezoidtrapzr  r   rl   )	r  r  mrecmpremethodr   funcr  r   s	            r3   
compute_apr    s,    >C5&3%011D>C5)cU344D 72:((7788D FK1c""%3BNGLLZr||RTRZT")AtT**A..HT!""Xcrc*++A.VT!a%[47*d1q5k9::tT>r5   gؗҜ<r.  r  r   pred_cls
target_clsr  prefixtuplec
                &   t          j        |           }
| |
         ||
         ||
         }}} t          j        |d          \  }}|j        d         }t          j        ddd          g }}t          j        || j        d         f          t          j        |df          t          j        |df          }}}t          |          D ]Q\  }}||k    }
||         }|
                                }|dk    s|dk    r5d| |
         z
                      d          }| |
                             d          }|||z   z  }t          j	        | ||
          |dddf         d          ||<   |||z   z  }t          j	        | ||
          |dddf         d          ||<   t          | j        d                   D ]^}t          |dd|f         |dd|f                   \  |||f<   }}|dk    r)|                    t          j	        |||                     _S|rt          j        |          nt          j        d          }d	|z  |z  ||z   |z   z  }fd
t          |          D             |rlt          |||||	 dz  |           t          ||||	 dz  d|           t          ||||	 dz  d|           t          ||||	 dz  d|           t!          |                    d          d                                          }
|dd|
f         |dd|
f         |dd|
f         }!} }| |z                                  } | ||z   z  | z
                                  }"| |"|| |!||                    t*                    |||||fS )a>  Compute the average precision per class for object detection evaluation.

    Args:
        tp (np.ndarray): Binary array indicating whether the detection is correct (True) or not (False).
        conf (np.ndarray): Array of confidence scores of the detections.
        pred_cls (np.ndarray): Array of predicted classes of the detections.
        target_cls (np.ndarray): Array of true classes of the targets.
        plot (bool, optional): Whether to plot PR curves or not.
        on_plot (callable, optional): A callback to pass plots path and data when they are rendered.
        save_dir (Path, optional): Directory to save the PR curves.
        names (dict[int, str], optional): Dictionary of class names to plot PR curves.
        eps (float, optional): A small value to avoid division by zero.
        prefix (str, optional): A prefix string for saving the plot files.

    Returns:
        tp (np.ndarray): True positive counts at threshold given by max F1 metric for each class.
        fp (np.ndarray): False positive counts at threshold given by max F1 metric for each class.
        p (np.ndarray): Precision values at threshold given by max F1 metric for each class.
        r (np.ndarray): Recall values at threshold given by max F1 metric for each class.
        f1 (np.ndarray): F1-score values at threshold given by max F1 metric for each class.
        ap (np.ndarray): Average precision for each class at different IoU thresholds.
        unique_classes (np.ndarray): An array of unique classes that have data.
        p_curve (np.ndarray): Precision curves for each class.
        r_curve (np.ndarray): Recall curves for each class.
        f1_curve (np.ndarray): F1-score curves for each class.
        x (np.ndarray): X-axis values for the curves.
        prec_values (np.ndarray): Precision values at mAP@0.5 for each class.
    T)return_countsr   r8     N)rZ  )r8   r  r9   c                0    i | ]\  }}|v 	||         S r   r   )r   r   r   r   s      r3   r   z ap_per_class.<locals>.<dictcomp>@  s(    MMMTQ!u**Qa***r5   zPR_curve.pngr  zF1_curve.pngF1)r  r  zP_curve.pngr  zR_curve.pngr  r   )r$   r   r   r   r  r   r   rl   cumsumr  r   r  r  r  r  r  r  r  r  r  r   r   )#r  r   r  r  r  r  r  r   r   r  r   unique_classesntr   r   prec_valuesr  p_curver_curvecir   n_ln_pfpctpcr  r  r  r  r  f1_curver   rf1r  s#          `                           r3   ap_per_classr    s	   R 	
D5AAQ!hB :TBBBNB		a	 B [At,,b{A 8R!$566"d8L8LbhXZ\`WaNbNbB>** = =AMfeegg!88saxx 2a5y  ##ell1oo c	"iT!WHfQQQTlCCC 39%	iT!WHi1oAFFF rx{## 	= 	=A$.vaaad|Yqqq!t_$M$M!Br1uItTAvv""29Qd#;#;<<<	=
 ,7O"(;'''BHY<O<OK 7{W$'(9C(?@HMMMMY~%>%>MMME nab(5L5L5L*Le]deeeea8.E.E.E#EuUYcjkkkka(-C-C-C"CUS^hoppppa(-C-C-C"CUS[elmmmmx}}Q%%,,..Aqqq!t}gaaadmXaaad^"qA
b&		B
C.2
	$	$	&	&Br1aR!6!6s!;!;WgxYZ\gggr5   c                  *   e Zd ZdZddZed d            Zed d            Zed!d	            Zed!d
            Z	ed!d            Z
ed!d            Zed!d            Zd"dZd#dZed$d            Zd!dZd%dZed&d            Zed'd            ZdS )(r  a  Class for computing evaluation metrics for Ultralytics YOLO models.

    Attributes:
        p (list): Precision for each class. Shape: (nc,).
        r (list): Recall for each class. Shape: (nc,).
        f1 (list): F1 score for each class. Shape: (nc,).
        all_ap (list): AP scores for all classes and all IoU thresholds. Shape: (nc, 10).
        ap_class_index (list): Index of class for each AP score. Shape: (nc,).
        nc (int): Number of classes.

    Methods:
        ap50: AP at IoU threshold of 0.5 for all classes.
        ap: AP at IoU thresholds from 0.5 to 0.95 for all classes.
        mp: Mean precision of all classes.
        mr: Mean recall of all classes.
        map50: Mean AP at IoU threshold of 0.5 for all classes.
        map75: Mean AP at IoU threshold of 0.75 for all classes.
        map: Mean AP at IoU thresholds from 0.5 to 0.95 for all classes.
        mean_results: Mean of results, returns mp, mr, map50, map.
        class_result: Class-aware result, returns p[i], r[i], ap50[i], ap[i].
        maps: mAP of each class.
        fitness: Model fitness as a weighted combination of metrics.
        update: Update metric attributes with new evaluation results.
        curves: Provides a list of curves for accessing specific metrics like precision, recall, F1, etc.
        curves_results: Provide a list of results for accessing specific metrics like precision, recall, F1, etc.
    r!   r   c                Z    g | _         g | _        g | _        g | _        g | _        d| _        dS )zQInitialize a Metric instance for computing evaluation metrics for the YOLO model.r   N)r   r  r  all_apap_class_indexr   r	  s    r3   r   zMetric.__init__j  s1     r5   np.ndarray | listc                P    t          | j                  r| j        dddf         ng S )zReturn the Average Precision (AP) at an IoU threshold of 0.5 for all classes.

        Returns:
            (np.ndarray | list): Array of shape (nc,) with AP50 values per class, or an empty list if not available.
        Nr   )r   r  r	  s    r3   ap50zMetric.ap50s  s-     %($4$4<t{111a4  "<r5   c                b    t          | j                  r| j                            d          ng S )zReturn the Average Precision (AP) at an IoU threshold of 0.5-0.95 for all classes.

        Returns:
            (np.ndarray | list): Array of shape (nc,) with AP50-95 values per class, or an empty list if not available.
        r8   r   r  r  r	  s    r3   r  z	Metric.ap|  s.     '*$+&6&6>t{"""B>r5   r    c                `    t          | j                  r| j                                        ndS )z|Return the Mean Precision of all classes.

        Returns:
            (float): The mean precision of all classes.
        r=  )r   r   r  r	  s    r3   mpz	Metric.mp  %     !$DF4tv{{}}}4r5   c                `    t          | j                  r| j                                        ndS )zvReturn the Mean Recall of all classes.

        Returns:
            (float): The mean recall of all classes.
        r=  )r   r  r  r	  s    r3   mrz	Metric.mr  r  r5   c                t    t          | j                  r#| j        dddf                                         ndS )zReturn the mean Average Precision (mAP) at an IoU threshold of 0.5.

        Returns:
            (float): The mAP at an IoU threshold of 0.5.
        Nr   r=  r  r	  s    r3   map50zMetric.map50  9     ,/t{+;+;Dt{111a4 %%'''Dr5   c                t    t          | j                  r#| j        dddf                                         ndS )zReturn the mean Average Precision (mAP) at an IoU threshold of 0.75.

        Returns:
            (float): The mAP at an IoU threshold of 0.75.
        Nr   r=  r  r	  s    r3   map75zMetric.map75  r$  r5   c                `    t          | j                  r| j                                        ndS )zReturn the mean Average Precision (mAP) over IoU thresholds of 0.5 - 0.95 in steps of 0.05.

        Returns:
            (float): The mAP over IoU thresholds of 0.5 - 0.95 in steps of 0.05.
        r=  r  r	  s    r3   r  z
Metric.map  s,     &)%5%5>t{!!!3>r5   rr   c                6    | j         | j        | j        | j        gS )z+Return mean of results, mp, mr, map50, map.)r  r!  r#  r  r	  s    r3   mean_resultszMetric.mean_results  s    $*dh77r5   r   r   !tuple[float, float, float, float]c                f    | j         |         | j        |         | j        |         | j        |         fS )z6Return class-aware result, p[i], r[i], ap50[i], ap[i].)r   r  r  r  r  s     r3   class_resultzMetric.class_result  s)    vay$&)TYq\471:==r5   r   c                    t          j        | j                  | j        z   }t	          | j                  D ]\  }}| j        |         ||<   |S )zReturn mAP of each class.)r$   r   r   r  r   r  r  )r   mapsr   r   s       r3   r.  zMetric.maps  sP     x  48+d122 	! 	!DAqgajDGGr5   c                    g d}t          t          j        t          j        |                                                     |z                                            S )z:Return model fitness as a weighted combination of metrics.)r=  r=  r=  r   )r    r$   
nan_to_numr  r)  rl   )r   ws     r3   fitnesszMetric.fitness  sL       bmBHT->->-@-@$A$ABBQFKKMMNNNr5   resultsr  c                    |\
  | _         | _        | _        | _        | _        | _        | _        | _        | _        | _	        dS )a  Update the evaluation metrics with a new set of results.

        Args:
            results (tuple): A tuple containing evaluation metrics:
                - p (list): Precision for each class.
                - r (list): Recall for each class.
                - f1 (list): F1 score for each class.
                - all_ap (list): AP scores for all classes and all IoU thresholds.
                - ap_class_index (list): Index of class for each AP score.
                - p_curve (list): Precision curve for each class.
                - r_curve (list): Recall curve for each class.
                - f1_curve (list): F1 curve for each class.
                - px (list): X values for the curves.
                - prec_values (list): Precision values for each class.
        N)
r   r  r  r  r  r	  r
  r  r  r  )r   r3  s     r3   updatezMetric.update  sF    6 	
FFGKLLMGr5   r   c                    g S >Return a list of curves for accessing specific metrics curves.r   r	  s    r3   curveszMetric.curves  	     	r5   
list[list]c                ~    | j         | j        ddg| j         | j        ddg| j         | j        ddg| j         | j        ddggS )FReturn a list of curves results for accessing specific metrics curves.r  r  r  r  )r  r  r  r	  r
  r	  s    r3   curves_resultszMetric.curves_results  sO     Wd&+>Wdm\48WdlL+>WdlL(;	
 	
r5   Nr!   r   )r!   r  r!   r    r!   rr   r   r   r!   r*  r!   r   )r3  r  r!   r   r!   r;  )r  r  r  r  r   propertyr  r  r  r!  r#  r&  r  r)  r,  r.  r2  r5  r9  r>  r   r5   r3   r  r  N  s        6    = = = X= ? ? ? X? 5 5 5 X5 5 5 5 X5 E E E XE E E E XE ? ? ? X?8 8 8 8> > > >    XO O O O
   :    X 
 
 
 X
 
 
r5   c                     e Zd ZdZi fd-dZd.d	Z ed
          ddfd/dZd Ze	d0d            Z
d1dZd2dZe	d3d            Ze	d4d            Ze	d5d!            Ze	d6d#            Ze	d0d$            Ze	d7d&            Zd8d9d,ZdS ):
DetMetricsa  Utility class for computing detection metrics such as precision, recall, and mean average precision (mAP).

    Attributes:
        names (dict[int, str]): A dictionary of class names.
        box (Metric): An instance of the Metric class for storing detection results.
        speed (dict[str, float]): A dictionary for storing execution times of different parts of the detection process.
        stats (dict[str, list]): A dictionary containing lists for true positives, confidence scores, predicted classes,
            target classes, and target images.
        nt_per_class: Number of targets per class.
        nt_per_image: Number of targets per image.

    Methods:
        update_stats: Update statistics by appending new values to existing stat collections.
        process: Process predicted results for object detection and update metrics.
        clear_stats: Clear the stored statistics.
        keys: Return a list of keys for accessing specific metrics.
        mean_results: Calculate mean of detected objects & return precision, recall, mAP50, and mAP50-95.
        class_result: Return the result of evaluating the performance of an object detection model on a specific class.
        maps: Return mean Average Precision (mAP) scores per class.
        fitness: Return the fitness of box object.
        ap_class_index: Return the average precision index per class.
        results_dict: Return dictionary of computed performance metrics and statistics.
        curves: Return a list of curves for accessing specific metrics curves.
        curves_results: Return a list of computed performance metrics and statistics.
        summary: Generate a summarized representation of per-class detection metrics as a list of dictionaries.
    r   r   r!   r   c                    || _         t                      | _        ddddd| _        t	          g g g g g           | _        d| _        d| _        dS )zInitialize a DetMetrics instance with class names.

        Args:
            names (dict[int, str], optional): Dictionary of class names.
        r=  
preprocess	inferencelosspostprocess)r  r   r  r  
target_imgN)r   r  boxspeedr  statsnt_per_classnt_per_imager   r   s     r3   r   zDetMetrics.__init__  s[     
88$'c3WZ[[
Rb2"QSTTT
  r5   statr   c                    | j                                         D ](}| j         |                             ||                    )dS )zUpdate statistics by appending new values to existing stat collections.

        Args:
            stat (dict[str, Any]): Dictionary containing new statistical values to append. Keys should match existing
                keys in self.stats.
        N)rR  r&  r  )r   rV  r   s      r3   update_statszDetMetrics.update_stats  sJ     "" 	* 	*AJqM  a))))	* 	*r5   .FNr  r   r  r   dict[str, np.ndarray]c                j   d | j                                         D             }|s|S t          |d         |d         |d         |d         ||| j        |d	  	        dd	         }t	          | j                  | j        _        | j                            |           t          j	        |d         
                    t                    t	          | j                  
          | _        t          j	        |d         
                    t                    t	          | j                  
          | _        |S )a  Process predicted results for object detection and update metrics.

        Args:
            save_dir (Path): Directory to save plots. Defaults to Path(".").
            plot (bool): Whether to plot precision-recall curves. Defaults to False.
            on_plot (callable, optional): Function to call after plots are generated. Defaults to None.

        Returns:
            (dict[str, np.ndarray]): Dictionary containing concatenated statistics arrays.
        c                @    i | ]\  }}|t          j        |d           S r  )r$   r  r  s      r3   r   z&DetMetrics.process.<locals>.<dictcomp>2  s*    HHHTQBN1a((HHHr5   r  r   r  r  Box)r  r  r   r  r  r9   N)	minlengthrO  )rR  r   r  r   r   rP  r   r5  r$   bincountr   r   rS  rT  )r   r  r  r  rR  r3  s         r3   processzDetMetrics.process'  s    IHTZ5E5E5G5GHHH 	L$K&M*,*

 

 

 ""
 $*oo   Kl(;(B(B3(G(GSVW[WaSbSbcccKl(;(B(B3(G(GSVW[WaSbSbcccr5   c                f    | j                                         D ]}|                                 dS )zClear the stored statistics.N)rR  rl  clear)r   rd   s     r3   clear_statszDetMetrics.clear_statsF  s8    ""$$ 	 	AGGIIII	 	r5   	list[str]c                
    g dS )z5Return a list of keys for accessing specific metrics.)zmetrics/precision(B)zmetrics/recall(B)zmetrics/mAP50(B)zmetrics/mAP50-95(B)r   r	  s    r3   r&  zDetMetrics.keysK  s     hgggr5   rr   c                4    | j                                         S )zSCalculate mean of detected objects & return precision, recall, mAP50, and mAP50-95.)rP  r)  r	  s    r3   r)  zDetMetrics.mean_resultsP  s    x$$&&&r5   r   r   r*  c                6    | j                             |          S )zaReturn the result of evaluating the performance of an object detection model on a specific class.)rP  r,  r  s     r3   r,  zDetMetrics.class_resultT  s    x$$Q'''r5   r   c                    | j         j        S )z5Return mean Average Precision (mAP) scores per class.)rP  r.  r	  s    r3   r.  zDetMetrics.mapsX  s     x}r5   r    c                4    | j                                         S )z!Return the fitness of box object.)rP  r2  r	  s    r3   r2  zDetMetrics.fitness]  s     x!!!r5   r   c                    | j         j        S )z-Return the average precision index per class.)rP  r  r	  s    r3   r  zDetMetrics.ap_class_indexb       x&&r5   dict[str, float]c                    g | j         d}d g |                                 | j        D             }t          t	          ||                    S )zAReturn dictionary of computed performance metrics and statistics.r2  c              3  X   K   | ]%}t          |d           rt          |          n|V  &dS )r   N)hasattrr    r   s     r3   r   z*DetMetrics.results_dict.<locals>.<genexpr>k  s;      jjawq&1185888qjjjjjjr5   )r&  r)  r2  r  r   )r   r&  rl  s      r3   results_dictzDetMetrics.results_dictg  s[     '&I&jjDhdFWFWFYFYDh[_[gDhjjjCf%%&&&r5   c                
    g dS )r8  )Precision-Recall(B)F1-Confidence(B)Precision-Confidence(B)Recall-Confidence(B)r   r	  s    r3   r9  zDetMetrics.curvesn  s     nmmmr5   r;  c                    | j         j        S z=Return a list of computed performance metrics and statistics.)rP  r>  r	  s    r3   r>  zDetMetrics.curves_resultss  rk  r5   Tr   r/  r  list[dict[str, Any]]c                      j         j         j         j         j         j        d fdt	          t          d                             D             S )a  Generate a summarized representation of per-class detection metrics as a list of dictionaries. Includes
        shared scalar metrics (mAP, mAP50, mAP75) alongside precision, recall, and F1-score for each class.

        Args:
            normalize (bool): For Detect metrics, everything is normalized by default [0-1].
            decimals (int): Number of decimal places to round the metrics values to.

        Returns:
            (list[dict[str, Any]]): A list of dictionaries, each representing one class with corresponding metric
                values.

        Examples:
           >>> results = model.val(data="coco8.yaml")
           >>> detection_summary = results.summary()
           >>> print(detection_summary)
        )Box-PzBox-RzBox-F1c           	        g | ]j         j                          j        j                          j        j                          d fd                                D             t                                        d                   t                                        d                   dS ))ClassImages	Instancesc                D    i | ]\  }}|t          |                   S r   r  r   r   rd   r  r   s      r3   r   z1DetMetrics.summary.<locals>.<listcomp>.<dictcomp>  s-    JJJ11eAaD(++JJJr5   r9   r   )mAP50zmAP50-95)r   r  rT  rS  r   r  r,  )r   r   r  	per_classr   s    @r3   r  z&DetMetrics.summary.<locals>.<listcomp>  s     

 

 

  D$7$:;+D,?,BC!.t/B1/EF  KJJJJ	8I8IJJJ	
 t0033A6AA!$"3"3A"6"6q"98DD  

 

 

r5   rz  )rP  r   r  r  r   r   )r   r/  r  r  s   ` `@r3   r  zDetMetrics.summaryx  st    $ XZXZhk
 
	


 

 

 

 

 

 3y12233

 

 

 
	
r5   r   r   r!   r   )rV  r   r!   r   r  r   r  r   r!   rZ  r!   rd  rA  rB  rC  r@  rD  r!   rl  rE  Tr   r/  r   r  r   r!   rx  )r  r  r  r  r   rX  r   r`  rc  rF  r&  r)  r,  r.  r2  r  rp  r9  r>  r  r   r5   r3   rH  rH    s        6 02 ! ! ! ! !* * * * (,tCyyud     >  
 h h h Xh' ' ' '( ( ( (    X " " " X" ' ' ' X' ' ' ' X' n n n Xn ' ' ' X' 
  
  
  
  
  
  
r5   rH  c                      e Zd ZdZi fd$dZ ed          dd	fd%dZed&d            Zd'dZ	d(dZ
ed)d            Zed*d            Zed&d            Zed+d            Zd,d-d#Zd	S ).SegmentMetricsa  Calculate and aggregate detection and segmentation metrics over a given set of classes.

    Attributes:
        names (dict[int, str]): Dictionary of class names.
        box (Metric): An instance of the Metric class for storing detection results.
        seg (Metric): An instance of the Metric class to calculate mask segmentation metrics.
        speed (dict[str, float]): A dictionary for storing execution times of different parts of the detection process.
        stats (dict[str, list]): A dictionary containing lists for true positives, confidence scores, predicted classes,
            target classes, and target images.
        nt_per_class: Number of targets per class.
        nt_per_image: Number of targets per image.

    Methods:
        process: Process the detection and segmentation metrics over the given set of predictions.
        keys: Return a list of keys for accessing metrics.
        mean_results: Return the mean metrics for bounding box and segmentation results.
        class_result: Return classification results for a specified class index.
        maps: Return mAP scores for object detection and segmentation models.
        fitness: Return the fitness score for both segmentation and bounding box models.
        curves: Return a list of curves for accessing specific metrics curves.
        curves_results: Provide a list of computed performance metrics and statistics.
        summary: Generate a summarized representation of per-class segmentation metrics as a list of dictionaries.
    r   r   r!   r   c                v    t                               | |           t                      | _        g | j        d<   dS )zInitialize a SegmentMetrics instance with class names.

        Args:
            names (dict[int, str], optional): Dictionary of class names.
        tp_mN)rH  r   r  segrR  rU  s     r3   r   zSegmentMetrics.__init__  s7     	D%(((88
6r5   rY  FNr  r   r  r   rZ  c                ,   t                               | |||          }t          |d         |d         |d         |d         |||| j        d	  	        dd	         }t	          | j                  | j        _        | j                            |           |S )
a  Process the detection and segmentation metrics over the given set of predictions.

        Args:
            save_dir (Path): Directory to save plots. Defaults to Path(".").
            plot (bool): Whether to plot precision-recall curves. Defaults to False.
            on_plot (callable, optional): Function to call after plots are generated. Defaults to None.

        Returns:
            (dict[str, np.ndarray]): Dictionary containing concatenated statistics arrays.
        r  r  r   r  r  Maskr  r  r  r   r  r9   N)rH  r`  r  r   r   r  r   r5  )r   r  r  r  rR  results_masks         r3   r`  zSegmentMetrics.process  s     ""44"II#&M&M*,*

 

 

 ""
 $*oo%%%r5   rd  c                T    g t           j                            |           ddddS )z,Return a list of keys for accessing metrics.zmetrics/precision(M)zmetrics/recall(M)zmetrics/mAP50(M)zmetrics/mAP50-95(M)rH  r&  fgetr	  s    r3   r&  zSegmentMetrics.keys  J    
_!!$''
"
  
 	

 "
 	
r5   rr   c                j    t                               |           | j                                        z   S )zBReturn the mean metrics for bounding box and segmentation results.)rH  r)  r  r	  s    r3   r)  zSegmentMetrics.mean_results  s)    &&t,,tx/D/D/F/FFFr5   r   r   c                n    t                               | |          | j                            |          z   S )z:Return classification results for a specified class index.)rH  r,  r  r  s     r3   r,  zSegmentMetrics.class_result  s-    &&tQ//$(2G2G2J2JJJr5   r   c                Z    t           j                            |           | j        j        z   S )z?Return mAP scores for object detection and segmentation models.)rH  r.  r  r  r	  s    r3   r.  zSegmentMetrics.maps  s#     ##D))DHM99r5   r    c                t    | j                                         t          j                            |           z   S )zGReturn the fitness score for both segmentation and bounding box models.)r  r2  rH  r  r	  s    r3   r2  zSegmentMetrics.fitness  s.     x!!J$6$;$;D$A$AAAr5   c                T    g t           j                            |           ddddS )r8  zPrecision-Recall(M)zF1-Confidence(M)zPrecision-Confidence(M)zRecall-Confidence(M)rH  r9  r  r	  s    r3   r9  zSegmentMetrics.curves  sK    
##D))
!
 
 &	

 #
 	
r5   r;  c                Z    t           j                            |           | j        j        z   S rw  )rH  r>  r  r  r	  s    r3   r>  zSegmentMetrics.curves_results  s%     (--d33dh6MMMr5   Tr   r/  r  rx  c                    | j         j        | j         j        | j         j        d}t                              | |          }t          |          D ];\  }|                    i fd|                                D                        <|S )a  Generate a summarized representation of per-class segmentation metrics as a list of dictionaries. Includes
        both box and mask scalar metrics (mAP, mAP50, mAP75) alongside precision, recall, and F1-score for
        each class.

        Args:
            normalize (bool): For Segment metrics, everything is normalized by default [0-1].
            decimals (int): Number of decimal places to round the metrics values to.

        Returns:
            (list[dict[str, Any]]): A list of dictionaries, each representing one class with corresponding metric
                values.

        Examples:
            >>> results = model.val(data="coco8-seg.yaml")
            >>> seg_summary = results.summary(decimals=4)
            >>> print(seg_summary)
        )zMask-PzMask-RzMask-F1c                D    i | ]\  }}|t          |                   S r   r  r  s      r3   r   z*SegmentMetrics.summary.<locals>.<dictcomp>  -    PPPdaE!A$11PPPr5   )	r  r   r  r  rH  r  r   r5  r   r   r/  r  r  r  r  r   s     `   @r3   r  zSegmentMetrics.summary  s    & hjhjx{
 
	
 $$T9h??g&& 	S 	SDAqHHQPPPPPioo>O>OPPPQRRRRr5   r  r  r  rA  r   r   r!   rr   rC  r@  rE  r  r  )r  r  r  r  r   r   r`  rF  r&  r)  r,  r.  r2  r9  r>  r  r   r5   r3   r  r    sW        0 02           (,tCyyud     6 
 
 
 X
G G G GK K K K : : : X: B B B XB 
 
 
 X
 N N N XN      r5   r  c                       e Zd ZdZi fd$ fdZ ed          dd	fd%dZed&d            Zd'dZ	d(dZ
ed)d            Zed*d            Zed&d            Zed+d            Zd,d-d#Z xZS ).PoseMetricsa  Calculate and aggregate detection and pose metrics over a given set of classes.

    Attributes:
        names (dict[int, str]): Dictionary of class names.
        pose (Metric): An instance of the Metric class to calculate pose metrics.
        box (Metric): An instance of the Metric class for storing detection results.
        speed (dict[str, float]): A dictionary for storing execution times of different parts of the detection process.
        stats (dict[str, list]): A dictionary containing lists for true positives, confidence scores, predicted classes,
            target classes, and target images.
        nt_per_class: Number of targets per class.
        nt_per_image: Number of targets per image.

    Methods:
        process: Process the detection and pose metrics over the given set of predictions.
        keys: Return a list of keys for accessing metrics.
        mean_results: Return the mean results of box and pose.
        class_result: Return the class-wise detection results for a specific class i.
        maps: Return the mean average precision (mAP) per class for both box and pose detections.
        fitness: Return combined fitness score for pose and box detection.
        curves: Return a list of curves for accessing specific metrics curves.
        curves_results: Provide a list of computed performance metrics and statistics.
        summary: Generate a summarized representation of per-class pose metrics as a list of dictionaries.
    r   r   r!   r   c                    t                                          |           t                      | _        g | j        d<   dS )zInitialize the PoseMetrics class with class names.

        Args:
            names (dict[int, str], optional): Dictionary of class names.
        tp_pN)superr   r  poserR  )r   r   	__class__s     r3   r   zPoseMetrics.__init__<  s:     	HH	
6r5   rY  FNr  r   r  r   rZ  c                ,   t                               | |||          }t          |d         |d         |d         |d         |||| j        d	  	        dd	         }t	          | j                  | j        _        | j                            |           |S )
a  Process the detection and pose metrics over the given set of predictions.

        Args:
            save_dir (Path): Directory to save plots. Defaults to Path(".").
            plot (bool): Whether to plot precision-recall curves. Defaults to False.
            on_plot (callable, optional): Function to call after plots are generated.

        Returns:
            (dict[str, np.ndarray]): Dictionary containing concatenated statistics arrays.
        r  r  r   r  r  Poser  r9   N)rH  r`  r  r   r   r  r   r5  )r   r  r  r  rR  results_poses         r3   r`  zPoseMetrics.processF  s     ""44"II#&M&M*,*

 

 

 ""
 4:		&&&r5   rd  c                T    g t           j                            |           ddddS )z(Return a list of evaluation metric keys.zmetrics/precision(P)zmetrics/recall(P)zmetrics/mAP50(P)zmetrics/mAP50-95(P)r  r	  s    r3   r&  zPoseMetrics.keysa  r  r5   rr   c                j    t                               |           | j                                        z   S )z(Return the mean results of box and pose.)rH  r)  r  r	  s    r3   r)  zPoseMetrics.mean_resultsl  s)    &&t,,ty/E/E/G/GGGr5   r   r   c                n    t                               | |          | j                            |          z   S )z?Return the class-wise detection results for a specific class i.)rH  r,  r  r  s     r3   r,  zPoseMetrics.class_resultp  s-    &&tQ//$)2H2H2K2KKKr5   r   c                Z    t           j                            |           | j        j        z   S )zSReturn the mean average precision (mAP) per class for both box and pose detections.)rH  r.  r  r  r	  s    r3   r.  zPoseMetrics.mapst  s#     ##D))DIN::r5   r    c                t    | j                                         t          j                            |           z   S )z9Return combined fitness score for pose and box detection.)r  r2  rH  r  r	  s    r3   r2  zPoseMetrics.fitnessy  s.     y  ""Z%7%<%<T%B%BBBr5   c                d    g t           j                            |           ddddddddS )	r8  rr  rs  rt  ru  zPrecision-Recall(P)zF1-Confidence(P)zPrecision-Confidence(P)zRecall-Confidence(P)r  r	  s    r3   r9  zPoseMetrics.curves~  ss    

##D))

!

 

 &	


 #

 "

 

 &

 #

 
	
r5   r;  c                Z    t           j                            |           | j        j        z   S rw  )rH  r>  r  r  r	  s    r3   r>  zPoseMetrics.curves_results  s%     (--d33di6NNNr5   Tr   r/  r  rx  c                    | j         j        | j         j        | j         j        d}t                              | |          }t          |          D ];\  }|                    i fd|                                D                        <|S )a  Generate a summarized representation of per-class pose metrics as a list of dictionaries. Includes both box
        and pose scalar metrics (mAP, mAP50, mAP75) alongside precision, recall, and F1-score for each class.

        Args:
            normalize (bool): For Pose metrics, everything is normalized by default [0-1].
            decimals (int): Number of decimal places to round the metrics values to.

        Returns:
            (list[dict[str, Any]]): A list of dictionaries, each representing one class with corresponding metric
                values.

        Examples:
            >>> results = model.val(data="coco8-pose.yaml")
            >>> pose_summary = results.summary(decimals=4)
            >>> print(pose_summary)
        )zPose-PzPose-RzPose-F1c                D    i | ]\  }}|t          |                   S r   r  r  s      r3   r   z'PoseMetrics.summary.<locals>.<dictcomp>  r  r5   )	r  r   r  r  rH  r  r   r5  r   r  s     `   @r3   r  zPoseMetrics.summary  s    $ ikiky|
 
	
 $$T9h??g&& 	S 	SDAqHHQPPPPPioo>O>OPPPQRRRRr5   r  r  r  rA  r  rC  r@  rE  r  r  )r  r  r  r  r   r   r`  rF  r&  r)  r,  r.  r2  r9  r>  r  __classcell__)r  s   @r3   r  r  #  sl        0 02               (,tCyyud     6 
 
 
 X
H H H HL L L L ; ; ; X; C C C XC 
 
 
 X
 O O O XO        r5   r  c                      e Zd ZdZddZddZedd
            Zedd            Zedd            Z	ed d            Z
ed d            Zd!d"dZdS )#ClassifyMetricsay  Class for computing classification metrics including top-1 and top-5 accuracy.

    Attributes:
        top1 (float): The top-1 accuracy.
        top5 (float): The top-5 accuracy.
        speed (dict[str, float]): A dictionary containing the time taken for each step in the pipeline.

    Methods:
        process: Process target classes and predicted classes to compute metrics.
        fitness: Return mean of top-1 and top-5 accuracies as fitness score.
        results_dict: Return a dictionary with model's performance metrics and fitness score.
        keys: Return a list of keys for the results_dict property.
        curves: Return a list of curves for accessing specific metrics curves.
        curves_results: Provide a list of computed performance metrics and statistics.
        summary: Generate a single-row summary of classification metrics (Top-1 and Top-5 accuracy).
    r!   r   c                :    d| _         d| _        ddddd| _        dS )z&Initialize a ClassifyMetrics instance.r   r=  rJ  N)top1top5rQ  r	  s    r3   r   zClassifyMetrics.__init__  s(    		$'c3WZ[[


r5   r   r6   predc                v   t          j        |          t          j        |          }}|dddf         |k                                    }t          j        |dddf         |                    d          j        fd          }|                    d                                          \  | _        | _	        dS )zProcess target classes and predicted classes to compute metrics.

        Args:
            targets (torch.Tensor): Target classes.
            pred (torch.Tensor): Predicted classes.
        Nr   r8   r   )
r<   r   r    r   r>   rl  r  r   r  r  )r   r   r  correctaccs        r3   r`  zClassifyMetrics.process  s     	$7););g111d7#t+2244k7111a4='++a..*?@aHHH"xx{{1133	4999r5   r    c                &    | j         | j        z   dz  S )z;Return mean of top-1 and top-5 accuracies as fitness score.r9   )r  r  r	  s    r3   r2  zClassifyMetrics.fitness  s     	DI%**r5   rl  c                r    t          t          g | j        d| j        | j        | j        g                    S )zGReturn a dictionary with model's performance metrics and fitness score.r2  )r  r   r&  r  r  r2  r	  s    r3   rp  zClassifyMetrics.results_dict  s6     C/$)/Y/$)TY1UVVWWWr5   rd  c                
    ddgS )z4Return a list of keys for the results_dict property.zmetrics/accuracy_top1zmetrics/accuracy_top5r   r	  s    r3   r&  zClassifyMetrics.keys  s     ()@AAr5   r   c                    g S r7  r   r	  s    r3   r9  zClassifyMetrics.curves  r:  r5   c                    g S )r=  r   r	  s    r3   r>  zClassifyMetrics.curves_results  r:  r5   Tr   r/  r   r  r   r  c                Z    t          | j        |          t          | j        |          dgS )aW  Generate a single-row summary of classification metrics (Top-1 and Top-5 accuracy).

        Args:
            normalize (bool): For Classify metrics, everything is normalized by default [0-1].
            decimals (int): Number of decimal places to round the metrics values to.

        Returns:
            (list[dict[str, float]]): A list with one dictionary containing Top-1 and Top-5 classification accuracy.

        Examples:
            >>> results = model.val(data="imagenet10")
            >>> classify_summary = results.summary(decimals=4)
            >>> print(classify_summary)
        )top1_acctop5_acc)r  r  r  )r   r/  r  s      r3   r  zClassifyMetrics.summary  s.     #49h77U49V^E_E_``aar5   Nr?  )r   r6   r  r6   r@  r  r  rD  r  r  )r  r  r  r  r   r`  rF  r2  rp  r&  r9  r>  r  r   r5   r3   r  r    s        "\ \ \ \
4 
4 
4 
4 + + + X+ X X X XX B B B XB    X    Xb b b b b b br5   r  c                      e Zd ZdZi fddZdS )	
OBBMetricsa  Metrics for evaluating oriented bounding box (OBB) detection.

    Attributes:
        names (dict[int, str]): Dictionary of class names.
        box (Metric): An instance of the Metric class for storing detection results.
        speed (dict[str, float]): A dictionary for storing execution times of different parts of the detection process.
        stats (dict[str, list]): A dictionary containing lists for true positives, confidence scores, predicted classes,
            target classes, and target images.
        nt_per_class: Number of targets per class.
        nt_per_image: Number of targets per image.

    References:
        https://arxiv.org/pdf/2106.06072.pdf
    r   r   r!   r   c                <    t                               | |           dS )zInitialize an OBBMetrics instance with class names.

        Args:
            names (dict[int, str], optional): Dictionary of class names.
        N)rH  r   rU  s     r3   r   zOBBMetrics.__init__  s      	D%(((((r5   Nr  )r  r  r  r  r   r   r5   r3   r  r    s<          02 ) ) ) ) ) ) )r5   r  )Fr   )
r   r   r   r   r   r   r   r    r!   r   )r   )r   r6   r   r6   r   r    r!   r6   )TFFFr   )r   r6   r   r6   rG   r   rH   r   rI   r   rJ   r   r   r    r!   r6   )rh   r6   ri   r6   r   r    r!   r6   )ro   r6   rp   r6   r1   r6   rq   rr   r   r    r!   r6   )r{   r6   r!   r|   )
r   r6   r   r6   rJ   r   r   r    r!   r6   )r   r   r   r   r   r    r!   r6   )r   )r   r    r!   r   )rM  )rY  r   r  r    r!   r   )
r  r   r  r   r  r   r  r   r   r   )r  r   r  r   r  r   r   r   r  r   r  r   )r  rr   r  rr   r!   r  )r  r   r   r   r  r   r  r   r  r   r  r   r   r   r   r    r  r   r!   r  ).r  
__future__r   rO   ro  collectionsr   pathlibr   typingr   r   r$   r<   ultralytics.utilsr   r   r	   r
   r   r   r  float32	OKS_SIGMA
RLE_WEIGHTr4   rF   rg   rn   rz   r   r   r   r   r   r  r  r  r  r  r  rH  r  r  r  r  r   r5   r3   <module>r     ss     " " " " " "   # # # # # #                  c c c c c c c c c c c c c c c c BHnnnj   	 
 RXkkkll
% % % % %>I I I I I4 B B B B BJ( ( ( ( (& bfX X X X X.I I I I(* * * * *Z! ! ! ! !H& & & & & t
 t
 t
 t
 t
o t
 t
 t
n	; ; ; ; ; 
 T.)))i )i )i )i )iX  T.))*c *c *c *c *cZ   J TVV]h ]h ]h ]h ]h@c
 c
 c
 c
 c
[ c
 c
 c
Ld
 d
 d
 d
 d
o d
 d
 d
NE E E E EZ E E EPH H H H H* H H HVLb Lb Lb Lb Lbk? Lb Lb Lb^) ) ) ) ) ) ) ) ) )r5   