
    |h                        d Z ddlZddlZddlmZ ddlmZmZmZm	Z	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      dz  ZdMd	ej.                  d
ej.                  dededej.                  f
dZdNd	ej6                  d
ej6                  dedej6                  fdZ	 	 	 	 	 dOd	ej6                  d
ej6                  dedededededej6                  fdZdNdej6                  dej6                  dedej6                  fdZ	 dNdej6                  dej6                  dej6                  dee   dedej6                  fdZdej6                  de	ej6                  ej6                  ej6                  f   fdZ dMdej6                  d ej6                  dededej6                  f
d!Z!	 dNde
ej6                  ej.                  f   d e
ej6                  ej.                  f   dedej6                  fd"Z"dPdede	eef   fd#Z# G d$ d%e      Z$dQd&ej.                  d'edej.                  fd(Z% e        ed)      i dfd*ej.                  d+ej.                  d,ej.                  d-ed.ee&e'f   f
d/       Z( e        ed0      i d1d2dfd*ej.                  d+ej.                  d-ed.ee&e'f   d3e'd4e'fd5       Z)d6ee   d7ee   de	eej.                  ej.                  f   fd8Z*dd e       i d9d:fd;ej.                  d<ej.                  d=ej.                  d>ej.                  d?ed-ed.ee&e'f   ded@e'de	fdAZ+ G dB d2e      Z, G dC dDee      Z- G dE dFe-      Z. G dG dHe-      Z/ G dI dJee      Z0 G dK dLe-      Z1y)RzModel validation metrics.    N)Path)AnyDictListTupleUnion)LOGGERDataExportMixinSimpleClass	TryExceptchecksplt_settings)gp=
ף?      ?r   ffffff?r   HzG?r   
ףp=
?r   ףp=
?r   Q?r   ףp=
?r   {Gz?r   g      $@Fbox1box2iouepsreturnc                    | j                   \  }}}}|j                   \  }}	}
}t        j                  |dddf   |
      t        j                  |dddf   |      z
  j	                  d      t        j                  |dddf   |      t        j                  |dddf   |	      z
  j	                  d      z  }|
|z
  ||	z
  z  }|r||z
  ||z
  z  }||dddf   z   |z
  }|||z   z  S )aD  
    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                  X/var/www/html/test/engine/venv/lib/python3.12/site-packages/ultralytics/utils/metrics.pybbox_ioar.      s     "&E5%!%E5% **U1d7^U3bjjq$wQV6WW]]^_`


5D>5)BJJuQW~u,MM
d1gJ
 EMeem,D
U]uu}5	i4((:5 $$    c                    | j                         j                  d      j                  dd      |j                         j                  d      j                  dd      c\  }}\  }}t        j                  ||      t        j
                  ||      z
  j                  d      j                  d      }|||z
  j                  d      ||z
  j                  d      z   |z
  |z   z  S )aG  
    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   )float	unsqueezechunktorchminmaxclamp_prod)r   r   r   a1a2b1b2inters           r-   box_iour@   4   s    " //288A>

@V@VWX@Y@_@_`acd@eHRhr2YYr22r!22::1=BB1EE R"WNN1%bq(99EACGHHr/   xywhGIoUDIoUCIoUc                 6   |ru| j                  dd      |j                  dd      c\  }}}	}
\  }}}}|	dz  |
dz  |dz  |dz  f\  }}}}||z
  ||z   ||z
  ||z   f\  }}}}||z
  ||z   ||z
  ||z   f\  }}}}nH| j                  dd      \  }}}}|j                  dd      \  }}}}||z
  ||z
  |z   }
}	||z
  ||z
  |z   }}|j                  |      |j                  |      z
  j                  d      |j                  |      |j                  |      z
  j                  d      z  }|	|
z  ||z  z   |z
  |z   }||z  }|s|s|rK|j                  |      |j                  |      z
  }|j                  |      |j                  |      z
  }|s|r|j	                  d      |j	                  d      z   |z   } ||z   |z
  |z
  j	                  d      ||z   |z
  |z
  j	                  d      z   dz  }!|rdt
        j                  dz  z  ||z  j                         |	|
z  j                         z
  j	                  d      z  }"t        j                         5  |"|"|z
  d|z   z   z  }#ddd       ||!| z  |"#z  z   z
  S ||!| z  z
  S ||z  |z   }$||$|z
  |$z  z
  S |S # 1 sw Y   4xY w)a  
    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.
       r2   r   r1   N)
r5   r   r    r9   powmathpiatanr6   no_grad)%r   r   rA   rB   rC   rD   r   x1y1w1h1x2y2w2h2w1_h1_w2_h2_r"   r$   r#   r%   r&   r(   r'   r)   r?   unionr   cwchc2rho2valphac_areas%                                        r-   bbox_ioura   L   s   > -1ZZ2->

1b@Q*RR*2r2r!VR!VR!VR!V;S#s%'#XrCxc28%K"ueU%'#XrCxc28%K"ueU%)ZZ2%6"ueU%)ZZ2%6"ueU 3B 3B ]]5!EMM%$88@@Ceu}}U33fQiE
 Gb2g%+E %-Ctt]]5!EMM%$88]]5!EMM%$884RVVAY&,B&.33A6%%-%:ORW:W9\9\]^9__D !^b(8BG>>;K(K'P'PQR'SS]]_ 6SAG!45E6dRi!e)344?"b3fun...J6 6s   JJmask1mask2c                     t        j                  | |j                        j                  d      }| j	                  d      dddf   |j	                  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   r1   N)r6   matmulr   r9   sum)rb   rc   r   intersectionrY   s        r-   mask_iourh      s_     <<uww/66q9LYYq\!T'"UYYq\$%77<GE53;''r/   kpt1kpt2r+   sigmac                    | ddddddf   |d   z
  j                  d      | ddddddf   |d   z
  j                  d      z   }t        j                  || j                  | j                        }| d   dk7  }|d|z  j                  d      |ddddf   |z   z  dz  z  }| j                         |dddf   z  j                  d	      |j                  d	      dddf   |z   z  S )
aP  
    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): 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   r2   r1   ).r1   )devicedtype).r2   rG   )rH   r6   tensorrm   rn   exprf   )ri   rj   r+   rk   r   dkpt_maskes           r-   kpt_iourt      s      
aq!m	tF|	+003tAtQM7JTRX\7Y6^6^_`6aaALLt{{$**EEF|q H	a%i__Q44#6#<=ABARHHJ!T'**//3x||B7G47PSV7VWWr/   boxesc                 n   t        j                  | ddddf   j                  d      dz  | ddddf   fd      }|j                  dd      \  }}}|j	                         }|j                         }|j                  d      }|j                  d      }||z  ||z  z   ||z  ||z  z   ||z
  |z  |z  fS )a(  
    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:
        (torch.Tensor): Covariance matrices corresponding to original rotated bounding boxes.
    Nr2   rF      rG   dimr1   )r6   catrH   splitcossin)	ru   gbbsabcr|   r}   cos2sin2s	            r-   _get_covariance_matrixr      s     99eAqsFm''*R/q!"u>BGDjjj#GAq!
