§
    ß©ºjó�  ã                  óà  — U d Z ddlmZ ddlmZmZ ddlmZmZ ddl	m
Z
 ddlmZ ddlmZmZmZmZ ddlZdd	lmZ dd
lmZ ddlmZmZmZmZmZmZmZm Z m!Z!m"Z"m#Z# ddlm$Z% ddlm&Z' ddlm(Z) ddl*m+Z+ ddl,m-Z-m.Z.m/Z/m0Z0m1Z1m2Z2m3Z3m4Z4m5Z5 erddl6Z7ed         Z8 e9dh¦  «        Z:de;d<   g d¢Z< ed¬¦  «         G d„ d¦  «        ¦   «         Z=dZ>de;d<   dZ?de;d<   dZ@de;d<   dZAde;d <   dZBde;d!<   d"ZCde;d#<   dGd(„ZDdHd,„ZEdId3„ZF edd¬4¦  «         G d5„ d6¦  «        ¦   «         ZG edd¬4¦  «         G d7„ d8¦  «        ¦   «         ZHdJd>„ZIdKdA„ZJdLdD„ZK edd¬4¦  «         G dE„ dF¦  «        ¦   «         ZLdS )Mu!  Semantic-segmentation evaluation surface (ADR-0028).

Per ADR-0029, the semantic-segmentation evaluation paradigm lives
under ``vernier.semantic``. Sibling to :mod:`vernier.instance` (the
AP fold) and :mod:`vernier.panoptic` (panoptic-quality). The Rust
kernel ships in the ``vernier-semantic`` crate; this module is a thin
Python wrapper.

Surface:

- :class:`Dataset` / :class:`Predictions` â€” frozen dataclasses
  carrying the per-image label maps + dataset-level config
  (``n_classes`` / ``ignore_label``).
- :class:`Evaluator` â€” frozen dataclass holding ``parity_mode`` and
  optional ``label_remap``. ``Evaluator.evaluate(gt, dt)`` returns a
  :class:`Summary` (the FFI pyclass).
- :class:`Summary` / :class:`ClassSemanticStats` /
  :class:`ConfusionMatrix` â€” re-exported FFI pyclasses (under their
  unprefixed names per ADR-0029).
- Per-dataset presets â€” :meth:`Dataset.cityscapes`,
  :meth:`Dataset.ade20k`, :meth:`Dataset.pascal_voc` â€” bake the
  canonical ignore-label and class-count conventions; the user only
  passes the PNG paths.
é    )Úannotations)ÚMappingÚSequence)Ú	dataclassÚfield)Úcached_property)ÚPath)ÚTYPE_CHECKINGÚFinalÚLiteralÚoverloadN)ÚNDArray)ÚBackgroundSemanticEvaluator)Ú	BreakdownÚClassSemanticStatsÚConfusionMatrixÚPartialDatasetMismatchÚPartialFormatMismatchÚPartialParamsMismatchÚPartialPartitionOverlapÚPartialRankCollisionÚevaluate_semantic_from_arraysÚevaluate_semantic_from_pngsÚ%semantic_per_class_to_arrow_pycapsule)ÚSemanticSummary)Úevaluate_semantic_to_partial)Úmerge_semantic_partials)Úarrow_to_dataframe)	ÚCategoryFilterÚCategoryFilterAllÚCategoryFilterByGroupingÚCategoryFilterByIdsÚCategoryFilterFrequencyÚInvalidEvalParamsÚInvalidSemanticParamsÚ
ParityModeÚnormalize_tables_argÚ	per_classzfrozenset[TableName]ÚSUPPORTED_TABLES)ÚADE20K_IGNORE_LABELÚADE20K_N_CLASSESÚCITYSCAPES_IGNORE_LABELÚCITYSCAPES_N_CLASSESÚPASCAL_VOC_IGNORE_LABELÚPASCAL_VOC_N_CLASSESÚBackgroundEvaluatorr   r   r    r!   r"   r#   r   r   ÚDatasetÚ
EvalResultÚ	Evaluatorr$   r%   r&   r   r   r   r   r   ÚPredictionsÚSummaryÚ	TableNameÚdecode_label_map_pngT)Úfrozenc                  óÚ   — e Zd ZU dZded<    edd¬¦  «        Zded<    edd¬¦  «        Zded	<    ed¬
¦  «        Zded<    ed¬
¦  «        Z	ded<   e
dd„¦   «         Ze
dd„¦   «         ZdS )r2   a:  Opt-in result of :meth:`Evaluator.evaluate` when ``tables=`` is
    passed. Carries :class:`Summary` plus a polars DataFrame view of
    the per-class semantic breakdown in the canonical mmseg / ADE20K
    column order. Tables on :meth:`Evaluator.evaluate_from_pngs`
    (ADR-0037 fused path) are deferred.

    Also returned when ``manifest=`` is passed (ADR-0046 partitioned
    eval): the ``.summary`` field carries the bit-identical-to-
    un-partitioned ``overall`` summary, and the :attr:`slices`
    DataFrame view exposes the per-``(axis, value)`` cell metrics.r5   ÚsummaryNF)ÚdefaultÚreprúobject | NoneÚ_per_class_batchÚ_slices_batch©r;   ú
int | NoneÚoverall_n_imagesÚoverall_n_detectionsÚreturnúpl.DataFramec                ó,   — t          | j        d¦  «        S )z±One row per class. Columns: ``category_id``, ``iou``,
        ``accuracy``, ``precision``, ``n_gt_pixels``, ``n_dt_pixels``,
        ``tp_pixels``, ``fp_pixels``, ``fn_pixels``.r(   )r   r>   ©Úselfs    úi/root/private/project/pallet_detection_v2/.venv/lib/python3.11/site-packages/vernier/semantic/__init__.pyr(   zEvalResult.per_class—   s   € õ
 " $Ô"7¸ÑEÔEÐEó    c                ó,   — t          | j        d¦  «        S )uæ  One row per ``(axis, value)`` partition cell (ADR-0046).
        Columns: ``axis``, ``value``, ``n_images``, ``n_detections``,
        ``miou``, ``fwiou``, ``pixel_accuracy``, ``mean_accuracy``.
        ``n_detections`` is always 0 â€” semantic has no detection
        notion; the column is shape-parity with panoptic / instance.
        Available only when the originating ``evaluate(...)`` call
        carried a ``manifest=`` keyword; raises :class:`RuntimeError`
        otherwise.Úslices)r   r?   rG   s    rI   rL   zEvalResult.slicesž   s   € õ " $Ô"4°hÑ?Ô?Ð?rJ   )rD   rE   )Ú__name__Ú
