
    h                       d Z ddlZddlZddlm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dNd
ej2                  dej2                  dededej2                  f
dZdOd
ej:                  dej:                  dedej:                  fdZ	 	 	 	 	 dPd
ej:                  dej:                  dedededededej:                  fdZdOdej:                  dej:                  dedej:                  fdZ 	 dOdej:                  dej:                  dej:                  de
e   dedej:                  fdZ!dej:                  deej:                  ej:                  ej:                  f   fdZ"dNd ej:                  d!ej:                  dededej:                  f
d"Z#	 dOd eej:                  ej2                  f   d!eej:                  ej2                  f   dedej:                  fd#Z$dQdedeeef   fd$Z% G d% d&e      Z&dRd'ej2                  d(edej2                  fd)Z' e        ed*      i dfd+ej2                  d,ej2                  d-ej2                  d.ed/e	e(e)f   f
d0       Z* e        ed1      i d2d3dfd+ej2                  d,ej2                  d.ed/e	e(e)f   d4e)d5e)fd6       Z+d7e
e   d8e
e   deeej2                  ej2                  f   fd9Z,d	d e       i d:d;fd<ej2                  d=ej2                  d>ej2                  d?ej2                  d@ed.ed/e	e(e)f   dedAe)defdBZ- G dC d3e      Z. G dD dEee      Z/ G dF dGe/      Z0 G dH dIe/      Z1 G dJ dKee      Z2 G dL dMe/      Z3y)SzModel validation metrics.    N)defaultdict)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                  W/var/www/html/eduruby.in/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_iourA   5   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Hr0   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.
       r3   r   r2   N)
r6   r    r!   r:   powmathpiatanr7   no_grad)%r   r   rB   rC   rD   rE   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_iourb   M   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   r2   N)r7   matmulr   r:   sum)rc   rd   r   intersectionrZ   s        r.   mask_iouri      s_     <<uww/66q9LYYq\!T'"UYYq\$%77<GE53;''r0   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   r3   r2   ).r2   )devicedtype).r3   rH   )rI   r7   tensorrn   ro   exprg   )rj   rk   r,   rl   r   dkpt_maskes           r.   kpt_iouru      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Wr0   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.
    Nr3   rG      rH   dimr2   )r7   catrI   splitcossin)	rv   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Hr0   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
    .Nr3   r2   rH   ry   r         ?rG   r         Y@      ?)r|   r   rI   r:   sqrtlogclamprq   rJ   rK   rL   r7   rM   )r   r   rE   r   rN   rO   rR   rS   r<   r>   c1r=   r?   r]   t1t2t3bdhdr   rP   rQ   rT   rU   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
    .Nr3   r2   rH   ry   c              3   D   K   | ]  }|j                  d       d     ywrH   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   rG   r   r   r   )
