| """Paper-ready figures from `data/analysis/*.csv`. |
| |
| Reads the CSVs that `legex.analysis` emits and writes four PNGs into |
| ``data/analysis/figures/``: |
| |
| - ``hallucination_by_country.png`` — grouped bar, models side-by-side. |
| - ``recall_by_country.png`` — grouped bar, models side-by-side. |
| - ``per_variable_heatmap.png`` — variable × {accuracy, recall, hallu., F1}, one panel per model. |
| - ``hallu_vs_recall.png`` — scatter on the cost block, one marker per (cc, model). |
| """ |
|
|
| import argparse |
| import csv |
| import logging |
| import sys |
| from collections import defaultdict |
| from pathlib import Path |
|
|
| import matplotlib.pyplot as plt |
| import numpy as np |
|
|
| log = logging.getLogger(__name__) |
|
|
|
|
| def _read_csv(path: Path) -> list[dict[str, str]]: |
| with open(path, encoding="utf-8", newline="") as f: |
| return list(csv.DictReader(f)) |
|
|
|
|
| def _models_in(rows: list[dict[str, str]]) -> list[str]: |
| return sorted({r["model"] for r in rows}) |
|
|
|
|
| def _short_model(m: str) -> str: |
| return m.split("/")[-1] |
|
|
|
|
| def _grouped_bar( |
| rows: list[dict[str, str]], metric: str, title: str, ylabel: str, out: Path, |
| ) -> None: |
| """Grouped-bar chart: one bar per (country, model) pair.""" |
| countries = sorted({r["country"] for r in rows}) |
| models = _models_in(rows) |
| values: dict[str, dict[str, float]] = defaultdict(dict) |
| for r in rows: |
| values[r["country"]][r["model"]] = float(r[metric]) |
|
|
| x = np.arange(len(countries)) |
| width = 0.8 / max(1, len(models)) |
| fig, ax = plt.subplots(figsize=(max(10, 0.55 * len(countries)), 4.5)) |
| for i, model in enumerate(models): |
| ys = [values[cc].get(model, np.nan) * 100 for cc in countries] |
| ax.bar(x + (i - (len(models) - 1) / 2) * width, ys, width, label=_short_model(model)) |
| ax.set_xticks(x) |
| ax.set_xticklabels([cc.upper() for cc in countries], rotation=45, ha="right") |
| ax.set_ylabel(ylabel) |
| ax.set_title(title) |
| ax.set_ylim(0, 100) |
| ax.grid(axis="y", alpha=0.3) |
| ax.legend(frameon=False) |
| fig.tight_layout() |
| fig.savefig(out, dpi=150) |
| plt.close(fig) |
| log.info(f"wrote {out}") |
|
|
|
|
| def _heatmap( |
| rows: list[dict[str, str]], out: Path, |
| ) -> None: |
| """Variable × {accuracy, recall_when_filled, hallucination_rate, f1} for each model.""" |
| metrics = [ |
| ("accuracy", "Accuracy"), |
| ("recall_when_filled", "Recall$_{filled}$"), |
| ("hallucination_rate", "Hallu. rate"), |
| ("f1", "F1"), |
| ] |
| models = _models_in(rows) |
| columns = sorted({r["column"] for r in rows}) |
|
|
| fig, axes = plt.subplots(1, len(models), figsize=(5 * len(models), max(5, 0.32 * len(columns)))) |
| if len(models) == 1: |
| axes = [axes] |
| for ax, model in zip(axes, models): |
| grid = np.full((len(columns), len(metrics)), np.nan) |
| for r in rows: |
| if r["model"] != model: |
| continue |
| i = columns.index(r["column"]) |
| for j, (key, _label) in enumerate(metrics): |
| grid[i, j] = float(r[key]) |
| im = ax.imshow(grid, aspect="auto", cmap="RdYlGn", vmin=0, vmax=1) |
| ax.set_xticks(range(len(metrics))) |
| ax.set_xticklabels([m[1] for m in metrics], rotation=30, ha="right") |
| ax.set_yticks(range(len(columns))) |
| ax.set_yticklabels(columns, fontsize=8) |
| ax.set_title(_short_model(model), fontsize=10) |
| for i in range(len(columns)): |
| for j in range(len(metrics)): |
| v = grid[i, j] |
| if not np.isnan(v): |
| ax.text(j, i, f"{v:.2f}", ha="center", va="center", fontsize=7, |
| color="black" if 0.25 < v < 0.75 else "white") |
| fig.colorbar(im, ax=axes, shrink=0.8, label="value") |
| fig.suptitle("Per-variable metrics (summed across jurisdictions)") |
| fig.savefig(out, dpi=150, bbox_inches="tight") |
| plt.close(fig) |
| log.info(f"wrote {out}") |
|
|
|
|
| def _scatter(rows: list[dict[str, str]], out: Path) -> None: |
| """Hallucination vs recall on the cost block. One marker per (cc, model).""" |
| models = _models_in(rows) |
| markers = {models[0]: "o"} if len(models) == 1 else {models[0]: "o", models[1]: "s"} |
| colors = plt.cm.tab20.colors |
|
|
| fig, ax = plt.subplots(figsize=(7, 6)) |
| for r in rows: |
| m = r["model"] |
| x = float(r["cost_hallucination_rate"]) * 100 |
| y = float(r["cost_recall_when_filled"]) * 100 |
| cc = r["country"] |
| c = colors[hash(cc) % len(colors)] |
| ax.scatter(x, y, marker=markers.get(m, "o"), color=c, s=70, alpha=0.85, edgecolor="black", linewidth=0.4) |
| ax.annotate(cc.upper(), (x, y), fontsize=7, xytext=(3, 3), textcoords="offset points") |
| ax.set_xlabel("Cost-block hallucination rate (%)") |
| ax.set_ylabel("Cost-block recall when filled (%)") |
| ax.set_title("Cost extraction: recall vs hallucination, by jurisdiction × model") |
| ax.set_xlim(-2, 100) |
| ax.set_ylim(-2, 100) |
| ax.grid(alpha=0.3) |
| handles = [ |
| plt.Line2D([], [], marker=mk, linestyle="", color="grey", label=_short_model(m)) |
| for m, mk in markers.items() |
| ] |
| ax.legend(handles=handles, frameon=False, loc="lower right") |
| fig.tight_layout() |
| fig.savefig(out, dpi=150) |
| plt.close(fig) |
| log.info(f"wrote {out}") |
|
|
|
|
| def make_all(analysis_dir: Path, out_dir: Path) -> None: |
| out_dir.mkdir(parents=True, exist_ok=True) |
| per_country = _read_csv(analysis_dir / "per_country.csv") |
| per_column = _read_csv(analysis_dir / "per_column.csv") |
|
|
| _grouped_bar( |
| per_country, "hallucination_rate", |
| "Hallucination rate by jurisdiction (cells where the expert recorded nothing)", |
| "Hallucination rate (%)", |
| out_dir / "hallucination_by_country.png", |
| ) |
| _grouped_bar( |
| per_country, "recall_when_filled", |
| "Accuracy when the expert recorded a value", |
| "Accuracy (%)", |
| out_dir / "recall_by_country.png", |
| ) |
| _heatmap(per_column, out_dir / "per_variable_heatmap.png") |
| _scatter(per_country, out_dir / "hallu_vs_recall.png") |
|
|
|
|
| def main() -> None: |
| logging.basicConfig( |
| level=logging.INFO, |
| format="%(asctime)s [%(levelname)s] %(message)s", |
| handlers=[logging.StreamHandler(sys.stderr)], |
| ) |
| parser = argparse.ArgumentParser( |
| prog="legex-plots", |
| description="Render paper-ready figures from data/analysis/*.csv.", |
| ) |
| parser.add_argument("--in", dest="in_dir", type=Path, default=Path("data/analysis")) |
| parser.add_argument("--out", dest="out_dir", type=Path, default=Path("data/analysis/figures")) |
| args = parser.parse_args() |
| make_all(args.in_dir, args.out_dir) |
|
|
|
|
| if __name__ == "__main__": |
| main() |
|
|