
    ^j"0                        d Z ddlmZ ddlZddlZddlmc mZ	 ddl
mZ ddlmZ dej                  dej                  dej                  fd	Zd
ej                  dej                  dej                  dej                  dededeej&                  ej&                  ej&                  ef   fdZ	 	 ddeeeej                  f      deeeej                  f      dededeeeeef   f   f
dZdeeeeef   f   fdZdeeeeef   f   deeeeef   f   deeeeef   f   fdZdeeeeef   f   deeeeef   f   fdZy)zBGreedy matching and accumulation functions for evaluation metrics.    )AnyN)box_iou)
all_gather
pred_masksgt_masksreturnc                    | j                   d   }|j                   d   }| j                   dd |j                   dd k7  rX| j                   dd \  }}t        j                  |j                         j	                  d      ||fd      j                  d      }| j                         j                  |d      j                         }|j                         j                  |d      j                         }t        j                  ||j                               }|j                  dd	      }	|j                  dd	      }
|	|
j                         z   |z
  }t        j                  |dkD  ||z  t        j                  |            S )
a  Compute pairwise boolean-mask IoU between N predictions and M ground truths.

    Args:
        pred_masks: Boolean mask tensor of shape [N, H, W].
        gt_masks: Boolean mask tensor of shape [M, H, W].

    Returns:
        IoU tensor of shape [N, M].
    r   N   nearest)sizemodeT)dimkeepdim)shapeFinterpolatefloat	unsqueezesqueezeboolviewtorchmmtsumwhere
zeros_like)r   r   nmhw	pred_flatgt_flatinter	pred_areagt_areaunions               e/var/www/ramen.bs-engineer-server.com/venv/lib/python3.12/site-packages/rfdetr/evaluation/matching.py_compute_mask_iour+      sE    	AqArs 33$1==!1!;!;A!>aVR[\ddefg!&&q"-335Immo""1b)//1GHHY		,E!T2Ikkak.G		#e+E;;uqy%%-1A1A%1HII    pred_scores
pred_itemsgt_itemsgt_crowdiou_thresholdiou_typec                 h   | j                   d   }|j                   d   }t        j                  | d      }| |   }	||   }
|dk(  rt        |
|      }nt	        |
|      }| j
                  }t        j                  |t        j                  |      }t        j                  |t        j                  |      }t        j                  |t        j                  |      }t        |      D ]  }||   }|j                         }d||<   d||| z  <   |j                  d      \  }}||k\  rd||<   d||<   K|j                         s\|j                         }d|| <   |j                         |k\  sd||<    t        | j                         j                               }|	j!                         j#                         j%                         j'                  t(        j*                        |j#                         j%                         |j#                         j%                         j'                  t              |fS )	u>  Greedy highest-score-first matching for one class in one image.

    Implements the COCO matching algorithm: each GT is matched at most once; detections are processed in descending
    score order; detections matched to crowd GTs are marked as ignored rather than false positives.

    Args:
        pred_scores: Float tensor of shape [N] with detection confidences.
        pred_items: Predictions — boxes [N, 4] in xyxy coords or masks [N, H, W].
        gt_items: Ground truths — boxes [M, 4] in xyxy coords or masks [M, H, W].
        gt_crowd: Bool tensor of shape [M], True for crowd instances.
        iou_threshold: Minimum IoU to count as a positive match.
        iou_type: ``"bbox"`` for box IoU or ``"segm"`` for mask IoU.

    Returns:
        Tuple ``(scores_np, matches_np, ignore_np, total_gt)`` where:
            - scores_np: float32 array [N] ordered by descending score.
            - matches_np: int array [N], 1 = TP, 0 = FP.
            - ignore_np: bool array [N], True if matched to a crowd GT.
            - total_gt: number of non-crowd GT instances.
    r   T)
descendingbboxdtypedeviceg      )r   r   )r   r   argsortr   r+   r8   zerosr   longrangeclonemaxanyintr   itemr   cpunumpyastypenpfloat32)r-   r.   r/   r0   r1   r2   r    r!   sort_idxpred_scores_sortedpred_sorted
iou_matrixr8   
gt_matched
pred_matchpred_ignoreiiousnc_iousbest_nc_ioubest_nc_idx
crowd_ioustotal_gts                          r*   _match_single_classrU   4   s   8 	!AqA}}[T:H$X.X&K6[(3
&{H=
FQejj@JQejj@J++auzz&AK1X *!} **, *.
hY&'#*;;1;#5 [-'JqM&*J{# ||~!ZZ\
(,
H9%>>#}4%)KN%** XI??$))+,H  "&&(..077

C !((.	 r,   
preds_listtargets_listc                    i }t        | |      D ]  \  }}|d   }|d   }|d   }	|j                  d      }
|d   }|d   }|j                  d      }|j                  dt        j                  t	        |      t        j
                  |j                              }|j                         }t        |j                               t        |	j                               z  }|D ]  }|	|k(  }||k(  }||   }||   }t        |j                         j                               }t        |j                         j                               }|j                  |g g g dd      }|dk(  r4|d	xx   t        | j                         j                               z  cc<   |dk(  r|j                         j                         j!                         }t#        j$                  |       }|d   j'                  ||   j                                |d
   j'                  dg|z         |d   j'                  dg|z         T|dk(  r||   }||   }n|