isinstancer   ndarrayr7   
from_numpyr|   r   rI   r:   r   r   r   rq   )r   r   r   rN   rO   rR   rS   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r6Mr0   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%%r0   c                      e Zd ZdZg ddfdeeef   dedefdZded	eee	f   d
eddfdZ
deej                     deej                     ddf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dej                  dededd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.
        matches (dict): Contains the indices of ground truths and predictions categorized into TP, FP and FN.
    detectFnamestasksave_matchesc                 B   || _         t        |      | _        | j                   dk(  r+t        j                  | j                  | j                  f      n0t        j                  | j                  dz   | j                  dz   f      | _        || _        |ri | _        yd| _        y)aW  
        Initialize a ConfusionMatrix instance.

        Args:
            names (Dict[int, str], optional): Names of classes, used as labels on the plot.
            task (str, optional): Type of task, either 'detect' or 'classify'.
            save_matches (bool, optional): Save the indices of GTs, TPs, FPs, FNs for visualization.
        classifyr2   N)r   lenncr   zerosmatrixr   matches)selfr   r   r   s       r.   __init__zConfusionMatrix.__init__E  s     	e*6:ii:6Mbhh12SUS[S[]a]d]dgh]hjnjqjqtuju\vSw
)rtr0   mtypebatchidxr   Nc                    | j                   y|j                         D ]k  \  }}|dv r| j                   |   |xx   ||g   z  cc<   )|dk(  s/| j                   |   |xx   |j                         dkD  r|d   |dz   k(  gn||   gz  cc<   m y)a  
        Append the matches to TP, FP, FN or GT list for the last batch.

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

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

        Note:
            For masks, handles both overlap and non-overlap cases. When masks.max() > 1.0,
            it indicates overlap_mask=True with shape (1, H, W), otherwise uses direct indexing.
        N>   clsconfbboxes	keypointsmasksr   r   r2   )r   itemsr9   )r   r   r   r   kr_   s         r.   _append_matcheszConfusionMatrix._append_matchesT  s    " <<KKM 	[DAq::U#A&!SE(2&gU#A&quuw}1Q437?*;STUXSYRZZ&	[r0   predstargetsc                 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 (List[N, min(nc,5)]): Predicted class labels.
            targets (List[N, 1]): Ground truth class labels.
        Nr   r2   )r7   r{   zipcpunumpyr   )r   r   r   pts        r.   process_cls_predsz!ConfusionMatrix.process_cls_predsn  sx     5)!Q$/71Cw		))+W[[]-@-@-BC 	#DAqKKN1"	#r0   
detectionsr   	iou_thresc                 	   |d   |d   }}| j                   OdD ci c]  }|t        t               c}| _         t        t	        |            D ]  }| j                  d||        |j                  d   dk(  }	|d|	rdnd	hv rd
n|}t	        |d         dk(  }
|j                  d   dk(  r|
s|j                         D ci c]  }|||   |d   |kD      }}|d   j                         j                         }t        |      D ];  \  }}| j                  || j                  fxx   dz  cc<   | j                  d||       = y|
rh|j                         j                         }t        |      D ];  \  }}| j                  | j                  |fxx   dz  cc<   | j                  d||       = y|j                         D ci c]  }|||   |d   |kD      }}|j                         j                         }|d   j                         j                         }|d   }|	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-        j0                  d      }|j                  d   dkD  }|j3                         j5                  t              \  }}}t        |      D ]  \  }}||k(  }|rt7        |      dk(  r|||   j9                            }| j                  ||fxx   dz  cc<   ||k(  r%| j                  d|||   j9                                t| j                  d|||   j9                                | j                  d||       | j                  | j                  |fxx   dz  cc<   | j                  d||        t        |      D ]J  \  }}t;        ||k(        r| j                  || j                  fxx   dz  cc<   | j                  d||       L yc c}w 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.
        r   r   N>   FNFPGTTPr   r2      g{Gz?MbP?r   r   r   r   r   r3   rH   T)return_index)r      r   )r   r   listranger   r   shapekeysinttolist	enumerater   r   r   rA   r7   wherer{   stackr   r   argsortr   uniquer   	transposeastyperg   itemany)r   r   r   r   r   gt_cls	gt_bboxesr   iis_obbno_preddetection_classesdc
gt_classesgcr   r   r   r   nm0m1_js                           r.   process_batchzConfusionMatrix.process_batchz  s   & "%L%/	<<#:RSQA{400SDL3v;' 5$$T5!45#q(fd%@@tdj'(A-<<?aS]SbSbSdeaaAz&/AD/H!IIe
e$.u$5$9$9$;$B$B$D!&'89 >EArKKDGG,1,((z1=> ,,.J":. 52DGGRK(A-($$T5!45 KU??K\]aaAz&'9D'@AA]
]ZZ\((*
&u-113::<H%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* 	5EAraASVq[&r!uzz|4BF#q(#8((z2a5::<H((z2a5::<H((ua8DGGRK(A-($$T5!4	5 01 	:EArrQw<BK(A-($$T:q9	:m T f ^s   S*=S/<S4c                     | j                   S )zReturn the confusion matrix.)r   r   s    r.   r   zConfusionMatrix.matrix  s    {{r0   c                     | j                   j                         }| j                   j                  d      |z
  }| j                  dk(  r||fS |dd |dd fS )z
        Return true positives and false positives.

        Returns:
            tp (np.ndarray): True positives.
            fp (np.ndarray): False positives.
        r2   r   NrH   )r   diagonalrg   r   )r   tpfps      r.   tp_fpzConfusionMatrix.tp_fp  sX     [[!!#[[__Q"$99
2BxJCR"Sb'8JJr0   imgim_filesave_dirc           	      ^   | j                   syddlm} ddlm} t        t              }t        g d      D ]  \  }}| j                   |   }	d|	vr4t        j                  dgt        |	d         z  |j                  	      |	d<   t        j                  t        |	d         |j                  	      |z  |	d
<   |	j                         D ]  }
||
xx   |	|
   z  cc<     |j                         D 