%%'C
%%'C771:D771:Dt8a$hD1t8 3a!es]S5HHHr/   obb1obb2c                    | dddf   j                  dd      \  }}|dddf   j                  dd      \  }}t        |       \  }}	}
t        |      \  }}}||z   ||z
  j                  d      z  |	|z   ||z
  j                  d      z  z   ||z   |	|z   z  |
|z   j                  d      z
  |z   z  dz  }|
|z   ||z
  z  ||z
  z  ||z   |	|z   z  |
|z   j                  d      z
  |z   z  dz  }||z   |	|z   z  |
|z   j                  d      z
  d	||	z  |
j                  d      z
  j                  d
      ||z  |j                  d      z
  j                  d
      z  j	                         z  |z   z  |z   j                         dz  }||z   |z   j                  |d      }d| j                         z
  |z   j	                         }d|z
  }|r| ddd	f   j                  dd      \  }}|ddd	f   j                  dd      \  }}d	t        j                  dz  z  ||z  j                         ||z  j                         z
  j                  d      z  }t        j                         5  |||z
  d|z   z   z  }ddd       ||z  z
  S |S # 1 sw Y   xY w)a=  
    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
    .Nr2   r1   rG   rx   r         ?rF   r         Y@      ?)r{   r   rH   r9   sqrtlogclamprp   rI   rJ   rK   r6   rL   )r   r   rD   r   rM   rN   rQ   rR   r;   r=   c1r<   r>   r\   t1t2t3bdhdr   rO   rP   rS   rT   r^   r_   s                             r-   probiour      s   & #rr']   +FB#rr']   +FB'-JBB'-JBB r'b2g]]1%	%bR"WMM!4D(D	D"r'VX[]V]I^bdgibiananopaqIqtwIwx
B GR BG,"r'b2g1F"r'WXIY1Y\_1_
`dg	gB
r'b2g	"r'q!1	1b266!9$,,Q/27RVVAY3F2N2Nq2QQWWYY\__	a
	 
cec	
B
 r'B,		c5	)B
"		
c
!	'	'	)B
b&Cc1Q3h%%aR%0Bc1Q3h%%aR%0B!^b 0BG>>3C CHHKK]]_ 	.SAG,-E	.QYJ	. 	.s   "JJc                 j   t        | t        j                        rt        j                  |       n| } t        |t        j                        rt        j                  |      n|}| dddf   j                  dd      \  }}d |dddf   j                  dd      D        \  }}t        |       \  }}}	d t        |      D        \  }
}}||
z   ||z
  j                  d      z  ||z   ||z
  j                  d      z  z   ||
z   ||z   z  |	|z   j                  d      z
  |z   z  d	z  }|	|z   ||z
  z  ||z
  z  ||
z   ||z   z  |	|z   j                  d      z
  |z   z  d
z  }||
z   ||z   z  |	|z   j                  d      z
  d||z  |	j                  d      z
  j                  d      |
|z  |j                  d      z
  j                  d      z  j                         z  |z   z  |z   j                         d
z  }||z   |z   j                  |d      }d| j                         z
  |z   j                         }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
    .Nr2   r1   rG   rx   c              3   D   K   | ]  }|j                  d       d     ywrG   Nsqueeze.0xs     r-   	<genexpr>z batch_probiou.<locals>.<genexpr>  s     JaaiimD!J    c              3   D   K   | ]  }|j                  d       d     ywr   r   r   s     r-   r   z batch_probiou.<locals>.<genexpr>  s     L!!))B-%Lr   r   r   rF   r   r   r   )
isinstancer   ndarrayr6   
from_numpyr{   r   rH   r9   r   r   r   rp   )r   r   r   rM   rN   rQ   rR   r;   r=   r   r<   r>   r\   r   r   r   r   r   s                     r-   batch_probiour      sS   " &0bjj%A5D!tD%/bjj%A5D!tD#rr']   +FBJ4RaR=+>+>qb+>+IJFB'-JBBL/Ed/KLJBB r'b2g]]1%	%bR"WMM!4D(D	D"r'VX[]V]I^bdgibiananopaqIqtwIwx
B GR BG,"r'b2g1F"r'WXIY1Y\_1_
`dg	gB
r'b2g	"r'q!1	1b266!9$,,Q/27RVVAY3F2N2Nq2QQWWYY\__	a
	 
cec	
B
 r'B,		c5	)B
