Ë
    ëÓ^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ÚmodeéÿÿÿÿT)Ú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Ø×Ñ˜˜Ð §¡¨r¨sÐ 3Ò3Ø×Ñ  Ð$‰ˆˆ1Ü—=‘= §¡Ó!1×!;Ñ!;¸AÓ!>ÀaÈÀVÐR[Ô\×dÑdÐefÓgˆØ—‘Ó!×&Ñ& q¨"Ó-×3Ñ3Ó5€IØ�m‰m‹o×"Ñ" 1 bÓ)×/Ñ/Ó1€GÜ�H‰H�Y §	¡	£Ó,€EØ—‘ !¨T�Ó2€IØ�k‰k˜a¨ˆkÓ.€GØ˜Ÿ	™	›Ñ# eÑ+€EÜ�;‰;�u˜q‘y %¨%¡-´×1AÑ1AÀ%Ó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Ü—‘˜Q¤e§j¡j¸Ô@€JÜ—‘˜Q¤e§j¡j¸Ô@€JÜ—+‘+˜a¤u§z¡z¸&ÔA€Kä�1‹Xò *ˆØ˜!‰}ˆð —*‘*“,ˆØ ˆ�ÑØ*.ˆ�
˜h˜YÑ&Ñ'à#*§;¡;°1 ;Ó#5Ñ ˆ�[Ø˜-Ò'ØˆJ�q‰MØ&*ˆJ�{Ò#ð �|‰|�~Ø!ŸZ™Z›\�
Ø(,�
˜H˜9Ñ%Ø—>‘>Ó# }Ó4Ø%)�K ’Nð%*ô* �X�I—?‘?Ó$×)Ñ)Ó+Ó,€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‘^ˆ
Ø˜H‘oˆØ˜H‘oˆØ—Y‘Y˜wÓ'ˆ
à˜7Ñ#ˆØ˜HÑ%ˆ	Ø—;‘;˜wÓ'ˆØ—K‘KØÜ�K‰Kœ˜I›¬e¯j©jÀ×AQÑAQÔRó
ˆ	ð —>‘>Ó#ˆä"% i×&6Ñ&6Ó&8Ó"9¼CÀ×@RÑ@RÓ@TÓ<UÑ"Uˆà%ó +	*ˆHØ%¨Ñ1ˆKØ! XÑ-ˆIà" ;Ñ/ˆHØ! )Ñ,ˆJÜ˜Ÿ™Ó*×/Ñ/Ó1Ó2ˆFÜ�y—}‘}“×+Ñ+Ó-Ó.ˆDà—N‘NØØ¨"¸ÈÑJóˆEð
 ˜Š{Ø�jÓ!¤S¨:¨+×):Ñ):Ó)<×)AÑ)AÓ)CÓ%DÑDÓ!Øà�qŠyà—^‘^Ó%×)Ñ)Ó+×1Ñ1Ó3�ÜŸ
™
 B 3›�Ø�h‘×&Ñ& r¨%¡y×'7Ñ'7Ó'9Ô:Ø�iÑ ×'Ñ'¨¨¨f©Ô5Ø�h‘×&Ñ&¨ w°Ñ'7Ô8Ùà˜6Ò!Ø(2°;Ñ(?�Ø)1°)Ñ)<‘àÐ%¨Ð)9Ü$Ð%aÓbÐbØ$ [Ñ1�Ø# IÑ.�ä9LØ˜' 8¨Z¸Èó:Ñ6ˆI�z 9¨hð �(‰O×"Ñ" 9×#3Ñ#3Ó#5Ô6Ø�)Ñ×#Ñ# J×$5Ñ$5Ó$7Ô8Ø�(‰O×"Ñ" 9×#3Ñ#3Ó#5Ô6Ø�*Ó Ñ)ÕòW+	*ð#<*ðJ "Ÿi™i›k÷ñ ˆH�dð 	Ü—h‘h˜t H™~´R·Z±ZÔ@Ü—x‘x  Y¡´r·x±xÔ@Ü—h‘h˜t H™~´TÔ:Ø˜ZÑ(ñ	
ñ 	
óð ùó s   Ë=A=M>c                  ó   — i S )z¶Return 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Ü Ÿn™n¨e°H©o¸tÀH¹~Ð-NÓOˆE�(‰OÜ!Ÿ~™~¨u°YÑ/?ÀÀiÁÐ.QÓRˆE�)ÑÜ Ÿn™n¨e°H©o¸tÀH¹~Ð-NÓOˆE�(‰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;¸:Ó0F€HØ(*€FØò /ˆ	Ü˜F IÕ.ð/à€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ð �l‰lðHð �l‰lð	Hð
 ðHð ðHð ˆ2�:‰:�r—z‘z 2§:¡:¨sÐ2Ñ3óHð\ Øñ	oØ�T˜#˜uŸ|™|Ð+Ñ,Ñ-ðoà�t˜C §¡Ð-Ñ.Ñ/ðoð ðoð ð	oð
 
ˆ#ˆt�C˜�H‰~Ð
Ñóoðd 4¨¨T°#°s°(©^Ð(;Ñ#<ó ðØ�c˜4  S ™>Ð)Ñ*ðà�3˜˜S #˜X™Ð&Ñ'ðð 
ˆ#ˆt�C˜�H‰~Ð
ÑóðDØ�S˜$˜s C˜x™.Ð(Ñ)ðà	ˆ#ˆt�C˜�H‰~Ð
Ñôr,   