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,420 @@
1
+ """compare(): evaluate several models on the same test set with intervals and paired tests."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import itertools
6
+ import json
7
+ from collections.abc import Mapping, Sequence
8
+ from dataclasses import dataclass, field
9
+ from types import MappingProxyType
10
+ from typing import TYPE_CHECKING, Any, Optional, cast
11
+
12
+ import numpy as np
13
+
14
+ from ..core.exceptions import InputValidationError
15
+ from ..core.registry import metric_info
16
+ from ..core.result import _json_safe, _latex_escape, _latex_table
17
+ from ..core.types import ArrayLike
18
+ from ._resolve import MetricCall, as_items, as_observations, is_categorical, resolve_metric
19
+ from .effect import adjust_pvalues
20
+ from .intervals import _check_level, _check_resamples, bootstrap_distribution, resample_indices
21
+ from .paired import delong_test, mcnemar_test
22
+
23
+ if TYPE_CHECKING:
24
+ import pandas as pd
25
+
26
+ __all__ = ["ComparisonResult", "compare"]
27
+
28
+ _DEFAULT_CLF = ["accuracy", "f1", "mcc"]
29
+ _DEFAULT_CLF_PROB = ["roc_auc", "brier_score"]
30
+ _DEFAULT_REG = ["mae", "rmse", "r2"]
31
+
32
+
33
+ def _p(value: float) -> str:
34
+ return "<0.0001" if value < 1e-4 else f"={value:.4f}"
35
+
36
+
37
+ def _info(name: str) -> Any:
38
+ for cat in ("classification", "regression"):
39
+ try:
40
+ return metric_info(f"{cat}.{name}")
41
+ except KeyError:
42
+ continue
43
+ return None
44
+
45
+
46
+ def _needs_prob(name: str) -> bool:
47
+ info = _info(name)
48
+ return info is not None and "y_prob" in info.input_requirements
49
+
50
+
51
+ @dataclass(frozen=True, eq=False)
52
+ class ComparisonResult:
53
+ """Per-model estimates with confidence intervals, and pairwise tests with adjusted p-values."""
54
+
55
+ models: tuple[str, ...]
56
+ metrics: tuple[str, ...]
57
+ estimates: tuple[Mapping[str, Any], ...]
58
+ tests: tuple[Mapping[str, Any], ...]
59
+ settings: Mapping[str, Any] = field(default_factory=dict)
60
+
61
+ def __post_init__(self) -> None:
62
+ object.__setattr__(self, "estimates", tuple(MappingProxyType(dict(r)) for r in self.estimates))
63
+ object.__setattr__(self, "tests", tuple(MappingProxyType(dict(r)) for r in self.tests))
64
+ object.__setattr__(self, "settings", MappingProxyType(dict(self.settings)))
65
+
66
+ def estimate(self, model: str, metric: str) -> Mapping[str, Any]:
67
+ for row in self.estimates:
68
+ if row["model"] == model and row["metric"] == metric:
69
+ return row
70
+ raise KeyError(f"No estimate for model={model!r}, metric={metric!r}.")
71
+
72
+ def best(self, metric: str) -> str:
73
+ """Model with the best point estimate (direction from the metric registry)."""
74
+ rows = [r for r in self.estimates if r["metric"] == metric]
75
+ if not rows:
76
+ raise KeyError(f"Metric {metric!r} was not compared. Compared: {', '.join(self.metrics)}.")
77
+ info = _info(metric)
78
+ higher = True if info is None or info.higher_is_better is None else info.higher_is_better
79
+ pick = max if higher else min
80
+ return str(pick(rows, key=lambda r: r["estimate"])["model"])
81
+
82
+ def summary(self, *, digits: int = 3) -> str:
83
+ level = round(self.settings["level"] * 100, 6)
84
+ lines = [
85
+ f"EvalSuite model comparison (n={self.settings['n_samples']}, {level:g}% CIs, "
86
+ f"{self.settings['n_resamples']} paired bootstrap resamples, {self.settings['correction']} correction)"
87
+ ]
88
+ width = max(len(m) for m in self.models)
89
+ for metric in self.metrics:
90
+ lines.append(f"\n{metric} (best: {self.best(metric)})")
91
+ for row in (r for r in self.estimates if r["metric"] == metric):
92
+ lines.append(
93
+ f" {row['model']:<{width}} {row['estimate']:.{digits}f} "
94
+ f"({row['low']:.{digits}f}–{row['high']:.{digits}f})"
95
+ )
96
+ for t in (t for t in self.tests if t["metric"] == metric):
97
+ mark = " *" if t["significant"] else ""
98
+ lines.append(
99
+ f" {t['model_a']} − {t['model_b']}: {t['difference']:+.{digits}f} "
100
+ f"[{t['test']}, p={t['p_value']:.4f}, adjusted p={t['p_adjusted']:.4f}]{mark}"
101
+ )
102
+ lines.append(f"\n* significant at α = {self.settings['alpha']} after correction")
103
+ return "\n".join(lines)
104
+
105
+ def __repr__(self) -> str:
106
+ return self.summary()
107
+
108
+ def to_dict(self) -> dict[str, Any]:
109
+ return cast(
110
+ "dict[str, Any]",
111
+ _json_safe(
112
+ {
113
+ "models": list(self.models),
114
+ "metrics": list(self.metrics),
115
+ "estimates": [dict(r) for r in self.estimates],
116
+ "tests": [dict(r) for r in self.tests],
117
+ "settings": dict(self.settings),
118
+ }
119
+ ),
120
+ )
121
+
122
+ def to_json(self, *, indent: Optional[int] = 2) -> str:
123
+ return json.dumps(self.to_dict(), indent=indent, allow_nan=False)
124
+
125
+ def to_dataframe(self, which: str = "estimates") -> pd.DataFrame:
126
+ """``"estimates"`` (one row per model and metric) or ``"tests"`` (one row per comparison)."""
127
+ import pandas as pd
128
+
129
+ if which not in ("estimates", "tests"):
130
+ raise InputValidationError("which must be 'estimates' or 'tests'.")
131
+ frame: pd.DataFrame = pd.DataFrame(
132
+ [dict(r) for r in (self.estimates if which == "estimates" else self.tests)]
133
+ )
134
+ return frame
135
+
136
+ def _cell(self, model: str, metric: str, digits: int) -> str:
137
+ r = self.estimate(model, metric)
138
+ return f"{r['estimate']:.{digits}f} ({r['low']:.{digits}f}–{r['high']:.{digits}f})"
139
+
140
+ def to_markdown(self, *, digits: int = 3) -> str:
141
+ """Models as rows, metrics as columns: ``estimate (low–high)``; best value per metric in bold."""
142
+ header = "| Model | " + " | ".join(self.metrics) + " |"
143
+ sep = "| --- |" + " ---: |" * len(self.metrics)
144
+ rows = []
145
+ for model in self.models:
146
+ cells = []
147
+ for metric in self.metrics:
148
+ c = self._cell(model, metric, digits)
149
+ cells.append(f"**{c}**" if self.best(metric) == model else c)
150
+ rows.append(f"| {model} | " + " | ".join(cells) + " |")
151
+ return "\n".join([header, sep, *rows])
152
+
153
+ def to_latex(self, *, digits: int = 3, caption: Optional[str] = None, label: Optional[str] = None) -> str:
154
+ """Publication table: models × metrics with confidence intervals; best value per metric in bold."""
155
+ header = ["Model", *(_latex_escape(m) for m in self.metrics)]
156
+ rows = []
157
+ for model in self.models:
158
+ cells = [_latex_escape(model)]
159
+ for metric in self.metrics:
160
+ c = self._cell(model, metric, digits).replace("–", "--")
161
+ cells.append(rf"\textbf{{{c}}}" if self.best(metric) == model else c)
162
+ rows.append(cells)
163
+ level = round(self.settings["level"] * 100, 6)
164
+ cap = caption or f"Model comparison: estimate ({level:g}% CI)." # escaped once by _latex_table
165
+ return _latex_table(header, rows, caption=cap, label=label)
166
+
167
+ def _csv_rows(self) -> tuple[list[str], list[list[Any]]]:
168
+ header = ["model", "metric", "estimate", "low", "high"]
169
+ return header, [[r["model"], r["metric"], r["estimate"], r["low"], r["high"]] for r in self.estimates]
170
+
171
+ def to_csv(self, path: Optional[str] = None, *, which: str = "estimates") -> str:
172
+ """CSV of the estimates (``which="estimates"``) or the pairwise tests (``which="tests"``)."""
173
+ from ..core.export import csv_text
174
+
175
+ if which == "estimates":
176
+ header, rows = self._csv_rows()
177
+ elif which == "tests":
178
+ header = [
179
+ "metric",
180
+ "model_a",
181
+ "model_b",
182
+ "difference",
183
+ "ci_low",
184
+ "ci_high",
185
+ "test",
186
+ "statistic",
187
+ "p_value",
188
+ "p_adjusted",
189
+ "significant",
190
+ ]
191
+ rows = [[t[h] for h in header] for t in self.tests]
192
+ else:
193
+ raise InputValidationError("which must be 'estimates' or 'tests'.")
194
+ text = csv_text(header, rows)
195
+ if path is not None:
196
+ with open(path, "w", encoding="utf-8", newline="") as fh:
197
+ fh.write(text)
198
+ return text
199
+
200
+ def to_html(self, *, digits: int = 3, full: bool = False) -> str:
201
+ """Estimates table (best value per metric in bold) and the pairwise tests table."""
202
+ from ..core.export import html_document, html_table
203
+
204
+ rows = [[m, *(self._cell(m, metric, digits) for metric in self.metrics)] for m in self.models]
205
+ bold = {
206
+ (i, j + 1)
207
+ for i, m in enumerate(self.models)
208
+ for j, metric in enumerate(self.metrics)
209
+ if self.best(metric) == m
210
+ }
211
+ level = round(self.settings["level"] * 100, 6)
212
+ parts = [
213
+ html_table(
214
+ ["Model", *self.metrics], rows, caption=f"Estimate ({level:g}% CI); best in bold", bold=bold
215
+ )
216
+ ]
217
+ test_rows = [
218
+ [
219
+ t["metric"],
220
+ f"{t['model_a']} − {t['model_b']}",
221
+ f"{t['difference']:+.{digits}f}",
222
+ f"{t['ci_low']:.{digits}f}–{t['ci_high']:.{digits}f}",
223
+ t["test"],
224
+ f"{t['p_value']:.4g}",
225
+ f"{t['p_adjusted']:.4g}",
226
+ "yes" if t["significant"] else "no",
227
+ ]
228
+ for t in self.tests
229
+ ]
230
+ parts.append(
231
+ html_table(
232
+ ["Metric", "Comparison", "Difference", f"{level:g}% CI", "Test", "p", "Adjusted p", "Significant"],
233
+ test_rows,
234
+ caption=f"Pairwise tests ({self.settings['correction']} correction, α = {self.settings['alpha']})",
235
+ numeric=[False, False, True, True, False, True, True, False],
236
+ )
237
+ )
238
+ body = "\n".join(parts)
239
+ meta = f"n = {self.settings['n_samples']}, {self.settings['n_resamples']} paired bootstrap resamples"
240
+ return html_document("EvalSuite model comparison", body, meta) if full else body
241
+
242
+ def save(self, path: str, *, digits: int = 3) -> str:
243
+ """Save as .json .csv .md .tex .html or .txt (chosen by the extension)."""
244
+ from ..core.export import save_as
245
+
246
+ return save_as(
247
+ path,
248
+ {
249
+ "json": self.to_json,
250
+ "csv": self.to_csv,
251
+ "markdown": lambda: self.to_markdown(digits=digits) + "\n",
252
+ "latex": lambda: self.to_latex(digits=digits) + "\n",
253
+ "html": lambda: self.to_html(digits=digits, full=True),
254
+ "text": lambda: self.summary(digits=digits) + "\n",
255
+ },
256
+ )
257
+
258
+
259
+ def compare(
260
+ y_true: ArrayLike,
261
+ predictions: Optional[Mapping[str, ArrayLike]] = None,
262
+ *,
263
+ probabilities: Optional[Mapping[str, ArrayLike]] = None,
264
+ metrics: Optional[Sequence[str]] = None,
265
+ baseline: Optional[str] = None,
266
+ level: float = 0.95,
267
+ alpha: float = 0.05,
268
+ n_resamples: int = 1000,
269
+ correction: str = "holm",
270
+ random_state: Optional[int] = None,
271
+ stratify: Optional[bool] = None,
272
+ sample_weight: Optional[ArrayLike] = None,
273
+ metric_kwargs: Optional[Mapping[str, Mapping[str, Any]]] = None,
274
+ ) -> ComparisonResult:
275
+ """Compare models evaluated on the same test set.
276
+
277
+ ``predictions`` and/or ``probabilities`` map model names to that model's predicted labels/values or
278
+ probabilities. Every model is resampled on the same bootstrap indices (paired), giving a percentile
279
+ confidence interval per model and metric and a paired test per pair of models:
280
+
281
+ * accuracy: McNemar's test (exact when there are fewer than 25 discordant pairs);
282
+ * binary ROC AUC: DeLong's test;
283
+ * everything else: paired bootstrap test.
284
+
285
+ Pairs are every model against ``baseline`` if given, otherwise all pairs. p-values are adjusted within
286
+ each metric (``correction``: "holm", "bonferroni", "hochberg", "bh", "by"); ``significant`` uses the adjusted
287
+ p-value and ``alpha``. ``metric_kwargs`` passes options per metric, e.g. ``{"f1": {"average": "macro"}}``.
288
+ """
289
+ level = _check_level(level)
290
+ n_resamples = _check_resamples(n_resamples)
291
+ predictions = dict(predictions or {})
292
+ probabilities = dict(probabilities or {})
293
+ names = list(dict.fromkeys([*predictions, *probabilities]))
294
+ if len(names) < 2:
295
+ raise InputValidationError("compare() needs at least two models (a dict of name -> predictions).")
296
+ if baseline is not None and baseline not in names:
297
+ raise InputValidationError(f"baseline={baseline!r} is not one of the models: {', '.join(names)}.")
298
+ item_level = metrics is not None and any(
299
+ getattr(resolve_metric(m)[0], "__evalsuite_items__", False) for m in metrics
300
+ )
301
+ # Text, retrieval and other item-level metrics resample whole items and never stratify by value.
302
+ yt = as_items(y_true, "y_true") if item_level else as_observations(y_true, "y_true")
303
+ categorical = not item_level and is_categorical(yt)
304
+ if metrics is None:
305
+ if yt.ndim > 2 or (yt.dtype == object and yt.size and not isinstance(yt[0], (str, bytes))):
306
+ is_detection = yt.dtype == object and isinstance(yt[0], Mapping)
307
+ metric_names = ["mean_average_precision"] if is_detection else ["dice", "iou"]
308
+ elif categorical:
309
+ metric_names = list(_DEFAULT_CLF) if predictions else []
310
+ if probabilities:
311
+ metric_names += _DEFAULT_CLF_PROB if np.unique(yt).shape[0] <= 2 and yt.ndim == 1 else ["roc_auc"]
312
+ else:
313
+ metric_names = list(_DEFAULT_REG)
314
+ else:
315
+ metric_names = [resolve_metric(m)[1] for m in metrics]
316
+ kwargs_by_metric = {k: dict(v) for k, v in (metric_kwargs or {}).items()}
317
+
318
+ calls: dict[tuple[str, str], MetricCall] = {}
319
+ for metric in metric_names:
320
+ fn, _ = resolve_metric(metric)
321
+ prob = _needs_prob(metric)
322
+ source = probabilities if prob else predictions
323
+ for model in names:
324
+ if model not in source:
325
+ kind = "probabilities" if prob else "predictions"
326
+ raise InputValidationError(f"Metric '{metric}' needs {kind} for model '{model}'.")
327
+ calls[(model, metric)] = MetricCall(
328
+ fn,
329
+ yt,
330
+ None if prob else source[model],
331
+ source[model] if prob else None,
332
+ sample_weight,
333
+ kwargs_by_metric.get(metric),
334
+ )
335
+ # identical label set for every model of this metric
336
+ labs = [calls[(m, metric)].kwargs.get("labels") for m in names]
337
+ if all(lab is not None for lab in labs):
338
+ shared = labs[0]
339
+ for lab in labs[1:]:
340
+ shared = np.union1d(shared, lab)
341
+ for m in names:
342
+ calls[(m, metric)].kwargs["labels"] = shared
343
+
344
+ rng = np.random.default_rng(random_state)
345
+ use_strata = categorical if stratify is None else bool(stratify)
346
+ idx = resample_indices(yt.shape[0], n_resamples, rng, yt if use_strata else None)
347
+ a = (1 - level) / 2
348
+ boot: dict[tuple[str, str], np.ndarray] = {}
349
+ estimates: list[dict[str, Any]] = []
350
+ for metric in metric_names:
351
+ for model in names:
352
+ call = calls[(model, metric)]
353
+ dist, failed = bootstrap_distribution(call, idx)
354
+ boot[(model, metric)] = dist
355
+ low, high = np.nanquantile(dist, [a, 1 - a])
356
+ estimates.append(
357
+ {
358
+ "model": model,
359
+ "metric": metric,
360
+ "estimate": call(),
361
+ "low": float(low),
362
+ "high": float(high),
363
+ "failed_resamples": int(failed),
364
+ }
365
+ )
366
+
367
+ pairs = (
368
+ [(m, baseline) for m in names if m != baseline]
369
+ if baseline is not None
370
+ else list(itertools.combinations(names, 2))
371
+ )
372
+ tests: list[dict[str, Any]] = []
373
+ for metric in metric_names:
374
+ block: list[dict[str, Any]] = []
375
+ for ma, mb in pairs:
376
+ diff_dist = boot[(ma, metric)] - boot[(mb, metric)]
377
+ diff_dist = diff_dist[~np.isnan(diff_dist)]
378
+ observed = calls[(ma, metric)]() - calls[(mb, metric)]()
379
+ low, high = np.quantile(diff_dist, [a, 1 - a])
380
+ if metric == "accuracy" and sample_weight is None:
381
+ t = mcnemar_test(yt, predictions[ma], predictions[mb])
382
+ test_name, stat, p = t.test, t.statistic, t.p_value
383
+ elif metric == "roc_auc" and sample_weight is None and yt.ndim == 1 and np.unique(yt).shape[0] == 2:
384
+ t = delong_test(yt, probabilities[ma], probabilities[mb])
385
+ test_name, stat, p = t.test, t.statistic, t.p_value
386
+ else:
387
+ extreme = np.sum(np.abs(diff_dist - observed) >= abs(observed))
388
+ test_name, stat, p = "paired-bootstrap", observed, (1 + extreme) / (diff_dist.shape[0] + 1)
389
+ block.append(
390
+ {
391
+ "metric": metric,
392
+ "model_a": ma,
393
+ "model_b": mb,
394
+ "difference": float(observed),
395
+ "ci_low": float(low),
396
+ "ci_high": float(high),
397
+ "test": test_name,
398
+ "statistic": float(stat),
399
+ "p_value": float(p),
400
+ }
401
+ )
402
+ if block:
403
+ adjusted = adjust_pvalues([r["p_value"] for r in block], method=correction) # type: ignore[arg-type]
404
+ for r, pa in zip(block, adjusted):
405
+ r["p_adjusted"] = float(pa)
406
+ r["significant"] = bool(pa < alpha)
407
+ tests.extend(block)
408
+
409
+ settings = {
410
+ "n_samples": int(yt.shape[0]),
411
+ "level": level,
412
+ "alpha": alpha,
413
+ "n_resamples": n_resamples,
414
+ "correction": correction,
415
+ "random_state": random_state,
416
+ "stratified": use_strata,
417
+ "baseline": baseline,
418
+ "ci_method": "bootstrap-percentile (paired resamples)",
419
+ }
420
+ return ComparisonResult(tuple(names), tuple(metric_names), tuple(estimates), tuple(tests), settings)
@@ -0,0 +1,159 @@
1
+ """Effect sizes and multiple-comparison correction."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import TYPE_CHECKING, Literal
6
+
7
+ import numpy as np
8
+ from numpy.typing import NDArray
9
+
10
+ if TYPE_CHECKING:
11
+ from scipy import special
12
+ else:
13
+ from .._lazy import lazy_module
14
+
15
+ special = lazy_module("scipy.special")
16
+
17
+ from ..core.exceptions import InputValidationError, StatisticalTestError
18
+ from ..core.types import ArrayLike
19
+ from ..core.validation import check_finite, to_numpy
20
+
21
+ __all__ = ["adjust_pvalues", "cliffs_delta", "cohens_d", "cramers_v", "hedges_g"]
22
+
23
+
24
+ def _samples(a: ArrayLike, b: ArrayLike) -> tuple[NDArray[np.float64], NDArray[np.float64]]:
25
+ x = to_numpy(a, "a").astype(np.float64)
26
+ y = to_numpy(b, "b").astype(np.float64)
27
+ check_finite(x, "a")
28
+ check_finite(y, "b")
29
+ return x, y
30
+
31
+
32
+ def cohens_d(a: ArrayLike, b: ArrayLike, *, paired: bool = False) -> float:
33
+ """Cohen's d for mean(a) − mean(b).
34
+
35
+ Independent samples: difference over the pooled standard deviation. ``paired=True``: mean difference over
36
+ the standard deviation of the differences (d_z), for per-fold or per-subject scores of two models.
37
+
38
+ Reference: Cohen J. Statistical Power Analysis for the Behavioral Sciences. 2nd ed. Erlbaum; 1988.
39
+ Lakens D. Calculating and reporting effect sizes. Front Psychol. 2013;4:863.
40
+ """
41
+ x, y = _samples(a, b)
42
+ if paired:
43
+ if x.shape != y.shape:
44
+ raise InputValidationError("Paired samples must have the same length.")
45
+ d = x - y
46
+ if d.shape[0] < 2:
47
+ raise StatisticalTestError("Cohen's d needs at least two pairs.")
48
+ sd = d.std(ddof=1)
49
+ if sd == 0:
50
+ raise StatisticalTestError("Cohen's d is undefined: the paired differences are all identical.")
51
+ return float(d.mean() / sd)
52
+ n1, n2 = x.shape[0], y.shape[0]
53
+ if n1 < 2 or n2 < 2:
54
+ raise StatisticalTestError("Cohen's d needs at least two observations per group.")
55
+ pooled = np.sqrt(((n1 - 1) * x.var(ddof=1) + (n2 - 1) * y.var(ddof=1)) / (n1 + n2 - 2))
56
+ if pooled == 0:
57
+ raise StatisticalTestError("Cohen's d is undefined: both groups have zero variance.")
58
+ return float((x.mean() - y.mean()) / pooled)
59
+
60
+
61
+ def hedges_g(a: ArrayLike, b: ArrayLike, *, paired: bool = False) -> float:
62
+ """Hedges' g: Cohen's d with the exact small-sample bias correction J(df) = Γ(df/2) / (√(df/2) Γ((df−1)/2)).
63
+
64
+ Reference: Hedges LV. Distribution theory for Glass's estimator of effect size and related estimators.
65
+ J Educ Stat. 1981;6(2):107-128.
66
+ """
67
+ x, y = _samples(a, b)
68
+ df = (x.shape[0] - 1) if paired else (x.shape[0] + y.shape[0] - 2)
69
+ if df < 2:
70
+ raise StatisticalTestError("Hedges' g needs at least three observations.")
71
+ j = np.exp(special.gammaln(df / 2) - special.gammaln((df - 1) / 2)) / np.sqrt(df / 2)
72
+ return float(j * cohens_d(a, b, paired=paired))
73
+
74
+
75
+ def cliffs_delta(a: ArrayLike, b: ArrayLike) -> float:
76
+ """Cliff's delta: P(a > b) − P(a < b) over all pairs; a non-parametric effect size in [−1, 1].
77
+
78
+ Computed in O((n + m) log m). Reference: Cliff N. Dominance statistics: ordinal analyses to answer ordinal
79
+ questions. Psychol Bull. 1993;114(3):494-509.
80
+ """
81
+ x, y = _samples(a, b)
82
+ ys = np.sort(y)
83
+ less = np.searchsorted(ys, x, side="left") # y values below each x
84
+ greater = y.shape[0] - np.searchsorted(ys, x, side="right") # y values above each x
85
+ return float((less.sum() - greater.sum()) / (x.shape[0] * y.shape[0]))
86
+
87
+
88
+ def cramers_v(table: ArrayLike, *, bias_correction: bool = False) -> float:
89
+ """Cramér's V for an r × c contingency table: √(χ² / (n · (min(r, c) − 1))), from the uncorrected
90
+ Pearson χ². ``bias_correction=True`` applies Bergsma's correction, which reduces the upward bias in small
91
+ samples.
92
+
93
+ References: Cramér H. Mathematical Methods of Statistics. Princeton; 1946. Bergsma W. A bias-correction for
94
+ Cramér's V and Tschuprow's T. J Korean Stat Soc. 2013;42(3):323-328.
95
+ """
96
+ t = np.asarray(table, dtype=np.float64)
97
+ if t.ndim != 2 or min(t.shape) < 2:
98
+ raise InputValidationError("Give a contingency table with at least 2 rows and 2 columns.")
99
+ if np.any(~np.isfinite(t)) or np.any(t < 0):
100
+ raise InputValidationError("Contingency table counts must be finite and non-negative.")
101
+ if np.any(t.sum(axis=0) == 0) or np.any(t.sum(axis=1) == 0):
102
+ raise StatisticalTestError("Cramér's V is undefined when a row or column total is zero.")
103
+ n = t.sum()
104
+ rows, cols = t.sum(axis=1), t.sum(axis=0)
105
+ expected = np.outer(rows, cols) / n
106
+ dev = t - expected
107
+ chi2 = float(np.sum(dev * dev / expected)) # uncorrected Pearson χ², as scipy.stats.chi2_contingency
108
+ r, k = t.shape
109
+ if not bias_correction:
110
+ return float(np.sqrt(chi2 / (n * (min(r, k) - 1))))
111
+ if n < 2:
112
+ raise StatisticalTestError("The bias-corrected Cramér's V needs at least two observations.")
113
+ phi2 = max(0.0, chi2 / n - (k - 1) * (r - 1) / (n - 1))
114
+ rc = r - (r - 1) ** 2 / (n - 1)
115
+ kc = k - (k - 1) ** 2 / (n - 1)
116
+ denom = min(rc - 1, kc - 1)
117
+ if denom <= 0:
118
+ raise StatisticalTestError("The bias-corrected Cramér's V is undefined for this table size.")
119
+ return float(np.sqrt(phi2 / denom))
120
+
121
+
122
+ def adjust_pvalues(
123
+ p_values: ArrayLike, *, method: Literal["bonferroni", "holm", "hochberg", "bh", "by"] = "holm"
124
+ ) -> NDArray[np.float64]:
125
+ """Adjust p-values for multiple comparisons (same order as the input).
126
+
127
+ ``"holm"`` (default; controls the family-wise error rate, uniformly more powerful than Bonferroni),
128
+ ``"bonferroni"``, ``"hochberg"`` (step-up; controls the family-wise error rate under independence or
129
+ positive dependence, more powerful than Holm), ``"bh"`` (Benjamini-Hochberg false discovery rate) or
130
+ ``"by"`` (Benjamini-Yekutieli, FDR under arbitrary dependence).
131
+
132
+ References: Holm S. Scand J Stat. 1979;6(2):65-70. Hochberg Y. Biometrika. 1988;75(4):800-802.
133
+ Benjamini Y, Hochberg Y. J R Stat Soc B. 1995;57(1):289-300. Benjamini Y, Yekutieli D. Ann Stat.
134
+ 2001;29(4):1165-1188.
135
+ """
136
+ p = to_numpy(p_values, "p_values").astype(np.float64, copy=False)
137
+ check_finite(p, "p_values")
138
+ if float(np.min(p)) < 0 or float(np.max(p)) > 1:
139
+ raise InputValidationError("p-values must be between 0 and 1.")
140
+ m = p.shape[0]
141
+ if method == "bonferroni": # no ranking needed
142
+ bonf: NDArray[np.float64] = np.minimum(p * m, 1.0)
143
+ return bonf
144
+ order = np.argsort(p) # ties get the same adjusted value whatever their order
145
+ ranked = p[order]
146
+ if method == "holm":
147
+ adj = np.minimum(np.maximum.accumulate(ranked * (m - np.arange(m))), 1)
148
+ elif method == "hochberg":
149
+ scaled = ranked * (m - np.arange(m))
150
+ adj = np.minimum(np.minimum.accumulate(scaled[::-1])[::-1], 1)
151
+ elif method in ("bh", "by"):
152
+ factor = np.sum(1.0 / np.arange(1, m + 1)) if method == "by" else 1.0
153
+ scaled = ranked * m * factor / np.arange(1, m + 1)
154
+ adj = np.minimum(np.minimum.accumulate(scaled[::-1])[::-1], 1)
155
+ else:
156
+ raise InputValidationError("method must be 'holm', 'bonferroni', 'hochberg', 'bh' or 'by'.")
157
+ out = np.empty(m)
158
+ out[order] = adj
159
+ return out