__module__Ú__qualname__Ú__doc__Ú__annotations__r   r>   r?   rB   rC   r   r(   rL   © rJ   rI   r2   r2   |   sý   € € € € € € ð	Fð 	Fð ÐÐÑØ&+ e°D¸uÐ&EÑ&EÔ&EÐÐEÐEÐEÑEð $) 5°¸EÐ#BÑ#BÔ#B€MÐBÐBÐBÑBð $) 5°Ð#6Ñ#6Ô#6ÐÐ6Ð6Ð6Ñ6ð (- u°TÐ':Ñ':Ô':ÐÐ:Ð:Ð:Ñ:àðFð Fð Fñ „_ðFð ð	@ð 	@ð 	@ñ „_ð	@ð 	@ð 	@rJ   r2   éÿ   z
Final[int]r,   é   r-   r*   é–   r+   r.   é   r/   Úpathú
str | PathrD   úNDArray[np.uint32]c                ó6  — 	 ddl m} n"# t          $ r}t          d¦  «        |‚d}~ww xY w|                     | ¦  «        }t	          j        |¦  «        }|j        dk    rt          d| ›d|j        ›d�¦  «        ‚| 	                    t          j
        d	¬
¦  «        S )uP  Load a single-channel PNG label map as a ``(H, W)`` ``uint32``
    array.

    Lazy-imports Pillow; raises a structured :class:`ImportError` if
    Pillow is not installed. Multi-channel (RGB-encoded) panoptic
    PNGs belong in :func:`vernier.panoptic.decode_label_map_png` â€”
    they are rejected here with :class:`ValueError`.
    r   )ÚImagez§Pillow is required for `vernier.semantic.decode_label_map_png` (and the per-dataset presets); install via `pip install Pillow` (or include it in your dev environment).Né   zsemantic label-map PNG z) must be single-channel (2-D); got shape zb. RGB-encoded panoptic segment ids belong in `vernier.panoptic.Dataset`, not the semantic surface.F©Úcopy)ÚPILr[   ÚImportErrorÚopenÚnpÚasarrayÚndimÚ
ValueErrorÚshapeÚastypeÚuint32)rW   r[   ÚeÚimgÚarrs        rI   r7   r7   ¼   sÙ   € ðØÐÐÐÐÐÐøÝð ð ð Ýð7ñ
ô 
ð ð		øøøøðøøøð �*Š*�TÑ
Ô
€CÝ
Œ*�S‰/Œ/€CØ
„x�1‚}€}ÝðH dð Hð HØœðHð Hð Hñ
ô 
ð 	
ð
 �:Š:•b”i eˆ:Ñ,Ô,Ð,s   ‚	 ‰
(“#£(Ú	png_pathsúMapping[int, str | Path]údict[int, NDArray[np.uint32]]c                ó>   — d„ |                       ¦   «         D ¦   «         S )ub   Decode a mapping of image_id â†’ png path into the ``uint32``
    label-map dict the FFI consumes.c                ó4   — i | ]\  }}|t          |¦  «        “ŒS rR   )r7   )Ú.0Úimage_idÚps      rI   ú
<dictcomp>z%_decode_png_paths.<locals>.<dictcomp>Ý   s'   € ÐSÐSÐS±+°(¸AˆHÕ*¨1Ñ-Ô-ÐSÐSÐSrJ   ©Úitems)rl   s    rI   Ú_decode_png_pathsrw   Ø   s#   € ð
 TÐSÀÇÂÑARÔARÐSÑSÔSÐSrJ   ÚmasksúNDArray[np.uint8]Úmergeú.Literal['argmax', 'first', 'highest_class_id']Úunlabeled_classÚintc               ó.  — | j         dk    rt          d| j        ›�¦  «        ‚| j        \  }}}t          j        ||f|t          j        ¬¦  «        }|                      d¬¦  «        }|dv r6|                      d¬¦  «                             t          j        d¬¦  «        }n^|d	k    rE|d
z
  | ddd…                              d¬¦  «        z
                       t          j        d¬¦  «        }nt          d|›d�¦  «        ‚t          j	        |||¦  «        }|S )u¬  Merge a `(K, H, W)` stack of per-class binary masks into a
    single `(H, W)` ``uint32`` class-id label map. Per quirk **AN3**,
    the merge rule is explicit and load-bearing.

    - ``argmax``: standard argmax over the channel axis. Requires score
      channels (or, on binary inputs, ties go to the lowest class id â€”
      argmax tiebreak).
    - ``first``: the first channel with value 1 wins (order-dependent).
    - ``highest_class_id``: the highest class id with value 1 wins
      (convention-dependent).

    Pixels where every mask is zero are written as ``unlabeled_class``
    (per quirk **AN4**); typical use is to set this to the dataset's
    ``ignore_label``.
    é   z8binary masks must be 3-D `(n_classes, H, W)`; got shape )Údtyper   )Úaxis)ÚargmaxÚfirstFr]   Úhighest_class_idé   Néÿÿÿÿzunknown merge rule z3; expected 'argmax', 'first', or 'highest_class_id')