ci c])  \  }
}|
t        |      rt        j                  |d      n|+ }}
}| j                   dk(  st        |d         r ||d         |d<   |dz  j#                  dd        |||j%                  dddd      g d|dz  t'        |      j(                  z  | j*                  dd       yc c}}
w )a  
        Plot grid of GT, TP, FP, FN for each image.

        Args:
            img (torch.Tensor): Image to plot onto.
            im_file (str): Image filename to save visualizations.
            save_dir (Path): Location to save the visualizations to.
        Nr2   )	xyxy2xywh)plot_images)r   r   r   r   r   r   r   )rn   	batch_idxr   obbvisualizationsT)parentsexist_okrG   )zGround TruthzFalse PositiveszTrue PositiveszFalse Negativesr   )pathsfnamer   max_subplots
conf_thres)r   opsr   plottingr  r   r   r   r7   rp   r   rn   onesr   r   r   r   mkdirrepeatr   namer   )r   r   r   r   r   r  labelsr   r   mbatchr   r_   s               r.   plot_matcheszConfusionMatrix.plot_matches  s    ||") T"!":; 	'HAu\\%(FV#!&sec&:J6K.KTWT^T^!_v"'**S1A-B3::"VYZ"ZF;[[] 'q	VAY&	'	' EKLLNSDAq!#a&U[[A&a7SSyyE!c&*:&;()9:F8	$	$++D4+HJJq!Q"Z--W0B0BB**	
	 Ts   0.F)zConfusionMatrix plot failure)msg	normalizec                 x   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      \  }}t        | j                  j                               | j                  }	}| j                  d	k\  rPt        d
| j                  dz        }
t        dd|
      }||   }||ddf   dd|f   }| j                  |
z   dz
  |
