§
    ­¸jÇ!  ã                  óR   — d Z ddlmZ ddlmZ ddlmZ ddlZddl	m
Z
 dd„Zdd„ZdS )z?Confidence-threshold sweep for precision/recall/F1 computation.é    )Úannotations)ÚIterable)ÚAnyN)ÚNDArrayÚper_class_dataúlist[dict[str, Any]]Úconf_thresholds_arrúNDArray[np.float64]Úreturnú>tuple[NDArray[np.int64], NDArray[np.int64], NDArray[np.int64]]c           	     óŠ  — t          | ¦  «        }t          |¦  «        }t          j        ||ft          j        ¬¦  «        }t          j        ||ft          j        ¬¦  «        }t          j        |t          j        ¬¦  «        }t	          |¦  «        D �],}| |         }|d         }	|d         }
|d         }|d         ||<   t          j        |	d¬¦  «        }|	|         }||          t          j        |¦  «         z  }||
|         dk    z  }||
|         dk    z  }t          j        t          j        |d	d	d
…         ¦  «        d	d	d
…         dgf¦  «        }t          j        t          j        |d	d	d
…         ¦  «        d	d	d
…         dgf¦  «        }t          j	        ||d¬¦  «        }||         ||<   ||         ||<   �Œ.|||fS )aº  Tabulate per-class TP/FP counts at every threshold in a single O(N log N) pass per class.

    Sorts each class's detections by score once, then reads off TP/FP counts for every threshold
    via a `np.searchsorted` binary search into precomputed suffix sums, instead of rescanning all
    of a class's detections at every threshold.

    Args:
        per_class_data: Per-class matching data list indexed by class id. Each entry is a dict with
            keys ``"scores"``, ``"matches"``, ``"ignore"``, and ``"total_gt"``.
        conf_thresholds_arr: Confidence thresholds to evaluate, as a float64 array.

    Returns:
        Tuple of ``(per_class_tp, per_class_fp, total_gt_per_class)``, where ``per_class_tp`` and
        ``per_class_fp`` are ``(num_classes, num_thresholds)`` int64 arrays and
        ``total_gt_per_class`` is a ``(num_classes,)`` int64 array.

    Examples:
        >>> data = [{"scores": np.array([0.9, 0.4]), "matches": np.array([1, 0]),
        ...          "ignore": np.array([False, False]), "total_gt": 1}]
        >>> tp, fp, total_gt = _per_class_counts(data, np.array([0.0, 0.5]))
        >>> tp.tolist(), fp.tolist(), total_gt.tolist()
        ([[1, 1]], [[1, 0]], [1])
    ©ÚdtypeÚscoresÚmatchesÚignoreÚtotal_gtÚstable)Úkindr   NéÿÿÿÿÚleft)Úside)