rd   re   rf   rb   Úfullrh   Úanyr‚   rg   Úwhere)	rx   rz   r|   Ú	n_classesÚhÚwÚoutÚany_setÚchosens	            rI   Ú_merge_binary_masksr�   à   s%  € ð* „z�Q‚€ÝÐcÐTYÔT_ÐcÐcÑdÔdÐdØ”k�O€Iˆq�!Ý
Œ'�1�a�&˜/µ´Ð
;Ñ
;Ô
;€CØ�iŠi˜QˆiÑÔ€GØÐ#Ð#Ð#ð
 —’ 1�Ñ%Ô%×,Ò,­R¬Y¸UÐ,ÑCÔCˆˆØ	Ð$Ò	$Ð	$à˜a‘- %¨¨¨"¨¤+×"4Ò"4¸!Ð"4Ñ"<Ô"<Ñ<×DÒDÅRÄYÐUZÐDÑ[Ô[ˆˆåØ^ %Ð^Ð^Ð^ñ
ô 
ð 	
õ Œ(�7˜F CÑ
(Ô
(€CØ€JrJ   )r8   Úslotsc                  ó¾   — e Zd ZU dZded<   ded<   dZded<   dd„Ze	 ddd„¦   «         Ze	 ddd„¦   «         Z	edd„¦   «         Z
edd„¦   «         Zedd„¦   «         ZdS )r1   uÚ  Semantic-segmentation ground truth.

    Carries per-image label maps, the evaluation class count, and the
    ignore label. Constructors:

    - :meth:`from_arrays` â€” pre-decoded ``uint8`` / ``uint16`` /
      ``uint32`` ``ndarray`` per image. Zero-copy on the FFI hot
      path; the kernel walks at native dtype (ADR-0037).
    - :meth:`from_files` â€” PNG paths; decoded via Pillow.
    - :meth:`cityscapes` / :meth:`ade20k` / :meth:`pascal_voc` â€”
      per-dataset presets that bake the canonical ``n_classes`` and
      ``ignore_label`` conventions.

    Predictions are constructed via the sibling :class:`Predictions`
    type â€” same shape, no class-count metadata (the dataset is the
    authoritative source).
    úMapping[int, np.ndarray]Ú
label_mapsr}   rŠ   NrA   Úignore_labelrD   ÚNonec                ó    — | j         dk     rt          d| j         ›�¦  «        ‚| j        �"| j        dk     rt          d| j        ›�¦  «        ‚d S d S )Nr…   zn_classes must be >= 1; got r   z1ignore_label must be a non-negative integer; got )rŠ   re   r•   rG   s    rI   Ú__post_init__zDataset.__post_init__#  sl   € ØŒ>˜AÒÐÝÐN¸D¼NÐNÐNÑOÔOÐOØÔÐ(¨TÔ->ÀÒ-BÐ-BÝØYÀDÔDUÐYÐYñô ð ð )Ð(Ð-BÐ-BrJ   c                ó8   —  | t          |¦  «        ||¬¦  «        S )a…  Construct from pre-decoded label-map ``ndarray`` per image.

        Each ``label_maps[image_id]`` must be a 2-D integer array. The
        FFI boundary accepts ``uint8`` / ``uint16`` / ``uint32`` natively
        (ADR-0037); the kernel walks at native dtype, so passing
        ``uint8`` from a ``torch.Tensor`` avoids the 4x upcast that
        earlier wheel versions paid here.
        ©r”   rŠ   r•   ©Údict)Úclsr”   rŠ   r•   s       rI   Úfrom_arrayszDataset.from_arrays+  s$   € ð ˆs�d :Ñ.Ô.¸)ÐR^Ð_Ñ_Ô_Ð_rJ   rl   rm   c                ó8   —  | t          |¦  «        ||¬¦  «        S )u  Decode PNG paths via Pillow into a :class:`Dataset`.

        Each PNG must be a single-channel label map. Multi-channel
        (RGB-encoded) panoptic PNGs belong in
        :class:`vernier.panoptic.Dataset` â€” they are rejected here
        with a :class:`ValueError`.
        rš   ©rw   )r�   rl   rŠ   r•   s       rI   Ú
from_fileszDataset.from_files<  s.   € ð ˆsÝ(¨Ñ3Ô3ØØ%ð
ñ 
ô 
ð 	
rJ   c                óF   — |                       |t          t          ¬¦  «        S )u  Cityscapes 19-class evaluation preset.

        ``n_classes=19``, ``ignore_label=255``. PNGs are expected to
        be ``*_labelTrainIds.png`` files (already in trainId space â€”
        the 30+ raw label space pre-mapped to 19 classes by the
        ``cityscapesscripts/preparation/createTrainIdLabelImgs.py``
        helper).

        Users with predictions in the raw 30+ label space should
        construct :class:`Evaluator` with an explicit ``label_remap``
        dict that maps raw ids to trainIds.
        ©rŠ   r•   )r¡   r-   r,   ©r�   rl   s     rI   Ú
cityscapeszDataset.cityscapesP  s(   € ð �~Š~ØÝ*Ý0ð ñ 
ô 
ð 	
rJ   c                óF   — |                       |t          t          ¬¦  «        S )z¼ADE20K (SceneParse150) preset.

        ``n_classes=150``, ``ignore_label=0``. Class 0 is the
        "other/unlabeled" sentinel; predictions are expected in
        ``[1, 150]``.
        r£   )r¡   r+   r*   r¤   s     rI   Úade20kzDataset.ade20kd  s(   € ð �~Š~ØÝ&Ý,ð ñ 
ô 
ð 	
rJ   c                óF   — |                       |t          t          ¬¦  «        S )zÕPascal VOC preset.

        ``n_classes=21``, ``ignore_label=255``. 20 object classes plus
        a ``background`` class indexed at 0; the 255 sentinel marks
        ``void`` pixels at object boundaries.
        r£   )r¡   r/   r.   r¤   s     rI   Ú
