From 1bac196fd07db562d6b29c0925fecb93aa69561d Mon Sep 17 00:00:00 2001 From: eranario Date: Mon, 23 Nov 2026 13:23:41 -0800 Subject: [PATCH] agbench.viz: paper figures and a self-contained HTML report for any runs - viz.aggregate: runs grouped into entries (seed replicates), per-dataset mean, macro over datasets, 95% bootstrap CI; YOLO top-1 and chance handled as in the paper; reproduces all 183 main/ag-task/fuzzy/YOLO numbers in numbers.json - viz.figures: fig_main_results and fig_agtask (matplotlib, uv sync --extra viz), CVD-checked palette - viz.html: one offline file (inlined data, SVG charts, hover, light/dark): overview, ag tasks, datasets, runs - agbench eval report --html / --figures / --label / --title Co-Authored-By: Claude Opus 5.5 --- README.md | 3 + pyproject.toml | 2 + src/agbench/eval/cli.py | 20 +- src/agbench/viz/__init__.py | 0 src/agbench/viz/aggregate.py | 170 +++++++++++++++++ src/agbench/viz/figures.py | 132 +++++++++++++ src/agbench/viz/html.py | 349 +++++++++++++++++++++++++++++++++++ tests/test_viz.py | 69 +++++++ uv.lock | 6 +- 9 files changed, 749 insertions(+), 2 deletions(-) create mode 100644 src/agbench/viz/__init__.py create mode 100644 src/agbench/viz/aggregate.py create mode 100644 src/agbench/viz/figures.py create mode 100644 src/agbench/viz/html.py create mode 100644 tests/test_viz.py diff --git a/README.md b/README.md index 5ceef5a..529999d 100644 --- a/README.md +++ b/README.md @@ -105,6 +105,9 @@ uv run agbench eval judge --run runs/ uv run agbench eval judge --run runs/ --judge-model gpt-5-mini --judge-endpoint https://api.openai.com/v1 --judge-api-key-env OPENAI_API_KEY # not comparable uv run agbench eval report --runs runs uv run agbench eval report --runs runs --csv reports/scores # scores.csv, ag_tasks.csv, datasets.csv +uv run agbench eval report --runs runs --html reports/report.html # charts, tables, runs; one offline file +uv sync --extra viz && uv run agbench eval report --runs runs --figures reports/figures # paper figures (PNG) +uv run agbench eval report --runs runs --html reports/report.html --label "my-org/My-VLM=My VLM" --label "baseline/chance=Chance" uv run agbench eval stats --runs runs --out reports/stats uv run agbench eval view --runs runs # http://localhost:8502 ``` diff --git a/pyproject.toml b/pyproject.toml index 9a14817..df53bcb 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -32,6 +32,8 @@ dependencies = [ [project.optional-dependencies] # Few-shot YOLO11 baselines (agbench eval yolo) yolo = ["ultralytics>=8.3.0"] +# PNG figures (agbench eval report --figures) +viz = ["matplotlib>=3.11"] [project.scripts] agbench = "agbench.cli:app" diff --git a/src/agbench/eval/cli.py b/src/agbench/eval/cli.py index 4be4483..892577b 100644 --- a/src/agbench/eval/cli.py +++ b/src/agbench/eval/cli.py @@ -599,8 +599,13 @@ def report( average: str = typer.Option("macro", "--average", help="macro | micro"), out: Path = typer.Option(None, "--out", help="Write the leaderboard markdown here."), csv: Path = typer.Option(None, "--csv", help="Write scores.csv (per task), ag_tasks.csv and datasets.csv to this dir."), + html: Path = typer.Option(None, "--html", help="Write a self-contained HTML report (charts, tables, runs)."), + figures: Path = typer.Option(None, "--figures", help="Write the paper's figures as PNG to this dir (uv sync --extra viz)."), + label: list[str] = typer.Option(None, "--label", help="Display name: METHOD_NAME=LABEL (repeatable)."), + title: str = typer.Option("AgML benchmark results", "--title", help="HTML report title."), ): - """Leaderboard across runs.""" + """Leaderboard across runs. --html and --figures group repeated runs of a setting (sampling seeds) and aggregate + them as in the paper: per-dataset mean, macro over datasets, 95% bootstrap CI.""" from agbench.eval.report import leaderboard_md, load_runs, write_csv rs = load_runs(runs) @@ -610,6 +615,19 @@ def report( out.write_text(md) if csv: typer.echo(f"csv: {write_csv(rs, csv)}") + if html or figures: + from agbench.viz.aggregate import entries + + labels = dict(x.split("=", 1) for x in label or []) + es = entries(runs, labels) + if html: + from agbench.viz.html import write + + typer.echo(f"html: {write(es, html, title)}") + if figures: + from agbench.viz.figures import agtask, main_results + + typer.echo(f"figures: {main_results(es, figures / 'fig_main_results.png')}, {agtask(es, figures / 'fig_agtask.png')}") @app.command() diff --git a/src/agbench/viz/__init__.py b/src/agbench/viz/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/src/agbench/viz/aggregate.py b/src/agbench/viz/aggregate.py new file mode 100644 index 0000000..7b31aa0 --- /dev/null +++ b/src/agbench/viz/aggregate.py @@ -0,0 +1,170 @@ +"""Scores for charts and reports, aggregated as in the paper. + +Per run, an item's score is the judge verdict for an open-ended answer and its graded score otherwise (accuracy for +boxes). Scores are averaged per dataset; repeated runs of one entry (sampling seeds, YOLO training subsets, chance +seeds) are averaged per dataset; the entry's score is the macro mean over datasets, with a 95% bootstrap CI over +datasets. + +An entry is one method with one setting: runs that differ only in their sampling seed are its replicates. Chance +baselines (baseline/chance) become reference lines; YOLO runs (method name yolo*) score classification by top-1 +accuracy, the same value in every classification format. +""" + +import json +import random +from collections import defaultdict +from dataclasses import dataclass, field +from pathlib import Path + +import numpy as np + +COLS = [("mcqa_across", "MCQA across"), ("mcqa_within", "MCQA within"), ("oeq", "OEQ"), ("itt", "VQA"), + ("detection", "Detection"), ("segmentation", "Segmentation")] +AG = [("disease", "Disease"), ("pest_damage", "Pest/Damage"), ("species_id", "Species"), ("quality_maturity", "Quality")] +CLS_FORMATS = [("mcqa_across", "MCQA across"), ("mcqa_within", "MCQA within"), ("oeq", "OEQ (judged)")] + + +def column(p: dict) -> str: + if p["task"] == "classification": + return p["format"] + return "itt" if p["task"] == "image_text_to_text" else p["task"] + + +def item_score(p: dict) -> float: + if p.get("needs_judge"): + return 1.0 if p.get("judge_correct") else 0.0 + c = p.get("correct") + if isinstance(c, bool): + return 1.0 if c else 0.0 + return float(p.get("acc", c) or 0.0) + + +def _mean(v): + return sum(v) / len(v) if len(v) else float("nan") + + +def boot_ci(vals, B: int = 10000, seed: int = 0, exact: bool = False) -> tuple[float, float]: + """95% bootstrap CI of the mean. `exact`: the paper's pure-Python resampling (same numbers, slower).""" + if not len(vals): + return float("nan"), float("nan") + if exact: + rnd, n = random.Random(seed), len(vals) + ms = sorted(sum(rnd.choice(vals) for _ in range(n)) / n for _ in range(B)) + return ms[int(0.025 * B)], ms[int(0.975 * B) - 1] + v = np.asarray(vals, float) + ms = np.sort(v[np.random.default_rng(seed).integers(0, len(v), (B, len(v)))].mean(1)) + return float(ms[int(0.025 * B)]), float(ms[int(0.975 * B) - 1]) + + +@dataclass +class RunScores: + """Per-dataset mean scores of one run.""" + dir: str + per: dict = field(default_factory=dict) # (col, dataset) -> mean score + ag: dict = field(default_factory=dict) # (format, ag_task, dataset) -> mean score (classification) + fuzzy: dict = field(default_factory=dict) # (ag_task, dataset) -> mean fuzzy-match score (OEQ) + itt_fmt: dict = field(default_factory=dict) # qa_format -> pooled mean over questions + pending_judge: int = 0 + + @classmethod + def load(cls, run_dir) -> "RunScores": + per, ag, fz, itt = (defaultdict(list) for _ in range(4)) + pending = 0 + with open(Path(run_dir) / "predictions.jsonl") as f: + for line in f: + p = json.loads(line) + s, k = item_score(p), column(p) + pending += bool(p.get("needs_judge") and p.get("judge_correct") is None) + per[(k, p["dataset"])].append(s) + if p["task"] == "classification": + ag[(k, p.get("ag_task"), p["dataset"])].append(s) + if k == "oeq": + fz[(p.get("ag_task"), p["dataset"])].append(1.0 if p.get("correct") else 0.0) + elif p["task"] == "image_text_to_text": + itt[p.get("qa_format")].append(s) + m = lambda d: {k: _mean(v) for k, v in d.items()} # noqa: E731 + return cls(str(run_dir), m(per), m(ag), m(fz), m(itt), pending) + + +@dataclass +class Entry: + label: str + kind: str # model | yolo | chance + runs: list[RunScores] + meta: list[dict] # run_manifest.json (or run.json) of each run + cells: dict = field(default_factory=dict) # col -> (mean, lo, hi, n datasets), percent + ag: dict = field(default_factory=dict) # (format, ag_task) -> (mean, lo, hi, n) + fuzzy: dict = field(default_factory=dict) # ag_task -> mean, percent + itt_fmt: dict = field(default_factory=dict) # qa_format -> mean, percent + datasets: dict = field(default_factory=dict) # (col, dataset) -> mean over replicates, percent + + @property + def replicates(self) -> int: + return len(self.runs) + + +def _cell(runs: list[RunScores], key_of, exact: bool) -> tuple: + keys = sorted({k for r in runs for k in key_of(r)}) + vals = [100 * _mean([key_of(r)[k] for r in runs if k in key_of(r)]) for k in keys] + return (_mean(vals), *boot_ci(vals, exact=exact), len(vals)) if vals else (float("nan"),) * 3 + (0,) + + +def _meta(d: Path) -> dict: + for f in ("run_manifest.json", "run.json"): + if (d / f).exists(): + return json.loads((d / f).read_text()) + return {} + + +def _setting(meta: dict) -> tuple: + """What makes runs one entry: the method and its settings, minus the sampling seed.""" + m = dict(meta.get("method") or {}) + m.pop("gen_seed", None) + m["body"] = {k: v for k, v in (m.get("body") or {}).items() if k != "seed"} + args = meta.get("benchmark") if "item_seed" not in meta else {"seed": meta.get("item_seed"), "mcqa": meta.get("mcqa")} + args = args or {} + return json.dumps(m, sort_keys=True, default=str), json.dumps({"seed": args.get("seed"), "mcqa": args.get("mcqa")}, sort_keys=True) + + +def run_dirs(paths) -> list[Path]: + out = [] + for p in map(Path, paths): + dirs = [p] if (p / "predictions.jsonl").exists() else sorted(d.parent for d in p.glob("**/predictions.jsonl")) + out += [d for d in dirs if (d / "run.json").exists()] + return out + + +def entries(paths, labels: dict | None = None, exact: bool = False) -> list[Entry]: + """Group the runs under `paths` into entries and aggregate them. `labels`: {method name: display label}.""" + groups: dict[tuple, list[Path]] = defaultdict(list) + for d in run_dirs(paths): + meta = _meta(d) + groups[(str((meta.get("method") or {}).get("name", d.name)), *_setting(meta))].append(d) + names = defaultdict(list) + for key in groups: + names[key[0]].append(key) + out = [] + for key, dirs in groups.items(): + name = key[0] + kind = "chance" if name == "baseline/chance" else "yolo" if name.lower().startswith("yolo") else "model" + label = (labels or {}).get(name, name.split("/")[-1] if kind == "model" else name) + if len(names[name]) > 1: # one method in several settings + label += f" [{names[name].index(key) + 1}]" + runs = [RunScores.load(d) for d in dirs] + e = Entry(label, kind, runs, [_meta(d) for d in dirs]) + for col, _ in COLS: + src = "oeq" if kind == "yolo" and col in ("mcqa_across", "mcqa_within") else col + e.cells[col] = _cell(runs, lambda r, s=src: {d: v for (c, d), v in r.per.items() if c == s}, exact) + for f, _ in CLS_FORMATS: + for a, _ in AG: + src = "oeq" if kind == "yolo" else f + e.ag[(f, a)] = _cell(runs, lambda r, s=src, a=a: {d: v for (c, g, d), v in r.ag.items() if c == s and g == a}, exact) + for a, _ in AG: + e.fuzzy[a] = _cell(runs, lambda r, a=a: {d: v for (g, d), v in r.fuzzy.items() if g == a}, exact)[0] + for q in sorted({q for r in runs for q in r.itt_fmt}): + e.itt_fmt[q] = 100 * _mean([r.itt_fmt[q] for r in runs if q in r.itt_fmt]) + for k in sorted({k for r in runs for k in r.per}): + e.datasets[k] = 100 * _mean([r.per[k] for r in runs if k in r.per]) + out.append(e) + order = {"model": 0, "yolo": 1, "chance": 2} + return sorted(out, key=lambda e: (order[e.kind], e.label.lower())) diff --git a/src/agbench/viz/figures.py b/src/agbench/viz/figures.py new file mode 100644 index 0000000..69d79f7 --- /dev/null +++ b/src/agbench/viz/figures.py @@ -0,0 +1,132 @@ +"""The paper's result figures for any set of runs (matplotlib; uv sync --extra viz). + + main_results(entries, "fig_main_results.png") accuracy per task, 95% CI over datasets; YOLO hatched; chance lines + agtask(entries, "fig_agtask.png") classification by agricultural task, per question format +""" + +from pathlib import Path + +from agbench.viz.aggregate import AG, CLS_FORMATS, COLS, Entry + +# Categorical slots in fixed order (validated for colour-vision deficiency; contrast relief: legend + tables) +PALETTE = ["#2a78d6", "#eb6834", "#1baf7a", "#eda100", "#e87ba4", "#008300", "#6250d6", "#e34948"] +INK, MUTED, GRID = "#0b0b0b", "#52514e", "#e1e0d9" +YOLO_STYLE = {"facecolor": "#d9d9d9", "edgecolor": "#555555", "hatch": "////", "lw": 0.6} +MAX_MODELS = len(PALETTE) + + +def _plt(): + try: + import matplotlib + + matplotlib.use("Agg") + import matplotlib.pyplot as plt + except ImportError as e: + raise SystemExit("figures need matplotlib: uv sync --extra viz") from e + plt.rcParams.update({"font.size": 9, "font.family": "sans-serif", "axes.edgecolor": MUTED, "axes.labelcolor": INK, + "xtick.color": MUTED, "ytick.color": MUTED, "text.color": INK}) + return plt + + +def _split(entries: list[Entry]): + models = [e for e in entries if e.kind == "model"] + if len(models) > MAX_MODELS: + raise ValueError(f"{len(models)} models: a figure shows at most {MAX_MODELS} (pass fewer runs)") + return models, [e for e in entries if e.kind == "yolo"][:1], [e for e in entries if e.kind == "chance"][:1] + + +def _style(ax): + ax.yaxis.grid(True, color=GRID, lw=0.6) + ax.set_axisbelow(True) + for s in ("top", "right"): + ax.spines[s].set_visible(False) + + +def _err(cells): + return [[c[0] / 100 - c[1] / 100 for c in cells], [c[2] / 100 - c[0] / 100 for c in cells]] + + +ERR = {"elinewidth": 0.6, "capsize": 1.2, "ecolor": "#444444"} + + +def main_results(entries: list[Entry], path, cols=None) -> Path: + """Accuracy per CV task (macro over datasets, 95% bootstrap CI): one bar per model, YOLO hatched (top-1 accuracy + in the classification columns), chance as a dashed line over each group.""" + plt = _plt() + models, yolo, chance = _split(entries) + cols = [c for c in (cols or COLS) if any(e.cells[c[0]][3] for e in models + yolo)] + nb = len(models) + len(yolo) + w = 0.8 / max(nb, 1) + fig, ax = plt.subplots(figsize=(10, 4.6)) + for i, e in enumerate(models + yolo): + js = [j for j, (k, _) in enumerate(cols) if e.cells[k][3]] + xs = [j + (i - nb / 2 + 0.5) * w for j in js] + cells = [e.cells[cols[j][0]] for j in js] + style = YOLO_STYLE if e.kind == "yolo" else {"color": PALETTE[i]} + label = e.label + (" (top-1 for classification)" if e.kind == "yolo" else "") + ax.bar(xs, [c[0] / 100 for c in cells], w * 0.92, label=label, yerr=_err(cells), error_kw=ERR, **style) + for e in chance: + for j, (k, _) in enumerate(cols): + if e.cells[k][3]: + ax.hlines(e.cells[k][0] / 100, j - 0.43, j + 0.43, colors="#222222", linestyles=[(0, (3, 2))], lw=1.1, zorder=5, + label="Chance (random answer)" if j == 0 else None) + n = {k: max((e.cells[k][3] for e in models + yolo), default=0) for k, _ in cols} + ax.set_xticks(range(len(cols))) + ax.set_xticklabels([f"{h}\n(n={n[k]})" for k, h in cols]) + ax.set_ylabel("Accuracy (avg. across datasets)") + ax.set_xlabel("Task (n = number of datasets)") + ax.set_ylim(0, 1) + _style(ax) + h, lab = ax.get_legend_handles_labels() + k = [i for i, x in enumerate(lab) if x.startswith("Chance")] # chance last + h, lab = [h[i] for i in range(len(h)) if i not in k] + [h[i] for i in k], [lab[i] for i in range(len(lab)) if i not in k] + [lab[i] for i in k] + ncol = 3 if max(map(len, lab), default=0) > 30 else 4 + fig.legend(h, lab, loc="lower center", ncol=ncol, frameon=False, fontsize=8) + fig.tight_layout(rect=(0, 0.06 + 0.045 * -(-len(lab) // ncol), 1, 1)) + path = Path(path) + path.parent.mkdir(parents=True, exist_ok=True) + fig.savefig(path, dpi=200) + plt.close(fig) + return path + + +def agtask(entries: list[Entry], path) -> Path: + """Classification accuracy by agricultural task, one panel per question format; OEQ panel also shows the + fuzzy-match score (hatched ghost bar, dark tick).""" + plt = _plt() + from matplotlib.lines import Line2D + from matplotlib.patches import Patch + + models, yolo, _ = _split(entries) + ags = [(a, h) for a, h in AG if any(e.ag[(f, a)][3] for e in models + yolo for f, _ in CLS_FORMATS)] + nb = len(models) + len(yolo) + w = 0.8 / max(nb, 1) + fig, axes = plt.subplots(1, len(CLS_FORMATS), figsize=(10, 4.4), sharey=True) + for ax, (f, title) in zip(axes, CLS_FORMATS): + for i, e in enumerate(models + yolo): + xs = [j + (i - nb / 2 + 0.5) * w for j in range(len(ags))] + cells = [e.ag[(f, a)] for a, _ in ags] + style = YOLO_STYLE if e.kind == "yolo" else {"color": PALETTE[i]} + ax.bar(xs, [c[0] / 100 for c in cells], w * 0.92, zorder=2, label=e.label + (", top-1 (same in every panel)" if e.kind == "yolo" else ""), **style) + ax.errorbar(xs, [c[0] / 100 for c in cells], yerr=_err(cells), fmt="none", zorder=4, **{**ERR, "capsize": 1.0}) + if f == "oeq" and e.kind == "model": + ys = [e.fuzzy[a] / 100 for a, _ in ags] + ax.bar(xs, ys, w * 0.92, facecolor="none", edgecolor=PALETTE[i], hatch="//////", lw=0, zorder=1) + ax.hlines(ys, [x - w / 2 for x in xs], [x + w / 2 for x in xs], color="#222222", lw=0.9, zorder=3) + ax.set_xticks(range(len(ags))) + ax.set_xticklabels([h.replace("/", "/\n") for _, h in ags]) + ax.set_title(title if f != "oeq" else "OEQ (judged vs. fuzzy match)") + _style(ax) + axes[0].set_ylabel("Accuracy (avg. across datasets)") + axes[0].set_ylim(0, 1) + h, lab = axes[0].get_legend_handles_labels() + h += [Patch(facecolor="#888888"), (Patch(facecolor="none", edgecolor="#888888", hatch="//////", lw=0), Line2D([], [], color="#222222", lw=0.9))] + lab += ["OEQ: LLM judge", "OEQ: fuzzy match"] + ncol = 3 if max(map(len, lab), default=0) > 30 else 4 + fig.legend(h, lab, loc="lower center", ncol=ncol, frameon=False, fontsize=7.5) + fig.tight_layout(rect=(0, 0.06 + 0.045 * -(-len(lab) // ncol), 1, 1)) + path = Path(path) + path.parent.mkdir(parents=True, exist_ok=True) + fig.savefig(path, dpi=200) + plt.close(fig) + return path diff --git a/src/agbench/viz/html.py b/src/agbench/viz/html.py new file mode 100644 index 0000000..e5efa54 --- /dev/null +++ b/src/agbench/viz/html.py @@ -0,0 +1,349 @@ +"""Self-contained HTML report: one file, data inlined, charts drawn in the browser (no server, no network). + +Tabs: overview (accuracy per task with 95% CI, table), agricultural tasks, datasets (filterable, sortable), runs +(benchmark, hash, judge, coverage, comparable). +""" + +import html +import json +import math +from datetime import datetime, timezone +from pathlib import Path + +from agbench.viz.aggregate import AG, CLS_FORMATS, COLS, Entry +from agbench.viz.figures import MAX_MODELS + + +def _num(x): + return None if x is None or (isinstance(x, float) and math.isnan(x)) else round(x, 2) + + +def _cell(c): + return {"m": _num(c[0]), "lo": _num(c[1]), "hi": _num(c[2]), "n": c[3]} + + +def _run_info(meta: dict, d: str) -> dict: + m = meta.get("method") or {} + bm = meta.get("benchmark") if isinstance(meta.get("benchmark"), dict) and "name" in meta.get("benchmark", {}) else \ + (meta.get("benchmark") or {}).get("benchmark") + cov = meta.get("coverage") or {} + return {"dir": d, "model": m.get("model_id") or m.get("name"), "effort": m.get("effort"), "thinking": m.get("thinking"), + "gen_seed": m.get("gen_seed"), "benchmark": (bm or {}).get("name"), "hash": (bm or {}).get("hash"), + "variant": (bm or {}).get("variant"), "judge": (meta.get("judge") or {}).get("model"), + "comparable": meta.get("comparable"), "why": meta.get("not_comparable") or [], + "answered": cov.get("answered"), "items": cov.get("items"), "complete": cov.get("complete")} + + +def payload(entries: list[Entry], title: str) -> dict: + models = [e for e in entries if e.kind == "model"] + if len(models) > MAX_MODELS: + raise ValueError(f"{len(models)} models: the report shows at most {MAX_MODELS} (pass fewer runs)") + ds = sorted({k for e in entries for k in e.datasets}) + return { + "title": title, "written": datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M UTC"), + "cols": [{"key": k, "label": h} for k, h in COLS], "ag": [{"key": a, "label": h} for a, h in AG], + "formats": [{"key": f, "label": h} for f, h in CLS_FORMATS], + "entries": [{"label": e.label, "kind": e.kind, "replicates": e.replicates, + "cells": {k: _cell(v) for k, v in e.cells.items()}, + "ag": {f"{f}|{a}": _cell(v) for (f, a), v in e.ag.items()}, + "fuzzy": {a: _num(v) for a, v in e.fuzzy.items()}, "itt_fmt": {q: _num(v) for q, v in e.itt_fmt.items()}, + "pending_judge": sum(r.pending_judge for r in e.runs), + "runs": [_run_info(m, r.dir) for m, r in zip(e.meta, e.runs)]} for e in entries], + "datasets": [{"col": c, "dataset": d, "scores": [_num(e.datasets.get((c, d))) for e in entries]} for c, d in ds], + } + + +def write(entries: list[Entry], path, title: str = "AgML benchmark results") -> Path: + data = json.dumps(payload(entries, title), separators=(",", ":")).replace(" + + + + +__TITLE__ + + + +
+

