o
    Wh                     @   s  d Z ddlZddl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 e	g dd Zd;d	d
Zd<ddZd=ddZd<ddZd<ddZdd Zd;ddZd<ddZd>ddZG dd dZd?d d!Ze ed"i dfd#d$Ze ed%i d&d'dfd(d)Zd*d+ Z dde i d,d-fd.d/Z!G d0d' d'eZ"G d1d2 d2eZ#G d3d4 d4eZ$G d5d6 d6e$Z%G d7d8 d8eZ&G d9d: d:eZ'dS )@zModel validation metrics.    N)Path)LOGGERSimpleClass	TryExceptchecksplt_settings)gp=
ף?      ?r   ffffff?r	   HzG?r
   
ףp=
?r   ףp=
?r   Q?r   ףp=
?r   {Gz?r   g      $@FHz>c                 C   s   | j \}}}}|j \}}	}
}t|dddf |
t|dddf | dt|dddf |t|dddf |	 d }|
| ||	  }|rb|| ||  }||dddf  | }|||  S )a2  
    Calculate the intersection over box2 area given box1 and box2. Boxes are in x1y1x2y2 format.

    Args:
        box1 (np.ndarray): A numpy array of shape (n, 4) representing n bounding boxes.
        box2 (np.ndarray): A numpy array of shape (m, 4) representing m bounding boxes.
        iou (bool): 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)box1box2iouepsb1_x1b1_y1b1_x2b1_y2b2_x1b2_y1b2_x2b2_y2
inter_areaarea	box1_area r%   M/var/www/vscode/kcb/lib/python3.10/site-packages/ultralytics/utils/metrics.pybbox_ioa   s   4.r'   c                 C   s   |   ddd|  ddd\}}\}}t||t|| dd}||| d|| d | |  S )aH  
    Calculate intersection-over-union (IoU) of boxes. Both sets of boxes are expected to be in (x1, y1, x2, y2) format.
    Based on https://github.com/pytorch/vision/blob/main/torchvision/ops/boxes.py.

    Args:
        box1 (torch.Tensor): A tensor of shape (N, 4) representing N bounding boxes.
        box2 (torch.Tensor): A tensor of shape (M, 4) representing M bounding boxes.
        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.
          r   )float	unsqueezechunktorchminmaxclamp_prod)r   r   r   a1a2b1b2interr%   r%   r&   box_iou4   s   6$(r7   Tc           %      C   s|  |rN|  dd| dd\}}}	}
\}}}}|	d |
d |d |d f\}}}}|| || || || f\}}}}|| || || || f\}}}}n*|  dd\}}}}| dd\}}}}|| || | }	}
|| || | }}|||| d|||| d }|	|
 ||  | | }|| }|s|s|r<|||| }|||| }|s|r.|d|d | } || | | d|| | | d d }!|r(dtjd  ||  |	|
   d }"t	  |"|"| d|   }#W d   n	1 sw   Y  ||!|  |"|#   S ||!|   S || | }$||$| |$  S |S )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.
       r)   r   r(   N)
r,   r   r   r0   powmathpiatanr-   no_grad)%r   r   xywhGIoUDIoUCIoUr   x1y1w1h1x2y2w2h2w1_h1_w2_h2_r   r   r   r   r   r    r   r!   r6   unionr   cwchc2rho2valphac_arear%   r%   r&   bbox_iouJ   sB   *$$&
*,
rW   c                 C   sH   t | |jd}| ddddf |dd  | }|||  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   r(   N)r-   matmulr   r0   sum)mask1mask2r   intersectionrO   r%   r%   r&   mask_iou   s   (r]   c                 C   s   | ddddddf |d   d| ddddddf |d   d }tj|| j| jd}| d dk}|d|  d|ddddf |  d  }|  |dddf  d	|d	dddf |  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   r)   r(   ).r(   )devicedtype).r)   r9   )r:   r-   tensorr^   r_   exprY   )kpt1kpt2r#   sigmar   dkpt_masker%   r%   r&   kpt_iou   s
   L,:rh   c           	      C   s   t j| ddddf dd | ddddf fdd}|jddd\}}}| }| }|d}|d}|| ||  || ||  || | | 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.
    Nr)   r8      r9   dimr(   )r-   catr:   splitcossin)	boxesgbbsabcrn   ro   cos2sin2r%   r%   r&   _get_covariance_matrix   s   <