pascal_voczDataset.pascal_vocr  s(   € ð �~Š~ØÝ*Ý0ð ñ 
ô 
ð 	
rJ   ©rD   r–   ©N)r”   r“   rŠ   r}   r•   rA   rD   r1   )rl   rm   rŠ   r}   r•   rA   rD   r1   )rl   rm   rD   r1   )rM   rN   rO   rP   rQ   r•   r˜   Úclassmethodrž   r¡   r¥   r§   r©   rR   rJ   rI   r1   r1     s  € € € € € € ðð ð$ )Ð(Ð(Ñ(Ø€N€N�NØ#€LÐ#Ð#Ð#Ñ#ðð ð ð ð ð
 $(ð	`ð `ð `ð `ñ „[ð`ð  ð
 $(ð	
ð 
ð 
ð 
ñ „[ð
ð& ð
ð 
ð 
ñ „[ð
ð& ð
ð 
ð 
ñ „[ð
ð ð
ð 
ð 
ñ „[ð
ð 
ð 
rJ   r1   c                  ón   — e Zd ZU dZded<   edd„¦   «         Zedd„¦   «         Zed	d
dœdd„¦   «         ZdS )r4   u  Semantic-segmentation predictions.

    Carries per-image label maps only â€” class-count and ignore-label
    metadata live on the sibling :class:`Dataset` (the authoritative
    source). Constructors mirror :class:`Dataset`:

    - :meth:`from_arrays` â€” pre-decoded ``uint8`` / ``uint16`` /
      ``uint32`` ``ndarray`` per image (ADR-0037).
    - :meth:`from_files` â€” PNG paths; decoded via Pillow.
    - :meth:`from_binary_masks` â€” per-class binary masks merged into
      a single class-id label map per image (quirk **AN2**).
    r“   r”   rD   c                ó4   —  | t          |¦  «        ¬¦  «        S )z¸Construct from pre-decoded label-map ``ndarray`` per image.

        Accepts ``uint8`` / ``uint16`` / ``uint32`` natively (ADR-0037);
        the FFI walks at the input dtype.
        ©r”   r›   )r�   r”   s     rI   rž   zPredictions.from_arrays’  s   € ð ˆs�d :Ñ.Ô.Ð/Ñ/Ô/Ð/rJ   rl   rm   c                ó4   —  | t          |¦  «        ¬¦  «        S )z…Decode PNG paths via Pillow into a :class:`Predictions`.

        See :meth:`Dataset.from_files` for the PNG shape contract.
        r¯   r    r¤   s     rI   r¡   zPredictions.from_files›  s    € ð ˆsÕ/°	Ñ:Ô:Ð;Ñ;Ô;Ð;rJ   r‚   rS   ©rz   r|   rx   úMapping[int, NDArray[np.uint8]]rz   r{   r|   r}   c               ó`   ‡‡— ˆˆfd„|                      ¦   «         D ¦   «         } | |¬¦  «        S )uè  Merge per-image `(n_classes, H, W)` binary mask stacks into
        single class-id label maps (quirks **AN2**, **AN3**, **AN4**).

        ``merge`` selects the precedence rule for overlapping pixels:

        - ``"argmax"`` (default) â€” argmax over channels; on score
          input the highest score wins, on binary input ties go to
          the lowest class id.
        - ``"first"`` â€” the first channel with value 1 wins
          (order-dependent).
        - ``"highest_class_id"`` â€” the highest class id with value 1
          wins (convention-dependent).

        ``unlabeled_class`` is written into pixels where every mask
        is zero (default ``255`` matches the Cityscapes / Pascal VOC
        ignore convention).
        c                ó<   •— i | ]\  }}|t          |‰‰¬ ¦  «        “ŒS )r±   )r�   )rq   rr   rk   rz   r|   s      €€rI   rt   z1Predictions.from_binary_masks.<locals>.<dictcomp>¼  s?   ø€ ð 1
ð 1
ð 1
á�˜#ð Õ)¨#°UÈOÐ\Ñ\Ô\ð1
ð 1
ð 1
rJ   r¯   ru   )r�   rx   rz   r|   Úmergeds     `` rI   Úfrom_binary_maskszPredictions.from_binary_masks£  sN   øø€ ð21
ð 1
ð 1
ð 1
ð 1
à!&§¢¡¤ð1
ñ 1
ô 1
ˆð ˆs˜fÐ%Ñ%Ô%Ð%rJ   N)r”   r“   rD   r4   )rl   rm   rD   r4   )rx   r²   rz   r{   r|   r}   rD   r4   )	rM   rN   rO   rP   rQ   r¬   rž   r¡   r¶   rR   rJ   rI   r4   r4   �  s    € € € € € € ðð ð )Ð(Ð(Ñ(àð0ð 0ð 0ñ „[ð0ð ð<ð <ð <ñ „[ð<ð ð
 AIØ"ð&ð &ð &ð &ð &ñ „[ð&ð &ð &rJ   r4   Úcfr   Úclass_groupingúBreakdown | Noner–   c           
     ó²  — t          | t          ¦  «        rt          d| d¬¦  «        ‚t          | t          ¦  «        r*t	          | j        ¦  «        dk    rt          d| d¬¦  «        ‚t          | t          ¦  «        rY|€t          d| d¬¦  «        ‚d„ |j        D ¦   «         }| j        |vr-t          d| d	| j        ›d
t          |¦  «        ›d�¬¦  «        ‚dS dS )u†  Validate a ``class_filter`` for the semantic paradigm (ADR-0041).

    ``Frequency`` is rejected (LVIS-only â€” no semantic frequency tag).
    ``ByIds`` requires non-empty unique ids; bounds against ``n_classes``
    are checked at evaluate time once the Dataset is in scope.
    ``ByGrouping`` requires that ``class_grouping`` is configured and
    that the named label exists in it.
    Úclass_filterz—Frequency is LVIS-only - semantic has no per-class frequency tag analogous to r/c/f. Use ByIds or ByGrouping instead (ADR-0026 lines 178-182, ADR-0041)©r   ÚvalueÚremediationr   z3ByIds must contain at least one class id (ADR-0041)NzqByGrouping requires class_grouping to also be set; the label is resolved against the grouping's labels (ADR-0041)c                ó   — h | ]\  }}|’ŒS rR   rR   )rq   ÚlabelÚ_s      rI   ú	<setcomp>z2_validate_semantic_class_filter.<locals>.<setcomp>æ  s   € ÐDÐDÐD™H˜E 1�%ÐDÐDÐDrJ   zByGrouping label z1 is not a label of class_grouping (known labels: z); ADR-0041)
Ú
isinstancer#   r%   r"   ÚlenÚidsr!   Úclass_groupsrÀ   Úsorted)r·   r¸   Úlabelss      rI   Ú_validate_semantic_class_filterrÉ   Ã  sD  € õ �"Õ-Ñ.Ô.ð 	
Ý#Ø Øð5ð	
ñ 
ô 
ð 	
õ �"Õ)Ñ*Ô*ð 
­s°2´6©{¬{¸aÒ/?Ð/?Ý#Ø ØØMð
ñ 
ô 
ð 	
õ
 �"Õ.Ñ/Ô/ð ØÐ!Ý'Ø$ØðUð	ñ ô ð ð EÐD¨Ô(CÐDÑDÔDˆØŒ8˜6Ð!Ð!Ý'Ø$ØðD¨¬ð Dð DÝ&,¨V¡n¤nðDð Dð Dð	ñ ô ð ðð ð "Ð!rJ   úCategoryFilter | Noneúlist[int] | Nonec                ód  — | �t          | t          ¦  «        rdS t          | t          ¦  «        rt          | j        ¦  «        S t          | t
          ¦  «        rH|€J ‚|j        D ]!\  }}|| j        k    rt          |¦  «        c S Œ"t          d| d| j        ›d�¬¦  «        ‚t          d| d¬¦  «        ‚)a\  Resolve an ADR-0041 ``class_filter`` to the kernel's class-id form.

    ``None`` and :class:`CategoryFilterAll` produce ``None`` (no
    filtering at the kernel). :class:`CategoryFilterByIds` returns a
    sorted list of its ids. :class:`CategoryFilterByGrouping` resolves
    the label against the active ``class_grouping`` partition and
    returns the union of that group's class ids.

    The construction-time validator (:func:`_validate_semantic_class_filter`)
    has already rejected :class:`CategoryFilterFrequency` and
    cross-checked the grouping label, so this function trusts inputs.
    Nr»   zlabel z  disappeared from class_groupingr¼   z"unsupported CategoryFilter variant)
rÃ   r    r"   rÇ   rÅ   r!   rÆ   rÀ   Úlistr%   )r·   r¸   rÀ   rÅ   s       rI   Ú_resolve_class_filterrÎ   ò  sê   € ð  
€z•Z Õ$5Ñ6Ô6€zØˆtÝ�"Õ)Ñ*Ô*ð Ý�b”f‰~Œ~ÐÝ�"Õ.Ñ/Ô/ð 
ð Ð)Ð)Ð)Ø(Ô5ð 	!ð 	!‰JˆE�3Ø˜œÒ Ð Ý˜C‘y”yÐ Ð Ð ð !õ $Ø ØØM ¤ÐMÐMÐMð
ñ 
ô 
ð 	
õ  ØØØ8ðñ ô ð rJ   Úbdú"list[tuple[str, list[int]]] | Nonec                ó,   — | €dS d„ | j         D ¦   «         S )z±Resolve a ``class_grouping`` :class:`Breakdown` to the kernel's
    list-of-pairs form. ``None`` passes through; the kernel skips the
    per-group rollup when this is ``None``.Nc                ó6   — g | ]\  }}|t          |¦  «        f‘ŒS rR   )rÍ   )rq   rÀ   rÅ   s      rI   ú
