Add protocol v4: M5 error taxonomy and the RQ4 EGS analysis
Protocol v4 extends locked v3 and fixes, before any count was computed, a first-rule-wins error class per T4 prediction and an adaptation of the TADI evidence grounding score to the JSON answer format (measurement with a TADI unit plus a cited known DDR report; section term 0). Spearman correlation with the automatic score is computed pooled and within each run, with whole-well bootstrap intervals. Only complete runs with current input digests are used. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
68
configs/protocol_v4.yaml
Normal file
68
configs/protocol_v4.yaml
Normal file
@@ -0,0 +1,68 @@
|
||||
# Protocol v4: M5 error taxonomy by question family and RQ4 (EGS against the automatic score). Extends locked v3.
|
||||
protocol: volve-dia
|
||||
version: 4
|
||||
status: locked
|
||||
drafted: 2026-11-20
|
||||
locked_before: any error-class count or EGS value was computed; only the G2 v2 headline metrics were known
|
||||
extends:
|
||||
file: configs/protocol_v3.yaml
|
||||
sha256: 61bc3e1d4f2e7840adb9e5c5fd14bd445c25b988666eca2217325ccda3001622
|
||||
deviation:
|
||||
date: 2026-11-20
|
||||
what: >-
|
||||
Protocols v1 to v3 list error analysis (M5) and RQ4 without fixing rules. v4 fixes both before computing them.
|
||||
TADI (arXiv 2605.00060, eq. 3) defines EGS = (1/3)(has_measurement + has_ddr_quote + sections_present/6) for a
|
||||
six-section narrative answer. The locked T4 baselines answer in a JSON object {answer, unit, citations} with no
|
||||
sections and no quoted text, so v4 adapts the two signals that can be observed and records the section term as 0.
|
||||
consequence: >-
|
||||
EGS here is an adaptation of TADI's proxy to the benchmark's answer format, not TADI's agent output. Its rank
|
||||
correlation with correctness is unaffected by the constant section term. Correctness is the automatic score
|
||||
against the XML answer; no human rater exists (plan section 12 item 20).
|
||||
unchanged:
|
||||
- protocols v1, v2 and v3 in full, including T4 automatic scoring, headline metrics, G2 and G3
|
||||
predictions:
|
||||
primary: VAI DeepSeek-V4.1-Flash-1017, repetitions 0, 1 and 2 (outputs/m34/v2/qa/vai-deepseek-v4-1-flash/rep*.sqlite)
|
||||
secondary: Qwen v1 seed 0 (outputs/m34/qa/qwen.sqlite), complete runs only, reported as partial v1
|
||||
complete_run: a (model, mode, source, seed) run whose item set equals the locked question set of that condition
|
||||
provenance: checkpoint input digests must equal the current M3-M4 input digests (as in the G2 report)
|
||||
universe: well-scoped questions (single and pair; the 10 field questions are excluded), as in the T4 headline
|
||||
error_taxonomy:
|
||||
unit: prediction
|
||||
rule: >-
|
||||
Each well-scoped prediction gets exactly one class, the first rule that matches, in this order. Answerable
|
||||
questions: correct; failed (call or parse failure); abstained (no answer to an answerable question); wrong_wellbore
|
||||
(the scorer's wrong_wellbore flag: a cited or named wellbore outside the question); no_citation (no citation);
|
||||
evidence_missed (citations, none of them an evidence report, report recall 0); wrong_with_evidence (at least one
|
||||
evidence report cited, answer still wrong). Unanswerable questions: correct (abstained); failed;
|
||||
answered_unanswerable.
|
||||
fields: the stored scorer fields failed, correct, wrong_wellbore and report_recall, and t4.is_abstention on the answer
|
||||
report: >-
|
||||
Share of each class among all predictions of a run, per family (lookup, aggregation, temporal_event, comparison,
|
||||
multi_hop) and macro over families (mean of family shares, as the headline); counts alongside. Primary numbers
|
||||
are the mean over the three DeepSeek repetitions with the per-repetition range. Cross-tabulation by answer type.
|
||||
Descriptive only: no test and no gate.
|
||||
rq4:
|
||||
egs:
|
||||
has_measurement: >-
|
||||
a number followed by a TADI drilling unit in the text "<answer> <unit>". Units, matched case-insensitively as
|
||||
a whole token after optional space: m, m/hr, kN, sg, g/cm3, mPa, Pa, ppm, hrs, days, %
|
||||
has_measurement_extended: >-
|
||||
sensitivity only: the TADI units plus h, hr, hour(s), metre(s), meter(s), mMD, mTVD, in, inch(es), ft, ft/h,
|
||||
deg, degree(s), bar, psi, pcf, degC
|
||||
has_ddr_quote: >-
|
||||
at least one citation that resolves to a known DDR report (the report id names the wellbore and the date);
|
||||
quoted text cannot be observed in the JSON answer format
|
||||
sections_present: 0 of 6 for every prediction (no sections in the answer format)
|
||||
formula: EGS = (has_measurement + has_ddr_quote + 0) / 3, so EGS takes the values 0, 1/3 and 2/3
|
||||
correctness: the stored automatic `correct` flag (failed predictions are excluded)
|
||||
universe: well-scoped answerable questions, failed predictions excluded; abstentions included (primary)
|
||||
sensitivity: [abstentions excluded, extended unit list]
|
||||
statistic: >-
|
||||
Spearman rank correlation between EGS and correctness over all modes and sources of one repetition (pooled), and
|
||||
within each (mode, source) run. 95% interval by whole-well cluster bootstrap, 2,000 resamples, seed 20261117.
|
||||
Accuracy at each EGS level is reported beside it.
|
||||
h4_reading: >-
|
||||
H4 (EGS correlates weakly with correctness) is supported if the pooled point rho of the primary model is below
|
||||
0.3 in absolute value in every repetition; a pooled rho of 0.3 or more in every repetition does not support it;
|
||||
otherwise mixed. Within-run rhos are reported, since pooling across modes mixes mode differences into rho.
|
||||
code: scripts/19_m5_errors.py, volve_dia/m5_errors.py
|
||||
1
configs/protocol_v4.yaml.sha256
Normal file
1
configs/protocol_v4.yaml.sha256
Normal file
@@ -0,0 +1 @@
|
||||
6a9ad0fb64e319b914427e4ec58c4cfafdca91b393da9309f9b30391a12568d0 configs/protocol_v4.yaml
|
||||
86
scripts/19_m5_errors.py
Normal file
86
scripts/19_m5_errors.py
Normal file
@@ -0,0 +1,86 @@
|
||||
#!/usr/bin/env python3
|
||||
"""M5 error taxonomy by question family and RQ4 (EGS against the automatic score) under protocol v4.
|
||||
|
||||
scripts/19_m5_errors.py read the complete T4 runs, write outputs/m5/errors/
|
||||
|
||||
Refuses to run unless configs/protocol_v4.yaml matches its checksum and every checkpoint carries the current M3-M4
|
||||
input digests. Correctness is the automatic score against the XML answer; no human rater exists.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
import duckdb
|
||||
import yaml
|
||||
|
||||
from volve_dia import m34, m5_errors as me
|
||||
from volve_dia.m34_qa import qa_universe
|
||||
from volve_dia.m5_judge import sha256_file
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
PROTOCOL = ROOT / "configs/protocol_v4.yaml"
|
||||
PRIMARY = "vai-deepseek-v4-1-flash"
|
||||
RESAMPLES, SEED = 2000, 20261117
|
||||
SHARE_COLUMNS = ("n",) + me.CLASSES
|
||||
|
||||
|
||||
def main():
|
||||
expected = (PROTOCOL.with_suffix(".yaml.sha256")).read_text().split()[0]
|
||||
if sha256_file(PROTOCOL) != expected:
|
||||
raise SystemExit("configs/protocol_v4.yaml does not match its checksum")
|
||||
v4 = yaml.safe_load(PROTOCOL.read_text())
|
||||
protocol, _ = m34.configuration()
|
||||
root, digests = m34.inputs(protocol)
|
||||
out = root / "m34"
|
||||
questions, paired, _, blocked = qa_universe(root, protocol)
|
||||
by_id = {q["id"]: q for q in questions}
|
||||
paired_ids = {q["id"] for q in paired}
|
||||
sets = {"c4": paired_ids, "c4_clean": paired_ids - blocked}
|
||||
all_ids = set(by_id)
|
||||
|
||||
with duckdb.connect(str(root / "ddr/volve_ddr.duckdb"), read_only=True) as con:
|
||||
known = {r[0] for r in con.execute("SELECT report_id FROM reports").fetchall()}
|
||||
sources = [(db, PRIMARY) for db in sorted((out / f"v2/qa/{PRIMARY}").glob("rep*.sqlite"))]
|
||||
sources.append((out / "qa/qwen.sqlite", "qwen"))
|
||||
frame = me.load_predictions(sources, digests, by_id, known)
|
||||
frame, coverage = me.complete_runs(frame, lambda mode: sets.get(mode, all_ids))
|
||||
frame = frame[frame["scope"].ne("field")].reset_index(drop=True)
|
||||
|
||||
dest = root / "m5/errors"
|
||||
dest.mkdir(parents=True, exist_ok=True)
|
||||
tax = me.taxonomy(frame)
|
||||
tax.to_csv(dest / "taxonomy_by_run.csv", index=False)
|
||||
summary = me.mean_over_seeds(tax, ["model", "mode", "modality", "family"], SHARE_COLUMNS)
|
||||
summary.to_csv(dest / "taxonomy.csv", index=False)
|
||||
me.by_answer_type(frame).to_csv(dest / "by_answer_type.csv", index=False)
|
||||
rows = me.rq4(frame, RESAMPLES, SEED)
|
||||
egs = frame.groupby(["model", "mode", "modality", "seed"]).agg(
|
||||
n=("egs", "size"), mean_egs=("egs", "mean"), measurement=("measurement", "mean"),
|
||||
measurement_ext=("measurement_ext", "mean"), ddr_reference=("ddr_reference", "mean"),
|
||||
accuracy=("correct", "mean")).reset_index()
|
||||
egs.to_csv(dest / "egs_by_run.csv", index=False)
|
||||
frame.drop(columns=["answerable"]).to_parquet(dest / "predictions.parquet", index=False)
|
||||
|
||||
macro = summary[summary["family"].eq("macro")]
|
||||
report = {
|
||||
"protocol": {"file": str(PROTOCOL.relative_to(ROOT)), "sha256": expected, "version": v4["version"]},
|
||||
"inputs": digests,
|
||||
"reference": "automatic score against the XML answer (no human rater)",
|
||||
"coverage": coverage,
|
||||
"n_predictions_well_scoped": int(len(frame)),
|
||||
"taxonomy_macro": json.loads(macro.to_json(orient="records")),
|
||||
"rq4": rows,
|
||||
"h4": [me.h4_reading(rows, model) for model in sorted(frame["model"].unique())],
|
||||
"primary_model": PRIMARY,
|
||||
}
|
||||
m34.atomic_write(dest / "report.json", json.dumps(report, indent=1).encode())
|
||||
for h in report["h4"]:
|
||||
print(h)
|
||||
print(macro[["model", "mode", "modality", "correct", "wrong_wellbore", "no_citation", "evidence_missed",
|
||||
"wrong_with_evidence", "abstained", "answered_unanswerable"]].round(3).to_string(index=False))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
99
tests/test_m5_errors.py
Normal file
99
tests/test_m5_errors.py
Normal file
@@ -0,0 +1,99 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import sqlite3
|
||||
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
import pytest
|
||||
|
||||
from volve_dia import m5_errors as me
|
||||
|
||||
KNOWN = {"15_9_F_14_2008_05_23"}
|
||||
|
||||
|
||||
@pytest.mark.parametrize("answer,unit,tadi,ext", [
|
||||
("3520", "m", True, True), ("3,520.5 m", "", True, True), ("1.48", "g/cm3", True, True),
|
||||
("12", "hours", False, True), ("12 1/4", "in", False, True), ("3520", "mMD", False, True),
|
||||
("3520 m MD", "", True, True), ("15/9-F-14", "", False, False), ("MAERSK INSPIRER", "", False, False),
|
||||
("25", "%", True, True), ("40", "mm", False, False), ("2008-05-23", "", False, False)])
|
||||
def test_has_measurement(answer, unit, tadi, ext):
|
||||
p = {"answer": answer, "unit": unit}
|
||||
assert me.has_measurement(p) is tadi
|
||||
assert me.has_measurement(p, me.EXTENDED_MEASUREMENT) is ext
|
||||
|
||||
|
||||
def test_ddr_reference_and_egs():
|
||||
cited = {"answer": "3520", "unit": "m", "citations": ["reports:15_9_F_14_2008_05_23"]}
|
||||
assert me.has_ddr_reference(cited, KNOWN)
|
||||
assert me.has_ddr_reference({"citations": ["activities:15_9_F_14_2008_05_23:3"]}, KNOWN)
|
||||
assert not me.has_ddr_reference({"citations": ["reports:15_9_F_99_2008_05_23", "nonsense"]}, KNOWN)
|
||||
assert me.egs(cited, KNOWN) == pytest.approx(2 / 3)
|
||||
assert me.egs({"answer": None, "citations": []}, KNOWN) == 0
|
||||
|
||||
|
||||
def row(**kw):
|
||||
base = {"correct": False, "failed": False, "answerable": True, "abstained": False, "wrong_wellbore": False,
|
||||
"n_citations": 1, "report_recall": 0.0}
|
||||
return base | kw
|
||||
|
||||
|
||||
@pytest.mark.parametrize("kw,expected", [
|
||||
({"correct": True}, "correct"), ({"failed": True}, "failed"), ({"answerable": False}, "answered_unanswerable"),
|
||||
({"abstained": True, "wrong_wellbore": True}, "abstained"), ({"wrong_wellbore": True}, "wrong_wellbore"),
|
||||
({"n_citations": 0}, "no_citation"), ({"report_recall": None}, "evidence_missed"),
|
||||
({"report_recall": 0.5}, "wrong_with_evidence"), ({"answerable": False, "correct": True}, "correct")])
|
||||
def test_error_class_first_rule_wins(kw, expected):
|
||||
assert me.error_class(row(**kw)) == expected
|
||||
|
||||
|
||||
def store(path, rows, inputs):
|
||||
con = sqlite3.connect(path)
|
||||
con.execute("CREATE TABLE metadata (provenance TEXT)")
|
||||
con.execute("INSERT INTO metadata VALUES (?)", (json.dumps({"inputs": inputs}),))
|
||||
con.execute("CREATE TABLE predictions (mode TEXT, modality TEXT, seed INT, item TEXT, data TEXT)")
|
||||
con.executemany("INSERT INTO predictions VALUES (?, ?, ?, ?, ?)", rows)
|
||||
con.commit()
|
||||
con.close()
|
||||
|
||||
|
||||
def test_load_complete_and_taxonomy(tmp_path):
|
||||
questions = {f"q{i}": {"well": f"W{i % 2}", "family": ("lookup", "aggregation")[i % 2], "template_id": "T",
|
||||
"scope": "single", "answer_type": "number", "answerable": i != 3} for i in range(4)}
|
||||
preds = []
|
||||
for i in range(4):
|
||||
d = {"item": f"q{i}", "failed": False, "correct": i in (0, 3), "wrong_wellbore": i == 1,
|
||||
"report_recall": 0.0, "prediction": {"answer": None if i == 3 else "10", "unit": "m",
|
||||
"citations": ["reports:15_9_F_14_2008_05_23"]}}
|
||||
preds.append(("rag", "xml", 0, f"q{i}", json.dumps(d)))
|
||||
store(tmp_path / "a.sqlite", preds, {"x": "1"})
|
||||
store(tmp_path / "b.sqlite", preds[:2], {"x": "1"})
|
||||
with pytest.raises(ValueError, match="Stale"):
|
||||
me.load_predictions([(tmp_path / "a.sqlite", "m")], {"x": "2"}, questions, KNOWN)
|
||||
frame = me.load_predictions([(tmp_path / "a.sqlite", "m"), (tmp_path / "b.sqlite", "n")], {"x": "1"},
|
||||
questions, KNOWN)
|
||||
kept, coverage = me.complete_runs(frame, lambda mode: set(questions))
|
||||
assert set(kept["model"]) == {"m"} and [c["complete"] for c in coverage] == [True, False]
|
||||
assert list(kept.sort_values("item")["error_class"]) == ["correct", "wrong_wellbore", "evidence_missed",
|
||||
"correct"]
|
||||
assert kept.loc[kept["item"] == "q3", "egs"].item() == pytest.approx(1 / 3)
|
||||
tax = me.taxonomy(kept)
|
||||
macro = tax[tax["family"] == "macro"].iloc[0]
|
||||
assert macro["correct"] == pytest.approx((0.5 + 0.5) / 2) and macro["n"] == 4
|
||||
assert macro["wrong_wellbore"] == pytest.approx((0 + 0.5) / 2)
|
||||
|
||||
|
||||
def test_spearman_bootstrap_and_h4():
|
||||
rng = np.random.default_rng(0)
|
||||
n = 400
|
||||
frame = pd.DataFrame({"well": rng.choice(list("ABCDEFGH"), n), "egs": rng.choice([0, 1 / 3, 2 / 3], n),
|
||||
"mode": "rag", "modality": "xml", "model": "m", "seed": 0, "answerable": True,
|
||||
"failed": False, "abstained": False})
|
||||
frame["egs_ext"] = frame["egs"]
|
||||
frame["correct"] = rng.random(n) < 0.2 + 0.6 * frame["egs"]
|
||||
rows = me.rq4(frame, 200, 1)
|
||||
pooled = [r for r in rows if r["variant"] == "primary" and r["mode"] == "pooled"][0]
|
||||
assert pooled["rho"] > 0.3 and pooled["ci95"][0] < pooled["rho"] < pooled["ci95"][1]
|
||||
assert set(pooled["by_level"]) == {"0.000", "0.333", "0.667"}
|
||||
assert me.h4_reading(rows, "m")["reading"] == "not supported"
|
||||
assert me.spearman([0, 0, 0], [1, 0, 1]) is None
|
||||
229
volve_dia/m5_errors.py
Normal file
229
volve_dia/m5_errors.py
Normal file
@@ -0,0 +1,229 @@
|
||||
"""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"(?<![\w.])-?\d+(?:[.,]\d+)*(?:\s+\d+/\d+)?"
|
||||
|
||||
|
||||
def unit_pattern(units):
|
||||
"""A number followed by one of `units` as a whole token (longest unit first), case-insensitive."""
|
||||
alternatives = "|".join(re.escape(u) for u in sorted(units, key=len, reverse=True))
|
||||
return re.compile(rf"{NUMBER}\s*(?:{alternatives})(?![\w/])", re.IGNORECASE)
|
||||
|
||||
|
||||
TADI_MEASUREMENT = unit_pattern(TADI_UNITS)
|
||||
EXTENDED_MEASUREMENT = unit_pattern(EXTENDED_UNITS)
|
||||
|
||||
|
||||
def answer_text(prediction):
|
||||
answer = prediction.get("answer")
|
||||
if isinstance(answer, (list, tuple)):
|
||||
answer = "; ".join(str(a) for a in answer)
|
||||
unit = prediction.get("unit") or ""
|
||||
return f"{'' if answer is None else answer} {unit}".strip()
|
||||
|
||||
|
||||
def has_measurement(prediction, pattern=TADI_MEASUREMENT):
|
||||
return bool(pattern.search(answer_text(prediction)))
|
||||
|
||||
|
||||
def has_ddr_reference(prediction, known_reports):
|
||||
"""At least one citation that resolves to a known DDR report id (wellbore and date)."""
|
||||
for c in prediction.get("citations") or []:
|
||||
parsed = t4.parse_citation(c)
|
||||
if parsed and len(parsed.split(":")) > 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}
|
||||
Reference in New Issue
Block a user