.rw   c                 C   s<  | dddf j ddd\}}|dddf j ddd\}}t| \}}	}
t|\}}}|| || d |	| || d  || |	|  |
| d |  d }|
| ||  ||  || |	|  |
| d |  d }|| |	|  |
| d d	||	 |
d d
|| |d d
   |  |  d }|| | |d}d|   |  }d| }|r| ddd	f j ddd\}}|ddd	f j ddd\}}d	tj	d  || 
 || 
  d }t  ||| d|   }W d   n	1 sw   Y  |||  S |S )aO  
    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].
        - Implements the algorithm from https://arxiv.org/pdf/2106.06072v1.pdf.
    .Nr)   r(   r9   rj   r         ?r8   r         Y@      ?)rm   rw   r:   r0   sqrtlogclampra   r;   r<   r=   r-   r>   )obb1obb2rB   r   rC   rD   rG   rH   r2   r4   c1r3   r5   rR   t1t2t3bdhdr   rE   rF   rI   rJ   rT   rU   r%   r%   r&   probiou   s6   L>:,
r   c                 C   s  t | tjrt| n| } t |tjrt|n|}| dddf jddd\}}dd |dddf jdddD \}}t| \}}}	d	d t|D \}
}}||
 || d || || d  ||
 ||  |	| d |  d
 }|	| ||  ||  ||
 ||  |	| d |  d }||
 ||  |	| d d|| |	d d|
| |d d 	  |  | 
 d }|| | |d}d|   | 	 }d| 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
    .Nr)   r(   r9   rj   c                 s       | ]
}| d d V  qdS r9   Nsqueeze.0xr%   r%   r&   	<genexpr>      z batch_probiou.<locals>.<genexpr>c                 s   r   r   r   r   r%   r%   r&   r     r   r   rx   r8   r   ry   rz   )
isinstancer   ndarrayr-   
from_numpyrm   rw   r:   r0   r{   r|   r}   ra   )r~   r   r   rC   rD   rG   rH   r2   r4   r   r3   r5   rR   r   r   r   r   r   r%   r%   r&   batch_probiou   s(   (L>:r   皙?c                 C   s   dd|   d|  fS )ai  
    Compute smoothed positive and negative Binary Cross-Entropy targets.

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

    Returns:
        (tuple): A tuple containing the positive and negative label smoothing BCE targets.

    References:
        https://github.com/ultralytics/yolov3/issues/238#issuecomment-598028441
    rz   rx   r%   )r   r%   r%   r&   
smooth_bce  s   r   c                   @   s\   e Zd ZdZdddZdd Zd	d
 Zdd Zdd Ze	dde
 dddZdd 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.
        conf (float): The confidence threshold for detections.
        iou_thres (float): The Intersection over Union threshold.
    r   ?detectc                 C   sX   || _ | j dkrt|d |d fnt||f| _|| _|dv r$dn|| _|| _dS )ah  
        Initialize a ConfusionMatrix instance.

        Args:
            nc (int): Number of classes.
            conf (float, optional): Confidence threshold for detections.
            iou_thres (float, optional): IoU threshold for matching detections to ground truth.
            task (str, optional): Type of task, either 'detect' or 'classify'.
        r   r(   >   NMbP?r   N)taskr   zerosmatrixncconf	iou_thres)selfr   r   r   r   r%   r%   r&   __init__3  s
   