<listcomp>z+_resolve_class_grouping.<locals>.<listcomp>#  s'   € ÐAÐAÐA¡: 5¨#ˆU•D˜‘I”IÐÐAÐAÐArJ   )rÆ   )rÏ   s    rI   Ú_resolve_class_groupingrÔ     s$   € ð 
€zØˆtØAÐA°´ÐAÑAÔAÐArJ   c                  óH  — e Zd ZU dZdZded<    ed¬¦  «        Zded<   dZd	ed
<   dZ	ded<   dEd„Z
dFd„ZedddddœdGd„¦   «         ZeddddœdHd!„¦   «         Zedddd"œdId%„¦   «         ZdddddœdJd)„Zddd*œdKd1„Zdd2œdLd5„Zedddd6œdMd9„¦   «         Z	 dNdd:dd;d<dd=œdOdD„ZdS )Pr3   aÆ  Semantic-segmentation evaluator (ADR-0028, ADR-0041).

    Sibling to :class:`vernier.instance.Evaluator` (AP fold) and
    :class:`vernier.panoptic.Evaluator` (panoptic-quality). Computes
    mIoU, FWIoU, pixel accuracy, mean accuracy, per-class IoU, and
    per-class accuracy from per-image confusion matrices accumulated
    into a global confusion matrix.

    The instance is immutable per ADR-0006: construct once, call
    :meth:`evaluate` per dataset/predictions pair.

    Defaults match net-new-user expectations: ``parity_mode="corrected"``
    (per ADR-0002 recommendation); migrating users wanting bit-exact
    mmsegmentation behavior should set ``parity_mode="strict"``.

    ``class_filter`` and ``class_grouping`` (ADR-0041) parameterize the
    evaluation scope and rollup. ``class_filter`` restricts the headline
    scalars (``miou`` etc.) to a subset of classes; ``class_grouping``
    adds an optional per-group rollup alongside ``per_class``. Both
    default to ``None`` (kernel-canonical: every class contributes to
    headline scalars; no per-group rollup).

    **PR scope cut:** the kernel-side plumbing for honoring custom
    ``class_filter`` / ``class_grouping`` is a follow-up to ADR-0041
    (`per_group` lives on `SemanticSummary` once the Rust struct gains
    it). Until that lands, ``evaluate()`` raises
    :class:`NotImplementedError` when either is set; the surface
    (fields, validation, ``with_options`` threading) is in place.
    Ú	correctedr&   Úparity_modeNr@   zMapping[int, int] | NoneÚlabel_remaprÊ   r»   r¹   r¸   rD   r–   c                ó¨   — | j         �'| j         j        dk    rt          d| j         d¬¦  «        ‚| j        �t	          | j        | j         ¦  «         d S d S )NrÆ   r¸   z‰must be a class-groups Breakdown (Breakdown.from_class_groups(...)); range Breakdowns belong on instance.Evaluator.area_ranges (ADR-0041)r¼   )r¸   Úkindr%   r»   rÉ   rG   s    rI   r˜   zEvaluator.__post_init__K  sp   € ØÔÐ*¨tÔ/BÔ/GÈ>Ò/YÐ/YÝ'Ø&ØÔ)ðJð	ñ ô ð ð ÔÐ(Ý+¨DÔ,=¸tÔ?RÑSÔSÐSÐSÐSð )Ð(rJ   Úboolc                ó&   — | j         dup| j        duS )z(``True`` when any ADR-0041 field is set.N)r»   r¸   rG   s    rI   Ú_has_custom_class_paramsz"Evaluator._has_custom_class_paramsY  s   € àÔ ¨Ð,ÐO°Ô0CÈ4Ð0OÐOrJ   )ÚtablesÚmanifestÚ
