evalsuite-python 0.6.0__cp39-abi3-win_arm64.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (72) hide show
  1. evalsuite/__init__.py +268 -0
  2. evalsuite/__main__.py +5 -0
  3. evalsuite/_bench_metrics.py +2080 -0
  4. evalsuite/_core.pyd +0 -0
  5. evalsuite/_lazy.py +32 -0
  6. evalsuite/_native.py +60 -0
  7. evalsuite/api.py +275 -0
  8. evalsuite/benchmarks.py +946 -0
  9. evalsuite/calibration.py +392 -0
  10. evalsuite/classification/__init__.py +51 -0
  11. evalsuite/classification/_common.py +111 -0
  12. evalsuite/classification/metrics.py +945 -0
  13. evalsuite/cli/__init__.py +5 -0
  14. evalsuite/cli/main.py +606 -0
  15. evalsuite/clinical/__init__.py +18 -0
  16. evalsuite/clinical/metrics.py +342 -0
  17. evalsuite/clinical/report.py +366 -0
  18. evalsuite/core/__init__.py +1 -0
  19. evalsuite/core/context.py +199 -0
  20. evalsuite/core/exceptions.py +52 -0
  21. evalsuite/core/export.py +100 -0
  22. evalsuite/core/registry.py +90 -0
  23. evalsuite/core/result.py +379 -0
  24. evalsuite/core/types.py +23 -0
  25. evalsuite/core/validation.py +256 -0
  26. evalsuite/llmsys/__init__.py +189 -0
  27. evalsuite/llmsys/_common.py +215 -0
  28. evalsuite/llmsys/agents.py +384 -0
  29. evalsuite/llmsys/code.py +923 -0
  30. evalsuite/llmsys/efficiency.py +346 -0
  31. evalsuite/llmsys/longcontext.py +361 -0
  32. evalsuite/llmsys/multilingual.py +339 -0
  33. evalsuite/llmsys/robustness.py +504 -0
  34. evalsuite/llmsys/safety.py +509 -0
  35. evalsuite/llmsys/uncertainty.py +229 -0
  36. evalsuite/plot.py +651 -0
  37. evalsuite/py.typed +0 -0
  38. evalsuite/regression/__init__.py +41 -0
  39. evalsuite/regression/metrics.py +629 -0
  40. evalsuite/reporting.py +241 -0
  41. evalsuite/stats/__init__.py +46 -0
  42. evalsuite/stats/_resolve.py +229 -0
  43. evalsuite/stats/compare.py +420 -0
  44. evalsuite/stats/effect.py +159 -0
  45. evalsuite/stats/hypothesis.py +593 -0
  46. evalsuite/stats/intervals.py +338 -0
  47. evalsuite/stats/paired.py +214 -0
  48. evalsuite/stats/results.py +129 -0
  49. evalsuite/text/__init__.py +154 -0
  50. evalsuite/text/_common.py +97 -0
  51. evalsuite/text/factuality.py +469 -0
  52. evalsuite/text/generation.py +1346 -0
  53. evalsuite/text/judge.py +556 -0
  54. evalsuite/text/qa.py +108 -0
  55. evalsuite/text/rag.py +235 -0
  56. evalsuite/text/reasoning.py +215 -0
  57. evalsuite/text/report.py +158 -0
  58. evalsuite/text/retrieval.py +238 -0
  59. evalsuite/text/semantic.py +499 -0
  60. evalsuite/text/spice.py +162 -0
  61. evalsuite/text/structured.py +793 -0
  62. evalsuite/version.py +3 -0
  63. evalsuite/vision/__init__.py +47 -0
  64. evalsuite/vision/detection.py +696 -0
  65. evalsuite/vision/segmentation.py +1028 -0
  66. evalsuite_python-0.6.0.dist-info/METADATA +509 -0
  67. evalsuite_python-0.6.0.dist-info/RECORD +72 -0
  68. evalsuite_python-0.6.0.dist-info/WHEEL +4 -0
  69. evalsuite_python-0.6.0.dist-info/entry_points.txt +2 -0
  70. evalsuite_python-0.6.0.dist-info/licenses/LICENSE +21 -0
  71. evalsuite_python-0.6.0.dist-info/licenses/LICENSE-APACHE +191 -0
  72. evalsuite_python-0.6.0.dist-info/sboms/evalsuite-py.cyclonedx.json +576 -0