ÚlenÚnpÚemptyÚint64ÚrangeÚargsortÚisnanÚconcatenateÚcumsumÚsearchsorted)r   r	   Únum_classesÚnum_thresholdsÚper_class_tpÚper_class_fpÚtotal_gt_per_classÚkÚdatar   r   r   ÚorderÚsorted_scoresÚvalidÚis_tpÚis_fpÚ	suffix_tpÚ	suffix_fpÚinsertion_idxs                       új/root/private/project/pallet_detection_v2/.venv/lib/python3.11/site-packages/rfdetr/evaluation/f1_sweep.pyÚ_per_class_countsr3      sÊ  € õ6 �nÑ%Ô%€KÝÐ,Ñ-Ô-€Nå”8˜[¨.Ð9ÅÄÐJÑJÔJ€LÝ”8˜[¨.Ð9ÅÄÐJÑJÔJ€LÝœ +µR´XÐ>Ñ>Ô>Ðå�;ÑÔð 3ñ 3ˆØ˜aÔ ˆØ�h”ˆØ�y”/ˆØ�h”ˆØ $ ZÔ 0Ð˜1Ñõ ”
˜6¨Ð1Ñ1Ô1ˆØ˜uœˆØ˜”�¥"¤(¨=Ñ"9Ô"9Ð!9Ñ9ˆØ˜ œ¨1Ò,Ñ-ˆØ˜ œ¨1Ò,Ñ-ˆõ
 ”N¥B¤I¨e°D°D°b°D¬kÑ$:Ô$:¸4¸4¸R¸4Ô$@À1À#Ð#FÑGÔGˆ	Ý”N¥B¤I¨e°D°D°b°D¬kÑ$:Ô$:¸4¸4¸R¸4Ô$@À1À#Ð#FÑGÔGˆ	åœ¨Ð7JÐQWÐXÑXÔXˆØ# MÔ2ˆ�Q‰Ø# MÔ2ˆ�Q‰‰à˜Ð'9Ð9Ð9ó    Úconf_thresholdsúIterable[float]Úclasses_with_gtú	list[int]c                ó4  ‡‡‡— t          j        t          |¦  «        t           j        ¬¦  «        }t	          | ¦  «        }t          | |¦  «        \  }}}g }t          |¦  «        D �]±\  }	}
g Šg Šg Št          |¦  «        D ]¡}|||	f         }|||	f         }||         }||z
  }||z   dk    r|||z   z  nd}||z   dk    r|||z   z  nd}||z   dk    rd|z  |z  ||z   z  nd}‰                     |¦  «         ‰                     |¦  «         ‰                     |¦  «         Œ¢t	          |¦  «        dk    rˆt          t          j
        ˆfd„|D ¦   «         ¦  «        ¦  «        }t          t          j
        ˆfd„|D ¦   «         ¦  «        ¦  «        }t          t          j
        ˆfd„|D ¦   «         ¦  «        ¦  «        }nd}d}d}|                     |
