§
    ß©ºj8  ã                  óª   — d Z ddlmZ ddlmZ ddlmZmZ ddlm	Z	m
Z
mZ ddlmZ erddlZddlmZ dd	lmZ dd
lmZ dddddddœd)d"„Zd*d%„Zd+d(„ZdS ),a#  Public surface for the confusion-matrix capability (ADR-0023).

Lives in its own module so the lazy ``polars`` import stays contained:
``import vernier`` does not pull in polars; calling
:func:`confusion_matrix` is what triggers it. Mirrors the lazy-import
pattern in :mod:`vernier._types`.
é    )Úannotations)ÚMapping)ÚTYPE_CHECKINGÚNoReturn)Úconfusion_matrix_bboxÚconfusion_matrix_boundaryÚconfusion_matrix_segm)Ú
ParityModeN)ÚDetectionsInput)ÚCocoDataset)ÚIouKindg      à?éd   TÚ	correctedF)ÚiouÚt_fÚmax_dets_per_imageÚuse_catsÚparity_modeÚcast_inputsÚgtúbytes | CocoDatasetÚdtr   r   úIouKind | Noner   Úfloatr   Úintr   Úboolr   r
   r   Úreturnúpl.DataFramec          
     ój  — ddl m}m}	m}
m} |€
 |¦   «         }|x|d˜ x�\    t          | ||||||¬¦  «        }nl x|d˜ x�\    t          | ||||||¬¦  «        }nK x|	d˜ x�\  } t          | |||||||¬¦  «        }n( |
d˜ x�\   t          d¦  «        ‚ 	 t          |¦  «         t          |¦  «        S )u  Confusion matrix counts in long format (ADR-0023).

    Counts ``(true_class, predicted_class)`` pairs across the dataset
    using the same cross-class IoU side pass that powers
    :func:`vernier.error_decomposition`. One per-image walk produces:

    - **Diagonal cells** (``gt_class == dt_class``) â€” true positives.
    - **Off-diagonal cells** (``gt_class != dt_class``) â€” classification
      confusion (a detection of class B was the best overlap of a GT
      of class A at IoU >= ``t_f``).
    - **``__none__`` row** (``gt_class == "__none__"``) â€” false
      positives: the detection had no overlapping GT at the threshold.
    - **``__none__`` column** (``dt_class == "__none__"``) â€” missed GTs:
      a non-ignore GT was not covered by any detection at the threshold.

    Output is a :class:`polars.DataFrame` with three columns:

    - ``gt_class: str`` â€” the true class id as a decimal string, or the
      sentinel ``"__none__"`` for false-positive rows.
    - ``dt_class: str`` â€” the predicted class id as a decimal string, or
      ``"__none__"`` for missed-GT columns.
    - ``count: i64`` â€” number of ``(gt_class, dt_class)`` pairs in the
      dataset.

    The class columns are typed ``str`` rather than mixed ``int|str``
    because polars does not have a clean dtype for the union (the
    ``__none__`` sentinel is fundamentally not an integer). Callers
    wanting numeric ids can ``df.with_columns(pl.col("gt_class").cast(pl.Int64,
    strict=False))`` â€” ``__none__`` rows surface as ``null``, the
    natural representation of "no class".

    Output is **long-format** (one row per non-zero cell) rather than
    wide-format (a square matrix) because long-format composes better
    with polars' filter / group / agg idioms. Pivot to wide via
    ``df.pivot(values="count", index="gt_class", on="dt_class")`` if
    needed for visualization.

    Args:
        gt: Ground-truth COCO JSON payload as bytes (the same shape
            ``pycocotools.COCO(...)`` consumes) or a
            :class:`CocoDataset` handle (ADR-0020, ADR-0060). A handle
            carrying LVIS federated metadata is refused â€” the confusion
            matrix has no federated disposition (ADR-0064).
        dt: Any detection form the evaluator accepts â€” the detection
            COCO JSON payload as bytes, columnar
            :class:`vernier.instance.Detections`, result dicts, or an ``(N, 7)``
            matrix (ADR-0030, ADR-0057, ADR-0064). The pair
            :func:`vernier.adapters.coco_inputs` returns is read here
            unchanged.
        iou: Kernel selector. Pass :class:`Bbox()` (default),
            :class:`Segm()`, or :class:`Boundary(dilation_ratio=...)`.
            :class:`Keypoints` is rejected per ADR-0024 (OKS is
            single-class in COCO; cross-class confusion is undefined).
        t_f: Foreground IoU threshold for declaring a ``(gt, dt)`` pair
            matched. Default ``0.5`` matches the COCO convention.
        max_dets_per_image: Per-image detection cap (matches the
            matching path's cap). Default ``100``.
        use_cats: Reserved; must be ``True``. A category-collapsed
            evaluation has no meaningful confusion matrix (every cell
            collapses to a single virtual class).
        parity_mode: ``"strict"`` or ``"corrected"`` per ADR-0002.
            Defaults to ``"corrected"``.
        cast_inputs: Convert array dtypes rather than refusing them, as
            on :class:`vernier.instance.Evaluator`. Defaults to
            ``False``; no effect on the bytes route.

    Returns:
        A :class:`polars.DataFrame` with columns ``gt_class``,
        ``dt_class``, ``count``.

    Raises:
        NotImplementedError: ``iou=Keypoints(...)`` (ADR-0024), or
            ``gt`` is a federated :class:`CocoDataset` handle
            (ADR-0026 / ADR-0064).
        ValueError: ``t_f`` outside ``[0, 1]``, ``max_dets_per_image
            < 1``, or ``use_cats=False``.
        ImportError: ``polars`` not installed (install via
            ``pip install 'vernier[tables]'``).

    Example:
        >>> import vernier
        >>> df = vernier.confusion_matrix(gt_bytes, dt_bytes, iou=vernier.Bbox())
        >>> df.filter(pl.col("gt_class") != pl.col("dt_class"))  # only mistakes
        >>> df.pivot(values="count", index="gt_class", on="dt_class")  # wide
    r   )ÚBboxÚBoundaryÚ	KeypointsÚSegmN© )r   )Údilation_ratiou“   confusion_matrix on keypoints (OKS) is deferred per ADR-0024 â€” OKS is single-class in COCO, so cross-class confusion is undefined for this kernel)Úvernier.instancer    r!   r"   r#   r   r	   r   ÚNotImplementedErrorÚ_reject_unknown_iouÚ_to_dataframe)r   r   r   r   r   r   r   r   r    r!   r"   r#   ÚresultÚrs                 úb/root/private/project/pallet_detection_v2/.venv/lib/python3.11/site-packages/vernier/_confusion.pyÚconfusion_matrixr-      sM  € ðH AÐ@Ð@Ð@Ð@Ð@Ð@Ð@Ð@Ð@Ð@Ð@à
