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,5 @@
1
+ """Command-line interface: ``evalsuite --help``."""
2
+
3
+ from .main import main
4
+
5
+ __all__ = ["main"]
evalsuite/cli/main.py ADDED
@@ -0,0 +1,606 @@
1
+ """``evalsuite``: evaluate, compare, report, plot and benchmark from the command line.
2
+
3
+ Examples::
4
+
5
+ evalsuite evaluate predictions.csv --y-true label --y-pred pred --y-prob prob
6
+ evalsuite report predictions.csv --y-true label --y-pred pred --format markdown
7
+ evalsuite compare predictions.csv --y-true label --pred lr=pred_lr --pred rf=pred_rf \\
8
+ --prob lr=p_lr --prob rf=p_rf
9
+ evalsuite plot roc predictions.csv --y-true label --y-prob prob --output roc.png
10
+ evalsuite metrics --category regression
11
+ evalsuite info classification.mcc
12
+ evalsuite benchmark --quick
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ import argparse
18
+ import os
19
+ import sys
20
+ from collections.abc import Sequence
21
+ from typing import Any, Optional
22
+
23
+ from ..core.exceptions import EvalSuiteError
24
+ from ..version import __version__
25
+
26
+ FORMATS = ("text", "json", "csv", "markdown", "latex", "html")
27
+ _EXT = {
28
+ ".json": "json",
29
+ ".csv": "csv",
30
+ ".md": "markdown",
31
+ ".tex": "latex",
32
+ ".html": "html",
33
+ ".htm": "html",
34
+ ".txt": "text",
35
+ }
36
+
37
+
38
+ class CLIError(Exception):
39
+ """A user-facing error: printed without a traceback, exit code 2."""
40
+
41
+
42
+ # ---- input ---------------------------------------------------------------------------------------
43
+ def read_table(path: str) -> Any:
44
+ import pandas as pd
45
+
46
+ if path == "-":
47
+ return pd.read_csv(sys.stdin)
48
+ if not os.path.exists(path):
49
+ raise CLIError(f"File not found: {path}")
50
+ ext = os.path.splitext(path)[1].lower()
51
+ try:
52
+ if ext in (".tsv", ".tab"):
53
+ return pd.read_csv(path, sep="\t")
54
+ if ext == ".parquet":
55
+ return pd.read_parquet(path)
56
+ if ext in (".json", ".jsonl"):
57
+ return pd.read_json(path, lines=ext == ".jsonl")
58
+ return pd.read_csv(path)
59
+ except ImportError as exc:
60
+ raise CLIError(f"Reading {ext} files needs an extra package: {exc}") from exc
61
+ except Exception as exc:
62
+ raise CLIError(f"Could not read {path}: {exc}") from exc
63
+
64
+
65
+ def column(df: Any, name: str, role: str) -> Any:
66
+ if name not in df.columns:
67
+ raise CLIError(
68
+ f"Column '{name}' ({role}) not found. Columns in the file: {', '.join(map(str, df.columns))}."
69
+ )
70
+ return df[name].to_numpy()
71
+
72
+
73
+ def columns(df: Any, names: Sequence[str], role: str) -> Any:
74
+ import numpy as np
75
+
76
+ cols = [column(df, n, role) for n in names]
77
+ return cols[0] if len(cols) == 1 else np.column_stack(cols)
78
+
79
+
80
+ def pairs(items: Optional[Sequence[str]], flag: str) -> dict[str, list[str]]:
81
+ """``name=col`` or ``name=col1,col2,col3`` (multiclass probabilities) -> {name: [cols]}."""
82
+ out: dict[str, list[str]] = {}
83
+ for item in items or []:
84
+ name, sep, cols = item.partition("=")
85
+ if not sep or not name or not cols:
86
+ raise CLIError(f"{flag} expects NAME=COLUMN (or NAME=COL1,COL2,... for multiclass); got '{item}'.")
87
+ out[name] = [c for c in cols.split(",") if c]
88
+ return out
89
+
90
+
91
+ def metric_list(text: Optional[str]) -> Optional[list[str]]:
92
+ return [m.strip() for m in text.split(",") if m.strip()] if text else None
93
+
94
+
95
+ def label_value(text: Optional[str]) -> Any:
96
+ if text is None:
97
+ return None
98
+ try:
99
+ return int(text)
100
+ except ValueError:
101
+ return text
102
+
103
+
104
+ # ---- output --------------------------------------------------------------------------------------
105
+ def render(obj: Any, fmt: str, digits: int) -> str:
106
+ if fmt == "text":
107
+ return obj.summary(digits=digits) if hasattr(obj, "summary") else str(obj)
108
+ if fmt == "json":
109
+ return str(obj.to_json())
110
+ if fmt == "csv":
111
+ return str(obj.to_csv())
112
+ if fmt == "markdown":
113
+ return str(obj.to_markdown(digits=digits))
114
+ if fmt == "latex":
115
+ return str(obj.to_latex(digits=digits))
116
+ return str(obj.to_html(digits=digits, full=True))
117
+
118
+
119
+ def emit(obj: Any, args: argparse.Namespace) -> None:
120
+ fmt = args.format
121
+ if fmt is None:
122
+ fmt = _EXT.get(os.path.splitext(args.output)[1].lower(), "text") if args.output else "text"
123
+ text = render(obj, fmt, args.digits)
124
+ if not text.endswith("\n"):
125
+ text += "\n"
126
+ if args.output:
127
+ with open(args.output, "w", encoding="utf-8", newline="") as fh:
128
+ fh.write(text)
129
+ print(f"Wrote {fmt} to {args.output}", file=sys.stderr)
130
+ else:
131
+ sys.stdout.write(text)
132
+
133
+
134
+ def add_output(p: argparse.ArgumentParser, digits: int = 4) -> None:
135
+ p.add_argument(
136
+ "--format",
137
+ "-f",
138
+ choices=FORMATS,
139
+ default=None,
140
+ help="output format (default: from --output extension, else text)",
141
+ )
142
+ p.add_argument("--output", "-o", help="write to this file instead of standard output")
143
+ p.add_argument("--digits", type=int, default=digits, help=f"decimal places (default {digits})")
144
+
145
+
146
+ def add_targets(p: argparse.ArgumentParser, pred_required: bool = False) -> None:
147
+ p.add_argument(
148
+ "file", help="CSV/TSV/Parquet/JSON file with one row per observation ('-' reads CSV from stdin)"
149
+ )
150
+ p.add_argument("--y-true", required=True, metavar="COL", help="column with the true labels or values")
151
+ p.add_argument(
152
+ "--y-pred", required=pred_required, metavar="COL", help="column with predicted labels or values"
153
+ )
154
+ p.add_argument(
155
+ "--y-prob",
156
+ nargs="+",
157
+ metavar="COL",
158
+ help="probability column(s): one for P(positive), or one per class in label order",
159
+ )
160
+ p.add_argument("--weight", metavar="COL", help="column with sample weights")
161
+
162
+
163
+ # ---- commands ------------------------------------------------------------------------------------
164
+ def cmd_evaluate(args: argparse.Namespace) -> int:
165
+ import evalsuite as es
166
+
167
+ df = read_table(args.file)
168
+ if not args.y_pred and not args.y_prob:
169
+ raise CLIError("Give --y-pred, --y-prob, or both.")
170
+ result = es.evaluate(
171
+ column(df, args.y_true, "--y-true"),
172
+ column(df, args.y_pred, "--y-pred") if args.y_pred else None,
173
+ y_prob=columns(df, args.y_prob, "--y-prob") if args.y_prob else None,
174
+ task=args.task,
175
+ metrics=metric_list(args.metrics),
176
+ average=args.average,
177
+ pos_label=label_value(args.pos_label),
178
+ sample_weight=column(df, args.weight, "--weight") if args.weight else None,
179
+ )
180
+ emit(result, args)
181
+ return 0
182
+
183
+
184
+ def cmd_report(args: argparse.Namespace) -> int:
185
+ import evalsuite as es
186
+
187
+ df = read_table(args.file)
188
+ report = es.classification_report(
189
+ column(df, args.y_true, "--y-true"),
190
+ column(df, args.y_pred, "--y-pred"),
191
+ sample_weight=column(df, args.weight, "--weight") if args.weight else None,
192
+ )
193
+ emit(report, args)
194
+ return 0
195
+
196
+
197
+ def cmd_diagnostic(args: argparse.Namespace) -> int:
198
+ import evalsuite as es
199
+
200
+ df = read_table(args.file)
201
+ report = es.diagnostic_report(
202
+ column(df, args.y_true, "--y-true"),
203
+ column(df, args.y_pred, "--y-pred"),
204
+ pos_label=label_value(args.pos_label),
205
+ level=args.level,
206
+ )
207
+ emit(report, args)
208
+ return 0
209
+
210
+
211
+ def cmd_calibration(args: argparse.Namespace) -> int:
212
+ import evalsuite as es
213
+
214
+ df = read_table(args.file)
215
+ if not args.y_prob or len(args.y_prob) != 1:
216
+ raise CLIError("calibration needs exactly one --y-prob column (predicted risk of the positive class).")
217
+ report = es.calibration_report(
218
+ column(df, args.y_true, "--y-true"),
219
+ column(df, args.y_prob[0], "--y-prob"),
220
+ n_bins=args.bins,
221
+ strategy=args.strategy,
222
+ n_groups=args.groups,
223
+ pos_label=label_value(args.pos_label),
224
+ )
225
+ emit(report, args)
226
+ return 0
227
+
228
+
229
+ def read_masks(path: str, name: str) -> Any:
230
+ """Masks from .npy / .npz (first array, or the array named like the file stem) or a folder of image
231
+ files (PNG, TIFF, ...; read with Pillow, sorted by file name)."""
232
+ import numpy as np
233
+
234
+ if not os.path.exists(path):
235
+ raise CLIError(f"{name}: no such file or folder: {path}")
236
+ if os.path.isdir(path):
237
+ try:
238
+ from PIL import Image
239
+ except ImportError as exc:
240
+ raise CLIError(f"{name}: reading image folders needs Pillow (pip install pillow).") from exc
241
+ files = sorted(
242
+ f for f in os.listdir(path) if f.lower().endswith((".png", ".tif", ".tiff", ".bmp", ".gif", ".jpg"))
243
+ )
244
+ if not files:
245
+ raise CLIError(f"{name}: no image files in {path}.")
246
+ return [np.asarray(Image.open(os.path.join(path, f))) for f in files]
247
+ ext = os.path.splitext(path)[1].lower()
248
+ if ext == ".npy":
249
+ return np.load(path, allow_pickle=False)
250
+ if ext == ".npz":
251
+ with np.load(path, allow_pickle=False) as data:
252
+ if not data.files:
253
+ raise CLIError(f"{name}: {path} contains no arrays.")
254
+ return data[data.files[0]]
255
+ raise CLIError(f"{name}: use a .npy or .npz file, or a folder of mask images.")
256
+
257
+
258
+ def cmd_segmentation(args: argparse.Namespace) -> int:
259
+ import evalsuite as es
260
+
261
+ spacing = tuple(float(x) for x in args.spacing.split(",")) if args.spacing else None
262
+ report = es.segmentation_report(
263
+ read_masks(args.y_true, "y_true"),
264
+ read_masks(args.y_pred, "y_pred"),
265
+ num_classes=args.num_classes,
266
+ ignore_index=args.ignore_index,
267
+ spacing=spacing,
268
+ aggregate=args.aggregate,
269
+ include_background=not args.no_background,
270
+ )
271
+ emit(report, args)
272
+ if args.plot:
273
+ _save_figure(lambda ax: es.plot.per_class(_report_iou(report), ax=ax), args.plot)
274
+ return 0
275
+
276
+
277
+ def _report_iou(report: Any) -> Any:
278
+ import numpy as np
279
+
280
+ from ..core.result import MetricResult
281
+
282
+ return MetricResult(
283
+ "iou", "IoU", np.array([r["iou"] for r in report.rows]), labels=tuple(r["name"] for r in report.rows)
284
+ )
285
+
286
+
287
+ def cmd_detection(args: argparse.Namespace) -> int:
288
+ import evalsuite as es
289
+
290
+ y_true, y_pred = es.from_coco(args.ground_truth, args.results)
291
+ report = es.detection_report(y_true, y_pred, box_format="xywh", max_detections=args.max_detections)
292
+ emit(report, args)
293
+ if args.plot:
294
+ _save_figure(
295
+ lambda ax: es.plot.detection_pr(y_true, y_pred, ax=ax, box_format="xywh", iou_threshold=0.5), args.plot
296
+ )
297
+ return 0
298
+
299
+
300
+ def cmd_text(args: argparse.Namespace) -> int:
301
+ import evalsuite as es
302
+
303
+ df = read_table(args.file)
304
+ preds = [str(v) for v in column(df, args.prediction, "--prediction")]
305
+ ref_cols = [column(df, c, "--reference") for c in args.reference]
306
+ refs = [[str(col[i]) for col in ref_cols if not _missing(col[i])] for i in range(len(preds))]
307
+ if any(not r for r in refs):
308
+ raise CLIError("Every row needs at least one non-empty reference.")
309
+ report = es.text_report(refs, preds, metrics=metric_list(args.metrics))
310
+ emit(report, args)
311
+ return 0
312
+
313
+
314
+ def _missing(v: Any) -> bool:
315
+ return v is None or (isinstance(v, float) and v != v) or (isinstance(v, str) and not v.strip())
316
+
317
+
318
+ def cmd_compare(args: argparse.Namespace) -> int:
319
+ import evalsuite as es
320
+
321
+ df = read_table(args.file)
322
+ preds = {k: columns(df, v, "--pred") for k, v in pairs(args.pred, "--pred").items()}
323
+ probs = {k: columns(df, v, "--prob") for k, v in pairs(args.prob, "--prob").items()}
324
+ if len(set(preds) | set(probs)) < 2:
325
+ raise CLIError(
326
+ "compare needs at least two models: --pred NAME=COL (and/or --prob NAME=COL), twice or more."
327
+ )
328
+ result = es.compare(
329
+ column(df, args.y_true, "--y-true"),
330
+ preds or None,
331
+ probabilities=probs or None,
332
+ metrics=metric_list(args.metrics),
333
+ baseline=args.baseline,
334
+ level=args.level,
335
+ alpha=args.alpha,
336
+ n_resamples=args.resamples,
337
+ correction=args.correction,
338
+ random_state=args.seed,
339
+ )
340
+ emit(result, args)
341
+ if args.plot:
342
+ _save_figure(lambda ax: es.plot.comparison(result, ax=ax), args.plot)
343
+ return 0
344
+
345
+
346
+ def _save_figure(draw: Any, path: str) -> None:
347
+ from ..plot import _plt
348
+
349
+ plt = _plt()
350
+ fig, ax = plt.subplots(figsize=(5.5, 4.4), layout="constrained")
351
+ draw(ax)
352
+ fig.savefig(path, dpi=200)
353
+ plt.close(fig)
354
+ print(f"Wrote figure to {path}", file=sys.stderr)
355
+
356
+
357
+ def cmd_plot(args: argparse.Namespace) -> int:
358
+ import evalsuite as es
359
+
360
+ df = read_table(args.file)
361
+ y = column(df, args.y_true, "--y-true")
362
+ kind = args.kind
363
+ if kind in ("roc", "pr", "calibration", "decision"):
364
+ if not args.y_prob:
365
+ raise CLIError(f"'{kind}' needs --y-prob.")
366
+ prob = columns(df, args.y_prob, "--y-prob")
367
+ fn: Any = {
368
+ "roc": es.plot.roc,
369
+ "pr": es.plot.pr,
370
+ "calibration": es.plot.calibration,
371
+ "decision": es.plot.decision_curve,
372
+ }[kind]
373
+ _save_figure(lambda ax: fn(y, prob, ax=ax), args.output)
374
+ else:
375
+ if not args.y_pred:
376
+ raise CLIError(f"'{kind}' needs --y-pred.")
377
+ pred = column(df, args.y_pred, "--y-pred")
378
+ if kind == "confusion":
379
+ _save_figure(
380
+ lambda ax: es.plot.confusion_matrix(y, pred, ax=ax, normalize=args.normalize), args.output
381
+ )
382
+ else:
383
+ _save_figure(
384
+ lambda ax: es.plot.residuals(
385
+ y, pred, ax=ax, kind="predicted" if kind == "predicted" else "residuals"
386
+ ),
387
+ args.output,
388
+ )
389
+ return 0
390
+
391
+
392
+ def cmd_metrics(args: argparse.Namespace) -> int:
393
+ import evalsuite as es
394
+
395
+ for mid in es.list_metrics(args.category):
396
+ info = es.metric_info(mid)
397
+ print(f"{mid:<45} {info.name}")
398
+ return 0
399
+
400
+
401
+ def cmd_info(args: argparse.Namespace) -> int:
402
+ import evalsuite as es
403
+
404
+ try:
405
+ info = es.metric_info(args.metric)
406
+ except KeyError as exc:
407
+ raise CLIError(str(exc).strip("'\"")) from exc
408
+ better = {True: "higher is better", False: "lower is better", None: "closer to 0 is better"}
409
+ print(f"{info.name} ({info.id})\n")
410
+ print(f"Definition: {info.definition}")
411
+ print(f"Formula: {info.formula}")
412
+ print(f"Range: {info.range} ({better[info.higher_is_better]})")
413
+ print(f"Task: {info.task}")
414
+ print(f"Needs: {', '.join(info.input_requirements)}")
415
+ print(f"Python: es.{info.id.split('.')[-1]}(...)")
416
+ print("References:")
417
+ for ref in info.references:
418
+ print(f" - {ref}")
419
+ return 0
420
+
421
+
422
+ def cmd_benchmark(args: argparse.Namespace) -> int:
423
+ from ..benchmarks import run_benchmarks
424
+
425
+ sizes = (1_000, 10_000) if args.quick else tuple(args.sizes)
426
+ result = run_benchmarks(
427
+ sizes=sizes,
428
+ repeat=args.repeat,
429
+ compare_sklearn=not args.no_sklearn,
430
+ random_state=args.seed,
431
+ suite=args.suite,
432
+ )
433
+ emit(result, args)
434
+ return 0
435
+
436
+
437
+ # ---- parser --------------------------------------------------------------------------------------
438
+ def build_parser() -> argparse.ArgumentParser:
439
+ parser = argparse.ArgumentParser(
440
+ prog="evalsuite",
441
+ description="EvalSuite: unified, reproducible evaluation for machine learning and research.",
442
+ epilog="Run 'evalsuite COMMAND --help' for the options of each command.",
443
+ )
444
+ parser.add_argument("--version", action="version", version=f"evalsuite-python {__version__}")
445
+ sub = parser.add_subparsers(dest="command", metavar="COMMAND")
446
+
447
+ p = sub.add_parser("evaluate", help="evaluate predictions in a file with a standard or chosen set of metrics")
448
+ add_targets(p)
449
+ p.add_argument("--task", choices=("classification", "regression"), help="default: inferred from the data")
450
+ p.add_argument("--metrics", help="comma-separated metric names, e.g. accuracy,f1,mcc")
451
+ p.add_argument("--average", default="auto", help="binary, micro, macro, weighted, samples (default: auto)")
452
+ p.add_argument("--pos-label", help="positive class for binary metrics (default: 1)")
453
+ add_output(p)
454
+ p.set_defaults(func=cmd_evaluate)
455
+
456
+ p = sub.add_parser(
457
+ "report", help="per-class classification report (precision, recall, F1, specificity, support)"
458
+ )
459
+ add_targets(p, pred_required=True)
460
+ add_output(p)
461
+ p.set_defaults(func=cmd_report)
462
+
463
+ p = sub.add_parser("compare", help="compare models on the same test set with CIs and paired tests")
464
+ p.add_argument("file", help="CSV/TSV/Parquet/JSON file with one row per observation")
465
+ p.add_argument("--y-true", required=True, metavar="COL")
466
+ p.add_argument("--pred", action="append", metavar="NAME=COL", help="a model's predictions (repeat per model)")
467
+ p.add_argument(
468
+ "--prob", action="append", metavar="NAME=COL[,COL...]", help="a model's probabilities (repeat per model)"
469
+ )
470
+ p.add_argument("--metrics", help="comma-separated metric names")
471
+ p.add_argument("--baseline", help="compare every model with this one instead of all pairs")
472
+ p.add_argument("--level", type=float, default=0.95, help="confidence level (default 0.95)")
473
+ p.add_argument("--alpha", type=float, default=0.05, help="significance level (default 0.05)")
474
+ p.add_argument("--resamples", type=int, default=1000, help="bootstrap resamples (default 1000)")
475
+ p.add_argument("--correction", default="holm", choices=("holm", "bonferroni", "hochberg", "bh", "by"))
476
+ p.add_argument("--seed", type=int, default=0, help="random seed (default 0, for reproducibility)")
477
+ p.add_argument("--plot", metavar="PATH", help="also save a forest plot (needs matplotlib)")
478
+ add_output(p, digits=3)
479
+ p.set_defaults(func=cmd_compare)
480
+
481
+ p = sub.add_parser(
482
+ "diagnostic",
483
+ help="diagnostic accuracy of a binary test: sensitivity, specificity, PPV, NPV, LR+, LR−, DOR with CIs",
484
+ )
485
+ add_targets(p, pred_required=True)
486
+ p.add_argument("--pos-label", help="positive class (default: 1)")
487
+ p.add_argument("--level", type=float, default=0.95, help="confidence level (default 0.95)")
488
+ add_output(p, digits=3)
489
+ p.set_defaults(func=cmd_diagnostic)
490
+
491
+ p = sub.add_parser(
492
+ "calibration", help="calibration of predicted risks: Brier, ECE, MCE, intercept, slope, Hosmer–Lemeshow"
493
+ )
494
+ add_targets(p)
495
+ p.add_argument("--bins", type=int, default=10, help="bins for the calibration curve, ECE and MCE")
496
+ p.add_argument("--strategy", choices=("uniform", "quantile"), default="uniform")
497
+ p.add_argument("--groups", type=int, default=10, help="Hosmer–Lemeshow risk groups (default 10)")
498
+ p.add_argument("--pos-label", help="positive class (default: 1)")
499
+ add_output(p)
500
+ p.set_defaults(func=cmd_calibration)
501
+
502
+ p = sub.add_parser(
503
+ "segmentation",
504
+ help="segmentation masks: Dice, IoU, mIoU, Boundary IoU, HD95, ASSD per class",
505
+ )
506
+ p.add_argument("y_true", help="true masks: .npy/.npz (images on the first axis) or a folder of mask images")
507
+ p.add_argument("y_pred", help="predicted masks, same layout as y_true")
508
+ p.add_argument("--num-classes", type=int, help="number of classes (default: largest label + 1)")
509
+ p.add_argument("--ignore-index", type=int, help="label to ignore, e.g. 255")
510
+ p.add_argument("--spacing", help="pixel spacing per axis for surface distances, e.g. 0.8,0.8")
511
+ p.add_argument("--aggregate", choices=("dataset", "image"), default="dataset")
512
+ p.add_argument("--no-background", action="store_true", help="leave class 0 out")
513
+ p.add_argument("--plot", metavar="PATH", help="also save a per-class IoU bar chart")
514
+ add_output(p)
515
+ p.set_defaults(func=cmd_segmentation)
516
+
517
+ p = sub.add_parser(
518
+ "detection", help="object detection, COCO protocol: mAP, mAP@.50, mAP@.75, mAR, AP per class"
519
+ )
520
+ p.add_argument("ground_truth", help="COCO ground-truth JSON (images, annotations, categories)")
521
+ p.add_argument("results", help="COCO results JSON (image_id, category_id, bbox, score)")
522
+ p.add_argument("--max-detections", type=int, default=100)
523
+ p.add_argument("--plot", metavar="PATH", help="also save precision-recall curves per class (IoU 0.5)")
524
+ add_output(p, digits=3)
525
+ p.set_defaults(func=cmd_detection)
526
+
527
+ p = sub.add_parser(
528
+ "text", help="text generation: BLEU, chrF, chrF++, TER, ROUGE, METEOR, exact match, token F1"
529
+ )
530
+ p.add_argument("file", help="CSV, TSV, Parquet or JSON-lines file with one example per row ('-' for stdin)")
531
+ p.add_argument("--prediction", required=True, help="column with the model output")
532
+ p.add_argument(
533
+ "--reference", required=True, action="append", help="column with a reference (repeat for several)"
534
+ )
535
+ p.add_argument("--metrics", help="comma-separated subset, e.g. bleu,chrf,rouge_l")
536
+ add_output(p)
537
+ p.set_defaults(func=cmd_text)
538
+
539
+ p = sub.add_parser(
540
+ "plot", help="save a ROC, PR, calibration, decision-curve, confusion-matrix or residual plot"
541
+ )
542
+ p.add_argument("kind", choices=("roc", "pr", "calibration", "decision", "confusion", "residuals", "predicted"))
543
+ add_targets(p)
544
+ p.add_argument("--normalize", choices=("true", "pred", "all"), help="confusion matrix normalisation")
545
+ p.add_argument("--output", "-o", required=True, help="image file (.png, .pdf, .svg)")
546
+ p.set_defaults(func=cmd_plot)
547
+
548
+ p = sub.add_parser("metrics", help="list available metrics")
549
+ p.add_argument("--category", choices=("classification", "regression", "clinical", "calibration"))
550
+ p.set_defaults(func=cmd_metrics)
551
+
552
+ p = sub.add_parser("info", help="show a metric's definition, formula, range and references")
553
+ p.add_argument("metric", help="metric id, e.g. classification.mcc")
554
+ p.set_defaults(func=cmd_info)
555
+
556
+ p = sub.add_parser("benchmark", help="time and memory benchmarks (against scikit-learn if installed)")
557
+ p.add_argument("--sizes", type=int, nargs="+", default=[1_000, 100_000, 1_000_000])
558
+ p.add_argument("--quick", action="store_true", help="small sizes only (1k and 10k)")
559
+ p.add_argument("--repeat", type=int, default=5, help="timed repetitions per case; the fastest is reported")
560
+ p.add_argument(
561
+ "--suite",
562
+ choices=("all", "core", "clinical", "vision", "llm", "llmsys", "metrics"),
563
+ default="all",
564
+ help="core: classification/regression; clinical: clinical, calibration, tests; vision: segmentation, "
565
+ "detection; llm: text, retrieval, agreement, structured output; llmsys: v0.5.0 LLM systems; "
566
+ "metrics: one row per metric and statistics function (default all)",
567
+ )
568
+ p.add_argument("--no-sklearn", action="store_true", help="time EvalSuite only (skip reference libraries)")
569
+ p.add_argument("--seed", type=int, default=0)
570
+ add_output(p, digits=3)
571
+ p.set_defaults(func=cmd_benchmark)
572
+ return parser
573
+
574
+
575
+ def _unicode_safe_streams() -> None:
576
+ """Results contain characters such as −, χ², ≥ and ×. On a stream whose encoding cannot represent them
577
+ (for example cp1252 when output is piped on Windows), write UTF-8 to files and pipes, and replace
578
+ unrepresentable characters on interactive consoles, instead of failing."""
579
+ for stream in (sys.stdout, sys.stderr):
580
+ encoding = (getattr(stream, "encoding", None) or "").lower().replace("-", "").replace("_", "")
581
+ reconfigure = getattr(stream, "reconfigure", None)
582
+ if encoding == "utf8" or reconfigure is None:
583
+ continue
584
+ try:
585
+ if stream.isatty():
586
+ reconfigure(errors="replace")
587
+ else:
588
+ reconfigure(encoding="utf-8")
589
+ except (OSError, ValueError): # pragma: no cover - exotic streams
590
+ pass
591
+
592
+
593
+ def main(argv: Optional[Sequence[str]] = None) -> int:
594
+ _unicode_safe_streams()
595
+ parser = build_parser()
596
+ args = parser.parse_args(argv)
597
+ if not getattr(args, "command", None):
598
+ parser.print_help()
599
+ return 0
600
+ try:
601
+ return int(args.func(args))
602
+ except (CLIError, EvalSuiteError, ValueError) as exc:
603
+ print(f"evalsuite {args.command}: error: {exc}", file=sys.stderr)
604
+ return 2
605
+ except BrokenPipeError: # e.g. piped into `head`
606
+ return 0
@@ -0,0 +1,18 @@
1
+ """Clinical evaluation: diagnostic accuracy measures with confidence intervals, and decision curve analysis."""
2
+
3
+ from .metrics import diagnostic_odds_ratio, lr_negative, lr_positive, net_benefit, ppv, sensitivity, youden_j
4
+ from .report import DecisionCurve, DiagnosticReport, decision_curve, diagnostic_report
5
+
6
+ __all__ = [
7
+ "DecisionCurve",
8
+ "DiagnosticReport",
9
+ "decision_curve",
10
+ "diagnostic_odds_ratio",
11
+ "diagnostic_report",
12
+ "lr_negative",
13
+ "lr_positive",
14
+ "net_benefit",
15
+ "ppv",
16
+ "sensitivity",
17
+ "youden_j",
18
+ ]