0
zConfusionMatrix.__init__c                 C   s`   t |dddf t |}}t|  |  D ]\}}| j| |  d7  < qdS )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   r(   )r-   rl   zipcpunumpyr   )r   predstargetsptr%   r%   r&   process_cls_predsC  s   ""z!ConfusionMatrix.process_cls_predsc                 C   s  |j d dkr5|dur3||dddf | jk }|dddf  }|D ]}| j|| jf  d7  < q$dS |du rP| }|D ]}| j| j|f  d7  < q?dS ||dddf | jk }| }|dddf  }|j d dkox|j d dk}|rt|tj|ddddf |ddddf gddnt||ddddf }	t	|	| j
k}
|
d j d r!tt|
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d	f  ddd  }|tj|dddf d
dd  }ntd}|j d dk}| t\}}}t|D ]0\}}||k}|r^t|dkr^| j|||  |f  d7  < q;| j| j|f  d7  < q;t|D ]\}}t||ks| j|| jf  d7  < qpdS )a  
        Update confusion matrix for object detection task.

        Args:
            detections (Array[N, 6] | Array[N, 7]): Detected bounding boxes and their associated information.
                                      Each row should contain (x1, y1, x2, y2, conf, class)
                                      or with an additional element `angle` when it's obb.
            gt_bboxes (Array[M, 4]| Array[N, 5]): Ground truth bounding boxes with xyxy/xyxyr format.
            gt_cls (Array[M]): The class labels.
        r   Nr8      r(      r9   rj   r)   T)return_index)r      )shaper   intr   r   r   r-   rl   r7   wherer   stackr   r   argsortr   uniquer   	transposeastype	enumeraterY   any)r   
detections	gt_bboxesgt_clsdetection_classesdc
gt_classesgcis_obbr   r   matchesnm0m1_ijr%   r%   r&   process_batchO  sT   :<""""
"zConfusionMatrix.process_batchc                 C   s   | j S )zReturn the confusion matrix.)r   r   r%   r%   r&   r     s   zConfusionMatrix.matrixc                 C   sD   | j  }| j d| }| jdkr|dd |dd fS ||fS )z
        Return true positives and false positives.

        Returns:
            (tuple): True positives and false positives.
        r(   r   Nr9   )r   diagonalrY   r   )r   tpfpr%   r%   r&   tp_fp  s   
*zConfusionMatrix.tp_fpzConfusionMatrix plot failure)msgT r%   Nc                 C   s  ddl }| j|r| jdddd nd }tj||dk < tjddddd	\}}| jt	|}	}
|j
|	d
k r9dndd d|
  k oFdk n  oL|
|	k}|rVt|dg nd}t ' td |j|||	dk ddid|rqdnddd||d
d W d   n1 sw   Y  dd|  }|d |d || t|| dd  d! }|j|d"d# t| |r|| dS dS )$a  
        Plot the confusion matrix using seaborn and save it to a file.

        Args:
            normalize (bool): Whether to normalize the confusion matrix.
            save_dir (str): Directory where the plot will be saved.
            names (tuple): Names of classes, used as labels on the plot.
            on_plot (func): An optional callback to pass plots path and data when they are rendered.
        r   Nr(   r9   g&.>g{Gzt?)ri   	   Tfigsizetight_layout2   rz   g?)
font_scalec   
backgroundautoignore   size   Blues.2fz.0f        )	axannot	annot_kwscmapfmtsquarevminxticklabelsyticklabels)r(   r(   r(   zConfusion Matrixz NormalizedTrue	Predicted r   z.png   dpi)seabornr   rY   reshaper   nanpltsubplotsr   len	set_themelistwarningscatch_warningssimplefilterheatmapset_facecolor
set_xlabel
set_ylabel	set_titler   lowerreplacesavefigclose)r   	normalizesave_dirnameson_plotr   arrayfigr   r   nnlabels
ticklabelstitle
plot_fnamer%   r%   r&   plot  sD   & 







zConfusionMatrix.plotc              	   C   s6   t | jjd D ]}tdtt| j|  qdS )z*Print the confusion matrix to the console.r   r   N)ranger   r   r   infojoinmapstrr   r   r%   r%   r&   print  s   zConfusionMatrix.print)r   r   r   )Tr   r%   N)__name__
__module____qualname____doc__r   r   r   r   r   r   r   r  r  r%   r%   r%   r&   r   '  s    
:,r   皙?c                 C   sf   t t| | d d d }t|d }t|| d  | || d  fd}tj|t|| ddS )zBox filter of fraction f.r)   r(   r   r9   valid)mode)roundr   r   onesconcatenateconvolve)yfnfr   ypr%   r%   r&   smooth  s   "r$  zpr_curve.pngc           
   
   C   s6  t jddddd\}}tj|dd}dt|  k rdk r@n n t|jD ]\}}	|j| |	d||  d||df d	d
 q%n	|j| |ddd |j| |dddd|dddf  d	dd |	d |
d |dd |dd |jddd |d |j|dd t | |r|| 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, optional): Dictionary mapping class indices to class names.
        on_plot (callable, optional): Function to call after plot is saved.
    r(   r      Tr   )axisr      r   .3f	linewidthlabelgreyr+  colorr   blueall classes Nz mAP@0.5r+  r/  r,  Recall	Precisiongp=
ף?r(   
upper leftbbox_to_anchorloczPrecision-Recall Curver   r   )r   r   r   r   r   r   r   r  meanr   r   set_xlimset_ylimlegendr   r   r  )
pxpyapr  r  r  r  r   r   r   r%   r%   r&   plot_pr_curve  s&   ,4



rA  zmc_curve.png
ConfidenceMetricc                 C   s(  t jddddd\}}dt|  k rdk r/n nt|D ]\}	}
|j| |
d||	  d qn
|j| |jddd	 t|dd
}
|j| |
ddd|
 dd| |
	  dd |
| || |dd |dd |jddd || d |j|dd t | |r|| 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, 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(   r%  Tr   r   r(  r*  r-  r.  r   r   r0  r1  r   z at r)  r2  r5  r6  r7  z-Confidence Curver   r   N)r   r   r   r   r  r   r$  r:  r/   argmaxr   r   r;  r<  r=  r   r   r  )r>  r?  r  r  xlabelylabelr  r  r   r   r   r%   r%   r&   plot_mc_curve  s&   0


rG  c           	      C   s   t dg| dgf}t dg|dgf}t t jt |}d}|dkrEt ddd}tt jdr7t j	nt j
}|t ||||}n$t |dd |dd	 kd }t ||d  ||  ||d   }|||fS )
ay  
    Compute the average precision (AP) given the recall and precision curves.

    Args:
        recall (list): The recall curve.
        precision (list): The precision curve.

    Returns:
        (float): Average precision.
        (np.ndarray): Precision envelope curve.
        (np.ndarray): Modified recall curve with sentinel values added at the beginning and end.
    r   rz   interpr   r(   e   z>=2.0Nr9   )r   r  flipr   
accumulatelinspacer   check_version__version__	trapezoidtrapzrH  r   rY   )	recall	precisionmrecmpremethodr   funcr@  r   r%   r%   r&   
compute_ap  s   "&
rW  gؗҜ<r   c
           "         s  t | }
| |
 ||
 ||
 } }}t j|dd\ } jd }t dddg }}t || jd ft |dft |df}}}t D ]\}}||k}
|| }|
 }|dksb|dkrcqJd| |
  d}| |
 d}|||  }t j	| ||
  |dddf dd||< |||  }t j	| ||
  |dddf dd||< t
| jd D ](}t|dd|f |dd|f \|||f< }}|dkr|t 	||| qqJ|rt |nt d}d	| | || |  } fd
d| D }tt|}|rBt|||||	 d ||d t||||	 d |d|d t||||	 d |d|d t||||	 d |d|d t|dd }
|dd|
f |dd|
f |dd|
f }}} ||  } | ||  |   }!| |!||| | t|||||fS )a2  
    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 (func, 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, optional): Dict 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   r(     N)left)r(   rY  r)   c                    s   g | ]
\}}| v r|qS r%   r%   )r   krT   unique_classesr%   r&   
<listcomp>  s    z ap_per_class.<locals>.<listcomp>zPR_curve.png)r  zF1_curve.pngF1)rF  r  zP_curve.pngr4  zR_curve.pngr3  r   )r   r   r   r   rL  r   r   rY   cumsumrH  r  rW  appendr  itemsdictrA  rG  r$  r:  rD  r  r   r   )"r   r   pred_cls
target_clsr  r  r  r  r   prefixr   ntr   r   prec_valuesr@  p_curver_curvecirt   n_ln_pfpctpcrQ  rR  r   rT  rS  f1_curver   rf1r   r%   r\  r&   ap_per_class=  sL   !
4**04"rs  c                   @   s   e Zd ZdZd"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 )#rC  a  
    Class for computing evaluation metrics for YOLOv8 model.

    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.
    returnNc                 C   s(   g | _ g | _g | _g | _g | _d| _dS )zSInitialize a Metric instance for computing evaluation metrics for the YOLOv8 model.r   N)r   rq  rr  all_apap_class_indexr   r   r%   r%   r&   r     s   
zMetric.__init__c                 C   s    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   ru  r   r%   r%   r&   ap50  s    zMetric.ap50c                 C   s   t | jr| 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.
        r(   r   ru  r:  r   r%   r%   r&   r@    s   z	Metric.apc                 C      t | jr
| 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   r%   r%   r&   mp     z	Metric.mpc                 C   ry  )z
        Return the Mean Recall of all classes.

        Returns:
            (float): The mean recall of all classes.
        r   )r   rq  r:  r   r%   r%   r&   mr  r{  z	Metric.mrc                 C   $   t | jr| jdddf  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   rx  r   r%   r%   r&   map50     $zMetric.map50c                 C   r}  )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   rx  r   r%   r%   r&   map75  r  zMetric.map75c                 C   ry  )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   rx  r   r%   r%   r&   r    r{  z
Metric.mapc                 C   s   | j | j| j| jgS )z+Return mean of results, mp, mr, map50, map.)rz  r|  r~  r  r   r%   r%   r&   mean_results      zMetric.mean_resultsc                 C   s$   | j | | j| | j| | j| fS )z6Return class-aware result, p[i], r[i], ap50[i], ap[i].)r   rq  rw  r@  r  r%   r%   r&   class_result  s   $zMetric.class_resultc                 C   s8   t | j| j }t| jD ]\}}| j| ||< q|S )zReturn mAP of each class.)r   r   r   r  r   rv  r@  )r   mapsr   rt   r%   r%   r&   r    s   zMetric.mapsc                 C   s   g d}t |  |  S )z:Return model fitness as a weighted combination of metrics.)r   r   r   g?)r   r  r  rY   )r   wr%   r%   r&   fitness  s   zMetric.fitnessc                 C   s0   |\
| _ | _| _| _| _| _| _| _| _| _	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   rq  rr  ru  rv  ri  rj  rp  r>  rh  )r   resultsr%   r%   r&   update  s   zMetric.updatec                 C      g S >Return a list of curves for accessing specific metrics curves.r%   r   r%   r%   r&   curves3     zMetric.curvesc                 C   s<   | j | jddg| j | jddg| j | jddg| j | jddggS )r  r3  r4  rB  r_  )r>  rh  rp  ri  rj  r   r%   r%   r&   curves_results8  s
   zMetric.curves_resultsrt  N)r  r  r  r  r   propertyrw  r@  rz  r|  r~  r  r  r  r  r  r  r  r  r  r%   r%   r%   r&   rC    s6    
	
	
	
	
	
	
	
	

c                   @   s   e Zd ZdZeddi fdddZd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edd Zedd ZdS )
DetMetricsag  
    Utility class for computing detection metrics such as precision, recall, and mean average precision (mAP).

    Attributes:
        save_dir (Path): A path to the directory where the output plots will be saved.
        plot (bool): A flag that indicates whether to plot precision-recall curves for each class.
        names (dict): A dictionary of class names.
        box (Metric): An instance of the Metric class for storing detection results.
        speed (dict): A dictionary for storing execution times of different parts of the detection process.
        task (str): The task type, set to 'detect'.
    .Frt  Nc                 C   s4   || _ || _|| _t | _ddddd| _d| _dS )aO  
        Initialize a DetMetrics instance with a save directory, plot flag, and class names.

        Args:
            save_dir (Path, optional): Directory to save plots.
            plot (bool, optional): Whether to plot precision-recall curves.
            names (dict, optional): Dictionary mapping class indices to names.
        r   
preprocess	inferencelosspostprocessr   N)r  r  r  rC  boxspeedr   r   r  r  r  r%   r%   r&   r   P  s   	
zDetMetrics.__init__c              
   C   D   t ||||| j| j| j|ddd }t| j| j_| j| dS a  
        Process predicted results for object detection and update metrics.

        Args:
            tp (np.ndarray): True positive array.
            conf (np.ndarray): Confidence array.
            pred_cls (np.ndarray): Predicted class indices array.
            target_cls (np.ndarray): Target class indices array.
            on_plot (callable, optional): Function to call after plots are generated.
        )r  r  r  r  r)   Nrs  r  r  r  r   r  r   r  r   r   r   rd  re  r  r  r%   r%   r&   process`     	
