Files
Volve-DIA/scripts/10_m2_cross_checks.py
lamlvh 2b59d635ce Complete M2 validation and lock the G1 evaluation protocol
Run and record both blind LLM validation passes and the external
cross-checks. Freeze the evaluation inputs, well splits, and reporting
scope with a SHA-256 checksum.

Use NPT definition b for DDR-code prediction with definition a as a
sensitivity analysis. Retain the class reporting thresholds and record
the empty set of eligible classes. Make T4 and OCR fidelity the headline
analyses and align the progress report and project documentation.

Co-authored-by: OpenAI Codex <noreply@openai.com>
2026-11-18 04:13:13 +00:00

160 lines
9.1 KiB
Python

"""Reproduce the DrillScribe, Anatoly5ms and TSPP checks on the M1 tables."""
from __future__ import annotations
import argparse
import re
from collections import Counter
from pathlib import Path
import pandas as pd
import yaml
from volve_dia import m2, paths
DRILLSCRIBE = "0abca0097b57823898b520b6fec491d408fa33e7"
ANATOLY5MS = "a0e16ed97f64d142ca99eb8e4d73a89c05e82eec"
TSPP = "1297d8b274042904fbd0fb95f2521a953eedbab6"
CELL_KEYS = ["wellbore", "cell"]
CAUSE_MAP = {"lost_circulation": "lost_circulation", "well_control": "well_control", "stuck_pipe": "stuck_fishing"}
CASES = {
"TSPP2": ("15/9-F-4", "2007-10-23 16:59"),
"TSPP3": ("15/9-F-9 A", "2009-07-04 07:28"),
"TSPP4": ("15/9-F-1", None),
}
def drillscribe_check(activities: pd.DataFrame, reports: pd.DataFrame, source: Path) -> dict:
columns = ["well", "raw_label", "t_start", "n_lines"]
external = pd.read_csv(source, usecols=columns + ["is_npt"])
external["t_start"] = pd.to_datetime(external["t_start"], utc=True)
src = activities.loc[activities["comments"].str.strip().fillna("").ne("")].copy()
src["t_start"] = pd.to_datetime(src["start_utc"], utc=True)
src["well"] = src["report_id"].map(reports.set_index("report_id")["nameWell"])
src = src.sort_values(["well", "t_start"], kind="stable")
ends = src["well"].ne(src["well"].shift()) | src["stateDetailActivity"].ne(src["stateDetailActivity"].shift())
ours = src.groupby(ends.cumsum()).agg(well=("well", "first"), raw_label=("stateDetailActivity", "first"),
t_start=("t_start", "min"), n_lines=("report_id", "size"))
expected, actual = (Counter(df[columns].itertuples(index=False, name=None)) for df in (external, ours))
return {"revision": DRILLSCRIBE, "source_sha256": m2.digest(source), "external_episodes": len(external),
"rebuilt_episodes": len(ours), "matched": sum((expected & actual).values()),
"external_only": sum((expected - actual).values()), "rebuilt_only": sum((actual - expected).values()),
"external_npt_episodes": int(external["is_npt"].sum()), "activities": len(src),
"wellbores": int(src["wellbore"].nunique()), "key": columns}
def text_strength(comments: pd.Series, rules: dict) -> pd.Series:
# Phrase-level matching adapted from Anatoly5ms, MIT. Upstream rules are read from its pinned local checkout.
expr = {name: [re.compile(pattern, re.IGNORECASE) for pattern in rules[name + "_patterns"]]
for name in ("strong", "weak", "exclude")}
def match(comment: str) -> str:
strengths = set()
for clause in re.split(r"[.;\n]+|,\s+", comment):
if any(pattern.search(clause) for pattern in expr["exclude"]):
continue
strengths.update(name for name in ("strong", "weak") if any(p.search(clause) for p in expr[name]))
return "strong" if "strong" in strengths else ("weak" if "weak" in strengths else "none")
return comments.fillna("").map(match)
def overlap(left: pd.Series, right: pd.Series) -> dict:
both, union = int((left & right).sum()), int((left | right).sum())
return {"n": len(left), "text_positive": int(left.sum()), "code_positive": int(right.sum()), "both": both,
"text_only": int((left & ~right).sum()), "code_only": int((~left & right).sum()),
"jaccard": both / union if union else None}
def cell_hits(frame: pd.DataFrame, mask: pd.Series, universe: pd.DataFrame) -> pd.Series:
keys = pd.MultiIndex.from_frame(frame.loc[mask & frame["cell"].notna(), CELL_KEYS])
return pd.Series(pd.MultiIndex.from_frame(universe[CELL_KEYS]).isin(keys), index=universe.index)
def anatoly_check(source: Path, activities: pd.DataFrame, labels: Path, witsml: Path, out: Path) -> dict:
rules = yaml.safe_load(source.read_text(encoding="utf-8"))["labeler"]["complication_rules"]
t3 = pd.read_parquet(labels / "t3_activities.parquet")
t2 = pd.read_parquet(labels / "t2_labels.parquet", columns=["act_id", "cause_a", "cause_b"])
cells = pd.read_parquet(labels / "t3_cells.parquet")
logs = pd.read_parquet(witsml / "wellbores.parquet")
eligible = logs.loc[logs["in_ddr"] & logs["n_time_logs"].gt(0), "wellbore"]
primary = cells["in_own_hole"] & cells["wellbore"].isin(eligible)
frame = t3.merge(t2, on="act_id", validate="one_to_one").merge(
activities[["report_id", "seq", "comments"]], on=["report_id", "seq"], validate="one_to_one")
matches = pd.DataFrame({name: text_strength(frame["comments"], rule) for name, rule in rules.items()})
counts = {name: matches[name].value_counts().to_dict() for name in matches}
result = {"revision": ANATOLY5MS, "source_sha256": m2.digest(source),
"scope": "Upstream comment regex only. The Volve-DIA activity MD and 10 m grid are shared.",
"strength_by_rule": counts, "thresholds": {}}
columns = ["act_id", "wellbore", "cell", "depth_class", "npt_a", "npt_b", "cause_a", "cause_b"]
evidence = frame[columns].join(matches)
evidence.loc[matches.ne("none").any(axis=1)].to_csv(out / "anatoly_text_hits.csv", index=False)
for threshold in ("strong", "strong_or_weak"):
positive = matches.eq("strong") if threshold == "strong" else matches.ne("none")
any_text = positive.any(axis=1)
by_definition = {}
for definition in ("a", "b"):
reference = frame[f"npt_{definition}"]
by_definition[definition] = {
"activity_all": overlap(any_text, reference),
"cells_all": overlap(cell_hits(frame, any_text, cells), cells[f"label_{definition}"]),
"cells_own_hole_with_witsml": overlap(cell_hits(frame, any_text, cells.loc[primary]),
cells.loc[primary, f"label_{definition}"]),
"matched_cause_activity": {
r: overlap(positive[r], frame[f"cause_{definition}"].eq(c)) for r, c in CAUSE_MAP.items()},
"matched_cause_cells_own_hole_with_witsml": {
r: overlap(cell_hits(frame, positive[r], cells.loc[primary]),
cell_hits(frame, frame[f"cause_{definition}"].eq(c), cells.loc[primary]))
for r, c in CAUSE_MAP.items()},
}
result["thresholds"][threshold] = by_definition
return result
def tspp_check(activities: pd.DataFrame, source: Path, out: Path) -> dict:
records = {}
for case, (wellbore, onset) in CASES.items():
file = source / f"{case}.csv"
times = pd.to_datetime(pd.read_csv(file, usecols=["date"])["date"], utc=True)
bounds = times.min() - pd.Timedelta(hours=3), times.max() + pd.Timedelta(hours=3)
rows = activities.loc[activities["wellbore"].eq(wellbore)
& (activities["end_utc"] > bounds[0]) & (activities["start_utc"] < bounds[1])]
keywords = r"stuck|jarr|pack.?off|overpull|over pull|tight"
hits = rows["comments"].str.contains(keywords, case=False, na=False)
records[case] = {"wellbore": wellbore, "source_sha256": m2.digest(file), "source_rows": len(times),
"reported_onset_timezone_unspecified": onset,
"window_utc_assumed": [t.isoformat() for t in bounds],
"ddr_rows": len(rows), "ddr_code_counts": rows["stateDetailActivity"].value_counts().to_dict(),
"ddr_keyword_rows": int(hits.sum())}
rows[["report_id", "seq", "start_utc", "end_utc", "md", "stateDetailActivity", "comments"]].to_csv(
out / f"{case}_ddr.csv", index=False)
return {"revision": TSPP, "cases": records, "purpose": "qualitative case-level checks"}
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--third-party", type=Path, default=paths.REPO_ROOT / "data" / "third_party")
third_party = parser.parse_args().third_party
ddr = paths.outputs_dir() / "ddr"
activities = pd.read_parquet(ddr / "activities.parquet")
reports = pd.read_parquet(ddr / "reports.parquet", columns=["report_id", "nameWell"])
out = m2.directory() / "cross_checks"
out.mkdir(parents=True, exist_ok=True)
result = {
"drillscribe": drillscribe_check(activities, reports, third_party / "drillscribe/repo/data/episodes.csv"),
"anatoly5ms": anatoly_check(third_party / "anatoly5ms_drilling_complication/repo/config/config.yaml",
activities, paths.outputs_dir() / "labels", paths.outputs_dir() / "witsml", out),
"tspp": tspp_check(activities, third_party / "tspp_stuck_pipe_cao2024/repo/TSPP/TSPP", out),
}
m2.write_json(out / "summary.json", result)
print(f"DrillScribe: {result['drillscribe']['matched']}/{result['drillscribe']['external_episodes']} episodes")
for mode, definitions in result["anatoly5ms"]["thresholds"].items():
for definition, bases in definitions.items():
print(f"Anatoly5ms {mode}, NPT {definition}: {bases['cells_own_hole_with_witsml']}")
for case, data in result["tspp"]["cases"].items():
print(f"{case}: {data['ddr_rows']} DDR rows, {data['ddr_code_counts'].get('stuck equipment', 0)} stuck codes")
if __name__ == "__main__":
main()