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>
This commit is contained in:
2026-11-17 08:34:35 +00:00
parent a3c175638f
commit 17916650a5
37 changed files with 11098 additions and 415 deletions

351
scripts/08_t4_xml_check.py Normal file
View File

@@ -0,0 +1,351 @@
"""Third path for the T4 questions: recompute every answer and its evidence ids straight from the raw DDR XML files.
python scripts/08_t4_xml_check.py # after scripts/08_t4_questions.py; writes outputs/t4/xml_check.json
Uses xml.etree only: no volve_dia parser, no DuckDB, no parquet, so it also checks the DDR parser (scripts/02), which
the SQL and pandas paths of 08_t4_questions.py share. Exit 1 if any answer or evidence set differs.
"""
import datetime as dt
import glob
import json
import os
import re
import sys
import xml.etree.ElementTree as ET
from collections import defaultdict
from volve_dia import paths
XML_DIR = str(paths.ddr_xml_dir())
NS = "{http://www.witsml.org/schemas/1series}"
SENT = {-999.99, -999.25, -9999.0}
TAGS = {"activity": "activities", "fluid": "fluids", "stratInfo": "strat", "casing_liner_tubing": "casings",
"surveyStation": "surveys", "bitRecord": "bits", "equipFailureInfo": "equip_failures"}
def num(e, tag):
x = e.find(NS + tag) if e is not None else None
if x is None or not (x.text or "").strip():
return None
v = float(x.text)
return None if v in SENT else v
def txt(e, tag):
x = e.find(NS + tag) if e is not None else None
return x.text.strip() if x is not None and x.text else None
def ts(s):
return dt.datetime.fromisoformat(s)
_CACHE = {}
def load(stem):
"""All reports of the wellbore whose files are <stem>_YYYY_MM_DD.xml, in date order."""
if stem in _CACHE:
return _CACHE[stem]
out = _CACHE.setdefault(stem, [])
for p in sorted(glob.glob(os.path.join(XML_DIR, stem + "_*.xml"))):
rid = os.path.basename(p)[:-4]
if not re.fullmatch(re.escape(stem) + r"_\d{4}_\d{2}_\d{2}", rid):
continue # 15_9_F_1 must not pick up 15_9_F_1_A
rep = ET.parse(p).getroot().find(NS + "drillReport")
wi, si = rep.find(NS + "wellboreInfo"), rep.find(NS + "statusInfo")
r = {"rid": rid, "date": rid[-10:].replace("_", "-"), "spud": txt(wi, "dTimSpud"),
"done": txt(wi, "dateDrillComplete"), "md": num(si, "md"), "diaHole": num(si, "diaHole"),
"distDrill": num(si, "distDrill"), "mdCsgLast": num(si, "mdCsgLast"),
"mdKickoff": num(si, "mdKickoff"), "mdDiaHoleStart": num(si, "mdDiaHoleStart"),
"rig": next((txt(x, "name") for x in wi.findall(NS + "rigAlias")
if txt(x, "namingSystem") == "NPD Name"), None) if wi is not None else None}
for tag, name in TAGS.items():
r[name] = rep.findall(NS + tag)
out.append(r)
return out
def unstem(st):
m = re.fullmatch(r"(\d+)_(\d+)_(?:(F)_)?(\d+)(?:_([A-Z]+\d*))?", st)
a, b, f, n, suffix = m.groups()
return f"{a}/{b}-{'F-' if f else ''}{n}" + (f" {suffix}" if suffix else "")
def stem(wb):
return re.sub(r"[/\- ]", "_", wb)
def acts(reports):
"""(report_id, seq, element) of every activity, in start-time order."""
rows = [(r["rid"], i, a) for r in reports for i, a in enumerate(r["activities"])]
return sorted(rows, key=lambda x: ts(txt(x[2], "dTimStart")))
def dur(a):
return (ts(txt(a, "dTimEnd")) - ts(txt(a, "dTimStart"))).total_seconds() / 3600
def aid(rid, i):
return f"activities:{rid}:{i}"
def code_rows(reports, code):
return [(rid, i, a) for rid, i, a in acts(reports) if txt(a, "proprietaryCode") == code]
def first_event(reports, detail):
rows = [x for x in acts(reports) if txt(x[2], "stateDetailActivity") == detail]
return rows[0] if rows else None
def check(q):
s, tid = q["slots"], q["template_id"]
R = load(stem(s["wellbore"])) if "wellbore" in s else None
by = {r["rid"]: r for r in R} if R else {}
if tid == "A01_reports_per_hole_size":
rows = [r for r in R if r["diaHole"] == s["hole"]]
return len(rows), {f"reports:{r['rid']}" for r in rows}
if tid == "A02_metres_drilled":
rows = [r for r in R if (r["distDrill"] or 0) > 0]
return sum(r["distDrill"] for r in rows), {f"reports:{r['rid']}" for r in rows}
if tid == "A04_rop_section":
rows = [r for r in R if r["diaHole"] == s["hole"] and (r["distDrill"] or 0) > 0]
ev, hours = {f"reports:{r['rid']}" for r in rows}, 0.0
for r in rows:
d = [(i, a) for i, a in enumerate(r["activities"]) if txt(a, "proprietaryCode") == "drilling -- drill"]
assert d, "report with metres but no drill hours"
hours += sum(dur(a) for _, a in d)
ev |= {aid(r["rid"], i) for i, _ in d}
return round(sum(r["distDrill"] for r in rows) / hours, 2), ev
if tid == "C01_more_hours_pair":
tot, ev = {}, set()
for w in (s["wellbore_a"], s["wellbore_b"]):
rows = code_rows(load(stem(w)), s["code"])
tot[w] = sum(dur(a) for _, _, a in rows)
ev |= {aid(rid, i) for rid, i, _ in rows}
return max(tot, key=tot.get), ev
if tid == "C03_field_most_hours":
stems = sorted({re.sub(r"_\d{4}_\d{2}_\d{2}\.xml$", "", os.path.basename(p))
for p in glob.glob(os.path.join(XML_DIR, "*.xml"))})
tot, evs = {}, {}
for st in stems:
rows = code_rows(load(st), s["code"])
tot[st] = sum(dur(a) for _, _, a in rows)
evs[st] = {aid(rid, i) for rid, i, _ in rows}
best = max(tot, key=tot.get)
return unstem(best), evs[best]
if tid in ("E01_first_event_date", "E02_first_event_md"):
rid, i, a = first_event(R, s["detail"])
val = txt(a, "dTimStart")[:10] if tid.startswith("E01") else num(a, "md")
return val, {aid(rid, i)}
if tid == "E03_activity_before_first_event":
A = acts(R)
k = next(j for j, x in enumerate(A) if txt(x[2], "stateDetailActivity") == s["detail"])
assert txt(A[k - 1][2], "dTimEnd") and ts(txt(A[k - 1][2], "dTimEnd")) == ts(txt(A[k][2], "dTimStart"))
return txt(A[k - 1][2], "proprietaryCode"), {aid(A[k][0], A[k][1]), aid(A[k - 1][0], A[k - 1][1])}
if tid == "E04_first_episode_hours":
A = acts(R)
k = next(j for j, x in enumerate(A) if txt(x[2], "stateDetailActivity") == s["detail"])
e = k
while e < len(A) and txt(A[e][2], "stateDetailActivity") == s["detail"]:
e += 1
return sum(dur(x[2]) for x in A[k:e]), {aid(x[0], x[1]) for x in A[k:e]}
if tid == "E05_max_wow_day":
per = defaultdict(float)
rows = code_rows(R, "interruption -- waiting on weather")
for rid, i, a in rows:
per[rid] += dur(a)
best = max(per, key=per.get)
assert sum(v == per[best] for v in per.values()) == 1
return by[best]["date"], {aid(rid, i) for rid, i, _ in rows if rid == best}
if tid == "L02_drill_complete_date":
vals = {r["done"] for r in R if r["done"]}
return (vals.pop() if vals else "not reported"), {f"reports:{r['rid']}" for r in R if r["done"]}
if tid == "L04_deepest_md_date":
mx = max(r["md"] for r in R if r["md"] is not None)
first = next(r for r in R if r["md"] == mx)
return first["date"], {f"reports:{first['rid']}"}
if tid == "L06_casing_sizes":
rows = [(r["rid"], i, num(c, "od")) for r in R for i, c in enumerate(r["casings"])]
return sorted({od for _, _, od in rows}, reverse=True), {f"casings:{rid}:{i}" for rid, i, _ in rows}
if tid == "L07_hole_sizes":
rows = [r for r in R if r["diaHole"] is not None]
return sorted({r["diaHole"] for r in rows}, reverse=True), {f"reports:{r['rid']}" for r in rows}
if tid == "L13_mud_density_at_depth":
rows = [(r["rid"], i, num(f, "density")) for r in R for i, f in enumerate(r["fluids"])
if num(f, "md") == s["md"] and num(f, "density") is not None]
assert len({d for _, _, d in rows}) == 1
return rows[0][2], {f"fluids:{rid}:{i}" for rid, i, _ in rows}
if tid.startswith("M0") and tid != "M05_days_spud_to_deepest_md":
rid, i, a = first_event(R, s["detail"])
rep = by[rid]
if tid == "M01_mud_density_at_first_event":
rows = [(j, num(f, "density")) for j, f in enumerate(rep["fluids"]) if num(f, "density") is not None]
assert len({d for _, d in rows}) == 1
return rows[0][1], {aid(rid, i)} | {f"fluids:{rid}:{j}" for j, _ in rows}
if tid == "M02_hole_size_at_first_event":
return rep["diaHole"], {aid(rid, i), f"reports:{rid}"}
if tid == "M04_last_casing_at_first_event":
return rep["mdCsgLast"], {aid(rid, i), f"reports:{rid}"}
if tid == "M03_formation_at_first_event":
tops = [(r["rid"], j, num(x, "mdTop"), txt(x, "description").rstrip(" .")) for r in R
for j, x in enumerate(r["strat"])]
above = [x for x in tops if x[2] <= num(a, "md")]
mx = max(x[2] for x in above)
best = [x for x in above if x[2] == mx]
return best[0][3], {aid(rid, i)} | {f"strat:{x[0]}:{x[1]}" for x in best}
if tid == "M05_days_spud_to_deepest_md":
spud = {r["spud"][:10] for r in R if r["spud"]}
assert len(spud) == 1
mx = max(r["md"] for r in R if r["md"] is not None)
first = next(r for r in R if r["md"] == mx)
days = (dt.date.fromisoformat(first["date"]) - dt.date.fromisoformat(spud.pop())).days
return days, {f"reports:{first['rid']}"} | {f"reports:{r['rid']}" for r in R if r["spud"]}
raise NotImplementedError(tid)
def rop(R, hole):
rows = [r for r in R if r["diaHole"] == hole and (r["distDrill"] or 0) > 0]
ev, hours = {f"reports:{r['rid']}" for r in rows}, 0.0
for r in rows:
d = [(i, a) for i, a in enumerate(r["activities"]) if txt(a, "proprietaryCode") == "drilling -- drill"]
assert d, "report with metres but no drill hours"
hours += sum(dur(a) for _, a in d)
ev |= {aid(r["rid"], i) for i, _ in d}
return sum(r["distDrill"] for r in rows) / hours, ev
def one(values):
values = set(values)
assert len(values) == 1, values
return values.pop()
def check2(q):
s, tid = q["slots"], q["template_id"]
R = load(stem(s["wellbore"])) if "wellbore" in s else None
rep = lambda rows: {f"reports:{r['rid']}" for r in rows}
if tid == "L01_spud_date":
rows = [r for r in R if r["spud"]]
return one(r["spud"][:10] for r in rows), rep(rows)
if tid == "L03_deepest_md":
mx = max(r["md"] for r in R if r["md"] is not None)
return mx, rep(r for r in R if r["md"] == mx)
if tid == "L05_casing_bottom_md":
rows = [(r["rid"], i, num(c, "mdBottom")) for r in R for i, c in enumerate(r["casings"])
if num(c, "od") == s["od"]]
mx = max(x[2] for x in rows)
return mx, {f"casings:{rid}:{i}" for rid, i, v in rows if v == mx}
if tid == "L08_hole_section_start_md":
rows = [r for r in R if r["diaHole"] == s["hole"] and r["mdDiaHoleStart"] is not None]
return one(r["mdDiaHoleStart"] for r in rows), rep(rows)
if tid == "L09_hole_section_max_md":
rows = [r for r in R if r["diaHole"] == s["hole"] and r["md"] is not None]
mx = max(r["md"] for r in rows)
return mx, rep(r for r in rows if r["md"] == mx)
if tid in ("L10_max_inclination", "L11_max_inclination_md"):
rows = [(r["rid"], i, num(x, "incl"), num(x, "md")) for r in R for i, x in enumerate(r["surveys"])
if num(x, "incl") is not None]
mx = max(x[2] for x in rows)
top = [x for x in rows if x[2] == mx]
ev = {f"surveys:{rid}:{i}" for rid, i, _, _ in top}
return (mx if tid.startswith("L10") else one(x[3] for x in top)), ev
if tid == "L12_mud_density_on_date":
r = next(r for r in R if r["date"] == s["date"])
rows = [(i, num(f, "density")) for i, f in enumerate(r["fluids"]) if num(f, "density") is not None]
return one(d for _, d in rows), {f"fluids:{r['rid']}:{i}" for i, _ in rows}
if tid == "L14_formation_top_md":
rows = [(r["rid"], i, num(x, "mdTop")) for r in R for i, x in enumerate(r["strat"])
if txt(x, "description").rstrip(" .") == s["formation"]]
return one(v for _, _, v in rows), {f"strat:{rid}:{i}" for rid, i, _ in rows}
if tid == "L15_rig_name":
rows = [r for r in R if r["rig"]]
return one(r["rig"] for r in rows), rep(rows)
if tid == "L16_kickoff_md":
rows = [r for r in R if r["mdKickoff"] is not None]
return (one(r["mdKickoff"] for r in rows) if rows else "not reported"), rep(rows)
if tid == "A03_metres_drilled_section":
rows = [r for r in R if r["diaHole"] == s["hole"] and (r["distDrill"] or 0) > 0]
return sum(r["distDrill"] for r in rows), rep(rows)
if tid == "A05_bit_run_rop_max":
rows = [(r["rid"], i, num(b.find(NS + "bitRun"), "ropAv")) for r in R for i, b in enumerate(r["bits"])
if num(b, "diaBit") == s["bit"]]
rows = [x for x in rows if x[2] is not None]
mx = max(x[2] for x in rows)
return mx, {f"bits:{rid}:{i}" for rid, i, v in rows if v == mx}
if tid == "A06_hours_per_code":
rows = code_rows(R, s["code"])
return sum(dur(a) for _, _, a in rows), {aid(rid, i) for rid, i, _ in rows}
if tid == "A07_equip_failure_count":
rows = [(r["rid"], i) for r in R for i, _ in enumerate(r["equip_failures"])]
return len(rows), {f"equip_failures:{rid}:{i}" for rid, i in rows}
if tid == "A08_top_interruption_code":
tot, evs = defaultdict(float), defaultdict(set)
for rid, i, a in acts(R):
c = txt(a, "proprietaryCode")
if c.startswith("interruption -- "):
tot[c] += dur(a)
evs[c].add(aid(rid, i))
best = max(tot, key=tot.get)
assert sum(abs(v - tot[best]) < 1e-6 for v in tot.values()) == 1
return best, evs[best]
if tid == "A09_wow_days":
rows = code_rows(R, "interruption -- waiting on weather")
return len({rid for rid, _, _ in rows}), {aid(rid, i) for rid, i, _ in rows}
if tid == "E06_code_present":
rows = code_rows(R, s["code"])
return bool(rows), {aid(rid, i) for rid, i, _ in rows}
if tid == "C02_faster_rop_pair":
(ra, ea), (rb, eb) = rop(load(stem(s["wellbore_a"])), s["hole"]), rop(load(stem(s["wellbore_b"])), s["hole"])
assert abs(ra - rb) > 0.02 * max(ra, rb)
return (s["wellbore_a"] if ra > rb else s["wellbore_b"]), ea | eb
return check(q)
def same(gold, got):
if isinstance(gold, list):
return list(gold) == list(got)
if isinstance(gold, (int, float)) and not isinstance(gold, bool):
return abs(gold - got) < 0.006
return gold == got
def main() -> int:
stats = defaultdict(lambda: [0, 0, 0])
diffs = []
qfile = paths.outputs_dir() / "t4" / "questions.jsonl"
questions = [json.loads(line) for line in qfile.read_text(encoding="utf-8").splitlines() if line.strip()]
for q in questions:
if not q["answerable"] and q["template_id"] not in ("L02_drill_complete_date", "L16_kickoff_md"):
try:
first = first_event(load(stem(q["slots"]["wellbore"])), q["slots"]["detail"])
except Exception as exc:
first = exc
ans, ev = ("not reported" if first is None else first), set()
else:
ans, ev = check2(q)
gold_ev = {f"{e['table']}:{e['report_id']}" + ("" if e["seq"] is None else f":{e['seq']}")
for e in q["evidence"]}
a_ok, e_ok = same(q["answer"], ans), gold_ev == ev
st = stats[q["template_id"]]
st[0] += 1
st[1] += a_ok
st[2] += e_ok
if not (a_ok and e_ok):
diffs.append({"id": q["id"], "slots": q["slots"], "gold": q["answer"], "raw": str(ans),
"gold_evidence": len(gold_ev), "raw_evidence": len(ev)})
print("DIFF", diffs[-1])
for t, (n, a, e) in sorted(stats.items()):
print(f"{t:34s} n={n:4d} answer_ok={a:4d} evidence_ok={e:4d}")
total = [sum(v[i] for v in stats.values()) for i in range(3)]
print("TOTAL questions, answers ok, evidence ok:", total)
out = {"questions": total[0], "answers_ok": total[1], "evidence_ok": total[2], "templates": len(stats),
"per_template": {t: dict(zip(("n", "answer_ok", "evidence_ok"), v)) for t, v in sorted(stats.items())},
"diffs": diffs}
(paths.outputs_dir() / "t4" / "xml_check.json").write_text(json.dumps(out, indent=1) + "\n", encoding="utf-8")
return 0 if not diffs else 1
if __name__ == "__main__":
sys.exit(main())