zDetMetrics.processc                 C      g dS z5Return a list of keys for accessing specific metrics.)metrics/precision(B)metrics/recall(B)metrics/mAP50(B)metrics/mAP50-95(B)r%   r   r%   r%   r&   keysx     zDetMetrics.keysc                 C   
   | j  S zSCalculate mean of detected objects & return precision, recall, mAP50, and mAP50-95.r  r  r   r%   r%   r&   r  }     
zDetMetrics.mean_resultsc                 C      | j |S zaReturn the result of evaluating the performance of an object detection model on a specific class.r  r  r  r%   r%   r&   r       zDetMetrics.class_resultc                 C      | j jS z5Return mean Average Precision (mAP) scores per class.r  r  r   r%   r%   r&   r    r  zDetMetrics.mapsc                 C   r  z!Return the fitness of box object.r  r  r   r%   r%   r&   r       
zDetMetrics.fitnessc                 C   r  z-Return the average precision index per class.r  rv  r   r%   r%   r&   rv    r  zDetMetrics.ap_class_indexc                 C   "   t t| jdg |  | jg S AReturn dictionary of computed performance metrics and statistics.r  rc  r   r  r  r  r   r%   r%   r&   results_dict     "zDetMetrics.results_dictc                 C   r  )r  )Precision-Recall(B)F1-Confidence(B)Precision-Confidence(B)Recall-Confidence(B)r%   r   r%   r%   r&   r    r  zDetMetrics.curvesc                 C   r  r  )r  r  r   r%   r%   r&   r    r  zDetMetrics.curves_resultsr  Nr  r  r  r  r   r   r  r  r  r  r  r  r  rv  r  r  r  r%   r%   r%   r&   r  C  s(    






r  c                   @      e Zd ZdZedddfdddZd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edd Zedd ZdS )SegmentMetricsa  
    Calculates and aggregates detection and segmentation metrics over a given set of classes.

    Attributes:
        save_dir (Path): Path to the directory where the output plots should be saved.
        plot (bool): Whether to save the detection and segmentation plots.
        names (dict): Dictionary of class names.
        box (Metric): An instance of the Metric class to calculate box detection metrics.
        seg (Metric): An instance of the Metric class to calculate mask segmentation metrics.
        speed (dict): Dictionary to store the time taken in different phases of inference.
        task (str): The task type, set to 'segment'.
    r  Fr%   rt  Nc                 C   s<   || _ || _|| _t | _t | _ddddd| _d| _dS )aS  
        Initialize a SegmentMetrics instance with a save directory, plot flag, and class names.

        Args:
            save_dir (Path, optional): Directory to save plots.
            plot (bool, optional): Whether to plot precision-recall curves.
            names (dict, optional): Dictionary mapping class indices to names.
        r   r  segmentN)r  r  r  rC  r  segr  r   r  r%   r%   r&   r     s   	
