§
    ß©ºj^#  ã                  ó"  — d Z ddlmZ ddlmZmZ ddlmZ ddlm	Z	m
Z
 ddlmZ e	rddlZddlmZmZmZ e
d	         Ze
d
         Ze
d         Z ed¬¦  «         G d„ d¦  «        ¦   «         Zd#d „Z ed¬¦  «         G d!„ d"¦  «        ¦   «         ZdS )$a²  ADR-0018 detection-family calibration summarizer.

User-facing wrapper sitting on top of the Rust kernel
(:mod:`vernier_core::calibration`) and the FFI layer
(:class:`vernier._core.EvalCells`). ``result.calibration(...)`` is the
single public entry point on the batch surface;
:meth:`StreamingSnapshot.calibration` is the streaming sibling
(ADR-0018 Unit 6). :class:`CalibrationResult` is not re-exported from
:mod:`vernier` per the "one canonical path per item" rule.

The reliability and per-class tables are exposed lazily as
:class:`polars.DataFrame` via ``@cached_property``, mirroring
:class:`vernier.instance.EvalResult`. The underlying Arrow
``RecordBatch`` is retained under ``_reliability_batch`` /
``_per_class_batch`` for zero-copy consumers; the documented bridge
is the :meth:`ArrowRecordBatch.__arrow_c_array__` PyCapsule method.

