"""M5 error taxonomy by question family and RQ4 (protocol v4): the EGS proxy of TADI, adapted to the JSON answer format of the T4 baselines, against the automatic score from the XML answer. No human rater exists.""" from __future__ import annotations import json import re import sqlite3 from contextlib import closing from pathlib import Path import numpy as np import pandas as pd from scipy.stats import spearmanr from . import t4 FAMILIES = ("lookup", "aggregation", "temporal_event", "comparison", "multi_hop") ANSWERABLE_CLASSES = ("correct", "failed", "abstained", "wrong_wellbore", "no_citation", "evidence_missed", "wrong_with_evidence") UNANSWERABLE_CLASSES = ("correct", "failed", "answered_unanswerable") CLASSES = tuple(dict.fromkeys(ANSWERABLE_CLASSES + UNANSWERABLE_CLASSES)) TADI_UNITS = ("m/hr", "g/cm3", "mPa", "ppm", "hrs", "days", "kN", "sg", "Pa", "m", "%") EXTENDED_UNITS = TADI_UNITS + ("ft/h", "hours", "hour", "hr", "h", "metres", "metre", "meters", "meter", "mMD", "mTVD", "inches", "inch", "in", "ft", "degrees", "degree", "deg", "bar", "psi", "pcf", "degC") NUMBER = r"(? 1 and parsed.split(":")[1] in known_reports: return True return False def egs(prediction, known_reports, pattern=TADI_MEASUREMENT): """TADI eq. 3 with the section term fixed at 0: (has_measurement + has_ddr_quote + 0/6) / 3.""" return (has_measurement(prediction, pattern) + has_ddr_reference(prediction, known_reports)) / 3 def error_class(row): """One class per prediction, first matching rule (protocol v4).""" if row["correct"]: return "correct" if row["failed"]: return "failed" if not row["answerable"]: return "answered_unanswerable" if row["abstained"]: return "abstained" if row["wrong_wellbore"]: return "wrong_wellbore" if row["n_citations"] == 0: return "no_citation" if not (row["report_recall"] or 0) > 0: return "evidence_missed" return "wrong_with_evidence" def load_predictions(sources, digests, questions, known_reports): """Rows for every prediction of the given checkpoints [(path, model)], with the EGS signals of the answer.""" rows = [] for db, model in sources: with closing(sqlite3.connect(f"{Path(db).resolve().as_uri()}?mode=ro", uri=True)) as con: meta = json.loads(con.execute("SELECT provenance FROM metadata").fetchone()[0]) if digests is not None and meta["inputs"] != digests: raise ValueError(f"Stale T4 provenance for {db}.") query = ("SELECT mode, modality, seed, item, json_remove(data, '$.retrieved', '$.trace') " "FROM predictions") for mode, modality, seed, item, data in con.execute(query): d = json.loads(data) q = questions[item] p = d.get("prediction") or {} rows.append({ "model": model, "mode": mode, "modality": modality, "seed": int(seed), "item": item, "well": q["well"], "family": q["family"], "template": q["template_id"], "scope": q["scope"], "answer_type": q["answer_type"], "answerable": bool(q["answerable"]), "failed": bool(d["failed"]), "correct": bool(d["correct"]), "wrong_wellbore": bool(d["wrong_wellbore"]), "report_recall": d["report_recall"], "abstained": t4.is_abstention(p.get("answer")), "n_citations": len(p.get("citations") or []), "measurement": has_measurement(p), "measurement_ext": has_measurement(p, EXTENDED_MEASUREMENT), "ddr_reference": has_ddr_reference(p, known_reports)}) frame = pd.DataFrame(rows) if frame.empty: return frame frame["egs"] = (frame["measurement"].astype(int) + frame["ddr_reference"].astype(int)) / 3 frame["egs_ext"] = (frame["measurement_ext"].astype(int) + frame["ddr_reference"].astype(int)) / 3 frame["error_class"] = frame.apply(error_class, axis=1) return frame def complete_runs(frame, expected): """Keep runs whose item set equals the locked set of their condition; `expected(mode)` gives that set.""" keep, coverage = [], [] for keys, run in frame.groupby(["model", "mode", "modality", "seed"], sort=True): want = expected(keys[1]) ok = len(run) == len(want) and set(run["item"]) == want coverage.append(dict(zip(("model", "mode", "modality", "seed"), keys)) | { "n": len(run), "expected": len(want), "complete": ok}) if ok: keep.append(run) return (pd.concat(keep, ignore_index=True) if keep else frame.iloc[:0]), coverage def taxonomy(frame): """Class shares per run: per family and macro over families (mean of family shares), with counts.""" out = [] for keys, run in frame.groupby(["model", "mode", "modality", "seed"], sort=True): counts = run.groupby(["family", "error_class"]).size().unstack(fill_value=0).reindex(columns=CLASSES, fill_value=0) shares = counts.div(counts.sum(axis=1), axis=0) base = dict(zip(("model", "mode", "modality", "seed"), keys)) for family, row in shares.iterrows(): out.append(base | {"family": family, "n": int(counts.loc[family].sum()), **{c: float(row[c]) for c in CLASSES}, **{f"n_{c}": int(counts.loc[family, c]) for c in CLASSES}}) out.append(base | {"family": "macro", "n": int(counts.values.sum()), **{c: float(shares[c].mean()) for c in CLASSES}, **{f"n_{c}": int(counts[c].sum()) for c in CLASSES}}) return pd.DataFrame(out) def by_answer_type(frame): """Class shares among incorrect answerable predictions, by answer type, per run.""" wrong = frame[frame["answerable"] & ~frame["correct"]] counts = wrong.groupby(["model", "mode", "modality", "seed", "answer_type", "error_class"]).size() table = counts.unstack(fill_value=0) return table.div(table.sum(axis=1), axis=0).reset_index() def mean_over_seeds(table, keys, columns): grouped = table.groupby(keys, sort=True)[list(columns)] mean, low, high = grouped.mean(), grouped.min(), grouped.max() out = mean.reset_index() for c in columns: out[f"{c}_min"] = low[c].to_numpy() out[f"{c}_max"] = high[c].to_numpy() out["seeds"] = table.groupby(keys, sort=True)["seed"].nunique().to_numpy() return out def spearman(x, y): x, y = np.asarray(x, dtype=float), np.asarray(y, dtype=float) if len(x) < 3 or np.ptp(x) == 0 or np.ptp(y) == 0: return None return float(spearmanr(x, y).statistic) def spearman_ci(x, y, wells, resamples, seed): """Whole-well cluster bootstrap of Spearman rho (percentile 95% interval).""" x, y, wells = np.asarray(x, dtype=float), np.asarray(y, dtype=float), pd.Series(wells).to_numpy() names = np.unique(wells) index = {w: np.flatnonzero(wells == w) for w in names} rng = np.random.default_rng(seed) values = [] for _ in range(resamples): rows = np.concatenate([index[w] for w in rng.choice(names, size=len(names), replace=True)]) r = spearman(x[rows], y[rows]) if r is not None and np.isfinite(r): values.append(r) if not values: return None, 0 return [float(np.percentile(values, 2.5)), float(np.percentile(values, 97.5))], len(values) def rq4_block(frame, score, resamples, seed): rho = spearman(frame[score], frame["correct"]) ci, finite = spearman_ci(frame[score], frame["correct"], frame["well"], resamples, seed) if rho is not None \ else (None, 0) levels = {f"{k:.3f}": {"n": int(len(g)), "accuracy": float(g["correct"].mean())} for k, g in frame.groupby(score)} return {"n": int(len(frame)), "rho": rho, "ci95": ci, "finite_resamples": finite, "accuracy": float(frame["correct"].mean()), "mean_egs": float(frame[score].mean()), "by_level": levels} def rq4(frame, resamples, seed): """Spearman between EGS and correctness: pooled per (model, seed) and within each run; sensitivities.""" base = frame[frame["answerable"] & ~frame["failed"]] variants = {"primary": (base, "egs"), "no_abstentions": (base[~base["abstained"]], "egs"), "extended_units": (base, "egs_ext")} out = [] for variant, (data, score) in variants.items(): for (model, s), run in data.groupby(["model", "seed"], sort=True): out.append({"variant": variant, "model": model, "seed": int(s), "mode": "pooled", "modality": "all", **rq4_block(run, score, resamples, seed)}) for (mode, modality), cell in run.groupby(["mode", "modality"], sort=True): out.append({"variant": variant, "model": model, "seed": int(s), "mode": mode, "modality": modality, **rq4_block(cell, score, resamples, seed)}) return out def h4_reading(rows, model, threshold=0.3): pooled = [r["rho"] for r in rows if r["variant"] == "primary" and r["model"] == model and r["mode"] == "pooled"] if not pooled or any(r is None for r in pooled): return {"model": model, "pooled_rho": pooled, "reading": None} if all(abs(r) < threshold for r in pooled): reading = "supported" elif all(abs(r) >= threshold for r in pooled): reading = "not supported" else: reading = "mixed" return {"model": model, "pooled_rho": pooled, "threshold": threshold, "reading": reading}