zSegmentMetrics.__init__c           	      C      t ||||| j|| j| jdd	dd }t| j| j_| j| t ||||| j|| j| jdd	dd }t| j| j_| j| dS )a  
        Process the detection and segmentation metrics over the given set of predictions.

        Args:
            tp (np.ndarray): True positive array for boxes.
            tp_m (np.ndarray): True positive array for masks.
            conf (np.ndarray): Confidence array.
            pred_cls (np.ndarray): Predicted class indices array.
            target_cls (np.ndarray): Target class indices array.
            on_plot (callable, optional): Function to call after plots are generated.
        Maskr  r  r  r  rf  r)   NBox)	rs  r  r  r  r   r  r   r  r  )	r   r   tp_mr   rd  re  r  results_maskresults_boxr%   r%   r&   r    <   

zSegmentMetrics.processc                 C   r  )z,Return a list of keys for accessing metrics.)r  r  r  r  zmetrics/precision(M)zmetrics/recall(M)zmetrics/mAP50(M)zmetrics/mAP50-95(M)r%   r   r%   r%   r&   r    r  zSegmentMetrics.keysc                 C      | j  | j  S )zBReturn the mean metrics for bounding box and segmentation results.)r  r  r  r   r%   r%   r&   r    r  zSegmentMetrics.mean_resultsc                 C      | j || j| S )z:Return classification results for a specified class index.)r  r  r  r  r%   r%   r&   r       zSegmentMetrics.class_resultc                 C      | j j| jj S )zHReturn mAP scores for object detection and semantic segmentation models.)r  r  r  r   r%   r%   r&   r        zSegmentMetrics.mapsc                 C   r  )zGReturn the fitness score for both segmentation and bounding box models.)r  r  r  r   r%   r%   r&   r       zSegmentMetrics.fitnessc                 C   r  )zb
        Return the class indices.

        Boxes and masks have the same ap_class_index.
        r  r   r%   r%   r&   rv  
  s   zSegmentMetrics.ap_class_indexc                 C   r  )z8Return results of object detection model for evaluation.r  r  r   r%   r%   r&   r    r  zSegmentMetrics.results_dictc                 C   r  )r  )r  r  r  r  zPrecision-Recall(M)zF1-Confidence(M)zPrecision-Confidence(M)zRecall-Confidence(M)r%   r   r%   r%   r&   r    r  zSegmentMetrics.curvesc                 C   r  r  )r  r  r  r   r%   r%   r&   r  &  r  zSegmentMetrics.curves_resultsr  r  r  r%   r%   r%   r&   r    s(    
'





r  c                       s   e Zd ZdZedddfd fddZd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  ZS )PoseMetricsaU  
    Calculates and aggregates detection and pose metrics over a given set of classes.

    Attributes:
        save_dir (Path): Path to the directory where the output plots should be saved.
        plot (bool): Whether to save the detection and pose plots.
        names (dict): Dictionary of class names.
        box (Metric): An instance of the Metric class to calculate box detection metrics.
        pose (Metric): An instance of the Metric class to calculate pose metrics.
        speed (dict): Dictionary to store the time taken in different phases of inference.
        task (str): The task type, set to 'pose'.

    Methods:
        process(tp_m, tp_b, conf, pred_cls, target_cls): Processes metrics over the given set of predictions.
        mean_results(): Returns the mean of the detection and segmentation metrics over all the classes.
        class_result(i): Returns the detection and segmentation metrics of class `i`.
        maps: Returns the mean Average Precision (mAP) scores for IoU thresholds ranging from 0.50 to 0.95.
        fitness: Returns the fitness scores, which are a single weighted combination of metrics.
        ap_class_index: Returns the list of indices of classes used to compute Average Precision (AP).
        results_dict: Returns the dictionary containing all the detection and segmentation metrics and fitness score.
    r  Fr%   rt  Nc                    sL   t  ||| || _|| _|| _t | _t | _ddddd| _d| _	dS )aT  
        Initialize the PoseMetrics class with directory path, class names, and plotting options.

        Args:
            save_dir (Path, optional): Directory to save plots.
            plot (bool, optional): Whether to plot precision-recall curves.
            names (dict, optional): Dictionary mapping class indices to names.
        r   r  poseN)