"		
c
!	'	'	)Br6Mr/   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    r-   
smooth_bcer   '  s     s?C#I%%r/   c                   (   e Zd ZdZg dfdee   defdZd Z	 ddeee	j                  f   deeef   d	ed
eddf
dZd Zdeej"                  ej"                  f   fdZ ed       e       ddedefd              Zd Zddededeeeef      fdZy)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 category.
        names (List[str]): The names of the classes, used as labels on the plot.
    detectnamestaskc                     || _         t        |      | _        | j                   dk(  r1t        j                  | j                  dz   | j                  dz   f      n*t        j                  | j                  | j                  f      | _        || _        y)z
        Initialize a ConfusionMatrix instance.

        Args:
            names (List[str], optional): Names of classes, used as labels on the plot.
            task (str, optional): Type of task, either 'detect' or 'classify'.
        r   r1   N)r   lenncr   zerosmatrixr   )selfr   r   s      r-   __init__zConfusionMatrix.__init__C  sn     	e*>Bii8>Sbhh!TWWq[9:Y[YaYacgcjcjlplslsbtYu
r/   c                 2   t        j                  |      dddf   t        j                  |      }}t        |j                         j	                         |j                         j	                               D ]  \  }}| j
                  |   |xx   dz  cc<   ! y)z
        Update confusion matrix for classification task.

        Args:
            preds (Array[N, min(nc,5)]): Predicted class labels.
            targets (Array[N, 1]): Ground truth class labels.
        Nr   r1   )r6   rz   zipcpunumpyr   )r   predstargetspts        r-   process_cls_predsz!ConfusionMatrix.process_cls_predsP  sx     5)!Q$/71Cw		))+W[[]-@-@-BC 	#DAqKKN1"	#r/   
detectionsbatchconf	iou_thresr   Nc                 `   |dv rdn|}|d   |d   }}t        |d         dk(  }|j                  d   dk(  rj|sgdD ci c]  }|||   |d   |kD      }}|d   j                         j                         }	|	D ]%  }
| j                  |
| j
                  fxx   dz  cc<   ' y	|rI|j                         j                         }|D ]%  }| j                  | j
                  |fxx   dz  cc<   ' y	dD ci c]  }|||   |d   |kD      }}|j                         j                         }|d   j                         j                         }	|d   }|j                  d   d
k(  }|rt        ||      nt        ||      }t        j                  ||kD        }|d   j                  d   rt        j                  t        j                  |d      ||d   |d   f   d	d	d	f   fd      j                         j                         }|d   j                  d   dkD  r||d	d	df   j                         d	d	d      }|t        j                   |d	d	df   d      d      }||d	d	df   j                         d	d	d      }|t        j                   |d	d	df   d      d      }nt        j"                  d      }|j                  d   dkD  }|j%                         j'                  t              \  }}}t)        |      D ]k  \  }}||k(  }|r<t+        |      dk(  r.| j                  |	||   j-                            |fxx   dz  cc<   I| j                  | j
                  |fxx   dz  cc<   m t)        |	      D ]7  \  }}
t/        ||k(        r| j                  |
| j
                  fxx   dz  cc<   9 y	c c}w c c}w )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.
        >   NMbP?r   clsbboxesr   >   r   r   r   r1   N   r2   rG   T)return_index)r      )r   shapeinttolistr   r   r   r@   r6   whererz   stackr   r   argsortr   uniquer   	transposeastype	enumeraterf   itemany)r   r   r   r   r   gt_cls	gt_bboxesno_predkdetection_classesdc
gt_classesgcr   is_obbr   r   matchesnm0m1_ijs                           r-   process_batchzConfusionMatrix.process_batch\  s    },t$!%L%/	j'(A-<<?aSdeaaAz&/AD/H!IIe
e$.u$5$9$9$;$B$B$D!+ 2BKKDGG,1,2,,.J  .DGGRK(A-(.K\]aaAz&'9D'@AA]
]ZZ\((*
&u-113::<H%aA%28mIv.giQW>XKKi(Q4::a=iiQ!2C!ad
OAtG4L MqQUUW]]_Gtzz!}q !'!Q$-"7"7"9$B$"?@!"))GAqDM"Ma"PQ!'!Q$-"7"7"9$B$"?@!"))GAqDM"Ma"PQhhv&GMM!q %%'..s3	Bz* 	.EAraASVq[-bejjl;R?@AE@DGGRK(A-(	. 01 	.EArrQw<BK(A-(	.M f ^s   N&/N+c                     | j                   S )zReturn the confusion matrix.)r   r   s    r-   r   zConfusionMatrix.matrix  s    {{r/   c                     | j                   j                         }| j                   j                  d      |z
  }| j                  dk(  r
|dd |dd fS ||fS )z
        Return true positives and false positives.

        Returns:
            tp (np.ndarray): True positives.
            fp (np.ndarray): False positives.
        r1   r   NrG   )r   diagonalrf   r   )r   tpfps      r-   tp_fpzConfusionMatrix.tp_fp  sX     [[!!#[[__Q"$%)YY(%:3BCR!HRHr/   zConfusionMatrix plot failure)msg	normalizesave_dirc                    ddl m} | j                  |r.| j                  j                  d      j	                  dd      dz   ndz  }t
        j                  ||dk  <   |j                  ddd      \  }}| j                  d	k\  rxt        d
| j                  dz        }t        dd|      }	| j                  |	   | _        ||	ddf   dd|	f   }| j                  |z   dz
  |z  }
| j                  dk(  r|
n|
dz   x}}n,| j                  dk(  r| j                  n| j                  dz   x}}d|cxk  rdk  rn n||k(  r| j                  dgz   nd}t        j                  t        |            }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       |j%                  |ddd      }|j&                  j)                  d       |dk  rd|rdnt        j*                  |      z  }t-        |d|       D ]g  \  }}t-        |d|       D ]Q  \  }}|||f   }t        j.                  |      r#|j1                  |||r|dnt3        |       ddd ||kD  rd!nd"#       S i |j5                  ||d$d%&      }ddd       d'd(|z  z   }|j7                  d)|d *       |j9                  d+|d *       |j;                  ||d,-       |j=                  |       |j?                  |       |jA                  d.d/d0d/d01       |jA                  d2d/d0d/d03       |dk7  r(|jC                  ||d4d5       |jE                  ||6       d7D ]M  }|d8k7  r|jF                  |   jI                  d0       jJ                  jF                  |   jI                  d0       O |jM                  dd9d:|;       tO        |      |jQ                         jS                  d<d=       d>z  }|jU                  |d?@       |jW                  |       |r	 ||       yy# 1 sw Y   xY w)Aav  
        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   Nr1   rG   &.>g{Gzt?)rw   	   )figsized   r2   <   classifyc   
backgroundauto      皙?rw   r   r   ignoreBlues        none)cmapvmininterpolationbottom   ?.2fcenter
   whiteblack)havafontsizecolorgZd;O?皙?)axfractionpadzConfusion Matrixz NormalizedTrue)r  labelpad	Predicted   )r  r  r   TF)axisr  toplabelbottomlabeltopy)r  leftright	labelleft
labelrightZ   )r  rotationr
  )r  >   r  r  r  r  outliner!  gzG?gGz?)r  r  r  r   r   z.png   dpi),matplotlib.pyplotpyplotr   rf   reshaper   nansubplotsr   r8   slicer   r   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_visibler  subplots_adjustr   lowerreplacesavefigclose)r   r   r   on_plotpltarrayfigr  r   keep_idxr   r   nn
ticklabelsxy_tickstick_fontsizelabel_fontsizetitle_fontsizebtmimcolor_thresholdr   rowr   valcbartitles
plot_fnames                                r-   plotzConfusionMatrix.plot  s+    	(Y 2 : :1b AD H\]^!vveem,,q!W,5R77c>Atww"}%AT4+HH-DJ(A+&q({3E1qQ&A99
2aA=B!%j!8dggdggkIB782{{rdjjL>1X^
99S_-ArC"H}-QS2X.QS2X.#tebj()$$& 	E!!(+5wSOBHH''1Bw"&y!bii>N"O'cr
3 FAs"+CH"5 3#AqDk88C=$,5s3ic#hZ''%'-0?-B'   	 <<rEt<DD)	E* #]Y%>>
f~C
kNRH
U^<
h
h
C%TTYZ
Cd%4TYZzMBS[\zMB> 	1AI~		!((/GGNN1))%0	1 	$DE(^)>)>sC)H(I&NN
JC(		#J Q	E 	Es   C4QQc           
          t        | j                  j                  d         D ]A  }t        j                  dj                  t        t        | j                  |                      C y)z*Print the confusion matrix to the console.r   r"  N)ranger   r   r	   infojoinmapstrr   r   s     r-   printzConfusionMatrix.print  sI    t{{((+, 	<AKKS$++a.!9:;	<r/   decimalsc                    ddl }| j                  dk(  r| j                  n| j                  dgz   }g t               }}|D ]z  }|j	                  dd|      }|}	d}
|j                         |v r|	 d|
 }|
dz  }
|j                         |v r|j                  |j                                |j                  |       | | j                  |r.| j                  j                  d      j                  dd      d	z   ndz  j                  |      }t        t        |            D cg c]<  }t        d
||   ifi t        t        |            D ci c]  }||   |||f    c}> c}}S c c}w c c}}w )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   r   z[^a-zA-Z0-9_]r   r1   rG   r   r  )rer   r   setsubrB  addappendr   rf   r(  roundr\  r   dict)r   r   rc  re  r   clean_namesseenname
clean_nameoriginal_cleancounterrH  r   r   s                 r-   summaryzConfusionMatrix.summary  sn   " 	"ii:5

4::;VT 	+D 0#t<J'NG""$, ./q	:
1 ""$, HHZ%%'(z*	+ i!3!;!;Ar!BT!I]^_ffgop 3{+,
 +{1~.qX]^abm^nXo2pST;q>5A;3N2pq
 	
2p
s    (E*E%E*%E*)r   r  )T N)Fr   )__name__
__module____qualname____doc__r   r`  r   r   r   r6   Tensorr   r3   r   r   r   r   r   r   r   r   boolrZ  rb  r   rr  r   r/   r-   r   r   8  s     +-( d3i C 
# rv<.sELL01<.:>sCx.<.PU<.in<.	<.|IuRZZ34 I 12^G d G S G   3G R<
"
 "
 "
T$sTYzJZE[ "
r/   r   r  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.r2   r1   r   rG   valid)mode)rj  r   r   onesconcatenateconvolve)r  rz  nfr   yps        r-   smoothr     s{    	s1vzA~	!	#a	'B
aA	QqT1a!B%i0!	4B;;r2772;+'::r/   zpr_curve.pngpxpyapr   r   c                    ddl m} |j                  dddd      \  }}t        j                  |d      }dt        |      cxk  rdk  rDn nAt        |j                        D ](  \  }	}
|j                  | |
d||	    d	||	df   d
       * n|j                  | |dd       |j                  | |j                  d      ddd|dddf   j                         d
d       |j                  d       |j                  d       |j                  dd       |j                  dd       |j                  dd       |j                  d       |j!                  |d       |j#                  |       |r	 ||       yy)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   Nr1   r   r   Tr   tight_layout)r     r"  .3f	linewidthlabelgreyr  r  r   blueall classes z mAP@0.5r  r  r  Recall	Precisiongp=
ף?r1   
upper leftbbox_to_anchorloczPrecision-Recall Curver#  r$  )r&  r'  r*  r   r   r   r   r   rZ  meanr7  r8  set_xlimset_ylimlegendr9  rD  rE  )r  r  r  r   r   rF  rG  rI  r  r   r  s              r-   plot_pr_curver  (  sY   ( $ll1adlCGC	"1	B3u:bddO 	LDAqGGBQq
!Bq!tHS>.JGK	L 	B!62GGB
av|BqRStHMMO\_K``h=iGjMM(MM+KK1KK1IIYLI9LL)*KKcK"IIcN r/   zmc_curve.png
ConfidenceMetricxlabelylabelc                    ddl m} |j                  dddd      \  }}	dt        |      cxk  rdk  r0n n-t	        |      D ]  \  }
}|	j                  | |d||
             n|	j                  | |j                  dd	
       t        |j                  d      d      }|	j                  | |ddd|j                         dd| |j                            d       |	j                  |       |	j                  |       |	j                  dd       |	j                  dd       |	j                  dd       |	j!                  | d       |j#                  |d       |j%                  |       |r	 ||       yy)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   Nr1   r  Tr  r  r  r  r  r   r   r  r  r  z at r  r  r  r  r  z-Confidence Curver#  r$  )r&  r'  r*  r   r   rZ  r   r  r  r8   argmaxr7  r8  r  r  r  r9  rD  rE  )r  r  r   r   r  r  rF  rG  rI  r  r   r  s               r-   plot_mc_curver  T  sS   , $ll1adlCGC3u:bM 	=DAqGGBQq