€{Øˆd‰fŒfˆà
ØˆTˆVˆVˆVˆV‰VˆVÝ*Ø�B˜ SÐ*<¸hÐT_ðñ ô ˆFˆFð ð ˆTˆVˆVˆVˆV‰VˆVÝ*Ø�B˜ SÐ*<¸hÐT_ðñ ô ˆFˆFð ð (ˆXÐ'Ð'Ð'Ð'Ñ' Q QÝ.Ø�B˜ SÐ*<¸hÈÐWbðñ ô ˆFˆFð (ð ˆ[ˆ[ˆ[ˆ[‰[Ý%ð,ñô ð ð ð Ý Ñ$Ô$Ð$å˜Ñ Ô Ð ó    r*   úMapping[str, object]c                óž   — 	 ddl }n"# t          $ r}t          d¦  «        |‚d}~ww xY w |j        | d         | d         | d         dœ¦  «        S )u¢  Lazy polars import + dictâ†’DataFrame conversion. Raises a
    structured :class:`ImportError` when polars is absent (steering the
    user to the install command).

    The FFI returns parallel arrays in a dict; we project the three
    long-format columns onto a polars frame. The auxiliary
    ``iou_threshold`` / ``kernel`` keys are dropped â€” they're
    introspection metadata, not part of the table shape.
    r   Nz_confusion_matrix returns a polars.DataFrame; install polars via `pip install 'vernier[tables]'`Úgt_classÚdt_classÚcount)r1   r2   r3   )ÚpolarsÚImportErrorÚ	DataFrame)r*   ÚplÚes      r,   r)   r)   Ÿ   sŠ   € ðØÐÐÐÐøÝð ð ð Ýð.ñ
ô 
ð ð	øøøøðøøøð ˆ2Œ<à˜zÔ*Ø˜zÔ*Ø˜G”_ð	
ð 	
ñô ð s   ‚ ‡
&‘!¡&Úobjectr   c                ó(   — t          d| ›d�¦  «        ‚)Nzunsupported iou kernel u@   ; expected Bbox(), Segm(), Boundary(...) â€” see vernier.IouKind)Ú	TypeError)r   s    r,   r(   r(   º   s*   € Ý
ð	1 #ð 	1ð 	1ð 	1ñô ð r.   )r   r   r   r   r   r   r   r   r   r   r   r   r   r
   r   r   r   r   )r*   r/   r   r   )r   r9   r   r   )Ú__doc__Ú
__future__r   Úcollections.abcr   Útypingr   r   Úvernier._corer   r   r	   Úvernier._typesr
   r4   r7   Úvernier._array_typesr   r   r&   r   r-   r)   r(   r$   r.   r,   ú<module>rC      sH  ððð ð #Ð "Ð "Ð "Ð "Ð "à #Ð #Ð #Ð #Ð #Ð #Ø *Ð *Ð *Ð *Ð *Ð *Ð *Ð *ðð ð ð ð ð ð ð ð ð ð
 &Ð %Ð %Ð %Ð %Ð %àð )ØÐÐÐà4Ð4Ð4Ð4Ð4Ð4Ø)Ð)Ð)Ð)Ð)Ð)Ø(Ð(Ð(Ð(Ð(Ð(ð ØØ!ØØ)Øð!ð !ð !ð !ð !ð !ðDð ð ð ð6ð ð ð ð ð r.   