superr   r  r  r  rC  r  r  r  r   r  	__class__r%   r&   r   C  s   	
zPoseMetrics.__init__c           	      C   r  )a  
        Process the detection and pose metrics over the given set of predictions.

        Args:
            tp (np.ndarray): True positive array for boxes.
            tp_p (np.ndarray): True positive array for keypoints.
            conf (np.ndarray): Confidence array.
            pred_cls (np.ndarray): Predicted class indices array.
            target_cls (np.ndarray): Target class indices array.
            on_plot (callable, optional): Function to call after plots are generated.
        Poser  r)   Nr  )	rs  r  r  r  r   r  r   r  r  )	r   r   tp_pr   rd  re  r  results_poser  r%   r%   r&   r  U  r  zPoseMetrics.processc                 C   r  )z&Return list of evaluation metric keys.)r  r  r  r  zmetrics/precision(P)zmetrics/recall(P)zmetrics/mAP50(P)zmetrics/mAP50-95(P)r%   r   r%   r%   r&   r  |  r  zPoseMetrics.keysc                 C   r  )z(Return the mean results of box and pose.)r  r  r  r   r%   r%   r&   r    r  zPoseMetrics.mean_resultsc                 C   r  )z?Return the class-wise detection results for a specific class i.)r  r  r  r  r%   r%   r&   r    r  zPoseMetrics.class_resultc                 C   r  )zSReturn the mean average precision (mAP) per class for both box and pose detections.)r  r  r  r   r%   r%   r&   r    r  zPoseMetrics.mapsc                 C   r  )z9Return combined fitness score for pose and box detection.)r  r  r  r   r%   r%   r&   r    r  zPoseMetrics.fitnessc                 C   r  )r  )r  r  r  r  zPrecision-Recall(P)zF1-Confidence(P)zPrecision-Confidence(P)zRecall-Confidence(P)r%   r   r%   r%   r&   r    r  zPoseMetrics.curvesc                 C   r  r  )r  r  r  r   r%   r%   r&   r    r  zPoseMetrics.curves_resultsr  r  )r  r  r  r  r   r   r  r  r  r  r  r  r  r  r  __classcell__r%   r%   r  r&   r  ,  s     
