
    /j)8                         d dl Z d dlZd dlZd dlmZ d dlmZmZ d dlm	Z	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 dde
de
dedededede
dededededefdZ G d d          ZdS )    N)LOGGER)batch_probioubox_iou)	xywh2xyxy      ??F ,  皙?0u     
conf_thres	iou_thresagnosticmulti_labelmax_detncmax_time_imgmax_nmsmax_whrotatedend2endreturn_idxsc           	         dcxk    rdk    sn J d d            d|cxk    rdk    sn J d| d            t          | t          t          f          r| d         } t          j        | j                  | j        d         d	k    s|r!fd
| D             }fd|D             }|S | j        d         }|p| j        d         dz
  }| j        d         |z
  dz
  }d|z   }| ddd|f                             d          k    }t          j        | j        d         | j                  	                    |d          d         }d|	|z  z   }||dk    z  }| 
                    dd          } |s t          | dddf                   | dddf<   t          j                    }t          j        dd	|z   f| j                  g|z  }t          j        d| j                  g|z  }t          t          | |                    D ]\  }\  }}||         }||         }|r||         }|rt!          ||                   r|s||         }t          j        t!          |          ||z   dz   f|j                  }t          |ddddf                   |ddddf<   d|t#          t!          |                    |dddf                                         dz   f<   t          j        ||fd          }|j        d         s|                    d||fd          \  }}} |rst          j        |k              \  }!}"t          j        ||!         ||!d|"z   df         |"dddf                                         | |!         fd          }|r||!         }nn|                    dd          \  }#}"|#                    d          k    }t          j        ||#|"                                | fd          |         }|r||         }7|dddd	f         k                        d          }||         }|r||         }|j        d         }$|$sG|$|
k    r:|dddf                             d          d|
         }||         }|r||         }|dddd	f         |rdn|z  }%|dddf         }&|rdt          j        |ddddf         |%z   |ddddf         |ddddf         fd          }'t6                              |'|&|t:                    }!n\|ddddf         |%z   }'dt<          j        v r!ddl }(|(j!        "                    |'|&|          }!nt6          "                    |'|&|          }!|!d         }!||!         ||<   |r||!                             d          ||<   t          j                    |z
  |k    rtG          j$        d|dd            n|r||fn|S )ad  Perform non-maximum suppression (NMS) on prediction results.

    Applies NMS to filter overlapping bounding boxes based on confidence and IoU thresholds. Supports multiple detection
    formats including standard boxes, rotated boxes, and masks.

    Args:
        prediction (torch.Tensor): Predictions with shape (batch_size, num_classes + 4 + num_masks, num_boxes)
            containing boxes, classes, and optional masks.
        conf_thres (float): Confidence threshold for filtering detections. Valid values are between 0.0 and 1.0.
        iou_thres (float): IoU threshold for NMS filtering. Valid values are between 0.0 and 1.0.
        classes (list[int], optional): List of class indices to consider. If None, all classes are considered.
        agnostic (bool): Whether to perform class-agnostic NMS.
        multi_label (bool): Whether each box can have multiple labels.
        labels (list[torch.Tensor]): A priori labels for each image.
        max_det (int): Maximum number of detections to keep per image.
        nc (int): Number of classes. Indices after this are considered masks.
        max_time_img (float): Maximum time in seconds for processing one image.
        max_nms (int): Maximum number of boxes for NMS.
        max_wh (int): Maximum box width and height in pixels.
        rotated (bool): Whether to handle Oriented Bounding Boxes (OBB).
        end2end (bool): Whether the model is end-to-end and doesn't require NMS.
        return_idxs (bool): Whether to return the indices of kept detections.

    Returns:
        (list[torch.Tensor] | tuple[list[torch.Tensor], list[torch.Tensor]]): List of detections per image with shape
            (num_boxes, 6 + num_masks) containing (x1, y1, x2, y2, confidence, class, mask1, mask2, ...). If
            return_idxs=True, returns a tuple of (output, keepi) where keepi contains indices of kept detections.
    r      zInvalid Confidence threshold z&, valid values are between 0.0 and 1.0zInvalid IoU Ndevice   c                 L    g | ] }||d d df         k             d          !S )N   r	   ).0predr   r   s     Z/home/longshao/multi-rider-rag/.venv/lib/python3.11/site-packages/ultralytics/utils/nms.py