See ``docs/adr/0018-calibration.md`` and the parity oracle at
``tests/python/parity_calibration/``.
é    )Úannotations)Ú	dataclassÚfield)Úcached_property)ÚTYPE_CHECKINGÚLiteral)Úarrow_to_dataframeN)ÚBackgroundEvaluatorÚ	EvalCellsÚSummary)ÚquantileÚequal_width)ÚwilsonÚclopper_pearson)ÚmacroÚmicroT)Úfrozenc                  ó¼   — e Zd ZU dZded<   ded<   ded<   ded<    ed¬	¦  «        Zd
ed<    edd¬¦  «        Zded<   edd„¦   «         Z	edd„¦   «         Z
ddd„ZdS )ÚCalibrationResulta™  Result of :meth:`vernier.instance.EvalResult.calibration`.

    Scalars are plain Python numbers; tabular outputs are exposed as
    :class:`polars.DataFrame` via lazy ``@cached_property`` (mirrors
    :class:`vernier.instance.EvalResult`). The underlying Arrow
    ``RecordBatch`` is retained under ``_reliability_batch`` /
    ``_per_class_batch`` for callers that want the zero-copy Arrow
    surface; :meth:`__arrow_c_array__` is the documented bridge.

    ``effective_n_bins`` is the bin count *after* duplicate-edge
    merging on small samples (quirk **P5**); it may be less than the
    requested ``n_bins`` and is what ``reliability.height`` reports.
    ÚfloatÚeceÚmceÚintÚn_detectionsÚeffective_n_binsF©ÚreprÚobjectÚ_reliability_batchN)Údefaultr   zobject | NoneÚ_per_class_batchÚreturnúpl.DataFramec                ó,   — t          | j        d¦  «        S )zþOne row per effective bin. Columns: ``bin_id``, ``score_lo``,
        ``score_hi``, ``mean_score``, ``accuracy``, ``count``, ``gap``,
        ``ci_lo``, ``ci_hi``. Zero-count bins emit ``NaN`` for the float
        columns per the kernel's R2 convention.Úcalibration_reliability)r	   r   ©Úselfs    úc/root/private/project/pallet_detection_v2/.venv/lib/python3.11/site-packages/vernier/calibration.pyÚreliabilityzCalibrationResult.reliabilityT   s   € õ " $Ô"9Ð;TÑUÔUÐUó    c                óX   — | j         €t          d¦  «        ‚t          | j         d¦  «        S )zšOne row per class. Columns: ``class_id``, ``ece``, ``mce``,
        ``n``. Raises :class:`RuntimeError` when ``per_class=True`` was
        not requested.NzGper_class table is unavailable: call result.calibration(per_class=True)Úcalibration_per_class)r!   ÚRuntimeErrorr	   r&   s    r(   Ú	per_classzCalibrationResult.per_class\   s8   € ð
 Ô Ð(ÝØYñô ð õ " $Ô"7Ð9PÑQÔQÐQr*   é   Úkc                ó`   — | j                              dd¬¦  «                             |¦  «        S )zƒTop-``k`` worst-calibrated classes by ECE. Raises
        :class:`RuntimeError` when the per-class table wasn't requested.
        r   T)Ú
descending)r.   ÚsortÚhead)r'   r0   s     r(   ÚworstzCalibrationResult.worstg   s-   € ð Œ~×"Ò" 5°TÐ"Ñ:Ô:×?Ò?ÀÑBÔBÐBr*   )r"   r#   )r/   )r0   r   r"   r#   )Ú__name__Ú
__module__Ú__qualname__Ú__doc__Ú__annotations__r   r   r!   r   r)   r.   r5   © r*   r(   r   r   4   sø   € € € € € € ðð ð €J€J�Jà€J€J�Jð ÐÐÑàÐÐÑð "' ¨EÐ!2Ñ!2Ô!2ÐÐ2Ð2Ð2Ñ2ð ', e°D¸uÐ&EÑ&EÔ&EÐÐEÐEÐEÑEàðVð Vð Vñ „_ðVð ðRð Rð Rñ „_ðRðCð Cð Cð Cð Cð Cð Cr*   r   Úcellsr   Úiour   Ún_binsr   ÚbinningÚBinningÚ	min_scoreÚ
confidenceÚ
Confidencer.   ÚboolÚper_class_aggregationÚAggregationr"   c          	     óš   — |                       |¦  «        }|                      |||||||¦  «        \  }	}
}}}}t          |	|
||||¬¦  «        S )uª  Resolve ``iou`` against the cell-store's pinned T-axis and fold
    into a :class:`CalibrationResult`.

    Shared helper called by both :meth:`vernier.instance.EvalResult.calibration`
    (batch path) and :meth:`StreamingSnapshot.calibration` (ADR-0018
    Unit 6 streaming path) â€” the post-cells fold is identical across
    both surfaces, so there's exactly one place that knows the kernel's
    return-tuple layout.
    )r   r   r   r   r   r!   )Úiou_to_indexÚ	calibrater   )r<   r=   r>   r?   rA   rB   r.   rE   Ú	iou_indexr   r   Ún_detÚeff_binsÚreliability_bÚper_class_bs                  r(   Ú_calibrate_from_cellsrO   n   sw   € ð( ×"Ò" 3Ñ'Ô'€IØ<A¿OºOØØØØØØØñ=ô =Ñ9€Cˆˆe�X˜}¨kõ ØØØØ!Ø(Ø$ðñ ô ð r*   c                  ór   — e Zd ZU dZded<    ed¬¦  «        Zded<   ed#d„¦   «         Zddddddddœd$d!„Z	d"S )%ÚStreamingSnapshotuF  Bundle returned by
    :meth:`StreamingSnapshot.from_background` â€” pairs the canonical
    :class:`vernier._core.Summary` produced by the streaming evaluator
    with the opaque :class:`vernier._core.EvalCells` handle the
    calibration summarizer consumes (ADR-0018 Unit 6).

    The :attr:`summary` axis is bit-identical to what
    :meth:`vernier._core.BackgroundEvaluator.finalize` would have
    produced for the same evaluator state; calibration adds the cells
    alongside, never mutates the canonical kernel maths.

    Mirrors the :class:`vernier.instance.EvalResult` convention: the
    raw cell handle is kept under :attr:`_eval_cells` (impl detail â€”
    do not depend on its shape) and the :meth:`calibration` method
    folds it into a :class:`CalibrationResult` with the same params
    the batch surface accepts.
    r   ÚsummaryFr   r   Ú_eval_cellsÚbgr
   r"   c                óJ   — |                      ¦   «         \  }} | ||¬¦  «        S )aî  Consume a :class:`vernier._core.BackgroundEvaluator` via
        :meth:`finalize_with_cells` and wrap the returned tuple into a
        :class:`StreamingSnapshot`.

        The background evaluator follows finalize-consumes-the-worker
        semantics (ADR-0014, ADR-0035); a second call to any
        ``finalize_*`` method raises "already finalized". Use
        :meth:`calibration` on the returned snapshot to fold the
        retained cell store into a :class:`CalibrationResult`.
        )rR   rS   )Úfinalize_with_cells)ÚclsrT   rR   r<   s       r(   Úfrom_backgroundz!StreamingSnapshot.from_background²   s.   € ð ×/Ò/Ñ1Ô1‰ˆ�Øˆs˜7°Ð6Ñ6Ô6Ð6r*   g      à?é   r   gš™™™™™©?r   r   ©r=   r>   r?   rA   rB   r.   rE   r=   r   r>   r   r?   r@   rA   rB   rC   r.   rD   rE   rF   r   c          
     ó:   — t          | j        |||||||¬¦  «        S )u÷  Fold the retained streaming cell store into a calibration
        summary (ADR-0018 Unit 6).

        Mirrors :meth:`vernier.instance.EvalResult.calibration` keyword
        for keyword â€” same parity-pinned defaults, same return type;
        re-folding with different params is cheap (no re-matching).
        ``iou`` resolves to the kernel's T-axis index under
        :data:`vernier_core::parity::PARITY_EPS`; values that don't
        land on a pinned threshold raise :class:`ValueError`.
        rZ   )rO   rS   )r'   r=   r>   r?   rA   rB   r.   rE   s           r(   ÚcalibrationzStreamingSnapshot.calibrationÁ   s6   € õ* %ØÔØØØØØ!ØØ"7ð	
ñ 	
ô 	
ð 		
r*   N)rT   r
   r"   rQ   )r=   r   r>   r   r?   r@   rA   r   rB   rC   r.   rD   rE   rF   r"   r   )
r6   r7   r8   r9   r:   r   rS   ÚclassmethodrX   r\   r;   r*   r(   rQ   rQ   –   s¡   € € € € € € ðð ð* ÐÐÑð #˜U¨Ð.Ñ.Ô.€KÐ.Ð.Ð.Ñ.àð7ð 7ð 7ñ „[ð7ð" ØØ%ØØ!)ØØ-4ð
ð 
ð 
ð 
ð 
ð 
ð 
ð 
r*   rQ   )r<   r   r=   r   r>   r   r?   r@   rA   r   rB   rC   r.   rD   rE   rF   r"   r   )r9   Ú
__future__r   Údataclassesr   r   Ú	functoolsr   Útypingr   r   Úvernier._tablesr	   ÚpolarsÚplÚvernier._corer
   r   r   r@   rC   rF   r   rO   rQ   r;   r*   r(   ú<module>rf      s‡  ððð ð* #Ð "Ð "Ð "Ð "Ð "à (Ð (Ð (Ð (Ð (Ð (Ð (Ð (Ø %Ð %Ð %Ð %Ð %Ð %Ø )Ð )Ð )Ð )Ð )Ð )Ð )Ð )à .Ð .Ð .Ð .Ð .Ð .àð FØÐÐÐàEÐEÐEÐEÐEÐEÐEÐEÐEÐEð Ð+Ô
,€ð
 Ð0Ô1€
ð
 Ð&Ô'€ð €�$ÐÑÔð6Cð 6Cð 6Cð 6Cð 6Cñ 6Cô 6Cñ Ôð6Cðr%ð %ð %ð %ðP €�$ÐÑÔðH
ð H
ð H
ð H
ð H
ñ H
ô H
ñ ÔðH
ð H
ð H
r*   