'



r  c                   @   s^   e Zd ZdZd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S )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'.
    rt  Nc                 C   s&   d| _ d| _ddddd| _d| _dS )z&Initialize a ClassifyMetrics instance.r   r   r  classifyN)top1top5r  r   r   r%   r%   r&   r     s   
zClassifyMetrics.__init__c                 C   sn   t |t |}}|dddf |k }t j|dddf |djfdd}|d \| _| _	dS )z
        Process target classes and predicted classes to compute metrics.

        Args:
            targets (torch.Tensor): Target classes.
            pred (torch.Tensor): Predicted classes.
        Nr   r(   rj   )
r-   rl   r*   r   r/   valuesr:  tolistr  r  )r   r   predcorrectaccr%   r%   r&   r    s   &zClassifyMetrics.processc                 C   s   | j | j d S )z;Return mean of top-1 and top-5 accuracies as fitness score.r)   )r  r  r   r%   r%   r&   r    r  zClassifyMetrics.fitnessc                 C   s"   t t| jdg | j| j| jgS )zGReturn a dictionary with model's performance metrics and fitness score.r  )rc  r   r  r  r  r  r   r%   r%   r&   r    r  zClassifyMetrics.results_dictc                 C   s   ddgS )z4Return a list of keys for the results_dict property.zmetrics/accuracy_top1zmetrics/accuracy_top5r%   r   r%   r%   r&   r    r  zClassifyMetrics.keysc                 C   r  r  r%   r   r%   r%   r&   r    r  zClassifyMetrics.curvesc                 C   r  r  r%   r   r%   r%   r&   r    r  zClassifyMetrics.curves_resultsr  )r  r  r  r  r   r  r  r  r  r  r  r  r%   r%   r%   r&   r    s    