@@ -0,0 +1,696 @@
1
+ """Object detection metrics: box IoU, average precision per class and COCO-style mean average precision.
2
+
3
+ The COCO protocol (Lin et al. 2014) is implemented exactly as in the reference ``pycocotools`` evaluator:
4
+ greedy matching of score-sorted detections to the best-overlapping unmatched ground truth, crowd regions
5
+ that may absorb several detections, area ranges, a maximum number of detections per image, and
6
+ 101-point interpolated precision. The test suite checks every number against ``pycocotools``.
7
+
8
+ Input format (one entry per image, in the same order for truth and predictions)::
9
+
10
+ y_true = [{"boxes": [[x1, y1, x2, y2], ...], "labels": [3, ...]}, ...] # optional "iscrowd", "area"
11
+ y_pred = [{"boxes": [[x1, y1, x2, y2], ...], "labels": [3, ...], "scores": [0.9, ...]}, ...]
12
+
13
+ ``box_format`` is ``"xyxy"`` (default), ``"xywh"`` (COCO) or ``"cxcywh"`` (YOLO-style centres).
14
+ :func:`from_coco` converts COCO-format ground truth and result files to this format.
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ import json
20
+ import math
21
+ from collections.abc import Mapping, Sequence
22
+ from dataclasses import dataclass, field
23
+ from types import MappingProxyType
24
+ from typing import TYPE_CHECKING, Any, Literal, Optional, Union, cast
25
+
26
+ import numpy as np
27
+ from numpy.typing import NDArray
28
+
29
+ from .._native import array_view, core
30
+ from ..core.exceptions import InputValidationError
31
+ from ..core.export import PathLike, csv_text, html_document, html_table, save_as
32
+ from ..core.registry import register
33
+ from ..core.result import MetricResult, _fmt, _json_safe, _latex_escape, _latex_table
34
+
35
+ if TYPE_CHECKING:
36
+ import pandas as pd
37
+
38
+ __all__ = [
39
+ "DetectionReport",
40
+ "average_precision_detection",
41
+ "box_iou",
42
+ "detection_pr_curve",
43
+ "detection_report",
44
+ "from_coco",
45
+ "mean_average_precision",
46
+ ]
47
+
48
+ _C = "detection"
49
+ BoxFormat = Literal["xyxy", "xywh", "cxcywh"]
50
+ _REF_COCO = "Lin TY, Maire M, Belongie S, et al. Microsoft COCO: common objects in context. ECCV 2014:740-755."
51
+ _REF_VOC = (
52
+ "Everingham M, Van Gool L, Williams CKI, Winn J, Zisserman A. The PASCAL Visual Object Classes (VOC) "
53
+ "challenge. Int J Comput Vis. 2010;88(2):303-338."
54
+ )
55
+ _REF_PADILLA = (
56
+ "Padilla R, Netto SL, da Silva EAB. A survey on performance metrics for object-detection algorithms. "
57
+ "IWSSIP 2020:237-242."
58
+ )
59
+ _AREAS = {"all": (0.0, 1e10), "small": (0.0, 32.0**2), "medium": (32.0**2, 96.0**2), "large": (96.0**2, 1e10)}
60
+ _REC_THRS = np.linspace(0.0, 1.00, 101)
61
+ _COCO_IOUS = np.linspace(0.5, 0.95, 10)
62
+
63
+
64
+ # ---- boxes -----------------------------------------------------------------------------------------
65
+ def _to_xyxy(boxes: Any, fmt: BoxFormat, name: str) -> NDArray[np.float64]:
66
+ b = np.asarray(boxes, dtype=np.float64)
67
+ if b.size == 0:
68
+ return np.zeros((0, 4))
69
+ if b.ndim != 2 or b.shape[1] != 4:
70
+ raise InputValidationError(f"{name} must have shape (n, 4); received {b.shape}.")
71
+ if not np.all(np.isfinite(b)):
72
+ raise InputValidationError(f"{name} contains NaN or infinite coordinates.")
73
+ out: NDArray[np.float64]
74
+ if fmt == "xyxy":
75
+ out = b.copy()
76
+ elif fmt == "xywh":
77
+ out = np.column_stack([b[:, 0], b[:, 1], b[:, 0] + b[:, 2], b[:, 1] + b[:, 3]])
78
+ elif fmt == "cxcywh":
79
+ out = np.column_stack(
80
+ [b[:, 0] - b[:, 2] / 2, b[:, 1] - b[:, 3] / 2, b[:, 0] + b[:, 2] / 2, b[:, 1] + b[:, 3] / 2]
81
+ )
82
+ else:
83
+ raise InputValidationError("box_format must be 'xyxy', 'xywh' or 'cxcywh'.")
84
+ if np.any(out[:, 2] < out[:, 0]) or np.any(out[:, 3] < out[:, 1]):
85
+ raise InputValidationError(f"{name} has boxes with negative width or height (check box_format).")
86
+ return np.asarray(out, dtype=np.float64)
87
+
88
+
89
+ def _count(n: int, noun: str) -> str:
90
+ plural = noun + ("es" if noun.endswith("s") else "s")
91
+ return f"{n} {noun if n == 1 else plural}"
92
+
93
+
94
+ def _area(b: NDArray[np.float64]) -> NDArray[np.float64]:
95
+ out: NDArray[np.float64] = (b[:, 2] - b[:, 0]) * (b[:, 3] - b[:, 1])
96
+ return out
97
+
98
+
99
+ def _iou_matrix(
100
+ dt: NDArray[np.float64], gt: NDArray[np.float64], crowd: Optional[NDArray[np.bool_]] = None
101
+ ) -> NDArray[np.float64]:
102
+ """IoU of every detection with every ground truth; for crowd ground truth, intersection over the
103
+ detection's area (as in COCO)."""
104
+ if dt.shape[0] == 0 or gt.shape[0] == 0:
105
+ return np.zeros((dt.shape[0], gt.shape[0]))
106
+ lt = np.maximum(dt[:, None, :2], gt[None, :, :2])
107
+ rb = np.minimum(dt[:, None, 2:], gt[None, :, 2:])
108
+ wh = np.clip(rb - lt, 0, None)
109
+ inter = wh[..., 0] * wh[..., 1]
110
+ a_d, a_g = _area(dt)[:, None], _area(gt)[None, :]
111
+ union = a_d + a_g - inter
112
+ if crowd is not None and crowd.any():
113
+ union = np.where(crowd[None, :], a_d, union)
114
+ with np.errstate(divide="ignore", invalid="ignore"):
115
+ return np.where(union > 0, inter / np.where(union > 0, union, 1), 0.0)
116
+
117
+
118
+ @register(
119
+ category=_C,
120
+ task="detection",
121
+ name="Box IoU",
122
+ definition="Overlap of two bounding boxes: area of intersection over area of union.",
123
+ formula="IoU(A, B) = area(A ∩ B) / area(A ∪ B)",
124
+ range="[0, 1]",
125
+ input_requirements=("boxes_a (n, 4)", "boxes_b (m, 4)"),
126
+ references=(_REF_VOC, _REF_COCO),
127
+ )
128
+ def box_iou(boxes_a: Any, boxes_b: Any, *, box_format: BoxFormat = "xyxy") -> NDArray[np.float64]:
129
+ """IoU matrix of shape (n, m) between two sets of boxes."""
130
+ return _iou_matrix(_to_xyxy(boxes_a, box_format, "boxes_a"), _to_xyxy(boxes_b, box_format, "boxes_b"))
131
+
132
+
133
+ # ---- input parsing ---------------------------------------------------------------------------------
134
+ @dataclass
135
+ class _Image:
136
+ gt_boxes: NDArray[np.float64]
137
+ gt_labels: NDArray[np.int64]
138
+ gt_crowd: NDArray[np.bool_]
139
+ gt_area: NDArray[np.float64]
140
+ dt_boxes: NDArray[np.float64]
141
+ dt_labels: NDArray[np.int64]
142
+ dt_scores: NDArray[np.float64]
143
+
144
+
145
+ def _labels(x: Any, n: int, name: str) -> NDArray[np.int64]:
146
+ arr = np.asarray(x if x is not None else [], dtype=np.int64).ravel()
147
+ if arr.shape[0] != n:
148
+ raise InputValidationError(f"{name} must have one label per box ({n}); received {arr.shape[0]}.")
149
+ return arr
150
+
151
+
152
+ def _parse(
153
+ y_true: Sequence[Mapping[str, Any]], y_pred: Sequence[Mapping[str, Any]], fmt: BoxFormat
154
+ ) -> list[_Image]:
155
+ if isinstance(y_true, Mapping) or isinstance(y_pred, Mapping):
156
+ raise InputValidationError("y_true and y_pred must be lists with one dict per image.")
157
+ t, p = list(y_true), list(y_pred)
158
+ if len(t) != len(p):
159
+ raise InputValidationError(f"y_true has {len(t)} images but y_pred has {len(p)}.")
160
+ if not t:
161
+ raise InputValidationError("No images to evaluate.")
162
+ images = []
163
+ for i, (g, d) in enumerate(zip(t, p)):
164
+ if not isinstance(g, Mapping) or not isinstance(d, Mapping):
165
+ raise InputValidationError(f"Image {i}: expected dicts with 'boxes' and 'labels'.")
166
+ gb = _to_xyxy(g.get("boxes", []), fmt, f"y_true[{i}]['boxes']")
167
+ db = _to_xyxy(d.get("boxes", []), fmt, f"y_pred[{i}]['boxes']")
168
+ gl = _labels(g.get("labels"), gb.shape[0], f"y_true[{i}]['labels']")
169
+ dl = _labels(d.get("labels"), db.shape[0], f"y_pred[{i}]['labels']")
170
+ scores = np.asarray(d.get("scores", np.ones(db.shape[0])), dtype=np.float64).ravel()
171
+ if scores.shape[0] != db.shape[0] or not np.all(np.isfinite(scores)):
172
+ raise InputValidationError(f"y_pred[{i}]['scores'] must have one finite score per box.")
173
+ crowd = np.asarray(g.get("iscrowd", np.zeros(gb.shape[0])), dtype=bool).ravel()
174
+ area = np.asarray(g["area"], dtype=np.float64).ravel() if "area" in g else _area(gb)
175
+ if crowd.shape[0] != gb.shape[0] or area.shape[0] != gb.shape[0]:
176
+ raise InputValidationError(f"y_true[{i}]: 'iscrowd' and 'area' need one value per box.")
177
+ images.append(_Image(gb, gl, crowd, area, db, dl, scores))
178
+ return images
179
+
180
+
181
+ # ---- COCO evaluation ---------------------------------------------------------------------------------
182
+ @dataclass
183
+ class _Eval:
184
+ dt_scores: NDArray[np.float64]
185
+ dt_matched: NDArray[np.bool_] # (T, D)
186
+ dt_ignore: NDArray[np.bool_] # (T, D)
187
+ gt_ignore: NDArray[np.bool_] # (G,)
188
+
189
+
190
+ @dataclass
191
+ class _Pair:
192
+ """One image and one class: ground truth, score-sorted (truncated) detections and their IoUs."""
193
+
194
+ gt_b: NDArray[np.float64]
195
+ gt_crowd: NDArray[np.bool_]
196
+ gt_area: NDArray[np.float64]
197
+ dt_b: NDArray[np.float64]
198
+ dt_s: NDArray[np.float64]
199
+ dt_area: NDArray[np.float64]
200
+ ious: NDArray[np.float64]
201
+
202
+
203
+ def _prepare(images: list[_Image], max_det: int) -> tuple[list[int], dict[int, list[_Pair]]]:
204
+ """Group boxes by class once and compute every IoU once (as COCOeval.computeIoU), so area ranges and
205
+ detection limits reuse them."""
206
+ cats = sorted({int(c) for im in images for c in (*im.gt_labels.tolist(), *im.dt_labels.tolist())})
207
+ pairs: dict[int, list[_Pair]] = {c: [] for c in cats}
208
+ for im in images:
209
+ for cat in np.union1d(im.gt_labels, im.dt_labels).astype(int).tolist():
210
+ gmask = im.gt_labels == cat
211
+ dmask = im.dt_labels == cat
212
+ dt_b, dt_s = im.dt_boxes[dmask], im.dt_scores[dmask]
213
+ order = np.argsort(-dt_s, kind="mergesort")[:max_det] # stable, as COCOeval
214
+ dt_b, dt_s = dt_b[order], dt_s[order]
215
+ gt_b, crowd = im.gt_boxes[gmask], im.gt_crowd[gmask]
216
+ pairs[cat].append(
217
+ _Pair(gt_b, crowd, im.gt_area[gmask], dt_b, dt_s, _area(dt_b), _iou_matrix(dt_b, gt_b, crowd))
218
+ )
219
+ return cats, pairs
220
+
221
+
222
+ def _evaluate_images(
223
+ pairs: list[_Pair], area_rng: tuple[float, float], iou_thrs: NDArray[np.float64]
224
+ ) -> list[_Eval]:
225
+ """COCOeval's per-image greedy matching for many images at once (one class, one area range).
226
+
227
+ Images are independent, so their matchings run side by side on arrays padded to the largest image: one Python
228
+ step per detection slot instead of one per detection. Per image this is exactly COCOeval.evaluateImg: ground
229
+ truths sorted with ignored ones last; each detection, in score order, takes the last best-IoU available
230
+ ground truth at or above the threshold, preferring non-ignored ones; crowd regions stay available after a
231
+ match; unmatched detections outside the area range are ignored."""
232
+ p_n = len(pairs)
233
+ if p_n == 0:
234
+ return []
235
+ t_n = len(iou_thrs)
236
+ g_sizes = np.array([pr.gt_b.shape[0] for pr in pairs])
237
+ d_sizes = np.array([pr.dt_b.shape[0] for pr in pairs])
238
+ g_max, d_max = int(g_sizes.max()), int(d_sizes.max())
239
+ lo, hi = area_rng
240
+ g_ign_list = []
241
+ gign = np.ones((p_n, g_max), dtype=bool)
242
+ crowd = np.zeros((p_n, g_max), dtype=bool)
243
+ ious = np.full((p_n, d_max, g_max), -1.0)
244
+ dt_out = np.zeros((p_n, d_max), dtype=bool)
245
+ for i, pr in enumerate(pairs):
246
+ g_ignore = pr.gt_crowd | (pr.gt_area < lo) | (pr.gt_area > hi)
247
+ gorder = np.argsort(g_ignore, kind="mergesort")
248
+ g_ignore = g_ignore[gorder]
249
+ g_ign_list.append(g_ignore)
250
+ g, d = g_ignore.shape[0], pr.dt_b.shape[0]
251
+ gign[i, :g] = g_ignore
252
+ crowd[i, :g] = pr.gt_crowd[gorder]
253
+ if g and d:
254
+ ious[i, :d, :g] = pr.ious[:, gorder]
255
+ dt_out[i, :d] = (pr.dt_area < lo) | (pr.dt_area > hi)
256
+ if core is not None and d_max:
257
+ a_iou, v_iou = array_view(ious, np.float64)
258
+ a_gi, v_gi = array_view(gign, np.bool_)
259
+ a_cr, v_cr = array_view(crowd, np.bool_)
260
+ a_out, v_out = array_view(dt_out, np.bool_)
261
+ raw_m, raw_i = core.coco_match(
262
+ v_iou,
263
+ v_gi,
264
+ v_cr,
265
+ v_out,
266
+ p_n,
267
+ d_max,
268
+ g_max,
269
+ [float(t) for t in iou_thrs],
270
+ )
271
+ del a_iou, a_gi, a_cr, a_out
272
+ dtm = np.frombuffer(raw_m, dtype=np.bool_).reshape(p_n, t_n, d_max)
273
+ dt_ig = np.frombuffer(raw_i, dtype=np.bool_).reshape(p_n, t_n, d_max)
274
+ return [
275
+ _Eval(pr.dt_s, dtm[i, :, : d_sizes[i]], dt_ig[i, :, : d_sizes[i]], g_ign_list[i])
276
+ for i, pr in enumerate(pairs)
277
+ ]
278
+ gtm = np.zeros((p_n, t_n, g_max), dtype=bool)
279
+ dtm = np.zeros((p_n, t_n, d_max), dtype=bool)
280
+ dt_ig = np.zeros((p_n, t_n, d_max), dtype=bool)
281
+ thr = np.minimum(np.asarray(iou_thrs, dtype=np.float64), 1 - 1e-10)[None, :, None]
282
+ if g_max:
283
+ p_idx = np.broadcast_to(np.arange(p_n)[:, None], (p_n, t_n))
284
+ t_idx = np.broadcast_to(np.arange(t_n)[None, :], (p_n, t_n))
285
+ not_ign = ~gign[:, None, :]
286
+ for di in range(d_max):
287
+ row = ious[:, di, :][:, None, :] # (P, 1, G); padding is -1, never above a threshold
288
+ ok = (~gtm | crowd[:, None, :]) & (row >= thr)
289
+ regular = ok & not_ign
290
+ cand = np.where(regular.any(2, keepdims=True), regular, ok)
291
+ found = cand.any(2)
292
+ if not found.any():
293
+ continue
294
+ vals = np.where(cand, row, -1.0)
295
+ m = g_max - 1 - np.argmax(vals[:, :, ::-1], axis=2) # the last best ground truth, as COCOeval
296
+ dtm[:, :, di] = found
297
+ dt_ig[:, :, di] = found & gign[p_idx, m]
298
+ gtm[p_idx[found], t_idx[found], m[found]] = True
299
+ dt_ig |= ~dtm & dt_out[:, None, :]
300
+ return [
301
+ _Eval(pr.dt_s, dtm[i, :, : d_sizes[i]], dt_ig[i, :, : d_sizes[i]], g_ign_list[i])
302
+ for i, pr in enumerate(pairs)
303
+ ]
304
+
305
+
306
+ def _coco_eval(
307
+ images: list[_Image],
308
+ iou_thrs: NDArray[np.float64],
309
+ max_dets: Sequence[int],
310
+ areas: Sequence[str],
311
+ ) -> tuple[list[int], NDArray[np.float64], NDArray[np.float64]]:
312
+ """precision (T, R, K, A, M) and recall (T, K, A, M); -1 where undefined (no ground truth)."""
313
+ top = max(max_dets)
314
+ cats, pairs = _prepare(images, top)
315
+ t_n, r_n, k_n, a_n, m_n = len(iou_thrs), _REC_THRS.size, len(cats), len(areas), len(max_dets)
316
+ precision = -np.ones((t_n, r_n, k_n, a_n, m_n))
317
+ recall = -np.ones((t_n, k_n, a_n, m_n))
318
+ for k, cat in enumerate(cats):
319
+ for a, area_name in enumerate(areas):
320
+ evals = _evaluate_images(pairs[cat], _AREAS[area_name], iou_thrs)
321
+ if not evals:
322
+ continue
323
+ gt_ignore = np.concatenate([e.gt_ignore for e in evals])
324
+ npig = int(np.count_nonzero(~gt_ignore))
325
+ if npig == 0:
326
+ continue
327
+ for m, max_det in enumerate(max_dets):
328
+ scores = np.concatenate([e.dt_scores[:max_det] for e in evals])
329
+ order = np.argsort(-scores, kind="mergesort")
330
+ dtm = np.concatenate([e.dt_matched[:, :max_det] for e in evals], axis=1)[:, order]
331
+ dtig = np.concatenate([e.dt_ignore[:, :max_det] for e in evals], axis=1)[:, order]
332
+ tps = dtm & ~dtig
333
+ fps = ~dtm & ~dtig
334
+ tp_sum = np.cumsum(tps, axis=1).astype(np.float64)
335
+ fp_sum = np.cumsum(fps, axis=1).astype(np.float64)
336
+ for ti in range(t_n):
337
+ tp, fp = tp_sum[ti], fp_sum[ti]
338
+ nd = tp.shape[0]
339
+ rc = tp / npig
340
+ pr = tp / (fp + tp + np.spacing(1))
341
+ recall[ti, k, a, m] = rc[-1] if nd else 0.0
342
+ pr = np.maximum.accumulate(pr[::-1])[::-1] if nd else pr
343
+ idx = np.searchsorted(rc, _REC_THRS, side="left")
344
+ q = np.zeros(r_n)
345
+ valid = idx < nd
346
+ q[valid] = pr[idx[valid]]
347
+ precision[ti, :, k, a, m] = q
348
+ return cats, precision, recall
349
+
350
+
351
+ def _mean_valid(x: NDArray[np.float64]) -> float:
352
+ v = x[x > -1]
353
+ return float(np.mean(v)) if v.size else math.nan
354
+
355
+
356
+ # ---- results -----------------------------------------------------------------------------------------
357
+ _SUMMARY = (
358
+ ("map", "mAP@[.50:.95]"),
359
+ ("map_50", "mAP@.50"),
360
+ ("map_75", "mAP@.75"),
361
+ ("map_small", "mAP small"),
362
+ ("map_medium", "mAP medium"),
363
+ ("map_large", "mAP large"),
364
+ ("mar_1", "mAR@1"),
365
+ ("mar_10", "mAR@10"),
366
+ ("mar_100", "mAR@100"),
367
+ ("mar_small", "mAR small"),
368
+ ("mar_medium", "mAR medium"),
369
+ ("mar_large", "mAR large"),
370
+ )
371
+
372
+
373
+ @dataclass(frozen=True, eq=False)
374
+ class DetectionReport:
375
+ """COCO summary (mAP@[.50:.95], mAP@.50, mAP@.75, by object size, and mean average recall) plus AP per
376
+ class. ``report["map"]`` is the headline number; NaN marks a value with no ground truth to score."""
377
+
378
+ values: Any
379
+ per_class: Any
380
+ params: Any = field(default_factory=dict)
381
+
382
+ def __post_init__(self) -> None:
383
+ object.__setattr__(self, "values", MappingProxyType(dict(self.values)))
384
+ object.__setattr__(self, "per_class", MappingProxyType(dict(self.per_class)))
385
+ object.__setattr__(self, "params", MappingProxyType(dict(self.params)))
386
+
387
+ def __getitem__(self, name: str) -> float:
388
+ try:
389
+ return float(self.values[name])
390
+ except KeyError:
391
+ raise KeyError(f"No value {name!r}. Available: {', '.join(self.values)}.") from None
392
+
393
+ def __float__(self) -> float:
394
+ return self["map"]
395
+
396
+ def summary(self, *, digits: int = 3) -> str:
397
+ p = self.params
398
+ lines = [
399
+ f"EvalSuite detection evaluation (COCO protocol, {_count(p['n_images'], 'image')}, "
400
+ f"{_count(p['n_classes'], 'class')}, "
401
+ f"max {p['max_detections']} detections per image)"
402
+ ]
403
+ width = max(len(label) for _, label in _SUMMARY)
404
+ lines += [f" {label:<{width}} {_fmt(self.values[k], digits)}" for k, label in _SUMMARY]
405
+ lines.append(
406
+ " AP@[.50:.95] per class: " + ", ".join(f"{c}: {_fmt(v, digits)}" for c, v in self.per_class.items())
407
+ )
408
+ return "\n".join(lines)
409
+
410
+ def __repr__(self) -> str:
411
+ return self.summary()
412
+
413
+ def to_dict(self) -> dict[str, Any]:
414
+ return cast(
415
+ "dict[str, Any]",
416
+ _json_safe(
417
+ {
418
+ "values": dict(self.values),
419
+ "per_class_ap": {str(k): v for k, v in self.per_class.items()},
420
+ "params": dict(self.params),
421
+ }
422
+ ),
423
+ )
424
+
425
+ def to_json(self, *, indent: Optional[int] = 2) -> str:
426
+ return json.dumps(self.to_dict(), indent=indent, allow_nan=False)
427
+
428
+ def to_dataframe(self) -> pd.DataFrame:
429
+ import pandas as pd
430
+
431
+ frame: pd.DataFrame = pd.DataFrame({"value": dict(self.values)})
432
+ return frame
433
+
434
+ def _rows(self, digits: int) -> list[list[str]]:
435
+ return [[label, _fmt(self.values[k], digits)] for k, label in _SUMMARY]
436
+
437
+ def to_markdown(self, *, digits: int = 3) -> str:
438
+ lines = ["| Measure | Value |", "| --- | ---: |"] + [
439
+ "| " + " | ".join(r) + " |" for r in self._rows(digits)
440
+ ]
441
+ lines += ["", "| Class | AP@[.50:.95] |", "| --- | ---: |"]
442
+ lines += [f"| {c} | {_fmt(v, digits)} |" for c, v in self.per_class.items()]
443
+ return "\n".join(lines)
444
+
445
+ def to_latex(self, *, digits: int = 3, caption: Optional[str] = None, label: Optional[str] = None) -> str:
446
+ rows = [[_latex_escape(c) for c in r] for r in self._rows(digits)]
447
+ return _latex_table(["Measure", "Value"], rows, caption or "Object detection (COCO protocol).", label)
448
+
449
+ def to_csv(self, path: Optional[PathLike] = None) -> str:
450
+ rows: list[list[Any]] = [[k, "", float(v)] for k, v in self.values.items()]
451
+ rows += [["ap", c, float(v)] for c, v in self.per_class.items()]
452
+ text = csv_text(["measure", "class", "value"], rows)
453
+ if path is not None:
454
+ with open(path, "w", encoding="utf-8", newline="") as fh:
455
+ fh.write(text)
456
+ return text
457
+
458
+ def to_html(self, *, digits: int = 3, full: bool = True) -> str:
459
+ body = html_table(["Measure", "Value"], self._rows(digits), caption="COCO summary")
460
+ body += "\n" + html_table(
461
+ ["Class", "AP@[.50:.95]"],
462
+ [[str(c), _fmt(v, digits)] for c, v in self.per_class.items()],
463
+ caption="Average precision per class",
464
+ )
465
+ return html_document("EvalSuite detection evaluation", body) if full else body
466
+
467
+ def save(self, path: PathLike) -> str:
468
+ return save_as(
469
+ path,
470
+ {
471
+ "json": self.to_json,
472
+ "csv": self.to_csv,
473
+ "markdown": self.to_markdown,
474
+ "latex": self.to_latex,
475
+ "html": self.to_html,
476
+ "text": self.summary,
477
+ },
478
+ )
479
+
480
+
481
+ Detections = Sequence[Mapping[str, Any]]
482
+
483
+
484
+ def detection_report(
485
+ y_true: Detections,
486
+ y_pred: Detections,
487
+ *,
488
+ box_format: BoxFormat = "xyxy",
489
+ max_detections: int = 100,
490
+ ) -> DetectionReport:
491
+ """Full COCO evaluation (the 12 numbers pycocotools prints, plus AP per class)."""
492
+ if not (isinstance(max_detections, (int, np.integer)) and max_detections >= 1):
493
+ raise InputValidationError("max_detections must be a positive integer.")
494
+ images = _parse(y_true, y_pred, box_format)
495
+ max_dets = sorted({1, 10, int(max_detections)})
496
+ areas = ("all", "small", "medium", "large")
497
+ cats, prec, rec = _coco_eval(images, _COCO_IOUS, max_dets, areas)
498
+ m = max_dets.index(int(max_detections))
499
+ t50, t75 = 0, 5
500
+
501
+ def ap(t: Optional[int], a: int) -> float:
502
+ p = prec[:, :, :, a, m] if t is None else prec[t, :, :, a, m]
503
+ return _mean_valid(p)
504
+
505
+ def ar(a: int, mi: int) -> float:
506
+ return _mean_valid(rec[:, :, a, mi])
507
+
508
+ values = {
509
+ "map": ap(None, 0),
510
+ "map_50": ap(t50, 0),
511
+ "map_75": ap(t75, 0),
512
+ "map_small": ap(None, 1),
513
+ "map_medium": ap(None, 2),
514
+ "map_large": ap(None, 3),
515
+ "mar_1": ar(0, max_dets.index(1)),
516
+ "mar_10": ar(0, max_dets.index(10)),
517
+ "mar_100": ar(0, m),
518
+ "mar_small": ar(1, m),
519
+ "mar_medium": ar(2, m),
520
+ "mar_large": ar(3, m),
521
+ }
522
+ per_class = {c: _mean_valid(prec[:, :, k, 0, m]) for k, c in enumerate(cats)}
523
+ return DetectionReport(
524
+ values,
525
+ per_class,
526
+ {
527
+ "n_images": len(images),
528
+ "n_classes": len(cats),
529
+ "max_detections": int(max_detections),
530
+ "iou_thresholds": _COCO_IOUS.round(2).tolist(),
531
+ "box_format": box_format,
532
+ },
533
+ )
534
+
535
+
536
+ @register(
537
+ category=_C,
538
+ task="detection",
539
+ name="Mean average precision (COCO mAP)",
540
+ definition="Average precision (area under the 101-point interpolated precision-recall curve) averaged over "
541
+ "classes and over IoU thresholds 0.50:0.05:0.95, as in the COCO benchmark.",
542
+ formula="mAP = (1/|T|·|K|) Σ_t Σ_k AP_k(t)",
543
+ range="[0, 1]",
544
+ input_requirements=("y_true boxes and labels per image", "y_pred boxes, labels and scores per image"),
545
+ references=(_REF_COCO, _REF_PADILLA),
546
+ )
547
+ def mean_average_precision(
548
+ y_true: Detections,
549
+ y_pred: Detections,
550
+ *,
551
+ iou_threshold: Optional[float] = None,
552
+ box_format: BoxFormat = "xyxy",
553
+ max_detections: int = 100,
554
+ ) -> MetricResult:
555
+ """COCO mAP@[.50:.95] by default; ``iou_threshold=0.5`` gives mAP@.50 (the PASCAL VOC-style headline)."""
556
+ thrs = _COCO_IOUS if iou_threshold is None else np.array([_check_iou(iou_threshold)])
557
+ images = _parse(y_true, y_pred, box_format)
558
+ _cats, prec, _rec = _coco_eval(images, thrs, [int(max_detections)], ("all",))
559
+ name = "mAP@[.50:.95]" if iou_threshold is None else f"mAP@{iou_threshold:g}"
560
+ return MetricResult(
561
+ "mean_average_precision",
562
+ name,
563
+ _mean_valid(prec[:, :, :, 0, 0]),
564
+ {"iou_threshold": iou_threshold, "max_detections": int(max_detections), "interpolation": "coco-101"},
565
+ )
566
+
567
+
568
+ def _check_iou(t: float) -> float:
569
+ if not (0 < float(t) < 1):
570
+ raise InputValidationError("iou_threshold must be between 0 and 1.")
571
+ return float(t)
572
+
573
+
574
+ def _voc_ap(rc: NDArray[np.float64], pr: NDArray[np.float64]) -> float:
575
+ """Area under the precision envelope at every recall change (PASCAL VOC 2010+, 'all points')."""
576
+ mrec = np.concatenate([[0.0], rc, [1.0]])
577
+ mpre = np.concatenate([[0.0], pr, [0.0]])
578
+ mpre = np.maximum.accumulate(mpre[::-1])[::-1]
579
+ i = np.flatnonzero(mrec[1:] != mrec[:-1])
580
+ return float(np.sum((mrec[i + 1] - mrec[i]) * mpre[i + 1]))
581
+
582
+
583
+ @register(
584
+ category=_C,
585
+ task="detection",
586
+ name="Average precision (per class)",
587
+ definition="Area under the precision-recall curve of one class's detections at a fixed IoU threshold.",
588
+ formula="AP = Σ_i (r_{i+1} − r_i) · p_interp(r_{i+1})",
589
+ range="[0, 1]",
590
+ input_requirements=("y_true boxes and labels per image", "y_pred boxes, labels and scores per image"),
591
+ references=(_REF_VOC, _REF_COCO),
592
+ )
593
+ def average_precision_detection(
594
+ y_true: Detections,
595
+ y_pred: Detections,
596
+ *,
597
+ iou_threshold: float = 0.5,
598
+ interpolation: Literal["coco", "voc"] = "coco",
599
+ average: Optional[Literal["macro"]] = None,
600
+ box_format: BoxFormat = "xyxy",
601
+ max_detections: int = 100,
602
+ ) -> MetricResult:
603
+ """AP for each class at one IoU threshold (per class by default; ``average="macro"`` gives mAP).
604
+
605
+ ``interpolation="coco"`` uses 101 recall points (as pycocotools); ``"voc"`` uses every recall change
606
+ (PASCAL VOC 2010 and later). Crowd boxes and areas follow the COCO rules in both cases.
607
+ """
608
+ t = _check_iou(iou_threshold)
609
+ images = _parse(y_true, y_pred, box_format)
610
+ if interpolation == "coco":
611
+ cats, prec, _ = _coco_eval(images, np.array([t]), [int(max_detections)], ("all",))
612
+ per = np.array([_mean_valid(prec[0, :, k, 0, 0]) for k in range(len(cats))])
613
+ elif interpolation == "voc":
614
+ cats, pairs = _prepare(images, int(max_detections))
615
+ per = np.full(len(cats), math.nan)
616
+ for k, cat in enumerate(cats):
617
+ evals = _evaluate_images(pairs[cat], _AREAS["all"], np.array([t]))
618
+ npig = int(sum(np.count_nonzero(~e.gt_ignore) for e in evals))
619
+ if npig == 0:
620
+ continue
621
+ scores = np.concatenate([e.dt_scores for e in evals])
622
+ order = np.argsort(-scores, kind="mergesort")
623
+ dtm = np.concatenate([e.dt_matched[0] for e in evals])[order]
624
+ dtig = np.concatenate([e.dt_ignore[0] for e in evals])[order]
625
+ tp = np.cumsum(dtm & ~dtig).astype(np.float64)
626
+ fp = np.cumsum(~dtm & ~dtig).astype(np.float64)
627
+ keep = ~dtig
628
+ tp, fp = tp[keep], fp[keep]
629
+ per[k] = _voc_ap(tp / npig, tp / np.maximum(tp + fp, np.spacing(1))) if tp.size else 0.0
630
+ else:
631
+ raise InputValidationError("interpolation must be 'coco' or 'voc'.")
632
+ params = {"iou_threshold": t, "interpolation": interpolation, "max_detections": int(max_detections)}
633
+ if average is None:
634
+ return MetricResult("average_precision_detection", f"AP@{t:g}", per, params, labels=tuple(cats))
635
+ if average != "macro":
636
+ raise InputValidationError("average must be 'macro' or None.")
637
+ valid = per[~np.isnan(per)]
638
+ return MetricResult(
639
+ "average_precision_detection", f"mAP@{t:g}", float(valid.mean()) if valid.size else math.nan, params
640
+ )
641
+
642
+
643
+ def detection_pr_curve(
644
+ y_true: Detections,
645
+ y_pred: Detections,
646
+ *,
647
+ iou_threshold: float = 0.5,
648
+ box_format: BoxFormat = "xyxy",
649
+ max_detections: int = 100,
650
+ ) -> dict[int, tuple[NDArray[np.float64], NDArray[np.float64]]]:
651
+ """COCO 101-point interpolated precision-recall curve per class at one IoU threshold:
652
+ ``{class: (recall_points, precision)}``. Classes without ground truth are left out."""
653
+ t = _check_iou(iou_threshold)
654
+ images = _parse(y_true, y_pred, box_format)
655
+ cats, prec, _ = _coco_eval(images, np.array([t]), [int(max_detections)], ("all",))
656
+ return {
657
+ c: (_REC_THRS.copy(), prec[0, :, k, 0, 0].copy()) for k, c in enumerate(cats) if prec[0, 0, k, 0, 0] > -1
658
+ }
659
+
660
+
661
+ def from_coco(
662
+ ground_truth: Union[PathLike, Mapping[str, Any]],
663
+ results: Union[PathLike, Sequence[Mapping[str, Any]], None] = None,
664
+ ) -> tuple[list[dict[str, Any]], list[dict[str, Any]]]:
665
+ """Convert a COCO ground-truth file (or dict) and an optional COCO results list/file into
666
+ ``(y_true, y_pred)`` with boxes in ``xywh`` format (pass ``box_format="xywh"``). Images keep the
667
+ ground-truth file's order; images without annotations or detections get empty entries."""
668
+
669
+ def load(x: Any) -> Any:
670
+ if isinstance(x, (str, bytes)) or hasattr(x, "__fspath__"):
671
+ with open(x, encoding="utf-8") as fh:
672
+ return json.load(fh)
673
+ return x
674
+
675
+ gt = load(ground_truth)
676
+ if not isinstance(gt, Mapping) or "images" not in gt or "annotations" not in gt:
677
+ raise InputValidationError("ground_truth must be a COCO dataset with 'images' and 'annotations'.")
678
+ ids = [img["id"] for img in gt["images"]]
679
+ pos = {i: k for k, i in enumerate(ids)}
680
+ y_true: list[dict[str, Any]] = [{"boxes": [], "labels": [], "iscrowd": [], "area": []} for _ in ids]
681
+ for ann in gt["annotations"]:
682
+ t = y_true[pos[ann["image_id"]]]
683
+ t["boxes"].append(ann["bbox"])
684
+ t["labels"].append(ann["category_id"])
685
+ t["iscrowd"].append(ann.get("iscrowd", 0))
686
+ w, h = ann["bbox"][2], ann["bbox"][3]
687
+ t["area"].append(ann.get("area", w * h))
688
+ y_pred: list[dict[str, Any]] = [{"boxes": [], "labels": [], "scores": []} for _ in ids]
689
+ for det in load(results) or []:
690
+ if det["image_id"] not in pos:
691
+ raise InputValidationError(f"Detection for image_id {det['image_id']} is not in the ground truth.")
692
+ d = y_pred[pos[det["image_id"]]]
693
+ d["boxes"].append(det["bbox"])
694
+ d["labels"].append(det["category_id"])
695
+ d["scores"].append(det["score"])
696
+ return y_true, y_pred