|t)        d      |
|   }||   }t+        ||||||      \  }}}} |d   j'                  |j                                |d
   j'                  |j                                |d   j'                  |j                                |d	xx   | z  cc<     |j-                         D !ci c]x  \  }}!|t#        j.                  |!d   t"        j0                        t#        j.                  |!d
   t"        j2                        t#        j.                  |!d   t              |!d	   dz c}!}S c c}!}w )a!  Build compact per-class matching data from a batch of predictions and targets.

    Implements greedy highest-score-first matching compatible with the COCO algorithm. The returned dict can be passed
    directly to ``merge_matching_data()`` and ultimately consumed by ``sweep_confidence_thresholds()`` after conversion
    to list form.

    Args:
        preds_list: Per-image predictions. Each dict must contain:

            - ``boxes``: float Tensor [N, 4] in absolute xyxy coordinates.
            - ``scores``: float Tensor [N].
            - ``labels``: int64 Tensor [N].
            - ``masks`` *(optional)*: bool Tensor [N, H, W] for segmentation.

        targets_list: Per-image ground truths. Each dict must contain:

            - ``boxes``: float Tensor [M, 4] in absolute xyxy coordinates.
            - ``labels``: int64 Tensor [M].
            - ``masks`` *(optional)*: bool Tensor [M, H, W] for segmentation.
            - ``iscrowd`` *(optional)*: int64 Tensor [M], 1 for crowd instances.

        iou_threshold: IoU threshold for positive matching. Defaults to 0.5.
        iou_type: ``"bbox"`` for bounding-box IoU; ``"segm"`` for boolean-mask
            IoU. Defaults to ``"bbox"``.

    Returns:
        Dict mapping ``class_id`` (int) to a compact matching dict with keys:

            - ``"scores"``: float32 ndarray of detection scores.
            - ``"matches"``: int ndarray (1 = TP, 0 = FP).
            - ``"ignore"``: bool ndarray (True if matched to a crowd GT).
            - ``"total_gt"``: int, count of non-crowd GT instances.
    boxesscoreslabelsmasksiscrowdr6   r   rZ   matchesignorerT   rT   r_   r`   Fr5   z:iou_type='segm' requires 'masks' in both preds and targets)r7   )zipgetr   r:   lenr;   r8   r   settolistr@   r   rA   
setdefaultr   rB   rC   rE   r9   extend
ValueErrorrU   itemsarrayrF   int64)"rV   rW   r1   r2   accpredstargets
pred_boxesr-   pred_labelsr   gt_boxes	gt_labelsr   	raw_crowdr0   all_class_idsclass_idpred_mask_c	gt_mask_cp_scores
gt_crowd_cn_predn_gtentryscorderp_itemsr/   	scores_np
matches_np	ignore_nprT   datas"                                     r*   build_matching_datar      sa   N -/Cj,7 <*w7^
HoHoYYw'
7#H%	;;w'KKKKIejjAQAQR
	 >>#"%i&6&6&8"9C@R@R@T<U"U% +	*H%1K!X-I";/H!),J*//12Fy}}++-.DNN"JE
 {j!S:+):):)<)A)A)C%DD!qy^^%))+113

B3h&&r%y'7'7'9:i ''f5h&&w'786!(2;(?)1))<%)9$%abb$[1#I.9L'8Z:6Iz9h (O""9#3#3#56)##J$5$5$78(O""9#3#3#56*)W+	*#<*J "iik Hd 	hhtH~RZZ@xxYrxx@hhtH~T:Z(	
 	
  s   =A=M>c                      i S )zReturn an empty matching accumulator compatible with ``merge_matching_data()``.

    Returns:
        Empty dict to be passed as the first argument to ``merge_matching_data()``.
     r   r,   r*   init_matching_accumulatorr      s	     Ir,   accumulatornew_datac                    |j                         D ]  \  }}|| vrA|d   j                         |d   j                         |d   j                         |d   d| |<   K| |   }t        j                  |d   |d   g      |d<   t        j                  |d   |d   g      |d<   t        j                  |d   |d   g      |d<   |dxx   |d   z  cc<    | S )a  Merge *new_data* into *accumulator* in place.

    Both arguments share the dict schema produced by ``build_matching_data()``: each class-keyed sub-dict contains
    ``"scores"`` (float32 ndarray), ``"matches"`` (int64 ndarray), ``"ignore"`` (bool ndarray), and ``"total_gt"``
    (int).

    Args:
        accumulator: Running accumulator, modified in place.
        new_data: Batch-level matching data to merge in.

    Returns:
        The modified *accumulator* (same object, for method chaining).
    rZ   r_   r`   rT   r^   )ri   copyrE   concatenate)r   r   ru   r   r|   s        r*   merge_matching_datar      s    " #..* 2$;&x.--/	?//1x.--/ ,	%K!  )E nneHotH~-NOE(O!~~uY/?i.QRE) nneHotH~-NOE(O*j!112 r,   
local_datac                 F    t        |       }i }|D ]  }t        ||        |S )a  Gather per-rank matching data from all DDP ranks and merge into one dict.

    Uses ``rfdetr.utilities.all_gather`` (pickle-based) so the data need not be a tensor. In single-process
    (non-distributed) mode, returns a merged copy of *local_data* unchanged.

    Args:
        local_data: Per-rank accumulator produced by ``merge_matching_data()``.

    Returns:
        Merged accumulator containing contributions from all ranks.
    )r   r   )r   gatheredmerged	rank_datas       r*   distributed_merge_matching_datar     s1     1;:0FH(*F /	FI./Mr,   )g      ?r5   )__doc__typingr   rC   rE   r   torch.nn.functionalnn
functionalr   torchvision.opsr   rfdetr.utilitiesr   Tensorr+   r   strtuplendarrayr@   rU   listdictr   r   r   r   r   r,   r*   <module>r      s    I      # 'J%,, J%,, J5<< J0HHH llH ll	H
 H H 2::rzz2::s23H\ 	oT#u||+,-otC-./o o 	o
 
#tCH~
od4T#s(^(;#< c4S>)*3S#X&' 
#tCH~
DS$sCx.()	#tCH~
r,   