<listcomp>z'non_max_suppression.<locals>.<listcomp>C   s8    QQQd$tAAAqDzJ./9QQQ    c                 f    g | ]-}||d d ddf         k                         d                   .S )N   r   r   )any)r"   r#   classess     r$   r%   z'non_max_suppression.<locals>.<listcomp>E   sA    PPPdDAaCLG388;;<PPPr&   r!   ).Ng       @.)r   r   r(   g      ?T)keepdim
descending   )dim)iou_functorchvisionzNMS time limit z.3fz
s exceeded)%
isinstancelisttupletorchtensorr   shapeamaxarangeexpand	transposer   timezeros	enumerateziplenrangelongcatsplitwherefloatmaxviewr)   argsortTorchNMSfast_nmsr   sysmodulesr2   opsnmsr   warning))
predictionr   r   r*   r   r   labelsr   r   r   r   r   r   r   r   outputbsextramixcxinds
time_limittkeepixixxkfiltlbvboxclsmaskijconfncscoresboxesr2   s)    ` `   `                                 r$   non_max_suppressionrm      s   \ 
a!s!s!s!s	Q `y ` ` `*tUm,, #]
,wz/@AAAq  G QQQQQjQQQPPPPPPPF		!	B		(
 #a'BQ"$q(E	
RB	AAAqtG		!	!!	$	$z	1BL)"-j6GHHHOOPRTVWWXabE |b((J26K%%b"--J ='
37(;<<
37	Ak1a%i.1BCCCDrIF[
(9:::;b@E Z!7!788 I IGQ "vdG 	DB  	%c&*oo 	%g 	%BSWWb5j1n5ahGGGA AAAqsF,,Aaaa!eH58AeCGGnnbAhmmoo112	1a&!$$A wqz 	 !R33S$ 
	;sZ/00DAq	3q61QAt^#4a4j6F6F6H6H$q'RTUVVA Uggag..GD!99R==:-D	3aggii6::4@A X aaa1fI(--a00D$A X GAJ 	w;;QQQT7??d?33HWH=D$A Xaaa1fIh2F3111a4 	;IqBQBx!|Qqqq!A#vY!!!RSS&	BKKKE!!%]!SSAAaaa!eHqLE++""""O''vyAALL	::hwhKqTr
 	'1

2E"IIKK!Oz))NGZGGGGHHHE * *5FE??v5r&   c                   
   e Zd ZdZededfdej        dej        dede	de	dej        fd	            Z
edej        dej        dedej        fd
            Ze	 ddej        dej        dej        dede	dej        fd            ZdS )rK   a  Ultralytics custom NMS implementation optimized for YOLO.

    This class provides static methods for performing non-maximum suppression (NMS) operations on bounding boxes,
    including standard NMS, fast NMS, and batched NMS for multi-class scenarios.

    Methods:
        fast_nms: Fast-NMS using upper triangular matrix operations.
        nms: Optimized NMS with early termination that matches torchvision behavior exactly.
        batched_nms: Batched NMS for class-aware suppression.

    Examples:
        Perform standard NMS on boxes and scores
        >>> boxes = torch.tensor([[0, 0, 10, 10], [5, 5, 15, 15]])
        >>> scores = torch.tensor([0.9, 0.8])
        >>> keep = TorchNMS.nms(boxes, scores, 0.5)
    Trl   rk   iou_thresholduse_triu
exit_earlyreturnc                 ~   |                                  dk    r(|r&t          j        dt          j        | j                  S t          j        |d          }| |         }  || |           }|rY|                    d          }t          j        ||k                        d          dk              	                    d          }n| j
        d         }	t          j        |	| j        	                              dd                              d|	          }
t          j        |	| j        	                              dd                              |	d          }|
|k     }||z  }||         }d|||k                        d          dk     <   |||<   t          j        ||j
        d                   j        }||         S )
a  Fast-NMS implementation from https://arxiv.org/pdf/1904.02689 using upper triangular matrix operations.

        Args:
            boxes (torch.Tensor): Bounding boxes with shape (N, 4) in xyxy format.
            scores (torch.Tensor): Confidence scores with shape (N,).
            iou_threshold (float): IoU threshold for suppression.
            use_triu (bool): Whether to use torch.triu operator for upper triangular matrix operations.
            iou_func (callable): Function to compute IoU between boxes.
            exit_early (bool): Whether to exit early if there are no boxes.

        Returns:
            (torch.Tensor): Indices of boxes to keep after NMS.

        Examples:
            Apply NMS to a set of boxes
            >>> boxes = torch.tensor([[0, 0, 10, 10], [5, 5, 15, 15]])
            >>> scores = torch.tensor([0.9, 0.8])
            >>> keep = TorchNMS.fast_nms(boxes, scores, 0.5)
        r   r   dtyper   Tr-   r   )diagonalr   r   )numelr6   emptyint64r   rJ   triu_nonzerosumsqueeze_r8   r:   rI   r;   topkindices)rl   rk   ro   rp   r1   rq   
sorted_idxiouspickri   row_idxcol_idx
upper_maskscores_s                 r$   rL   zTorchNMS.fast_nms   s   8 ;;==A*;t5;u|LLLL]6d;;;
j!xu%% 	A::q:))D=$-"7!<!<Q!?!?1!DEENNrRRDDAAl1U\:::??AFFMMbRSTTGl1U\:::??2FFMMaQSTTG 7*J*$DZ(G>?Gt},11!449:;!(F::gw}Q'788@D$r&   c                 B   |                                  dk    r&t          j        dt          j        | j                  S |                     d          \  }}}}||z
  ||z
  z  }|                    dd          }t          j        |                                 t          j        | j                  }	d}
|                                 dk    rI|d         }||	|
<   |
dz  }
|                                 dk    rn|dd         }t          j        ||         ||                   }t          j        ||         ||                   }t          j	        ||         ||                   }t          j	        ||         ||                   }||z
  
                    d          }||z
  
                    d          }||z  }|                                dk    r|}&|||         ||         z   |z
  z  }|||k             }|                                 dk    I|	d|
         S )	a  Optimized NMS with early termination that matches torchvision behavior exactly.

        Args:
            boxes (torch.Tensor): Bounding boxes with shape (N, 4) in xyxy format.
            scores (torch.Tensor): Confidence scores with shape (N,).
            iou_threshold (float): IoU threshold for suppression.

        Returns:
            (torch.Tensor): Indices of boxes to keep after NMS.

        Examples:
            Apply NMS to a set of boxes
            >>> boxes = torch.tensor([[0, 0, 10, 10], [5, 5, 15, 15]])
            >>> scores = torch.tensor([0.9, 0.8])
            >>> keep = TorchNMS.nms(boxes, scores, 0.5)
        r   rt   ru   r   Tr-   N)min)rx   r6   ry   rz   r   unbindrJ   r>   maximumminimumclamp_r}   )rl   rk   ro   x1y1x2y2areasorderkeepkeep_idxrf   restxx1yy1xx2yy2whinterious                        r$   rP   zTorchNMS.nms   s   $ ;;==A;t5;u|LLLL aBBbR"W% qT22 {5;;==ELQQQkkmmaaADNMH{{}}!!9D-1r$x00C-1r$x00C-1r$x00C-1r$x00C s""q"))As""q"))AEEyy{{a58eDk1E9:C-.E3 kkmma6 IXIr&   Fidxsuse_fast_nmsc                 n   |                                  dk    r&t          j        dt          j        | j                  S |                                 }|                    |           |dz   z  }| |dddf         z   }|rt                              |||          nt          	                    |||          S )a.  Batched NMS for class-aware suppression.

        Args:
            boxes (torch.Tensor): Bounding boxes with shape (N, 4) in xyxy format.
            scores (torch.Tensor): Confidence scores with shape (N,).
            idxs (torch.Tensor): Class indices with shape (N,).
            iou_threshold (float): IoU threshold for suppression.
            use_fast_nms (bool): Whether to use the Fast-NMS implementation.

        Returns:
            (torch.Tensor): Indices of boxes to keep after NMS.

        Examples:
            Apply batched NMS across multiple classes
            >>> boxes = torch.tensor([[0, 0, 10, 10], [5, 5, 15, 15]])
            >>> scores = torch.tensor([0.9, 0.8])
            >>> idxs = torch.tensor([0, 1])
            >>> keep = TorchNMS.batched_nms(boxes, scores, idxs, 0.5)
        r   rt   ru   r   N)
rx   r6   ry   rz   r   rH   torK   rL   rP   )rl   rk   r   ro   r   max_coordinateoffsetsboxes_for_nmss           r$   batched_nmszTorchNMS.batched_nms+  s    6 ;;==A;t5;u|LLLL ''%..NQ$674 00 DHmV]CCCmV]CC	
r&   N)F)__name__
__module____qualname____doc__staticmethodr   r6   TensorrG   boolrL   rP   r   r	   r&   r$   rK   rK      s<        " 
 1  1 |1 1  1  	1  1  
1  1  1  \1 f 95< 9 9e 9PUP\ 9 9 9 \9v  #&
 &
|&
&
 l&
 	&

 &
 
&
 &
 &
 \&
 &
 &
r&   rK   )r   r   NFFr	   r
   r   r   r   r   FFF)rM   r=   r6   ultralytics.utilsr   ultralytics.utils.metricsr   r   ultralytics.utils.opsr   rG   r   intrm   rK   r	   r&   r$   <module>r      sg   


   $ $ $ $ $ $ < < < < < < < < + + + + + +
 Y6 Y6Y6 Y6
 Y6 Y6 Y6 	Y6 Y6 Y6 Y6 Y6 Y6 Y6 Y6 Y6 Y6xi
 i
 i
 i
 i
 i
 i
 i
 i
 i
r&   