G<	= 	BDDAV4rwwqz3AGGBQfl15573-tTVWXW_W_WaTbcfSg4hGiMM&MM&KK1KK1IIYLI9LLF8,-.KKcK"IIcN r/   recall	precisionc                    t        j                  dg| dgf      }t        j                  dg|dgf      }t        j                  t         j                  j	                  t        j                  |                  }d}|dk(  rzt        j
                  ddd      }t        j                  t         j                  d      rt         j                  nt         j                  } |t        j                  |||      |      }nKt        j                  |dd |dd	 k7        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): The recall curve.
        precision (list): 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   r1   e   z>=2.0NrG   )r   r  flipr    
accumulatelinspacer   check_version__version__	trapezoidtrapzr  r   rf   )	r  r  mrecmpremethodr   funcr  r   s	            r-   
compute_apr    s    >>C5&3%01D>>C5)cU34D 772::((78D FKK1c"%33BNNGLr||RTRZRZ"))AtT*A.HHT!"Xcr*+A.VVT!a%[47*d1q5k9:tT>r/   gؗҜ<rs  r   r   pred_cls
target_clsrZ  prefixc
                    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 ]"  \  }}||k(  }
||   }|
j                         }|dk(  s|dk(  r,d| |
   z
  j                  d      }| |
   j                  d      }|||z   z  }t        j                  | ||
    |dddf   d      ||<   |||z   z  }t        j                  | ||
    |dddf   d      ||<   t        | j                  d         D ]Q  }t        |dd|f   |dd|f         \  |||f<   }}|dk(  s,|j                  t        j                  |||             S % |rt        j                  |      nt        j
                  d      }d	|z  |z  ||z   |z   z  }t        |      D 