|||t          j        ‰¦  «        t          j        ‰¦  «        t          j        ‰¦  «        dœ¦  «         �Œ³|S )	uˆ  Sweep confidence thresholds and compute precision/recall/F1 at each.

    Each class's detections are sorted by score once and reduced to suffix TP/FP sums; every
    threshold's counts are then a single ``np.searchsorted`` binary search away, giving
    O(N log N + T log N) per class instead of rescanning every detection at every threshold.

    Args:
        per_class_data: Per-class matching data list indexed by class id. Each entry is a dict with
            keys ``"scores"`` and ``"matches"`` (equal-length ndarrays), ``"ignore"`` (a boolean
            ndarray of the same length), and ``"total_gt"`` (an integer -- a float value silently
            truncates via an int64 cast rather than raising). Mismatched ``"scores"``/``"ignore"``
            lengths raise ``IndexError``.
        conf_thresholds: Iterable of float confidence thresholds to evaluate. Comparisons against
            detection scores always happen in float64, regardless of the dtype of
            ``per_class_data`` scores or of the threshold values themselves. This is deliberate,
            version-stable semantics and intentionally differs from the legacy
            ``scores >= conf_thresh`` comparison this function replaced, whose effective dtype
            depended on NumPy's (pre-2.0) value-based casting rules.
        classes_with_gt: List of class indices that have at least one GT instance â€” used for macro-averaging.

    Returns:
        List of result dicts, one per threshold, each containing:
            - ``"confidence_threshold"``: float
            - ``"macro_f1"``: float
            - ``"macro_precision"``: float
            - ``"macro_recall"``: float
            - ``"per_class_prec"``: float ndarray
            - ``"per_class_rec"``: float ndarray
            - ``"per_class_f1"``: float ndarray

    Examples:
        >>> data = [{"scores": np.array([0.9, 0.4]), "matches": np.array([1, 0]),
        ...          "ignore": np.array([False, False]), "total_gt": 1}]
        >>> results = sweep_confidence_thresholds(data, [0.5], classes_with_gt=[0])
        >>> round(results[0]["macro_precision"], 3), round(results[0]["macro_recall"], 3)
        (1.0, 1.0)
    r   r   g        é   c                ó    •— g | ]
}‰|         ‘ŒS © r<   )Ú.0r(   Úper_class_precisionss     €r2   ú
<listcomp>z/sweep_confidence_thresholds.<locals>.<listcomp>ž   s   ø€ Ð,^Ð,^Ð,^ÈÐ-AÀ!Ô-DÐ,^Ð,^Ð,^r4   c                ó    •— g | ]
}‰|         ‘ŒS r<   r<   )r=   r(   Úper_class_recallss     €r2   r?   z/sweep_confidence_thresholds.<locals>.<listcomp>Ÿ   s   ø€ Ð)XÐ)XÐ)XÀ1Ð*;¸AÔ*>Ð)XÐ)XÐ)Xr4   c                ó    •— g | ]
}‰|         ‘ŒS r<   r<   )r=   r(   Úper_class_f1ss     €r2   r?   z/sweep_confidence_thresholds.<locals>.<listcomp>    s   ø€ Ð%PÐ%PÐ%P¸1 m°AÔ&6Ð%PÐ%PÐ%Pr4   )Úconfidence_thresholdÚmacro_f1Úmacro_precisionÚmacro_recallÚper_class_precÚper_class_recÚper_class_f1)r   ÚasarrayÚlistÚfloat64r   r3   Ú	enumerater   ÚappendÚfloatÚmeanÚarray)r   r5   r7   r	   r#   r%   r&   r'   ÚresultsÚtÚconf_threshr(   ÚtpÚfpr   ÚfnÚ	precisionÚrecallÚf1rF   rG   rE   rC   r>   rA   s                         @@@r2   Úsweep_confidence_thresholdsr\   S   sw  øøø€ õ\ œ*¥T¨/Ñ%:Ô%:Å"Ä*ÐMÑMÔMÐÝ�nÑ%Ô%€Kõ 6GÀ~ÐWjÑ5kÔ5kÑ2€L�,Ð 2à$&€Gå#Ð$7Ñ8Ô8ð &
ñ &
‰ˆˆ;Ø,.ÐØ)+ÐØ%'ˆå�{Ñ#Ô#ð 	%ð 	%ˆAØ˜a ˜dÔ#ˆBØ˜a ˜dÔ#ˆBØ)¨!Ô,ˆHØ˜B‘ˆBà+-°©7°aª-¨-˜˜b 2™g™˜¸SˆIØ(*¨R©°1¢} }�R˜2 ™7‘^�^¸#ˆFØCLÈvÑCUÐYZÒBZÐBZ��Y‘ Ñ'¨9°vÑ+=Ñ>Ð>Ð`cˆBà ×'Ò'¨	Ñ2Ô2Ð2Ø×$Ò$ VÑ,Ô,Ð,Ø× Ò  Ñ$Ô$Ð$Ð$åˆÑÔ !Ò#Ð#Ý#¥B¤GÐ,^Ð,^Ð,^Ð,^ÈoÐ,^Ñ,^Ô,^Ñ$_Ô$_Ñ`Ô`ˆOÝ ¥¤Ð)XÐ)XÐ)XÐ)XÈÐ)XÑ)XÔ)XÑ!YÔ!YÑZÔZˆLÝ�RœWÐ%PÐ%PÐ%PÐ%PÀÐ%PÑ%PÔ%PÑQÔQÑRÔRˆHˆHà!ˆOØˆLØˆHà�Šà(3Ø$Ø#2Ø ,Ý"$¤(Ð+?Ñ"@Ô"@Ý!#¤Ð*;Ñ!<Ô!<Ý "¤¨Ñ 7Ô 7ðð ñ
	
ô 
	
ð 
	
ñ 
	
ð €Nr4   )r   r   r	   r
   r   r   )r   r   r5   r6   r7   r8   r   r   )Ú__doc__Ú
__future__r   Úcollections.abcr   Útypingr   Únumpyr   Únumpy.typingr   r3   r\   r<   r4   r2   ú<module>rc      s›   ðð FÐ Eà "Ð "Ð "Ð "Ð "Ð "à $Ð $Ð $Ð $Ð $Ð $Ø Ð Ð Ð Ð Ð à Ð Ð Ð Ø  Ð  Ð  Ð  Ð  Ð  ð?:ð ?:ð ?:ð ?:ðD_ð _ð _ð _ð _ð _r4   