z  }	| j                  dk(  r|	n|	dz   x}}d|cxk  rdk  rn n||k(  r|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  }t1        |d|       D ]g  \  }}t1        |d|       D ]Q  \  }}|||f   }t        j2                  |      r#|j5                  |||r|dnt7        |       ddd ||kD  rd!nd"#       S i |j9                  ||d$d%&      }ddd       d'd(|z  z   }|j;                  d)|d *       |j=                  d+|d *       |j?                  ||d,-       |jA                  |       |jC                  |       |jE                  d.d/d0d/d01       |jE                  d2d/d0d/d03       |dk7  r(|jG                  ||d4d5       |jI                  ||6       d7D ]M  }|d8k7  r|jJ                  |   jM                  d0       jN                  jJ                  |   jM                  d0       O |jQ                  dd9d:|;       tS        |      |jU                         jW                  d<d=       d>z  }|jY                  |d?@       |j[                  |       |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   Nr2   rH   &.>g{Gzt?)rx   	   )figsized   r3   <   r   c   
backgroundauto      皙?rx   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)r3  labelpad	Predicted   )r3  r8  r   TF)axisr)  toplabelbottomlabeltopy)r=  leftright	labelleft
labelrightZ   )r3  rotationr1  )r3  >   r>  rB  rC  r)  outlinerH  gzG?gGz?)rB  rC  r>  r)   r   z.png   dpi).matplotlib.pyplotpyplotr   rg   reshaper   nansubplotsr   r   valuesr   r9   slicer   aranger   warningscatch_warningssimplefilterimshowxaxisset_label_positionnanmaxr   isnantextr   colorbar
set_xlabel
set_ylabel	set_title
set_xticks
set_ytickstick_paramsset_xticklabelsset_yticklabelsspinesset_visibler6  subplots_adjustr   lowerreplacesavefigclose)r   r  r   on_plotpltarrayfigr6  r   r   r   keep_idxr   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

))+,dggq77c>Atww"}%AT4+H(OE(A+&q({3E1qQ&AyyJ.!AE9R23b+2+B"He|n,SY
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   .C4P//P9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   rI  N)r   r   r   r
   infojoinmapstrr   r   s     r.   printzConfusionMatrix.printK  sI    t{{((+, 	<AKKS$++a.!9:;	<r0   decimalsc                 <   ddl }| j                  dk(  r#t        | j                  j	                               n&t        | j                  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   r2   rH   r  r;  )rer   r   r   rR  setsubrj  addappendr   rg   rO  roundr   r   dict)r   r  r  r  r   clean_namesseenr  
clean_nameoriginal_cleancounterrp  r   r   s                 r.   summaryzConfusionMatrix.summaryP  s   " 	-1YY*-DTZZ&&()$tzzO`O`ObJcgsftJt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   (F6FFF)r   r+  )T N)Fr   )__name__
__module____qualname____doc__r   r   r  boolr   r   r   r   r7   Tensorr   r4   r   r   r   r   r   r   r   r  r   r   r  r  r  r   r0   r.   r   r   9  s   	 02x^c 4d38n 4 4W[ 4[S [c3h [c [d [4
#tELL'9 
#DDV 
#[_ 
#  N:ell*+N: CH~N: 	N:
 N: 
N:`KuRZZ34 K$
 $
s $
d $
t $
L 12^F d F S F   3F P<
"
 "
 "
T$sTYzJZE[ "
r0   r   rA  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.r3   r2   r   rH   valid)mode)r  r   r   r  concatenateconvolve)rA  r  nfr   yps        r.   smoothr  u  s{    	s1vzA~	!	#a	'B
aA	QqT1a!B%i0!	4B;;r2772;+'::r0   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   Nr2   r  r  Tr  tight_layout)r=     rI  .3f	linewidthlabelgreyr  r4  r   blueall classes z mAP@0.5r  r4  r  Recall	Precisiongp=
ף?r2   
upper leftbbox_to_anchorloczPrecision-Recall CurverJ  rK  )rM  rN  rQ  r   r   r   r   r   r  meanr_  r`  set_xlimset_ylimlegendra  rl  rm  )r  r  r  r   r   rn  ro  rq  r6  r   rA  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 r0   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   Nr2   r  Tr  r  r  r  r  r!  r   r  r  r,  z at r  r  r  r  r  z-Confidence CurverJ  rK  )rM  rN  rQ  r   r   r  r   r  r  r9   argmaxr_  r`  r  r  r  ra  rl  rm  )r  r  r   r   r  r  rn  ro  rq  r6  r   rA  s               r.   plot_mc_curver    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 r0   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   r2   e   z>=2.0NrH   )r   r  flipr!   
accumulatelinspacer   check_version__version__	trapezoidtrapzr  r   rg   )	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>r0   gؗҜ<r  r   r   pred_cls
target_clsr  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   r2     N)rB  )r2   r  r3   zPR_curve.pngrn  zF1_curve.pngF1)r  rn  zP_curve.pngr  zR_curve.pngr  r!  )r   r   r   r   r  r   r   rg   cumsumr  r   r  r  rp  r  r  r  r  r  r  r   r   )$r   r   r  r  r  rn  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.
        ap: AP at IoU thresholds from 0.5 to 0.95 for all classes.
        mp: Mean precision of all classes.
        mr: Mean recall of all classes.
        map50: Mean AP at IoU threshold of 0.5 for all classes.
        map75: Mean AP at IoU threshold of 0.75 for all classes.
        map: Mean AP at IoU thresholds from 0.5 to 0.95 for all classes.
        mean_results: Mean of results, returns mp, mr, map50, map.
        class_result: Class-aware result, returns p[i], r[i], ap50[i], ap[i].
        maps: mAP of each class.
        fitness: Model fitness as a weighted combination of metrics.
        update: Update metric attributes with new evaluation results.
        curves: Provides a list of curves for accessing specific metrics like precision, recall, F1, etc.
        curves_results: Provide a list of results for accessing specific metrics like precision, recall, F1, etc.
    r   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__v  s-     r0   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 <"<r0   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.
        r2   r   r  r  r   s    r.   r  z	Metric.ap  s)     '*$++&6t{{">B>r0   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4r0   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.mr  r  r0   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.map50  0     ,/t{{+;t{{1a4 %%'DDr0   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.map75  r  r0   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.map  s'     &)%5t{{!>3>r0   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_results  s!    $**dhh77r0   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  r  s     r.   class_resultzMetric.class_result  s1    vvay$&&)TYYq\4771:==r0   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.maps  sS     xx 488+d112 	!DAqggajDG	!r0   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_numrp  r	  rg   )r   ws     r.   fitnesszMetric.fitness  s6     bhht'8'8':;<q@EEGGr0   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r0   c                     g S >Return a list of curves for accessing specific metrics curves.r   r   s    r.   curveszMetric.curves  	     	r0   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(;	
 	
r0   r   N)r  r  r  r  r   propertyr	   r   r   r   r  r  r4   r  r  r  r  r  r	  r   r   r  r  r  tupler  r  r  r   r0   r.   r  r  Y  s   8 =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
 
 
r0   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.

    Methods:
        update_stats: Update statistics by appending new values to existing stat collections.
        process: Process predicted results for object detection and update metrics.
        clear_stats: Clear the stored statistics.
        keys: Return a list of keys for accessing specific metrics.
        mean_results: Calculate mean of detected objects & return precision, recall, mAP50, and mAP50-95.
        class_result: Return the result of evaluating the performance of an object detection model on a specific class.
        maps: Return mean Average Precision (mAP) scores per class.
        fitness: Return the fitness of box object.
        ap_class_index: Return the average precision index per class.
        results_dict: Return dictionary of computed performance metrics and statistics.
        curves: Return a list of curves for accessing specific metrics curves.
        curves_results: Return a list of computed performance metrics and statistics.
        summary: Generate a summarized representation of per-class detection metrics as a list of dictionaries.
    r   r   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   r  statsnt_per_classnt_per_imager   r   s     r.   r   zDetMetrics.__init__%  sQ     
8$'c3WZ[
	Rb2"QST
  r0   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*  r   r  )r   r.  r   s      r.   update_statszDetMetrics.update_stats4  s8     " 	*AJJqM  a)	*r0   .Fr   r  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)r  r   r   rn  r  r3   N)	minlengthr'  )r*  r   r   r  r   r  r   r(  r   r  bincountr   r   r+  r,  )r   r   r  rn  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*  rR  clear)r   r_   s     r.   clear_statszDetMetrics.clear_stats_  s'    ""$ 	AGGI	r0   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.keysd  s     hgr0   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_resultsi  s    xx$$&&r0   r   c                 8    | j                   j                  |      S )zaReturn the result of evaluating the performance of an object detection model on a specific class.)r(  r  r  s     r.   r  zDetMetrics.class_resultm  s    xx$$Q''r0   c                 .    | j                   j                  S )z5Return mean Average Precision (mAP) scores per class.)r(  r  r   s    r.   r  zDetMetrics.mapsq  s     xx}}r0   c                 6    | j                   j                         S )z!Return the fitness of box object.)r(  r  r   s    r.   r  zDetMetrics.fitnessv  s     xx!!r0   c                 .    | j                   j                  S )z-Return the average precision index per class.)r(  r  r   s    r.   r  zDetMetrics.ap_class_index{       xx&&&r0   c                     t        t        | j                  dgz   | j                         | j                  gz               S )zAReturn dictionary of computed performance metrics and statistics.r  )r  r   r   r	  r  r   s    r.   results_dictzDetMetrics.results_dict  s5     C		YK/1B1B1D~1UVWWr0   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mr0   c                 .    | j                   j                  S z=Return a list of computed performance metrics and statistics.)r(  r  r   s    r.   r  zDetMetrics.curves_results  r@  r0   r  r  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-F1rK  )ClassImages	Instancesr3   r   )mAP50zmAP50-95)r(  r   r  r  r   r   r   r  r,  r+  r   r  r  )r   r  r  	per_classr   r   r_   s          r.   r  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   )r  r  r  r  r   r   r  r   r   r0  r   r  r   r   r6  r9  r  r   r   r4   r	  r   r  r  r  r  rB  r  r  r  r   r0   r.   r   r     s   8 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  
r0   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.

    Methods:
        process: Process the detection and segmentation metrics over the given set of predictions.
        keys: Return a list of keys for accessing metrics.
        mean_results: Return the mean metrics for bounding box and segmentation results.
        class_result: Return classification results for a specified class index.
        maps: Return mAP scores for object detection and semantic segmentation models.
        fitness: Return the fitness score for both segmentation and bounding box models.
        curves: Return a list of curves for accessing specific metrics curves.
        curves_results: Provide a list of computed performance metrics and statistics.
        summary: Generate a summarized representation of per-class segmentation metrics as a list of dictionaries.
    r   r   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r0   r1  Fr   r  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  rV  r   r  r  Maskr  rn  r   r   r  r3   N)r   r6  r  r   r   rW  r   r  )r   r   r  rn  r*  results_masks         r.   r6  zSegmentMetrics.process  s     ""44"I#&M&M*,**

 "
 $**o%r0   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) -
 
 	
r0   c                 b    t         j                  |       | j                  j                         z   S )zBReturn the mean metrics for bounding box and segmentation results.)r   r	  rW  r   s    r.   r	  zSegmentMetrics.mean_results  s%    &&t,txx/D/D/FFFr0   r   c                 f    t         j                  | |      | j                  j                  |      z   S )z:Return classification results for a specified class index.)r   r  rW  r  s     r.   r  zSegmentMetrics.class_result  s)    &&tQ/$((2G2G2JJJr0   c                 n    t         j                  j                  |       | j                  j                  z   S )zHReturn mAP scores for object detection and semantic segmentation models.)r   r  r^  rW  r   s    r.   r  zSegmentMetrics.maps  s&     ##D)DHHMM99r0   c                 v    | j                   j                         t        j                  j                  |       z   S )zGReturn the fitness score for both segmentation and bounding box models.)rW  r  r   r^  r   s    r.   r  zSegmentMetrics.fitness  s-     xx!J$6$6$;$;D$AAAr0   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+ /
 
 	
r0   c                 n    t         j                  j                  |       | j                  j                  z   S rI  )r   r  r^  rW  r   s    r.   r  zSegmentMetrics.curves_results  s*     ((--d3dhh6M6MMMr0   r  r  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)
rW  r   r  r  r   r  r   r  r   r  	r   r  r  rP  r  r   r  r   r_   s	            r.   r  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rQ  )r  r  r  r  r   r   r  r   r   r  r   r   r6  r  r   r   r4   r	  r  r  r  r  r  r   r  r   r0   r.   rS  rS    sR   2 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 r0   rS  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: Process the detection and pose metrics over the given set of predictions. R
        keys: Return a list of keys for accessing metrics.
        mean_results: Return the mean results of box and pose.
        class_result: Return the class-wise detection results for a specific class i.
        maps: Return the mean average precision (mAP) per class for both box and pose detections.
        fitness: Return combined fitness score for pose and box detection.
        curves: Return a list of curves for accessing specific metrics curves.
        curves_results: Provide a list of computed performance metrics and statistics.
        summary: Generate a summarized representation of per-class pose metrics as a list of dictionaries.
    r   r   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  rm  r   r*  )r   r   	__class__s     r.   r   zPoseMetrics.__init__U  s0     	H		

6r0   r1  Fr   r  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  rn  r   r  r  PoserZ  r3   N)r   r6  r  r   r   rm  r   r  )r   r   r  rn  r*  results_poses         r.   r6  zPoseMetrics.processa  s     ""44"I#&M&M*,**

 "
 4::				&r0   c                 J    t         j                  j                  |       g dz   S )z(Return a list of evaluation metric keys.)zmetrics/precision(P)zmetrics/recall(P)zmetrics/mAP50(P)zmetrics/mAP50-95(P)r]  r   s    r.   r   zPoseMetrics.keys}  r_  r0   c                 b    t         j                  |       | j                  j                         z   S )z(Return the mean results of box and pose.)r   r	  rm  r   s    r.   r	  zPoseMetrics.mean_results  s%    &&t,tyy/E/E/GGGr0   r   c                 f    t         j                  | |      | j                  j                  |      z   S )z?Return the class-wise detection results for a specific class i.)r   r  rm  r  s     r.   r  zPoseMetrics.class_result  s)    &&tQ/$))2H2H2KKKr0   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^  rm  r   s    r.   r  zPoseMetrics.maps  s&     ##D)DIINN::r0   c                 v    | j                   j                         t        j                  j                  |       z   S )z9Return combined fitness score for pose and box detection.)rm  r  r   r^  r   s    r.   r  zPoseMetrics.fitness  s-     yy  "Z%7%7%<%<T%BBBr0   c                 J    t         j                  j                  |       g dz   S )r  )rD  rE  rF  rG  zPrecision-Recall(P)zF1-Confidence(P)zPrecision-Confidence(P)zRecall-Confidence(P)re  r   s    r.   r  zPoseMetrics.curves  s'       %%d+ 	/
 	
 		
r0   c                 n    t         j                  j                  |       | j                  j                  z   S rI  )r   r  r^  rm  r   s    r.   r  zPoseMetrics.curves_results  s*     ((--d3dii6N6NNNr0   r  r  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)
rm  r   r  r  r   r  r   r  r   r  rh  s	            r.   r  zPoseMetrics.summary  s    $ iikkiikkyy||
	
 $$T9h?g& 	SDAqHHQioo>OPdaE!A$11PQR	S Qri  rQ  )r  r  r  r  r   r   r  r   r   r  r   r   r6  r  r   r   r4   r	  r  r  r  r  r  r   r  __classcell__)rp  s   @r.   rk  rk  ;  sS   2 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 r0   rk  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)ClassifyMetricsa  
    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'.

    Methods:
        process: Process target classes and predicted classes to compute metrics.
        fitness: Return mean of top-1 and top-5 accuracies as fitness score.
        results_dict: Return a dictionary with model's performance metrics and fitness score.
        keys: Return a list of keys for the results_dict property.
        curves: Return a list of curves for accessing specific metrics curves.
        curves_results: Provide a list of computed performance metrics and statistics.
        summary: Generate a single-row summary of classification metrics (Top-1 and Top-5 accuracy).
    r   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[
	r0   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   r2   ry   )
r7   r{   r4   r   r9   rR  r  r   r  r  )r   r   r  correctaccs        r.   r6  zClassifyMetrics.process  s     		$7);g1d7#t+224kk71a4='++a.*?*?@aH"xx{113	49r0   c                 :    | j                   | j                  z   dz  S )z;Return mean of top-1 and top-5 accuracies as fitness score.r3   )r  r  r   s    r.   r  zClassifyMetrics.fitness  s     		DII%**r0   c                     t        t        | j                  dgz   | j                  | j                  | j
                  g            S )zGReturn a dictionary with model's performance metrics and fitness score.r  )r  r   r   r  r  r  r   s    r.   rB  zClassifyMetrics.results_dict  s4     C		YK/$))TYY1UVWWr0   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Ar0   c                     g S r  r   r   s    r.   r  zClassifyMetrics.curves  r  r0   c                     g S r  r   r   s    r.   r  zClassifyMetrics.curves_results  r  r0   r  r  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)r  r  r  )r   r  r  s      r.   r  zClassifyMetrics.summary	  s)      #499h7U499V^E_`aar0   r  rQ  )r  r  r  r  r   r7   r  r6  r  r4   r  r   r  rB  r   r   r  r  r  r   r  r   r0   r.   r~  r~    s    &4u|| 45<< 4 + + + Xd3:. X X Bd3i B B      b b bDcSXjIYDZ br0   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.
        r  N)r   r   r   r-  s     r.   r   zOBBMetrics.__init__-  s     	D%(	r0   )r  r  r  r  r   r   r  r   r   r0   r.   r  r    s'      02 	d38n 	d 	r0   r  )FHz>)r  )TFFFr  )r!  )r5  )4r  rJ   rU  collectionsr   pathlibr   typingr   r   r   r   r	   r   r   r7   ultralytics.utilsr
   r   r   r   r   r   rp  	OKS_SIGMAr   r  r4   r/   r  rA   rb   ri   ru   r   r   r   r   r   r  r   r  r  r  r  r  r  r   rS  rk  r~  r  r   r0   r.   <module>r     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 &"y
o y
x	;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l
[ l
^g
o g
TFZ FRJ* JZQbk? Qbh r0   