ci c]  \  }
}||v s|
||    }}
}|r\t        |||||	 d
z  ||       t        ||||	 dz  |d|       t        ||||	 dz  |d|       t        ||||	 dz  |d|       t!        |j#                  d      d      j%                         }
|dd|
f   |dd|
f   |dd|
f   }"}!} |!|z  j'                         } | | |z   z  | z
  j'                         }#| |#| |!|"||j)                  t*              |||||fS c c}}
w )aF  
    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 detections.
        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   r1     N)r  )r1   r  r2   zPR_curve.pngrF  zF1_curve.pngF1)r  rF  zP_curve.pngr  zR_curve.pngr  r   )r   r   r   r   r  r   r   rf   cumsumr  r\  r  ri  rH  r  r  r  r  r  rj  r   r   )$r   r   r  r  rZ  rF  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   rf1r   s$                                       r-   ap_per_classr    s   T 	

D5AAQ!hB :TBNB			a	 B [[At,b{A 88R!$56"d8LbhhXZ\`WaNbB>* =AMfeeg!8sax 2a5y  #ell1o c	"iiT!WHfQTlC 39%	iiT!WHi1oAF rxx{# 	=A$.vad|Yq!t_$M!Br1uItTAv""299Qd#;<	=)=2 ,7"((;'BHHY<OK 7{W$'(9C(?@H%.~%>MTQ!u*Qa[MEMab(x|5L*Le]dea8.E#EuUYcjka(x{-C"CUS^hopa(x{-C"CUS[elmx}}Q%,,.Aq!t}gadmXad^"qA
b&	B
C.2
	$	$	&Br1aR!6!6s!;WgxYZ\ggg Ns   6L=L=c                      e Zd ZdZddZedeej                  e	f   fd       Z
edeej                  e	f   fd       Zedefd       Zedefd       Zedefd	       Zedefd
       Zedefd       Zde	e   fdZdedeeeeef   fdZedej                  fd       ZdefdZdefdZede	fd       Zede	e	   fd       Zy)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. Returns: List of AP scores. Shape: (nc,) or [].
        ap(): AP at IoU thresholds from 0.5 to 0.95 for all classes. Returns: List of AP scores. Shape: (nc,) or [].
        mp(): Mean precision of all classes. Returns: Float.
        mr(): Mean recall of all classes. Returns: Float.
        map50(): Mean AP at IoU threshold of 0.5 for all classes. Returns: Float.
        map75(): Mean AP at IoU threshold of 0.75 for all classes. Returns: Float.
        map(): Mean AP at IoU thresholds from 0.5 to 0.95 for all classes. Returns: Float.
        mean_results(): Mean of results, returns mp, mr, map50, map.
        class_result(i): Class-aware result, returns p[i], r[i], ap50[i], ap[i].
        maps(): mAP of each class. Returns: Array of mAP scores, shape: (nc,).
        fitness(): Model fitness as a weighted combination of metrics. Returns: Float.
        update(results): Update metric attributes with new evaluation results.
    r   Nc                 X    g | _         g | _        g | _        g | _        g | _        d| _        y)zSInitialize a Metric instance for computing evaluation metrics for the YOLOv8 model.r   N)r   r  r  all_apap_class_indexr   r   s    r-   r   zMetric.__init__  s-     r/   c                 V    t        | j                        r| j                  dddf   S g S )z
        Return 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    r-   ap50zMetric.ap50(  s'     %($4t{{1a4 <"<r/   c                 f    t        | j                        r| j                  j                  d      S g S )z
        Return 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.
        r1   r   r  r  r   s    r-   r  z	Metric.ap2  s)     '*$++&6t{{">B>r/   c                 d    t        | j                        r| j                  j                         S dS )z
        Return the Mean Precision of all classes.

        Returns:
            (float): The mean precision of all classes.
        r   )r   r   r  r   s    r-   mpz	Metric.mp<  #     !$DFFtvv{{}44r/   c                 d    t        | j                        r| j                  j                         S dS )z
        Return the Mean Recall of all classes.

        Returns:
            (float): The mean recall of all classes.
        r   )r   r  r  r   s    r-   mrz	Metric.mrF  r  r/   c                 r    t        | j                        r!| j                  dddf   j                         S dS )z
        Return 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    r-   map50zMetric.map50P  0     ,/t{{+;t{{1a4 %%'DDr/   c                 r    t        | j                        r!| j                  dddf   j                         S dS )z
        Return 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    r-   map75zMetric.map75Z  r  r/   c                 d    t        | j                        r| j                  j                         S dS )z
        Return 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    r-   r_  z
Metric.mapd  s'     &)%5t{{!>3>r/   c                 ^    | j                   | j                  | j                  | j                  gS )z+Return mean of results, mp, mr, map50, map.)r  r  r  r_  r   s    r-   mean_resultszMetric.mean_resultsn  s!    $**dhh77r/   r   c                 v    | j                   |   | j                  |   | j                  |   | j                  |   fS )z6Return class-aware result, p[i], r[i], ap50[i], ap[i].)r   r  r  r  ra  s     r-   class_resultzMetric.class_resultr  s1    vvay$&&)TYYq\4771:==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       r-   r  zMetric.mapsv  sS     xx 488+d112 	!DAqggajDG	!r/   c                     g d}t        j                  t        j                  | j                                     |z  j	                         S )z:Return model fitness as a weighted combination of metrics.)r   r   r   g?)r   
nan_to_numrH  r  rf   )r   ws     r-   fitnesszMetric.fitness~  s6     bhht'8'8':;<q@EEGGr/   resultsc                     |\
  | _         | _        | _        | _        | _        | _        | _        | _        | _        | _	        y)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   r  s     r-   updatezMetric.update  s@    8 	
FFGKLLMGr/   c                     g S >Return a list of curves for accessing specific metrics curves.r   r   s    r-   curveszMetric.curves  	     	r/   c                     | j                   | j                  ddg| j                   | j                  ddg| j                   | j                  ddg| j                   | j                  ddggS )r  r  r  r  r  )r  r  r  r  r  r   s    r-   curves_resultszMetric.curves_results  s`     WWd&&+>WWdmm\48WWdllL+>WWdllL(;	
 	
r/   r   N)rt  ru  rv  rw  r   propertyr   r   r   r   r  r  r3   r  r  r  r  r_  r  r   r   r  r  r  tupler  r  r  r   r/   r-   r  r    s   4 =eBJJ,- = = ?E"**d*+ ? ? 5E 5 5 5E 5 5 Eu E E Eu E E ?U ? ?8d5k 8>c >eE5%,F&G > bjj  H H
e <    
T
 
 
r/   c            
          e Zd ZdZi fdeeef   ddfdZdeeef   ddfdZ	 e
d      d	dfd
e
dedeeej                  f   fdZd Zedee   fd       Zdee   fdZdedeeeeef   fdZedej                  fd       Zedefd       Zedefd       Zedeeef   fd       Zedee   fd       Zedee   fd       Zddededeeeef      fdZy)
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.
        task (str): The task type, set to 'detect'.
        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.
    r   r   Nc                     || _         t               | _        ddddd| _        d| _        t        g g g g g       | _        d| _        d| _        y)z
        Initialize a DetMetrics instance with a save directory, plot flag, and class names.

        Args:
            names (Dict[int, str], optional): Dictionary of class names.
        r   
preprocess	inferencelosspostprocessr   )r   r   r  r  
target_imgN)	r   r  boxspeedr   rk  statsnt_per_classnt_per_imager   r   s     r-   r   zDetMetrics.__init__  sQ     
8$'c3WZ[
	Rb2"QST
  r/   statc                     | j                   j                         D ]#  }| j                   |   j                  ||          % y)a  
        Update 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)r  keysri  )r   r	  r   s      r-   update_statszDetMetrics.update_stats  s8     " 	*AJJqM  a)	*r/   .Fr   rZ  c                    | j                   j                         D ci c]  \  }}|t        j                  |d       }}}t	        |      dk(  r|S t        |d   |d   |d   |d   ||| j                  |d	      dd	 }t	        | j                        | j                  _        | j                  j                  |       t        j                  |d   j                  t              t	        | j                        
      | _        t        j                  |d   j                  t              t	        | j                        
      | _        |S c c}}w )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.
        r   r   r   r  r  Box)rZ  r   r   rF  r  r2   N)	minlengthr  )r  itemsr   r  r   r  r   r  r   r  bincountr   r   r  r  )r   r   rZ  rF  r   r^   r  r  s           r-   processzDetMetrics.process  s    6:ZZ5E5E5GHTQBNN1a((HHu:?L$K&M*,**

 "
 $**o KKl(;(B(B3(GSVW[WaWaSbcKKl(;(B(B3(GSVW[WaWaSbc% Is   !E
c                 b    | j                   j                         D ]  }|j                           y)zClear the stored statistics.N)r  valuesclear)r   r^   s     r-   clear_statszDetMetrics.clear_stats  s'    ""$ 	AGGI	r/   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    r-   r  zDetMetrics.keys  s     hgr/   c                 6    | j                   j                         S )zSCalculate mean of detected objects & return precision, recall, mAP50, and mAP50-95.)r  r  r   s    r-   r  zDetMetrics.mean_results  s    xx$$&&r/   r   c                 8    | j                   j                  |      S )zaReturn the result of evaluating the performance of an object detection model on a specific class.)r  r  ra  s     r-   r  zDetMetrics.class_result  s    xx$$Q''r/   c                 .    | j                   j                  S )z5Return mean Average Precision (mAP) scores per class.)r  r  r   s    r-   r  zDetMetrics.maps  s     xx}}r/   c                 6    | j                   j                         S )z!Return the fitness of box object.)r  r  r   s    r-   r  zDetMetrics.fitness  s     xx!!r/   c                 .    | j                   j                  S )z-Return the average precision index per class.)r  r  r   s    r-   r  zDetMetrics.ap_class_index       xx&&&r/   c                     t        t        | j                  dgz   | j                         | j                  gz               S )AReturn dictionary of computed performance metrics and statistics.r  )rk  r   r  r  r  r   s    r-   results_dictzDetMetrics.results_dict  s5     C		YK/1B1B1D~1UVWWr/   c                 
    g dS )r  )Precision-Recall(B)F1-Confidence(B)Precision-Confidence(B)Recall-Confidence(B)r   r   s    r-   r  zDetMetrics.curves  s     nmr/   c                 .    | j                   j                  S r   )r  r  r   s    r-   r  zDetMetrics.curves_results$  r  r/   r   rc  c                 r   | j                   j                  | j                   j                  | j                   j                  d}t	        t        |d               D cg c]  }| j                  | j                  |      | j                  | j                  |      | j                  | j                  |      d|j                         D ci c]  \  }}|t        ||   |       c}}t        | j                  |      d   |      t        | j                  |      d   |      d c}}}S c c}}w c c}}}w )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-F1r*  )ClassImages	Instancesr2   r   )mAP50zmAP50-95)r  r   r  r  r\  r   r   r  r  r  r  rj  r  )r   r   rc  	per_classr   r   r^   s          r-   rr  zDetMetrics.summary)  s!   $ XXZZXXZZhhkk
	 3y123

 

  D$7$7$:;++D,?,?,BC!..t/B/B1/EF 9B8IJ11eAaD(++J	
 t003A6A!$"3"3A"6q"98D

 
	

 K

s   A+D2	D,#AD2,D2Tr   )rt  ru  rv  rw  r   r   r`  r   r   r  r   ry  r   r   r  r  r  r   r  r3   r  r   r  r  r  r  r!  r  r  rr  r   r/   r-   r  r    s    02 !d38n !d !	*c3h 	*D 	* (,Cyud   W[\_acakak\kWl @
 hd3i h h'd5k '(c (eE5%,F&G ( bjj   " " " ' ' ' Xd3:. X X nS	 n n 'T
 ' ' 
  
  
DcSVhDX  
r/   r  c            
       V   e Zd ZdZi fdeeef   ddfdZ ed      ddfded	e	deee
j                  f   fd
Zedee   fd       Zdee   fdZdedee   fdZede
j                  fd       Zedefd       Zedee   fd       Zedee   fd       Zdde	dedeeeef      fdZy)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.
        task (str): The task type, set to 'segment'.
        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.
    r   r   Nc                 z    t         j                  | |       t               | _        d| _        g | j
                  d<   y)z
        Initialize a SegmentMetrics instance with a save directory, plot flag, and class names.

        Args:
            names (Dict[int, str], optional): Dictionary of class names.
        segmenttp_mN)r  r   r  segr   r  r  s     r-   r   zSegmentMetrics.__init__[  s2     	D%(8	

6r/   r  Fr   rZ  c                    t         j                  | |||      }t        |d   |d   |d   |d   |||| j                  d	      dd	 }t	        | j                        | 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  r5  r   r  r  MaskrZ  rF  r   r   r  r2   N)r  r  r  r   r   r6  r   r  )r   r   rZ  rF  r  results_masks         r-   r  zSegmentMetrics.processg  s     ""44"I#&M&M*,**

 "
 $**o%r/   c                 J    t         j                  j                  |       g dz   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)r  r  fgetr   s    r-   r  zSegmentMetrics.keys  %     ##D) -
 
 	
