File size: 6,633 Bytes
6f5156a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
"""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()