+ +
+ +
+
+
+

Accuracy by task

+

Mean over datasets of each dataset's accuracy (averaged over repeated runs); bars show the 95% bootstrap CI over datasets. YOLO is scored by top-1 accuracy in every classification column. Dashed lines: chance.

+
+
+
+

Table

+
+ + + +
+ + + + +""" diff --git a/tests/test_viz.py b/tests/test_viz.py new file mode 100644 index 0000000..f515e9d --- /dev/null +++ b/tests/test_viz.py @@ -0,0 +1,69 @@ +import json + +import pytest + +from agbench import bench +from agbench.eval.baselines import NaiveBaseline, priors +from agbench.eval.methods import Method +from agbench.eval.runner import Benchmark +from agbench.viz import aggregate, html + +from test_bench import _fake_dataset + + +class Letter(Method): + def __init__(self, gen_seed=None): + self.name, self.gen_seed = "toy/letter-a", gen_seed + + def predict(self, item): + return "A" + + def config(self): + return {"name": self.name, "gen_seed": self.gen_seed} + + +@pytest.fixture(scope="module") +def runs(tmp_path_factory): + tmp = tmp_path_factory.mktemp("viz") + full = bench.load("agml-full-v1") + for ds in ("bean_disease_uganda", "tomato_leaf_disease"): + _fake_dataset(tmp, full, ds) + b = Benchmark(tmp, tasks=["classification"], limit_per_dataset=4) + for s in (0, 1): + b.run(Letter(s), tmp / "runs" / f"letter_s{s}") + b.run(NaiveBaseline("chance", priors(b.items), 0), tmp / "runs" / "chance") + return tmp / "runs" + + +def test_entries_group_seeds_and_kinds(runs): + es = aggregate.entries([runs], labels={"toy/letter-a": "Letter A"}) + assert [(e.label, e.kind, e.replicates) for e in es] == [("Letter A", "model", 2), ("baseline/chance", "chance", 1)] + e = es[0] + m, lo, hi, n = e.cells["mcqa_within"] + assert n == 2 and lo <= m <= hi and e.cells["detection"][3] == 0 + per = [e.datasets[("mcqa_within", d)] for d in ("bean_disease_uganda", "tomato_leaf_disease")] + assert m == pytest.approx(sum(per) / 2) + + +def test_bootstrap_exact_matches_fast_closely(): + vals = [10.0, 20.0, 30.0, 45.0, 60.0, 5.0] + fast, exact = aggregate.boot_ci(vals), aggregate.boot_ci(vals, exact=True) + assert all(abs(a - b) < 3 for a, b in zip(fast, exact)) + + +def test_html_report_is_self_contained(runs, tmp_path): + p = html.write(aggregate.entries([runs]), tmp_path / "r.html", "Toy report") + page = p.read_text() + assert "