cross_axesÚnum_threadsÚgtr1   Údtr4   rÞ   rß   rà   rá   rA   r5   c               ó   — d S r«   rR   ©rH   râ   rã   rÞ   rß   rà   rá   s          rI   ÚevaluatezEvaluator.evaluate]  s	   € ð �#rJ   )rß   rà   rá   ú&Literal['all'] | tuple[TableName, ...]r2   c               ó   — d S r«   rR   rå   s          rI   ræ   zEvaluator.evaluatei  ó	   € ð �SrJ   )rÞ   rà   rá   ÚobjectúSequence[Sequence[str]] | Nonec               ó   — d S r«   rR   rå   s          rI   ræ   zEvaluator.evaluateu  ré   rJ   ú-Literal['all'] | tuple[TableName, ...] | Noner=   úSummary | EvalResultc               óh  — |�Íddl m} |�t          d¦  «        ‚|                      ¦   «         rt	          d|d¬¦  «        ‚t          | j        | j        ¦  «        }t          | j        ¦  «        }	 ||j	        |j	        |j
        | j        |j        | j        �t          | j        ¦  «        nd||	|||¬¦  «        \  }
}}}t          |
|||¬	¦  «        S |�t          d
¦  «        ‚t          | j        | j        ¦  «        }t          | j        ¦  «        }	t!          t          |j	        ¦  «        t          |j	        ¦  «        |j
        | j        |j        | j        �t          | j        ¦  «        nd||	|¬¦	  «	        }|€|S t#          |t$          ¦  «        }d|v rt'          |¦  «        nd}t          ||¬¦  «        S )uÖ  Run the semantic-segmentation evaluation.

        ``gt`` and ``dt`` may be constructed via any combination of
        the per-class constructors (:meth:`Dataset.from_arrays`,
        :meth:`Predictions.from_files`, etc.); the FFI consumes
        whatever ``uint32`` ndarrays the constructors produced.

        Returns a :class:`Summary` carrying the four headline scalars
        (mIoU / FWIoU / pixel_accuracy / mean_accuracy), the per-class
        breakdown, and the accumulated :class:`ConfusionMatrix`.

        ``tables=`` is the opt-in keyword for result tables (ADR-0038).
        Defaults to ``None``, returning :class:`Summary` (existing
        behavior). Pass ``"all"`` or a tuple of :data:`TableName`
        values to opt into the wider :class:`EvalResult` return type.

        ``manifest=`` opts into ADR-0046 partitioned eval. Accepts a
        dict (the canonical JSON-records shape), a file path
        (``.json``), or any object exposing the Arrow PyCapsule
        Interface (a polars / pandas / pyarrow DataFrame of per-image
        metadata). Returns an :class:`EvalResult` whose ``.summary``
        is bit-identical to the un-partitioned call and whose
        ``.slices`` property is a polars DataFrame with one row per
        ``(axis, value)`` cell. ``cross_axes=`` opts joint cells in
        (per ADR-0046 Â§E2; marginals are the default).

        Per ADR-0046's C3 axiom, the per-image confusion-matrix fold
        runs exactly once regardless of slice count: the FFI retains a
        ``Vec<(image_id, ConfusionMatrix)>`` of per-image deltas and
        the partition orchestrator sums them under (a) no filter for
        ``overall`` and (b) each slice's image-id set for the per-slice
        rows. Confusion-matrix sums are u64-additive, so the parity
        contract is unconditional (no f64 non-associativity to worry
        about, unlike the panoptic path); the ``overall`` summary is
        bit-identical to the un-partitioned call by construction.
        Nr   )Úevaluate_partitionedu  tables= and manifest= cannot be combined. The partitioned eval returns headline metrics per slice on `result.slices`; for the per-class by per-slice cross product, run per_class evaluate once per slice with a filtered label-map set â€” see docs/how-to/per-class-by-slice.md.rß   zÃsemantic partitioned eval does not yet propagate the ADR-0041 custom fields (class_filter / class_grouping). Re-run with a default-config evaluator, or run manifest= and custom params separately.r¼   )	rŠ   r×   r•   rØ   r»   r¸   rß   rà   rá   )r:   r?   rB   rC   z•cross_axes= is only meaningful alongside manifest= (it opts joint cells into the manifest partition spec; with no manifest there is nothing to cross))rŠ   r×   r•   rØ   r»   r¸   rá   r(   )r:   r>   )Úvernier.semantic._partitionrð   re   rÝ   r%   rÎ   r»   r¸   rÔ   r”   rŠ   r×   r•   rØ   rœ   r2   r   r'   r)   r   )rH   râ   rã   rÞ   rß   rà   rá   Ú_evaluate_partitionedÚresolved_filterÚresolved_groupsÚoverallÚslices_batchÚn_imagesÚn_detsr:   Ú	requestedÚper_class_batchs                    rI   ræ   zEvaluator.evaluate�  s-  € ð\ Ððð ð ð ð ð ð Ð!Ý ð9ñô ð ð ×,Ò,Ñ.Ô.ð 
Ý+Ø$Ø"ðBð		ñ 	ô 	ð 	õ 4°DÔ4EÀtÔGZÑ[Ô[ˆOÝ5°dÔ6IÑJÔJˆOØ6KÐ6KØ”Ø”Øœ,Ø Ô,Øœ_Ø6:Ô6FÐ6R�D Ô!1Ñ2Ô2Ð2ÐX\Ø,Ø.Ø!Ø%Ø'ð7ñ 7ô 7Ñ3ˆG�\ 8¨Võ ØØ*Ø!)Ø%+ð	ñ ô ð ð Ð!Ýð6ñô ð õ 0°Ô0AÀ4ÔCVÑWÔWˆÝ1°$Ô2EÑFÔFˆÝ/Ý�”ÑÔÝ�”ÑÔØ”lØÔ(ØœØ26Ô2BÐ2N�˜TÔ-Ñ.Ô.Ð.ÐTXØ(Ø*Ø#ð