r  c                   @   r  )
OBBMetricsa  
    Metrics for evaluating oriented bounding box (OBB) detection.

    Attributes:
        save_dir (Path): Path to the directory where the output plots should be saved.
        plot (bool): Whether to save the detection plots.
        names (dict): Dictionary of class names.
        box (Metric): An instance of the Metric class for storing detection results.
        speed (dict): A dictionary for storing execution times of different parts of the detection process.

    References:
        https://arxiv.org/pdf/2106.06072.pdf
    r  Fr%   rt  Nc                 C   s.   || _ || _|| _t | _ddddd| _dS )aH  
        Initialize an OBBMetrics instance with directory, plotting, and class names.

        Args:
            save_dir (Path, optional): Directory to save plots.
            plot (bool, optional): Whether to plot precision-recall curves.
            names (dict, optional): Dictionary mapping class indices to names.
        r   r  N)r  r  r  rC  r  r  r  r%   r%   r&   r     s
   	zOBBMetrics.__init__c              
   C   r  r  r  r  r%   r%   r&   r    r  zOBBMetrics.processc                 C   r  r  r%   r   r%   r%   r&   r    r  zOBBMetrics.keysc                 C   r  r  r  r   r%   r%   r&   r  $  r  zOBBMetrics.mean_resultsc                 C   r  r  r  r  r%   r%   r&   r  (  r  zOBBMetrics.class_resultc                 C   r  r  r  r   r%   r%   r&   r  ,  r  zOBBMetrics.mapsc                 C   r  r  r  r   r%   r%   r&   r  1  r  zOBBMetrics.fitnessc                 C   r  r  r  r   r%   r%   r&   rv  6  r  zOBBMetrics.ap_class_indexc                 C   r  r  r  r   r%   r%   r&   r  ;  r  zOBBMetrics.results_dictc                 C   r  r  r%   r   r%   r%   r&   r  @  r  zOBBMetrics.curvesc                 C   r  r  r%   r   r%   r%   r&   r  E  r  zOBBMetrics.curves_resultsr  r  r  r%   r%   r%   r&   r    s(    






r  )Fr   )r   )TFFFr   )r   )r  )(r  r;   r   pathlibr   matplotlib.pyplotpyplotr   r   r   r-   ultralytics.utilsr   r   r   r   r   r  	OKS_SIGMAr'   r7   rW   r]   rh   rw   r   r   r   r   r$  rA  rG  rW  rs  rC  r  r  r  r  r  r%   r%   r%   r&   <module>   sP   

 

?


,
% 
'"#"
Y .a 	 9