evalsuite-python 0.6.0__cp39-abi3-win_amd64.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,256 @@
1
+ """Centralised input validation.
2
+
3
+ Inputs are converted to NumPy once, checked once, and never modified in place.
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ import warnings
9
+ from typing import Any, Literal, Optional
10
+
11
+ import numpy as np
12
+ from numpy.typing import NDArray
13
+
14
+ from .exceptions import InputValidationError, UndefinedMetricWarning
15
+ from .types import ArrayLike, FloatArray, ZeroDivision
16
+
17
+ __all__ = [
18
+ "TargetType",
19
+ "check_consistent_length",
20
+ "resolve_labels",
21
+ "safe_divide",
22
+ "target_type",
23
+ "to_numpy",
24
+ "validate_probabilities",
25
+ "validate_sample_weight",
26
+ "validate_zero_division",
27
+ ]
28
+
29
+ TargetType = Literal["binary", "multiclass", "multilabel", "continuous"]
30
+
31
+
32
+ def to_numpy(x: ArrayLike, name: str, *, allow_2d: bool = False) -> NDArray[Any]:
33
+ """Convert array-likes (lists, NumPy arrays, pandas objects) to a NumPy array without copying
34
+ when possible. Raises :class:`InputValidationError` for None, scalars, empty input or bad shapes."""
35
+ if x is None:
36
+ raise InputValidationError(f"{name} is required but was None.")
37
+ values = getattr(x, "to_numpy", None)
38
+ arr = np.asarray(values() if callable(values) else x)
39
+ if arr.ndim == 0:
40
+ raise InputValidationError(f"{name} must be one-dimensional array-like; received a scalar.")
41
+ if arr.ndim == 2 and arr.shape[1] == 1 and not allow_2d:
42
+ arr = arr.ravel()
43
+ if arr.ndim > (2 if allow_2d else 1):
44
+ expected = "1-D or 2-D" if allow_2d else "1-D"
45
+ raise InputValidationError(f"{name} must be {expected}; received an array with shape {arr.shape}.")
46
+ if arr.shape[0] == 0:
47
+ raise InputValidationError(f"{name} is empty. Provide at least one observation.")
48
+ if (
49
+ arr.ndim == 1
50
+ and arr.dtype.kind in "US"
51
+ and isinstance(x, (list, tuple))
52
+ and not all(isinstance(v, (str, bytes)) for v in x)
53
+ ):
54
+ # NumPy silently turns [0, "a"] into ["0", "a"]; a mix of numbers and strings is almost always a bug.
55
+ raise InputValidationError(f"{name} mixes numbers and strings; use one label type throughout.")
56
+ return arr
57
+
58
+
59
+ def _label_kind(arr: NDArray[Any]) -> str:
60
+ if arr.dtype.kind in "US":
61
+ return "string"
62
+ if arr.dtype.kind in "biuf":
63
+ return "number"
64
+ return "other"
65
+
66
+
67
+ def check_finite(arr: NDArray[Any], name: str) -> None:
68
+ if arr.dtype.kind in "fc" and not np.all(np.isfinite(arr)): # integers and booleans are always finite
69
+ n_nan = int(np.isnan(arr).sum())
70
+ n_inf = int(np.isinf(arr).sum())
71
+ raise InputValidationError(
72
+ f"{name} contains {n_nan} NaN and {n_inf} infinite value(s). Remove or impute them before evaluating."
73
+ )
74
+
75
+
76
+ def check_consistent_length(**arrays: Optional[NDArray[Any]]) -> int:
77
+ """All given arrays must have the same number of observations; returns that number."""
78
+ lengths = {name: a.shape[0] for name, a in arrays.items() if a is not None}
79
+ if len(set(lengths.values())) > 1:
80
+ detail = " and ".join(f"{k}={v}" for k, v in lengths.items())
81
+ names = " and ".join(lengths)
82
+ raise InputValidationError(f"{names} must contain the same number of observations. Received {detail}.")
83
+ return int(next(iter(lengths.values())))
84
+
85
+
86
+ def validate_sample_weight(sample_weight: Optional[ArrayLike], n: int) -> Optional[FloatArray]:
87
+ if sample_weight is None:
88
+ return None
89
+ w = to_numpy(sample_weight, "sample_weight").astype(np.float64, copy=False)
90
+ check_finite(w, "sample_weight")
91
+ if w.shape[0] != n:
92
+ raise InputValidationError(
93
+ f"sample_weight must contain one weight per observation. Received {w.shape[0]} for {n} observations."
94
+ )
95
+ if np.any(w < 0):
96
+ raise InputValidationError("sample_weight must be non-negative.")
97
+ if w.sum() == 0:
98
+ raise InputValidationError("sample_weight must not sum to zero.")
99
+ return w
100
+
101
+
102
+ def unique_labels(y: NDArray[Any]) -> NDArray[Any]:
103
+ """Sorted unique values, like ``np.unique``. Small-range integer labels (the usual case for class labels)
104
+ are found with one marking pass instead of a sort, which is several times faster on large arrays."""
105
+ if y.size and np.issubdtype(y.dtype, np.integer):
106
+ lo, hi = int(y.min()), int(y.max())
107
+ if hi - lo <= 1: # min and max are themselves the labels (the binary case): no counting pass
108
+ return np.array([lo] if hi == lo else [lo, hi], dtype=y.dtype)
109
+ if lo > -(2**62) and hi < 2**62 and hi - lo <= max(1024, y.size):
110
+ flat = y.ravel()
111
+ # bincount counts in one pass; offsets in int64 so small dtypes cannot overflow.
112
+ counts = np.bincount(flat if lo == 0 and flat.dtype.itemsize <= 8 else flat.astype(np.int64) - lo)
113
+ return (np.flatnonzero(counts).astype(np.int64) + lo).astype(y.dtype)
114
+ return np.unique(y)
115
+
116
+
117
+ def _has_fraction(y: NDArray[Any]) -> bool:
118
+ """Whether any value is non-integral. Real-valued targets almost always show it in the first few values,
119
+ so a short leading chunk is checked before the whole array."""
120
+ flat = y.ravel()
121
+ head = flat[:1024]
122
+ if not np.all(np.mod(head, 1) == 0):
123
+ return True
124
+ return flat.size > head.size and not np.all(np.mod(flat[head.size :], 1) == 0)
125
+
126
+
127
+ def target_type(y: NDArray[Any]) -> TargetType:
128
+ """Infer the type of a label array."""
129
+ if y.ndim == 2:
130
+ if y.shape[1] > 1 and np.isin(y, (0, 1)).all():
131
+ return "multilabel"
132
+ if np.issubdtype(y.dtype, np.floating) and _has_fraction(y):
133
+ return "continuous" # multi-output regression
134
+ raise InputValidationError(
135
+ "2-D targets must be a binary indicator matrix (0/1, one column per label) for multilabel tasks; "
136
+ f"received shape {y.shape} with values other than 0 and 1."
137
+ )
138
+ if np.issubdtype(y.dtype, np.floating) and _has_fraction(y):
139
+ return "continuous"
140
+ try:
141
+ n_unique = unique_labels(y).shape[0]
142
+ except TypeError as exc:
143
+ raise InputValidationError(
144
+ "Labels must be mutually comparable (for example all integers or all strings); found a mix of types."
145
+ ) from exc
146
+ return "binary" if n_unique <= 2 else "multiclass"
147
+
148
+
149
+ def resolve_labels(
150
+ y_true: NDArray[Any], y_pred: Optional[NDArray[Any]], labels: Optional[ArrayLike]
151
+ ) -> NDArray[Any]:
152
+ """Sorted labels present in y_true or y_pred, or the user's explicit list (order kept)."""
153
+ if labels is not None:
154
+ lab = to_numpy(labels, "labels")
155
+ if np.unique(lab).shape[0] != lab.shape[0]:
156
+ raise InputValidationError("labels contains duplicates.")
157
+ return lab
158
+ if y_pred is not None and {_label_kind(y_true), _label_kind(y_pred)} == {"string", "number"}:
159
+ raise InputValidationError(
160
+ f"y_true has {_label_kind(y_true)} labels but y_pred has {_label_kind(y_pred)} labels; "
161
+ "use the same label type in both (for example map class names to integers first)."
162
+ )
163
+ if (
164
+ y_pred is not None
165
+ and np.issubdtype(y_true.dtype, np.integer)
166
+ and np.issubdtype(y_pred.dtype, np.integer)
167
+ and y_true.dtype == y_pred.dtype
168
+ ):
169
+ # Union of each array's labels: no concatenated copy of the data.
170
+ return np.union1d(unique_labels(y_true), unique_labels(y_pred)).astype(y_true.dtype)
171
+ present = y_true if y_pred is None else np.concatenate([y_true, y_pred])
172
+ try:
173
+ return unique_labels(present)
174
+ except TypeError as exc:
175
+ raise InputValidationError(
176
+ "Labels in y_true and y_pred must be mutually comparable (for example all integers or all strings)."
177
+ ) from exc
178
+
179
+
180
+ def validate_probabilities(
181
+ y_prob: ArrayLike,
182
+ n: int,
183
+ *,
184
+ n_classes: Optional[int] = None,
185
+ name: str = "y_prob",
186
+ rows_sum_to_one: bool = True,
187
+ unit: str = "class",
188
+ ) -> FloatArray:
189
+ """Probabilities in [0, 1]. For multiclass (2-D), one column per class and rows summing to 1.
190
+ Multilabel probabilities are independent per label (``rows_sum_to_one=False``)."""
191
+ p = to_numpy(y_prob, name, allow_2d=True).astype(np.float64, copy=False)
192
+ check_finite(p, name)
193
+ if p.shape[0] != n:
194
+ raise InputValidationError(
195
+ f"{name} must contain one row per observation. Received {p.shape[0]} for {n} observations."
196
+ )
197
+ if np.any(p < 0) or np.any(p > 1):
198
+ raise InputValidationError(
199
+ f"{name} must contain probabilities in [0, 1]; found values from {float(np.min(p)):.4g} to "
200
+ f"{float(np.max(p)):.4g}. "
201
+ "If these are scores or logits, convert them to probabilities first."
202
+ )
203
+ if p.ndim == 2:
204
+ if n_classes is not None and p.shape[1] != n_classes:
205
+ raise InputValidationError(
206
+ f"{name} has {p.shape[1]} columns but there are {n_classes} {unit}es. "
207
+ f"Provide one probability column per {unit}, in label order."
208
+ if unit == "class"
209
+ else f"{name} has {p.shape[1]} columns but there are {n_classes} {unit}s. "
210
+ f"Provide one probability column per {unit}."
211
+ )
212
+ sums = p.sum(axis=1)
213
+ if rows_sum_to_one and not np.allclose(sums, 1.0, atol=1e-6):
214
+ worst = float(np.abs(sums - 1).max())
215
+ raise InputValidationError(
216
+ f"Each row of {name} must sum to 1 for multiclass probabilities (largest deviation {worst:.3g})."
217
+ )
218
+ return p
219
+
220
+
221
+ def validate_zero_division(zero_division: ZeroDivision) -> ZeroDivision:
222
+ if zero_division == "warn":
223
+ return zero_division
224
+ if isinstance(zero_division, (int, float)) and (np.isnan(zero_division) or 0 <= zero_division <= 1):
225
+ return float(zero_division)
226
+ raise InputValidationError('zero_division must be "warn", 0, 1 or np.nan.')
227
+
228
+
229
+ def safe_divide(
230
+ num: NDArray[np.float64] | float,
231
+ den: NDArray[np.float64] | float,
232
+ *,
233
+ zero_division: ZeroDivision = "warn",
234
+ metric: str = "metric",
235
+ ) -> NDArray[np.float64]:
236
+ """Element-wise num/den. Where den == 0 the result is ``zero_division``.
237
+
238
+ ``"warn"`` (default) returns 0 and emits :class:`UndefinedMetricWarning`, matching scikit-learn's
239
+ convention; pass ``zero_division=np.nan`` to propagate undefined values instead. Never silent.
240
+ """
241
+ num_a = np.asarray(num, dtype=np.float64)
242
+ den_a = np.asarray(den, dtype=np.float64)
243
+ zero = den_a == 0
244
+ out = np.divide(num_a, den_a, out=np.zeros(np.broadcast(num_a, den_a).shape), where=~zero)
245
+ if np.any(zero):
246
+ if zero_division == "warn":
247
+ warnings.warn(
248
+ f"{metric} is undefined for {int(np.sum(zero))} case(s) because the denominator is zero; "
249
+ "using 0. Set zero_division=0, 1 or np.nan to choose the value explicitly.",
250
+ UndefinedMetricWarning,
251
+ stacklevel=4,
252
+ )
253
+ out[zero] = 0.0
254
+ else:
255
+ out[zero] = float(zero_division)
256
+ return out
@@ -0,0 +1,189 @@
1
+ """LLM systems (v0.5.0): safety and responsible AI, robustness and reliability, calibration and uncertainty,
2
+ agents and tool use, multilingual, code generation, long context and summarization, and inference efficiency and
3
+ cost."""
4
+
5
+ from __future__ import annotations
6
+
7
+ from .agents import (
8
+ agent_cost_per_task,
9
+ human_intervention_rate,
10
+ invalid_tool_call_rate,
11
+ plan_adherence,
12
+ state_tracking_accuracy,
13
+ steps_per_task,
14
+ task_completion_rate,
15
+ tool_failure_recovery_rate,
16
+ tool_use_efficiency,
17
+ unnecessary_tool_call_rate,
18
+ )
19
+ from .code import (
20
+ PYTHON_KEYWORDS,
21
+ code_complexity,
22
+ codebleu,
23
+ coverage_rate,
24
+ execution_success_rate,
25
+ patch_acceptance_rate,
26
+ resolved_rate,
27
+ runtime_efficiency,
28
+ security_vulnerability_rate,
29
+ static_analysis_violation_rate,
30
+ syntax_validity_rate,
31
+ unit_test_pass_rate,
32
+ )
33
+ from .efficiency import (
34
+ availability,
35
+ energy_per_request,
36
+ inference_cost,
37
+ latency_percentiles,
38
+ requests_per_second,
39
+ resource_utilization,
40
+ throughput,
41
+ time_per_output_token,
42
+ time_to_first_token,
43
+ token_usage,
44
+ )
45
+ from .longcontext import (
46
+ citation_coverage,
47
+ compression_ratio,
48
+ context_utilization,
49
+ cross_document_consistency,
50
+ lost_in_the_middle,
51
+ needle_in_haystack,
52
+ position_accuracy,
53
+ retrieval_accuracy_by_length,
54
+ summary_coverage,
55
+ )
56
+ from .multilingual import (
57
+ bitext_mining_accuracy,
58
+ code_switching_robustness,
59
+ cross_lingual_consistency,
60
+ cultural_appropriateness,
61
+ direct_assessment,
62
+ language_consistency,
63
+ language_id_accuracy,
64
+ language_parity,
65
+ )
66
+ from .robustness import (
67
+ add_typos,
68
+ adversarial_robustness,
69
+ contradiction_rate,
70
+ distribution_shift_drop,
71
+ error_rate,
72
+ invariance_violation_rate,
73
+ noise_robustness,
74
+ ood_accuracy,
75
+ paraphrase_consistency,
76
+ prompt_sensitivity,
77
+ recovery_success_rate,
78
+ response_stability,
79
+ truncation_sensitivity,
80
+ )
81
+ from .safety import (
82
+ PII_PATTERNS,
83
+ attack_success_rate,
84
+ detect_pii,
85
+ exposure,
86
+ harmful_response_rate,
87
+ over_refusal_rate,
88
+ pii_leakage_rate,
89
+ policy_violation_rate,
90
+ red_team_success_rate,
91
+ refusal_rate,
92
+ stereotype_preference,
93
+ toxicity_score,
94
+ weat_effect_size,
95
+ )
96
+ from .uncertainty import (
97
+ adaptive_calibration_error,
98
+ aurc,
99
+ confidence_accuracy_correlation,
100
+ coverage_at_risk,
101
+ risk_at_coverage,
102
+ risk_coverage_curve,
103
+ selective_risk,
104
+ )
105
+
106
+ __all__ = [
107
+ "PII_PATTERNS",
108
+ "PYTHON_KEYWORDS",
109
+ "adaptive_calibration_error",
110
+ "add_typos",
111
+ "adversarial_robustness",
112
+ "agent_cost_per_task",
113
+ "attack_success_rate",
114
+ "aurc",
115
+ "availability",
116
+ "bitext_mining_accuracy",
117
+ "citation_coverage",
118
+ "code_complexity",
119
+ "code_switching_robustness",
120
+ "codebleu",
121
+ "compression_ratio",
122
+ "confidence_accuracy_correlation",
123
+ "context_utilization",
124
+ "contradiction_rate",
125
+ "coverage_at_risk",
126
+ "coverage_rate",
127
+ "cross_document_consistency",
128
+ "cross_lingual_consistency",
129
+ "cultural_appropriateness",
130
+ "detect_pii",
131
+ "direct_assessment",
132
+ "distribution_shift_drop",
133
+ "energy_per_request",
134
+ "error_rate",
135
+ "execution_success_rate",
136
+ "exposure",
137
+ "harmful_response_rate",
138
+ "human_intervention_rate",
139
+ "inference_cost",
140
+ "invalid_tool_call_rate",
141
+ "invariance_violation_rate",
142
+ "language_consistency",
143
+ "language_id_accuracy",
144
+ "language_parity",
145
+ "latency_percentiles",
146
+ "lost_in_the_middle",
147
+ "needle_in_haystack",
148
+ "noise_robustness",
149
+ "ood_accuracy",
150
+ "over_refusal_rate",
151
+ "paraphrase_consistency",
152
+ "patch_acceptance_rate",
153
+ "pii_leakage_rate",
154
+ "plan_adherence",
155
+ "policy_violation_rate",
156
+ "position_accuracy",
157
+ "prompt_sensitivity",
158
+ "recovery_success_rate",
159
+ "red_team_success_rate",
160
+ "refusal_rate",
161
+ "requests_per_second",
162
+ "resolved_rate",
163
+ "resource_utilization",
164
+ "response_stability",
165
+ "retrieval_accuracy_by_length",
166
+ "risk_at_coverage",
167
+ "risk_coverage_curve",
168
+ "runtime_efficiency",
169
+ "security_vulnerability_rate",
170
+ "selective_risk",
171
+ "state_tracking_accuracy",
172
+ "static_analysis_violation_rate",
173
+ "steps_per_task",
174
+ "stereotype_preference",
175
+ "summary_coverage",
176
+ "syntax_validity_rate",
177
+ "task_completion_rate",
178
+ "throughput",
179
+ "time_per_output_token",
180
+ "time_to_first_token",
181
+ "token_usage",
182
+ "tool_failure_recovery_rate",
183
+ "tool_use_efficiency",
184
+ "toxicity_score",
185
+ "truncation_sensitivity",
186
+ "unit_test_pass_rate",
187
+ "unnecessary_tool_call_rate",
188
+ "weat_effect_size",
189
+ ]
@@ -0,0 +1,215 @@
1
+ """Shared input handling for the v0.5.0 LLM-systems metrics."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import math
6
+ from collections.abc import Mapping, Sequence
7
+ from typing import Any, Optional
8
+
9
+ import numpy as np
10
+
11
+ from ..core.exceptions import InputValidationError
12
+ from ..core.result import MetricResult
13
+
14
+ _Z95 = 1.959963984540054
15
+ Sized = Any # anything with __len__
16
+
17
+
18
+ def seq(x: Any, name: str) -> list[Any]:
19
+ """A non-empty list, one entry per example."""
20
+ if x is None:
21
+ raise InputValidationError(f"{name} is required but was None.")
22
+ if isinstance(x, (str, bytes)):
23
+ raise InputValidationError(f"{name} must be a list (one entry per example), not a single string.")
24
+ if isinstance(x, Mapping):
25
+ raise InputValidationError(f"{name} must be a list, not a mapping.")
26
+ items = x.tolist() if isinstance(x, np.ndarray) else list(x)
27
+ if not items:
28
+ raise InputValidationError(f"{name} is empty. Provide at least one example.")
29
+ return items
30
+
31
+
32
+ def bools(x: Any, name: str) -> np.ndarray:
33
+ """A 1-D boolean array from booleans or 0/1 values (anything else is rejected, never coerced)."""
34
+ if isinstance(x, np.ndarray) and x.ndim == 1 and x.size and x.dtype.kind in "biuf":
35
+ if x.dtype.kind == "b":
36
+ return x.astype(bool, copy=False)
37
+ bad = ~np.isin(x, (0, 1))
38
+ if bad.any():
39
+ i = int(np.flatnonzero(bad)[0])
40
+ raise InputValidationError(f"{name}[{i}] must be a boolean (or 0/1); got {x[i]!r}.")
41
+ return x.astype(bool)
42
+ items = seq(x, name)
43
+ out = np.empty(len(items), dtype=bool)
44
+ for i, v in enumerate(items):
45
+ if isinstance(v, (bool, np.bool_)) or (
46
+ isinstance(v, (int, float, np.integer, np.floating)) and not isinstance(v, bool) and v in (0, 1)
47
+ ):
48
+ out[i] = bool(v)
49
+ else:
50
+ raise InputValidationError(f"{name}[{i}] must be a boolean (or 0/1); got {v!r}.")
51
+ return out
52
+
53
+
54
+ def floats(x: Any, name: str, *, lo: Optional[float] = None, hi: Optional[float] = None) -> np.ndarray:
55
+ """A finite 1-D float array, optionally bounded."""
56
+ items: Any = x if isinstance(x, np.ndarray) and x.size and x.dtype.kind in "biuf" else seq(x, name)
57
+ try:
58
+ a = np.asarray(items, dtype=np.float64)
59
+ except (TypeError, ValueError) as exc:
60
+ raise InputValidationError(f"{name} must contain numbers.") from exc
61
+ if a.ndim != 1:
62
+ raise InputValidationError(f"{name} must be one-dimensional (one number per example).")
63
+ if a.size:
64
+ # min and max propagate NaN and ±inf, so two reductions check finiteness and both bounds.
65
+ mn, mx = float(a.min()), float(a.max())
66
+ if not (math.isfinite(mn) and math.isfinite(mx)):
67
+ raise InputValidationError(f"{name} contains NaN or infinite values.")
68
+ if lo is not None and mn < lo:
69
+ raise InputValidationError(f"{name} must be >= {lo}.")
70
+ if hi is not None and mx > hi:
71
+ raise InputValidationError(f"{name} must be <= {hi}.")
72
+ return a
73
+
74
+
75
+ def same_length(*pairs: tuple[str, Sized]) -> int:
76
+ n = len(pairs[0][1])
77
+ for name, v in pairs[1:]:
78
+ if len(v) != n:
79
+ raise InputValidationError(
80
+ f"{pairs[0][0]} and {name} must contain the same number of examples. Received {n} and {len(v)}."
81
+ )
82
+ return n
83
+
84
+
85
+ def wilson(k: float, n: float) -> tuple[float, float]:
86
+ """95% Wilson interval for a proportion (Wilson 1927)."""
87
+ if n <= 0:
88
+ return (math.nan, math.nan)
89
+ p = k / n
90
+ z2 = _Z95**2
91
+ centre = (p + z2 / (2 * n)) / (1 + z2 / n)
92
+ half = _Z95 * math.sqrt(p * (1 - p) / n + z2 / (4 * n * n)) / (1 + z2 / n)
93
+ return (max(0.0, centre - half), min(1.0, centre + half))
94
+
95
+
96
+ def rate(metric: str, name: str, flags: np.ndarray, extra: Optional[dict[str, Any]] = None) -> MetricResult:
97
+ """A proportion with its count and 95% Wilson interval in ``params``."""
98
+ n = int(flags.size)
99
+ k = int(flags.sum())
100
+ lo, hi = wilson(k, n)
101
+ params = {"count": k, "n": n, "ci_low": lo, "ci_high": hi, **(extra or {})}
102
+ return MetricResult(metric, name, k / n, params)
103
+
104
+
105
+ def by_group(values: np.ndarray, groups: Optional[Sequence[Any]], name: str = "groups") -> dict[str, float]:
106
+ """Mean of ``values`` per group label (keys as strings, sorted)."""
107
+ if groups is None:
108
+ return {}
109
+ g = seq(groups, name)
110
+ if len(g) != values.size:
111
+ raise InputValidationError(f"{name} must have one label per example ({values.size}); got {len(g)}.")
112
+ out: dict[str, float] = {}
113
+ for label in sorted({str(v) for v in g}):
114
+ mask = np.array([str(v) == label for v in g])
115
+ out[label] = float(values[mask].mean())
116
+ return out
117
+
118
+
119
+ def _order_stats_partition(a: np.ndarray, ks: list[int]) -> dict[int, float]:
120
+ part = np.partition(a, ks)
121
+ return {k: float(part[k]) for k in ks}
122
+
123
+
124
+ def _order_stats_bracketed(a: np.ndarray, ks: list[int]) -> Optional[dict[int, float]]:
125
+ """Exact order statistics of a large array without partitioning all of it.
126
+
127
+ A sorted strided sample (about 8k values) brackets each wanted rank; one pass counts the values below the
128
+ bracket and extracts those inside it, and only that small subset is partitioned. Overlapping brackets are
129
+ merged. Returns None if a bracket misses its rank (possible only for adversarially ordered data), and the
130
+ caller falls back to a full partition, so the result is always exact."""
131
+ n = a.size
132
+ s = np.sort(a[:: max(1, n // 8192)])
133
+ ns = s.size
134
+ brackets: list[list[Any]] = []
135
+ for k in ks:
136
+ r = k / (n - 1) * (ns - 1)
137
+ margin = 6 * math.sqrt(max(r * (ns - r) / ns, 1.0)) + 4
138
+ lo_i, hi_i = max(0, math.floor(r - margin)), min(ns - 1, math.ceil(r + margin))
139
+ if brackets and lo_i <= brackets[-1][1]:
140
+ brackets[-1][1] = max(brackets[-1][1], hi_i)
141
+ brackets[-1][2].append(k)
142
+ else:
143
+ brackets.append([lo_i, hi_i, [k]])
144
+ out: dict[int, float] = {}
145
+ for lo_i, hi_i, group in brackets:
146
+ mask = np.ones(n, dtype=bool) if lo_i == 0 else a >= s[lo_i]
147
+ below = 0 if lo_i == 0 else n - int(np.count_nonzero(mask))
148
+ if hi_i < ns - 1:
149
+ mask &= a <= s[hi_i]
150
+ window = a[mask]
151
+ rel = [k - below for k in group]
152
+ if rel[0] < 0 or rel[-1] >= window.size:
153
+ return None
154
+ part = np.partition(window, rel)
155
+ for k, r_ in zip(group, rel):
156
+ out[k] = float(part[r_])
157
+ return out
158
+
159
+
160
+ def quantiles(a: np.ndarray, qs: Sequence[float]) -> list[float]:
161
+ """Percentiles ``qs`` (0-100, linear interpolation, as ``np.percentile``). Large arrays use bracketed
162
+ selection on a small window per percentile; small ones one partition. Both are exact."""
163
+ n = a.size
164
+ pos = [(n - 1) * (q / 100.0) for q in qs] # NumPy's order of operations
165
+ lo = [math.floor(h) for h in pos]
166
+ ks = sorted({k for i in lo for k in (i, min(i + 1, n - 1))})
167
+ stats = _order_stats_bracketed(a, ks) if n >= 65536 else None
168
+ if stats is None:
169
+ stats = _order_stats_partition(a, ks)
170
+ out = []
171
+ for h, i in zip(pos, lo):
172
+ v0, v1 = stats[i], stats[min(i + 1, n - 1)]
173
+ t = h - i
174
+ d = v1 - v0
175
+ # NumPy's lerp, so the result is bit-for-bit np.percentile(..., method="linear")
176
+ out.append(v1 - d * (1 - t) if t >= 0.5 else v0 + d * t)
177
+ return out
178
+
179
+
180
+ def summary(a: np.ndarray, extra: Sequence[float] = ()) -> dict[str, float]:
181
+ """Mean, standard deviation, min, max and the p50/p90/p95/p99 percentiles (linear interpolation), plus any
182
+ ``extra`` percentiles under keys ``p<q>``; all order statistics come from one partition."""
183
+ qs = [50.0, 90.0, 95.0, 99.0, *[q for q in extra if q not in (0.0, 50.0, 90.0, 95.0, 99.0, 100.0)]]
184
+ v = quantiles(a, qs)
185
+ by_q = dict(zip(qs, v))
186
+ mean = float(a.mean())
187
+ if a.size > 1:
188
+ c = a - mean
189
+ std = math.sqrt(float(np.dot(c, c)) / (a.size - 1))
190
+ else:
191
+ std = 0.0
192
+ out = {
193
+ "mean": mean,
194
+ "std": std,
195
+ "min": float(a.min()),
196
+ "max": float(a.max()),
197
+ "p50": by_q[50.0],
198
+ "p90": by_q[90.0],
199
+ "p95": by_q[95.0],
200
+ "p99": by_q[99.0],
201
+ }
202
+ for q in extra:
203
+ out[f"p{q:g}"] = float(a.min()) if q == 0 else float(a.max()) if q == 100 else by_q[q]
204
+ return out
205
+
206
+
207
+ def lists_of(x: Any, name: str) -> list[list[Any]]:
208
+ """One (possibly empty) list per example."""
209
+ rows = seq(x, name)
210
+ out = []
211
+ for i, r in enumerate(rows):
212
+ if isinstance(r, (str, bytes)) or not hasattr(r, "__iter__"):
213
+ raise InputValidationError(f"{name}[{i}] must be a list.")
214
+ out.append(list(r))
215
+ return out