Files
Volve-DIA/scripts/08_t4_questions.py
lamlvh 17916650a5 Add M1: OCR hub import, WITSML, labels T1-T3, T4 questions, trial raters, draft protocol
- OCR: match the colleague's full-set Dataset Hub export to the DDRs by content
  (3,059/3,066 pages) and QC it against the HTML (CER 2.40%, exact 0.9181).
- WITSML parser and formation tops: 21 DDR wellbores with time logs, 1,384
  reports; WITSML 15/9-F-15 S is DDR 15/9-F-15.
- Deterministic labels T1-T3 (configs/labels.yaml), 1,662 T4 questions with SQL,
  pandas and raw-XML answers in full agreement.
- Trial label validation by three blind LLM raters (not an author or expert audit)
  and rater agreement script; draft protocol_v1 (not locked): split by well.
- Literature notes and BibTeX; docs, report and run_m1.sh synchronised.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-17 08:34:35 +00:00

137 lines
7.0 KiB
Python

"""Build the T4 questions (evidence-grounded question answering) from the DDR tables: outputs/t4/.
python scripts/08_t4_questions.py
Reads `configs/t4_templates.yaml` and `outputs/ddr/` (scripts/02_parse_ddr.py). Writes
questions.jsonl, questions.parquet one question per row: id, template, family, wellbore(s) and well(s), text,
gold answer with unit and tolerance, answer SQL, evidence rows, caveats
dropped.jsonl every candidate instance that was dropped, with its reason
summary.json counts per template, family and wellbore; drops by reason; the agreement of
the SQL answers with the pandas implementation; the self-score check
Three checks, each of which fails the run:
* the SQL answers and evidence rows must agree with the independent pandas implementation
(`volve_dia/t4_pandas.py`) on every candidate instance;
* every gold answer, scored against itself by `t4.score` with its own evidence rows as citations, must be correct
with citation precision and recall of 1;
* the counts must equal EXPECTED, so a change of a template, of the parser or of the data that adds or loses
questions is caught.
"""
from __future__ import annotations
import hashlib
import json
import sys
import time
from volve_dia import paths, t4, t4_pandas
CONFIG = paths.REPO_ROOT / "configs" / "t4_templates.yaml"
EXPECTED = {
"templates": 39,
"candidates": 3915,
"questions": 1662,
"answerable": 1638,
"unanswerable": 24,
"dropped": {"ambiguous_multiple_values": 311, "implausible_value": 4, "inconsistent_source": 18,
"null_answer": 28, "tie": 10},
"not_sampled": {"answerable": 1763, "unanswerable": 119},
"per_family": {"aggregation": 513, "comparison": 102, "lookup": 825, "multi_hop": 88, "temporal_event": 134},
"per_template_questions": {
"L01_spud_date": 26, "L02_drill_complete_date": 26, "L03_deepest_md": 26, "L04_deepest_md_date": 26,
"L05_casing_bottom_md": 66, "L06_casing_sizes": 21, "L07_hole_sizes": 26, "L08_hole_section_start_md": 58,
"L09_hole_section_max_md": 72, "L10_max_inclination": 26, "L11_max_inclination_md": 24,
"L12_mud_density_on_date": 146, "L13_mud_density_at_depth": 102, "L14_formation_top_md": 147,
"L15_rig_name": 25, "L16_kickoff_md": 8, "A01_reports_per_hole_size": 72, "A02_metres_drilled": 26,
"A03_metres_drilled_section": 71, "A04_rop_section": 61, "A05_bit_run_rop_max": 62,
"A06_hours_per_code": 151, "A07_equip_failure_count": 21, "A08_top_interruption_code": 26,
"A09_wow_days": 23, "E01_first_event_date": 29, "E02_first_event_md": 20,
"E03_activity_before_first_event": 20, "E04_first_episode_hours": 26, "E05_max_wow_day": 15,
"E06_code_present": 24, "C01_more_hours_pair": 66, "C02_faster_rop_pair": 26, "C03_field_most_hours": 10,
"M01_mud_density_at_first_event": 15, "M02_hole_size_at_first_event": 15, "M03_formation_at_first_event": 13,
"M04_last_casing_at_first_event": 19, "M05_days_spud_to_deepest_md": 26,
},
}
def self_score(questions: list[dict]) -> dict:
"""Each gold answer as a prediction (the answer text with its unit, and every evidence row as a citation)."""
wrong = []
for q in questions:
cites = [t4.evidence_id(e["table"], e["report_id"], e["seq"]) for e in q["evidence"]]
s = t4.score({"answer": q["answer_text"], "citations": cites}, q)
ok = s["correct"] and not s["fabricated"]
if q["evidence"]:
ok = ok and s["citation_precision"] == 1.0 and s["citation_recall"] == 1.0
if not ok:
wrong.append(q["id"])
return {"questions": len(questions), "correct": len(questions) - len(wrong), "wrong": wrong[:20]}
def main() -> int:
t_start = time.time()
ddr, out = paths.outputs_dir() / "ddr", paths.outputs_dir() / "t4"
cfg = t4.load_config(CONFIG)
with t4.connect(ddr / "volve_ddr.duckdb") as con:
questions, outcomes, summary = t4.build(con, cfg)
t_build = time.time()
check = t4_pandas.crosscheck(cfg, outcomes, t4_pandas.Tables(ddr))
t_check = time.time()
scored = self_score(questions)
t4.write(questions, out)
dropped = [{"template_id": o.template_id, "slots": o.slots, "reason": o.reason}
for outs in outcomes.values() for o in outs if o.status == "drop"]
with (out / "dropped.jsonl").open("w", encoding="utf-8") as f:
for d in dropped:
f.write(json.dumps(d, ensure_ascii=False) + "\n")
summary = {
"config": {"path": str(CONFIG.relative_to(paths.REPO_ROOT)), "version": cfg.get("version"),
"seed": cfg.get("seed"), "sha256": hashlib.sha256(CONFIG.read_bytes()).hexdigest(),
"planned_templates": [t["id"] for t in cfg["disabled"]]},
**summary,
"crosscheck_pandas": check,
"self_score": scored,
"seconds": {"build_sql": round(t_build - t_start, 1), "crosscheck_pandas": round(t_check - t_build, 1)},
}
(out / "summary.json").write_text(json.dumps(summary, indent=1, ensure_ascii=False) + "\n", encoding="utf-8")
brief = {k: summary[k] for k in ("questions", "answerable", "unanswerable", "templates", "candidates", "dropped",
"not_sampled", "per_family", "per_answer_type", "per_scope", "evidence_rows",
"self_score", "seconds")}
brief["crosscheck_pandas"] = check["total"]
print(json.dumps(brief, indent=1, ensure_ascii=False))
print(f"{'template':34s} {'cand':>5s} {'drop':>5s} {'unsampled':>9s} {'quest':>5s} {'neg':>4s} pandas")
for tid, t in summary["per_template"].items():
c = check["per_template"][tid]
print(f"{tid:34s} {t['candidates']:5d} {sum(t['dropped'].values()):5d} "
f"{sum(t['not_sampled'].values()):9d} {t['questions']:5d} {t['unanswerable']:4d} "
f"{c['agree']}/{c['instances']}")
failed = False
total = check["total"]
if total["agree"] != total["instances"] or total["slot_differences"]:
failed = True
print("SQL and pandas disagree:")
for tid, c in check["per_template"].items():
if c["agree"] != c["instances"] or c["slots_only_sql"] or c["slots_only_pandas"]:
print(" ", tid, json.dumps({k: v for k, v in c.items()}, ensure_ascii=False, default=str))
if scored["correct"] != scored["questions"]:
failed = True
print("gold answers that do not score as correct against themselves:", scored["wrong"])
got = {k: summary[k] for k in EXPECTED if k != "per_template_questions"}
got["per_template_questions"] = {tid: t["questions"] for tid, t in summary["per_template"].items()}
diff = {k: (EXPECTED[k], got[k]) for k in EXPECTED if EXPECTED[k] != got[k]}
if diff:
failed = True
print("counts differ from EXPECTED (expected, got):", diff)
return 1 if failed else 0
if __name__ == "__main__":
sys.exit(main())