ñ 

ô 

ˆð ˆ>ØˆNÝ(¨Õ1AÑBÔBˆ	à>IÈYÐ>VÐ>VÕ1°'Ñ:Ô:Ð:Ð\`ð 	õ  '¸OÐLÑLÔLÐLrJ   ©r•   rá   Úgt_pathsrm   Údt_pathsrŠ   r}   r•   c               ó–   — | j         �t          d¦  «        ‚t          t          |¦  «        t          |¦  «        || j        ||¬¦  «        S )uî  Run the evaluation directly against 8-bit grayscale PNG label
        maps on disk (ADR-0037).

        Skips the Pillow â†’ ndarray â†’ ``astype(np.uint32)`` pipeline:
        the libpng decode and the per-image confusion-matrix fold run
        in Rust under ``py.detach``, so the GIL is released for the
        whole batch and only one decoded label-map per side is in
        flight at a time. Memory ceiling is bounded by image size,
        not dataset size.

        Format contract: 8-bit grayscale PNGs only (the natural width
        for class-id label maps up to 256 classes; covers every dataset
        in the per-paradigm presets â€” Cityscapes, ADE20K, Pascal VOC,
        plus panoptic-derived semantic). Wider class-id ranges should
        use :meth:`evaluate` with ``np.uint16`` / ``np.uint32`` ndarrays.

        ``label_remap`` does not propagate to the fused path; callers
        needing a remap should rewrite the DT PNGs upstream or fall
        back to :meth:`evaluate`.
        Nz�Evaluator.evaluate_from_pngs does not yet propagate label_remap; rewrite the DT PNGs upstream or fall back to Evaluator.evaluate.)rŠ   r×   r•   rá   )rØ   ÚNotImplementedErrorr   rœ   r×   )rH   rü   rý   rŠ   r•   rá   s         rI   Úevaluate_from_pngszEvaluator.evaluate_from_pngsú  s_   € ð: ÔÐ'Ý%ðSñô ð õ +Ý�‰NŒNÝ�‰NŒNØØÔ(Ø%Ø#ð
ñ 
ô 
ð 	
rJ   )rá   Úrank_idÚbytesc          	     óÀ   — | j         �t          d¦  «        ‚t          t          |j        ¦  «        t          |j        ¦  «        |j        | j        ||j        |¬¦  «        S )uÄ  Run the evaluation as a per-rank streaming submit and return
        the serialized partial bytes (ADR-0032, ADR-0035).

        ``rank_id`` identifies this evaluator's rank in a multi-process
        eval. The partial bytes can be gathered across ranks and merged
        with :meth:`from_partials` to produce a global :class:`Summary`
        bit-equal to a batch :meth:`evaluate` over the union (semantic
        confusion-matrix sums are u64-additive, so strict-mode
        bit-equality is unconditional per ADR-0032).

        ``label_remap`` does not propagate to the streaming path â€”
        callers needing remap apply it on the DT arrays themselves
        before passing the dataset in.
        NzƒEvaluator.evaluate_to_partial does not yet propagate label_remap; apply the remap on the DT arrays before constructing Predictions.)rŠ   r×   r  r•   rá   )rØ   rÿ   Ú_evaluate_semantic_to_partialrœ   r”   rŠ   r×   r•   )rH   râ   rã   r  rá   s        rI   Úevaluate_to_partialzEvaluator.evaluate_to_partial%  sn   € ð, ÔÐ'Ý%ðTñô ð õ -Ý�”ÑÔÝ�”ÑÔØ”lØÔ(ØØœØ#ð
ñ 
ô 
ð 	
rJ   )r×   r•   rá   ÚpartialsúSequence[bytes]c              óD   — t          |t          |¦  «        |||¬¦  «        S )a<  Merge ``partials`` (one per rank) into a global :class:`Summary`
        (ADR-0032, ADR-0035).

        ``n_classes``, ``parity_mode``, and ``ignore_label`` must match
        what each rank used to produce its partial. Mismatches raise
        the structured ``Partial*`` errors re-exported on this module.
        rû   )Ú_merge_semantic_partialsrÍ   )r�   rŠ   r  r×   r•   rá   s         rI   Úfrom_partialszEvaluator.from_partialsJ  s0   € õ$ (ØÝ�‰NŒNØØ%Ø#ð
ñ 
ô 
ð 	
rJ   é   é   g      @)r  Úqueue_capacityÚworker_affinityÚworker_niceÚshutdown_timeout_secondsrá   r  r  r  r  Úfloatr0   c               óh   — | j         �t          d¦  «        ‚t          || j        |||||||¬¦	  «	        S )u\  Build a :class:`BackgroundEvaluator` (ADR-0014 + ADR-0032)
        that shares this evaluator's ``parity_mode``.

        The returned wrapper owns a single dedicated worker thread
        running a :class:`StreamingEvaluator` of the same shape; calls
        to :meth:`BackgroundEvaluator.submit` enqueue per-image
        ``(gt, dt)`` pairs and return immediately. Use this when the
        confusion-matrix fold measurably stalls the training loop
        (most users won't notice â€” semantic is fast â€” but per-image
        update on dense Cityscapes pixels is the case where this
        starts to matter).

        ``rank_id``, when set, identifies this evaluator's rank in a
        multi-process eval (ADR-0032). The five queueing /
        scheduling knobs mirror :class:`vernier.instance.Evaluator
        .background`.

        ``num_threads`` (ADR-0047) is forwarded into the per-worker
        rayon pool. The worker drain-batches pending submissions and
        applies them via the parallel confusion-matrix kernel;
        single-threaded callers (``num_threads=None`` or ``1``) hit
        the unchanged single-image path with no batching overhead.

        ``label_remap`` does not propagate to the background path â€”
        callers needing remap on a streaming path apply it on the DT
        arrays themselves before each ``submit`` call.
        NzrEvaluator.background does not yet propagate label_remap; apply the remap on the DT arrays before each submit call.)r•   r  r  r  r  r  rá   )rØ   rÿ   r0   r×   )	rH   rŠ   r•   r  r  r  r  r  rá   s	            rI   Ú