r/   c                 b    t         j                  |       | j                  j                         z   S )zBReturn the mean metrics for bounding box and segmentation results.)r  r  r6  r   s    r-   r  zSegmentMetrics.mean_results  s%    &&t,txx/D/D/FFFr/   r   c                 f    t         j                  | |      | j                  j                  |      z   S )z:Return classification results for a specified class index.)r  r  r6  ra  s     r-   r  zSegmentMetrics.class_result  s)    &&tQ/$((2G2G2JJJr/   c                 n    t         j                  j                  |       | j                  j                  z   S )zHReturn mAP scores for object detection and semantic segmentation models.)r  r  r=  r6  r   s    r-   r  zSegmentMetrics.maps  s&     ##D)DHHMM99r/   c                 v    | j                   j                         t        j                  j                  |       z   S )zGReturn the fitness score for both segmentation and bounding box models.)r6  r  r  r=  r   s    r-   r  zSegmentMetrics.fitness  s-     xx!J$6$6$;$;D$AAAr/   c                 J    t         j                  j                  |       g dz   S )r  )zPrecision-Recall(M)zF1-Confidence(M)zPrecision-Confidence(M)zRecall-Confidence(M)r  r  r=  r   s    r-   r  zSegmentMetrics.curves  s'       %%d+ /
 
 	
r/   c                 n    t         j                  j                  |       | j                  j                  z   S r(  )r  r  r=  r6  r   s    r-   r  zSegmentMetrics.curves_results  s*     ((--d3dhh6M6MMMr/   r   rc  c                 n   | j                   j                  | j                   j                  | j                   j                  d}t        j                  | ||      }t        |      D ]G  \  }}|j                  i |j                         D ci c]  \  }}|t        ||   |       c}}       I |S c c}}w )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-F1)
r6  r   r  r  r  rr  r   r  r  rj  	r   r   rc  r/  rr  r   rX  r   r^   s	            r-   rr  zSegmentMetrics.summary  s    $ hhjjhhjjxx{{
	
 $$T9h?g& 	SDAqHHQioo>OPdaE!A$11PQR	S Q   
B1r0  )rt  ru  rv  rw  r   r   r`  r   r   ry  r   r   r  r  r   r  r3   r  r  r  r  r  r  r   rr  r   r/   r-   r2  r2  L  sR    02 
 d38n 
 d 
  (,Cyud   W[\_acakak\kWl 8 
d3i 
 
Gd5k GKc Kd5k K :bjj : : B B B 
S	 
 
 NT
 N N  DcSVhDX r/   r2  c            
       b    e Zd ZdZi fdeeef   ddf fdZ ed      ddfded	e	deee
j                  f   fd
Zedee   fd       Zdee   fdZdedee   fdZede
j                  fd       Zedefd       Zedee   fd       Zedee   fd       Zdde	dedeeeef      f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.
        task (str): The task type, set to 'pose'.
        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(tp_m, tp_b, conf, pred_cls, target_cls): Process metrics over the given set of predictions.
        mean_results(): Return the mean of the detection and segmentation metrics over all the classes.
        class_result(i): Return the detection and segmentation metrics of class `i`.
        maps: Return the mean Average Precision (mAP) scores for IoU thresholds ranging from 0.50 to 0.95.
        fitness: Return the fitness scores, which are a single weighted combination of metrics.
        ap_class_index: Return the list of indices of classes used to compute Average Precision (AP).
        results_dict: Return the dictionary containing all the detection and segmentation metrics and fitness score.
    r   r   Nc                 n    t         |   |       t               | _        d| _        g | j
                  d<   y)z
        Initialize the PoseMetrics class with directory path, class names, and plotting options.

        Args:
            names (Dict[int, str], optional): Dictionary of class names.
        posetp_pN)superr   r  rL  r   r  )r   r   	__class__s     r-   r   zPoseMetrics.__init__  s0     	H		

6r/   r  Fr   rZ  c                    t         j                  | |||      }t        |d   |d   |d   |d   |||| j                  d	      dd	 }t	        | j                        | 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  rM  r   r  r  Poser9  r2   N)r  r  r  r   r   rL  r   r  )r   r   rZ  rF  r  results_poses         r-   r  zPoseMetrics.process  s     ""44"I#&M&M*,**

 "
 4::				&r/   c                 J    t         j                  j                  |       g dz   S )z&Return 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    r-   r  zPoseMetrics.keys
  r>  r/   c                 b    t         j                  |       | j                  j                         z   S )z(Return the mean results of box and pose.)r  r  rL  r   s    r-   r  zPoseMetrics.mean_results  s%    &&t,tyy/E/E/GGGr/   r   c                 f    t         j                  | |      | j                  j                  |      z   S )z?Return the class-wise detection results for a specific class i.)r  r  rL  ra  s     r-   r  zPoseMetrics.class_result  s)    &&tQ/$))2H2H2KKKr/   c                 n    t         j                  j                  |       | j                  j                  z   S )zSReturn the mean average precision (mAP) per class for both box and pose detections.)r  r  r=  rL  r   s    r-   r  zPoseMetrics.maps  s&     ##D)DIINN::r/   c                 v    | j                   j                         t        j                  j                  |       z   S )z9Return combined fitness score for pose and box detection.)rL  r  r  r=  r   s    r-   r  zPoseMetrics.fitness!  s-     yy  "Z%7%7%<%<T%BBBr/   c                 J    t         j                  j                  |       g dz   S )r  )r#  r$  r%  r&  zPrecision-Recall(P)zF1-Confidence(P)zPrecision-Confidence(P)zRecall-Confidence(P)rD  r   s    r-   r  zPoseMetrics.curves&  s'       %%d+ 	/
 	
 		
r/   c                 n    t         j                  j                  |       | j                  j                  z   S r(  )r  r  r=  rL  r   s    r-   r  zPoseMetrics.curves_results4  s*     ((--d3dii6N6NNNr/   r   rc  c                 n   | j                   j                  | j                   j                  | j                   j                  d}t        j                  | ||      }t        |      D ]G  \  }}|j                  i |j                         D ci c]  \  }}|t        ||   |       c}}       I |S c c}}w )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-F1)
rL  r   r  r  r  rr  r   r  r  rj  rG  s	            r-   rr  zPoseMetrics.summary9  s    $ iikkiikkyy||
	
 $$T9h?g& 	SDAqHHQioo>OPdaE!A$11PQR	S QrH  r0  )rt  ru  rv  rw  r   r   r`  r   r   ry  r   r   r  r  r   r  r3   r  r  r  r  r  r  r   rr  __classcell__)rO  s   @r-   rJ  rJ    sS   . 02 
 d38n 
 d 
  (,Cyud   W[\_acakak\kWl 8 
d3i 
 
Hd5k HLc Ld5k L ;bjj ; ; C C C 
S	 
 
 OT
 O O  DcSVhDX r/   rJ  c            
           e Zd ZdZddZdej                  dej                  fdZede	fd       Z
edeee	f   fd	       Zedee   fd
       Zedefd       Zedefd       Zddededeeee	f      fdZy)ClassifyMetricsaO  
    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): A dictionary containing the time taken for each step in the pipeline.
        task (str): The task type, set to 'classify'.
    r   Nc                 F    d| _         d| _        ddddd| _        d| _        y)z&Initialize a ClassifyMetrics instance.r   r   r  r   N)top1top5r  r   r   s    r-   r   zClassifyMetrics.__init__`  s(    		$'c3WZ[
	r/   r   predc                 V   t        j                  |      t        j                  |      }}|dddf   |k(  j                         }t        j                  |dddf   |j	                  d      j
                  fd      }|j                  d      j                         \  | _        | _	        y)z
        Process target classes and predicted classes to compute metrics.

        Args:
            targets (torch.Tensor): Target classes.
            pred (torch.Tensor): Predicted classes.
        Nr   r1   rx   )
r6   rz   r3   r   r8   r  r  r   r_  r`  )r   r   ra  correctaccs        r-   r  zClassifyMetrics.processg  s     		$7);g1d7#t+224kk71a4='++a.*?*?@aH"xx{113	49r/   c                 :    | j                   | j                  z   dz  S )z;Return mean of top-1 and top-5 accuracies as fitness score.r2   )r_  r`  r   s    r-   r  zClassifyMetrics.fitnesst  s     		DII%**r/   c                     t        t        | j                  dgz   | j                  | j                  | j
                  g            S )zGReturn a dictionary with model's performance metrics and fitness score.r  )rk  r   r  r_  r`  r  r   s    r-   r!  zClassifyMetrics.results_dicty  s4     C		YK/$))TYY1UVWWr/   c                 
    ddgS )z4Return a list of keys for the results_dict property.zmetrics/accuracy_top1zmetrics/accuracy_top5r   r   s    r-   r  zClassifyMetrics.keys~  s     ()@AAr/   c                     g S r  r   r   s    r-   r  zClassifyMetrics.curves  r  r/   c                     g S r  r   r   s    r-   r  zClassifyMetrics.curves_results  r  r/   r   rc  c                 ^    t        | j                  |      t        | j                  |      dgS )aa  
        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)rj  r_  r`  )r   r   rc  s      r-   rr  zClassifyMetrics.summary  s)      #499h7U499V^E_`aar/   r  r0  )rt  ru  rv  rw  r   r6   rx  r  r  r3   r  r   r`  r!  r   r  r  r  ry  r   rr  r   r/   r-   r]  r]  U  s    4u|| 45<< 4 + + + Xd3:. X X Bd3i B B      b b bDcSXjIYDZ br/   r]  c                   .    e Zd ZdZi fdeeef   ddfdZy)
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.
        task (str): The task type, set to 'obb'.
        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   Nc                 >    t         j                  | |       d| _        y)z
        Initialize an OBBMetrics instance with directory, plotting, and class names.

        Args:
            names (Dict[int, str], optional): Dictionary of class names.
        obbN)r  r   r   r  s     r-   r   zOBBMetrics.__init__  s     	D%(	r/   )rt  ru  rv  rw  r   r   r`  r   r   r/   r-   rn  rn    s'      02 	d38n 	d 	r/   rn  )FHz>)rq  )TFFFrq  )r   )r  )2rw  rI   r-  pathlibr   typingr   r   r   r   r   r   r   r6   ultralytics.utilsr	   r
   r   r   r   r   rH  	OKS_SIGMAr   ry  r3   r.   rx  r@   ra   rh   rt   r   r   r   r   r   r  r   r`  r  r  r  r  r  r  r2  rJ  r]  rn  r   r/   r-   <module>rv     s       0 0   c c BHHst
 
%2:: %RZZ %d % %Z\ZdZd %@I%,, Iell I I%,, I6 D
,,D
,,D D 	D
 D D 
D \\DN(ELL ( (E (U\\ (( bfX
,,X#llX27,,XGKE{XY^X
\\X0I%,, I5u||UZUaUa9a3b I(+%,, +ell +$ +U +^c^j^j +^ `d$
bjj(
)$16u||RZZ7O1P$W\$
\\$N&E &E%,$7 &"e
o e
P;bjj ;U ;bjj ; 
 .)(


(


( 	

( 	(
 S>( (V  .)*


*


* * S>	*
 * * *ZtE{ tE{ uUBJJXZXbXbEb?c L V^h


^h
**^h jj^h 

	^h
 ^h ^h S>^h 
^h ^h ^hBj
[ j
ZX
o X
v{Z {|H* HVHbk? HbV r/   