backgroundzEvaluator.backgroundd  s]   € ðN ÔÐ'Ý%ðLñô ð õ #ØØÔØ%ØØ)Ø+Ø#Ø%=Ø#ð

ñ 

ô 

ð 
	
rJ   rª   )rD   rÛ   )râ   r1   rã   r4   rÞ   r–   rß   r–   rà   r–   rá   rA   rD   r5   )râ   r1   rã   r4   rÞ   rç   rß   r–   rà   r–   rá   rA   rD   r2   )râ   r1   rã   r4   rÞ   r–   rß   rê   rà   rë   rá   rA   rD   r2   )râ   r1   rã   r4   rÞ   rí   rß   r=   rà   rë   rá   rA   rD   rî   )rü   rm   rý   rm   rŠ   r}   r•   rA   rá   rA   rD   r5   )
râ   r1   rã   r4   r  r}   rá   rA   rD   r  )rŠ   r}   r  r  r×   r&   r•   rA   rá   rA   rD   r5   r«   )rŠ   r}   r•   rA   r  rA   r  r}   r  rA   r  r}   r  r  rá   rA   rD   r0   )rM   rN   rO   rP   r×   rQ   r   rØ   r»   r¸   r˜   rÝ   r   ræ   r   r  r¬   r
  r  rR   rJ   rI   r3   r3   &  s<  € € € € € € ðð ð< *€KÐ)Ð)Ð)Ñ)Ø,1¨E¸$Ð,?Ñ,?Ô,?€KÐ?Ð?Ð?Ñ?Ø*.€LÐ.Ð.Ð.Ñ.Ø'+€NÐ+Ð+Ð+Ñ+ðTð Tð Tð TðPð Pð Pð Pð ð ØØØ"&ð	ð 	ð 	ð 	ð 	ñ „Xð	ð ð ØØ"&ð	ð 	ð 	ð 	ð 	ñ „Xð	ð ð à59Ø"&ð	ð 	ð 	ð 	ð 	ñ „Xð	ð  AEØ"&Ø59Ø"&ðwMð wMð wMð wMð wMð wMð~ $(Ø"&ð)
ð )
ð )
ð )
ð )
ð )
ðb #'ð#
ð #
ð #
ð #
ð #
ð #
ðJ ð #.Ø#'Ø"&ð
ð 
ð 
ð 
ð 
ñ „[ð
ð8 $(ð6
ð
 #ØØ&*ØØ*-Ø"&ð6
ð 6
ð 6
ð 6
ð 6
ð 6
ð 6
ð 6
rJ   r3   )rW   rX   rD   rY   )rl   rm   rD   rn   )rx   ry   rz   r{   r|   r}   rD   rY   )r·   r   r¸   r¹   rD   r–   )r·   rÊ   r¸   r¹   rD   rË   )rÏ   r¹   rD   rÐ   )MrP   Ú
__future__r   Úcollections.abcr   r   Údataclassesr   r   Ú	functoolsr   Úpathlibr	   Útypingr
   r   r   r   Únumpyrb   Únumpy.typingr   Úvernier._corer   r0   r   r   r   r   r   r   r   r   r   r   r   r   r5   r   r  r   r	  Úvernier._tablesr   Úvernier._typesr   r    r!   r"   r#   r$   r%   r&   r'   ÚpolarsÚplr6   Ú	frozensetr)   rQ   Ú__all__r2   r,   r-   r*   r+   r.   r/   r7   rw   r�   r1   r4   rÉ   rÎ   rÔ   r3   rR   rJ   rI   ú<module>r#     s²  ððð ð ð2 #Ð "Ð "Ð "Ð "Ð "à -Ð -Ð -Ð -Ð -Ð -Ð -Ð -Ø (Ð (Ð (Ð (Ð (Ð (Ð (Ð (Ø %Ð %Ð %Ð %Ð %Ð %Ø Ð Ð Ð Ð Ð Ø :Ð :Ð :Ð :Ð :Ð :Ð :Ð :Ð :Ð :Ð :Ð :à Ð Ð Ð Ø  Ð  Ð  Ð  Ð  Ð  ðð ð ð ð ð ðð ð ð ð ð ð ð ð ð ð ð ð ð ð ð ð ð ð ð ð ð ð ð ð ð ðð ð ð ð ð ðð ð ð ð ð ðð ð ð ð ð ð /Ð .Ð .Ð .Ð .Ð .ð
ð 
ð 
ð 
ð 
ð 
ð 
ð 
ð 
ð 
ð 
ð 
ð 
ð 
ð 
ð 
ð 
ð 
ð 
ð 
ð 
ð 
ð ð ØÐÐÐð �KÔ €	Ø)2¨°K°=Ñ)AÔ)AÐ Ð AÐ AÐ AÑ Aðð ð €ðD €�$ÐÑÔð+@ð +@ð +@ð +@ð +@ñ +@ô +@ñ Ôð+@ðd '*Ð Ð )Ð )Ð )Ñ )à#%Ð Ð %Ð %Ð %Ñ %à"#Ð Ð #Ð #Ð #Ñ #à"Ð Ð "Ð "Ð "Ñ "à&)Ð Ð )Ð )Ð )Ñ )à#%Ð Ð %Ð %Ð %Ñ %ð-ð -ð -ð -ð8Tð Tð Tð Tð(ð (ð (ð (ðV €�$˜dÐ#Ñ#Ô#ðr
ð r
ð r
ð r
ð r
ñ r
ô r
ñ $Ô#ðr
ðj €�$˜dÐ#Ñ#Ô#ð>&ð >&ð >&ð >&ð >&ñ >&ô >&ñ $Ô#ð>&ðB,ð ,ð ,ð ,ð^&ð &ð &ð &ðRBð Bð Bð Bð €�$˜dÐ#Ñ#Ô#ðs
ð s
ð s
ð s
ð s
ñ s
ô s
ñ $Ô#ðs
ð s
ð s
rJ   