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

489
scripts/07_labels.py Normal file
View File

@@ -0,0 +1,489 @@
"""Build the deterministic labels T1-T3 from the DDR tables: outputs/labels/*.parquet, volve_labels.duckdb,
summary.json and analysis.md.
python scripts/07_labels.py # needs outputs/ddr/*.parquet (scripts/02_parse_ddr.py)
Rules and mapping: configs/labels.yaml and volve_dia/labels.py. The script fails if a count written in labels.yaml
differs from the data, or if a label count differs from EXPECTED, so neither the mapping nor the code can change a
label unnoticed. Undecided protocol choices are produced side by side (NPT definitions a and b, operation and cause
at two levels); summary.json holds what the protocol needs to choose: distributions per wellbore and per well, the
number of wellbores and wells that contain each class, rare classes, the fill-rule evaluation, the depth coverage
that limits T3 and the rate at which the free text names the label.
"""
from __future__ import annotations
import hashlib
import json
import os
import sys
import duckdb
import numpy as np
import pandas as pd
from volve_dia import labels as L
from volve_dia import paths
#: Label counts locked on 17/11/2026 (labels.yaml version 1). A change here is a change of the benchmark labels.
EXPECTED = {
"report_status": {"no_activities": 8, "ok": 1750, "placeholder_date": 1},
"t1_scope": {"drilling_day": 932, "excluded": 1, "no_activities": 8, "other_day": 818},
"t1_filled_by": {"bfill_leading": 17, "diaHole": 769, "ffill": 972},
"t1_section": {"12.25": 261, "17.5": 154, "26": 105, "36": 67, "6": 49, "8.5": 1111, "9.875": 11},
"t1_section_drilling_day": {"12.25": 196, "17.5": 151, "26": 93, "36": 57, "6": 27, "8.5": 404, "9.875": 4},
"t1_phase": {"conductor": 67, "intermediate": 154, "pilot": 29, "production": 261, "reservoir": 1142,
"surface": 105},
"t1_op_class": {"bop_wellhead": 2512, "casing_cement": 3204, "circulate": 1185, "completion": 657,
"drill_ream": 1925, "formation_evaluation": 520, "interruption": 3577, "other": 3538,
"perforate": 929, "plug_abandon": 1629, "rig_move": 241, "rig_up_down": 572, "trip": 1946,
"wait": 79, "wireline": 933},
"t2_npt_a": 3577,
"t2_cause_a": {"equipment": 1985, "lost_circulation": 78, "operation_failed": 101, "sidetrack": 202,
"stuck_fishing": 246, "unspecified": 262, "waiting": 229, "weather": 445, "well_control": 29},
"t2_npt_b": 4286,
"t2_cause_b": {"equipment": 2425, "hse": 1, "lost_circulation": 86, "operation_failed": 322, "sidetrack": 202,
"stuck_fishing": 248, "unspecified": 299, "waiting": 229, "weather": 445, "well_control": 29},
"t3_depth_class": {"above_mudline": 2923, "in_hole": 11408, "zero": 9116},
"t3_cells": 8757,
"t3_npt_in_hole_a": 1799, "t3_positive_cells_a": 844, "t3_intervals_a": 656, "t3_episodes_a": 1097,
"t3_npt_in_hole_b": 2165, "t3_positive_cells_b": 979, "t3_intervals_b": 728, "t3_episodes_b": 1193,
}
RARE = 20 # a class with fewer instances is flagged (plan, gate G1)
COVERAGE_BY_WELLBORE = ("ffill", "bfill", "ffill_bfill", "nearest", "hole_start")
def _counts(s: pd.Series) -> dict:
return {str(k): int(v) for k, v in s.value_counts().sort_index().items()}
def _records(df: pd.DataFrame) -> list[dict]:
return json.loads(df.to_json(orient="records"))
def _quantiles(s: pd.Series) -> dict:
q = s.quantile([0, 0.25, 0.5, 0.75, 0.9, 1.0])
return {"n": int(s.notna().sum()), **{f"q{int(k * 100)}": round(float(v), 2) for k, v in q.items()}}
def t1_summary(t1r: pd.DataFrame, t1a: pd.DataFrame, feat: pd.DataFrame, ev: pd.DataFrame, cfg: dict) -> dict:
live = t1r[t1r["status"].ne("placeholder_date")]
drilling = live[live["scope"].eq("drilling_day")]
missing = live[live["diaHole"].isna()]
f = feat[feat["status"].ne("placeholder_date")]
prev = f.groupby("wellbore")["dia"].ffill()
nxt = f.groupby("wellbore")["dia"].bfill()
where = np.select([prev.isna(), nxt.isna(), prev == nxt], ["leading", "trailing", "between_same_size"],
"between_different_sizes")
position = pd.Series(where, index=f.index)[f["dia"].isna()]
position_drilling = position[f.loc[position.index, "n_drilling_activities"] > 0]
known = f[f["dia"].notna()]
named = known[known["text_dia"].notna()]
overall = L.summarise_fill_eval(ev)
by_wellbore = L.summarise_fill_eval(ev[ev["rule"].isin(COVERAGE_BY_WELLBORE)], by_wellbore=True)
filled_drilling = drilling[drilling["filled_by"].isin(["ffill", "bfill_leading"])]
return {
"report_status": _counts(t1r["status"]),
"hole_sizes_published": _counts(live["diaHole"].dropna()),
"reports_without_diaHole": int(len(missing)),
"reports_without_diaHole_with_drilling_activities": int((missing["scope"] == "drilling_day").sum()),
"drilling_activities_on_those_reports": int(missing["n_drilling_activities"].sum()),
"wellbores_with_those_reports": int(missing.loc[missing["scope"] == "drilling_day", "wellbore"].nunique()),
"missing_position": {"all": _counts(position), "drilling_day": _counts(position_drilling)},
"filled_by": {"all": _counts(live["filled_by"]), "drilling_day": _counts(drilling["filled_by"])},
"fill_gap_days_filled_drilling_days": _quantiles(filled_drilling["fill_gap_days"]),
"fill_gap_reports_filled_drilling_days": _quantiles(filled_drilling["fill_gap_reports"]),
"section": {"all": _counts(live["section"]), "drilling_day": _counts(drilling["section"]),
"published_only": _counts(live.loc[live["filled_by"].eq("diaHole"), "section"])},
"phase": {"all": _counts(live["phase"]), "drilling_day": _counts(drilling["phase"])},
"pilot_reports": int(live["is_pilot"].sum()),
"scope": _counts(t1r["scope"]),
"day_op_group": _counts(live["day_op_group"].dropna()),
"day_op_class": _counts(live["day_op_class"].dropna()),
"op_group": _counts(t1a["op_group"]),
"op_class": _counts(t1a["op_class"]),
"op_sub_values": int(t1a["op_sub"].nunique()),
"fill_rule": cfg["t1"]["fill"],
"fill_evaluation": {
"note": "known diaHole masked and recovered; recovered = correct / masked, coverage = answered / masked",
"overall": _records(overall),
"by_wellbore": _records(by_wellbore),
"on_reports_without_diaHole": _records(L.fill_on_missing(feat)),
},
"hole_size_named_in_text": {
"note": "sum24Hr + drilling-group comments name a hole size as "
"'<size>\" hole|section|pilot hole|open hole'",
"reports_with_diaHole": int(len(known)), "of_which_text_names_a_size": int(len(named)),
"text_equals_diaHole": int((named["text_dia"] == named["dia"]).sum()),
"reports_without_diaHole_where_text_names_a_size": int(f.loc[f["dia"].isna(), "text_dia"].notna().sum()),
},
}
def t2_summary(t2: pd.DataFrame, activities: pd.DataFrame, tables: dict[str, pd.DataFrame]) -> dict:
out: dict = {"activities": int(len(t2)), "hours": round(float(t2["duration_h"].sum()), 2)}
out["candidates"] = {"interruption": int(t2["is_interruption"].sum()), "state_fail": int(t2["is_state_fail"].sum()),
"detail_nonsuccess": int(t2["is_detail_nonsuccess"].sum())}
for d in L.NPT_DEFINITIONS:
npt = t2[t2[f"npt_{d}"]]
hours = npt.groupby(f"cause_{d}")["duration_h"].sum().round(2)
out[f"npt_{d}"] = {"n": int(len(npt)), "share": round(len(npt) / len(t2), 4),
"hours": round(float(npt["duration_h"].sum()), 2),
"hours_share": round(float(npt["duration_h"].sum() / t2["duration_h"].sum()), 4),
"cause": _counts(npt[f"cause_{d}"]),
"cause_hours": {str(k): float(v) for k, v in hours.items()},
"cause_fine": _counts(npt["cause_fine"]),
"cause_rule": _counts(npt["cause_rule"]),
"cause_conflict": int(npt["cause_conflict"].sum())}
only_b = t2[t2["npt_b"] & ~t2["npt_a"]]
out["npt_b_not_a"] = {"n": int(len(only_b)), "op_group": _counts(activities.loc[only_b.index, "code_main"]),
"cause": _counts(only_b["cause_group"])}
conflicts = t2[t2["cause_conflict"]]
out["cause_conflicts"] = _counts(conflicts["cause_from_code"] + " | " + conflicts["cause_from_detail"])
wait = t2["wait_code_outside_interruption"]
out["wait_code_outside_interruption"] = {"n": int(wait.sum()), "of_which_npt_b": int((wait & t2["npt_b"]).sum())}
rig = activities["phase"].to_numpy()
out["npt_rate_by_rig_phase"] = {str(p): {"n": int((rig == p).sum()),
"npt_a": round(float(t2.loc[rig == p, "npt_a"].mean()), 4),
"npt_b": round(float(t2.loc[rig == p, "npt_b"].mean()), 4)}
for p in sorted(set(rig))}
# The equip_failures table is a structured near-label that the masked view leaves out: how much would it tell?
with_failure = set(tables["equip_failures"]["report_id"])
by_report = t2.assign(equipment=t2["cause_b"].eq("equipment")).groupby("report_id")["equipment"].any()
has = by_report.index.isin(with_failure)
out["equip_failures_table"] = {
"reports_with_rows": int(len(with_failure)),
"reports_with_equipment_npt_b": int(by_report.sum()),
"reports_with_both": int((by_report & has).sum()),
"share_of_equipment_npt_reports_with_rows": round(float((by_report & has).sum() / by_report.sum()), 4),
"share_of_reports_with_rows_that_have_equipment_npt": round(float((by_report & has).sum() / has.sum()), 4)}
for by in ("wellbore", "well"):
per = t2.groupby(by).agg(n=("act_id", "size"), npt_a=("npt_a", "mean"), npt_b=("npt_b", "mean"))
out[f"npt_rate_by_{by}"] = {w: {"n": int(r.n), "npt_a": round(float(r.npt_a), 4),
"npt_b": round(float(r.npt_b), 4)} for w, r in per.iterrows()}
return out
def t3_summary(t3a: pd.DataFrame, cells: pd.DataFrame, intervals: dict, episodes: dict, activities: pd.DataFrame,
reports: pd.DataFrame, t1r: pd.DataFrame, cfg: dict) -> dict:
grid = float(cfg["t3"]["grid_m"])
out: dict = {"grid_m": grid, "merge_gap_cells": cfg["t3"]["merge_gap_cells"],
"mudline_md": {w: round(float(v), 1) for w, v in L.mudline(reports).items()},
"own_hole_top_md": {w: round(float(v), 1) for w, v in L.own_hole_top(reports).items()}}
out["depth_class"] = {"all": _counts(t3a["depth_class"])}
hours = t3a.groupby("depth_class")["duration_h"].sum().round(2)
out["depth_class"]["all_hours"] = {str(k): float(v) for k, v in hours.items()}
code_main = activities.set_index("act_id")["code_main"].reindex(t3a["act_id"]).to_numpy()
table = pd.crosstab(code_main, t3a["depth_class"].to_numpy())
out["depth_class"]["by_op_group"] = {str(g): {str(k): int(v) for k, v in row.items()}
for g, row in table.iterrows()}
for d in L.NPT_DEFINITIONS:
npt = t3a[t3a[f"npt_{d}"]]
located = npt["depth_class"].eq("in_hole")
cause = pd.crosstab(npt["cause_group"], located)
out["depth_class"][f"npt_{d}"] = {
"n": _counts(npt["depth_class"]),
"hours": {str(k): float(v) for k, v in npt.groupby("depth_class")["duration_h"].sum().round(2).items()},
"located_share": round(float(located.mean()), 4),
"located_hours_share": round(float(npt.loc[located, "duration_h"].sum() / npt["duration_h"].sum()), 4),
"located_by_cause": {str(c): {"in_hole": int(row.get(True, 0)), "not_located": int(row.get(False, 0))}
for c, row in cause.iterrows()}}
# What the single depth value does and does not say.
hole = t3a[t3a["depth_class"].eq("in_hole")]
drill = hole[code_main[hole.index] == "drilling"]
code = activities.set_index("act_id")["proprietaryCode"].reindex(hole["act_id"])
is_drill = code.eq("drilling -- drill").to_numpy()
d = hole[is_drill]
back = d["md"] < d.groupby("wellbore")["md"].cummax() - grid
report_md = t3a["report_id"].map(reports.set_index("report_id")["md"])
deepest_report = t3a["wellbore"].map(reports.groupby("wellbore")["md"].max())
no_drilling_day = t3a["report_id"].map(t1r.set_index("report_id")["scope"]).ne("drilling_day")
out["md_checks"] = {
"activities_md_missing": int(t3a["md"].isna().sum()),
"activities_md_zero": int((t3a["md"] == 0).sum()),
"activities_above_mudline": int(t3a["depth_class"].eq("above_mudline").sum()),
"activities_in_hole": int(len(hole)),
"in_hole_in_drilling_group": int(len(drill)),
"in_hole_on_days_without_drilling_activities": int((t3a["depth_class"].eq("in_hole") & no_drilling_day).sum()),
"drill_rows_in_hole": int(len(d)),
"drill_rows_more_than_one_cell_above_deepest_so_far": int(back.sum()),
"activities_deeper_than_report_md_by_more_than_one_cell": int((t3a["md"] > report_md + grid).sum()),
"activities_on_reports_without_md": int(report_md.isna().sum()),
"activities_deeper_than_deepest_report_md_of_wellbore": int((t3a["md"] > deepest_report + grid).sum()),
}
out["cells"] = {"n": int(len(cells)), "without_activity": int((cells["n_activities"] == 0).sum()),
"in_own_hole": int(cells["in_own_hole"].sum()),
"by_wellbore": {w: int(n) for w, n in cells.groupby("wellbore").size().items()}}
for d in L.NPT_DEFINITIONS:
pos = cells[cells[f"label_{d}"]]
iv = intervals[d]
top = iv["wellbore"].map(L.own_hole_top(reports))
out["cells"][f"positive_{d}"] = int(len(pos))
out["cells"][f"positive_{d}_in_own_hole"] = int(pos["in_own_hole"].sum())
out["cells"][f"positive_{d}_by_wellbore"] = {w: int(n) for w, n in pos.groupby("wellbore").size().items()}
out[f"intervals_{d}"] = {
"n": int(len(iv)), "wellbores": int(iv["wellbore"].nunique()), "wells": int(iv["well"].nunique()),
"length_m_total": float(iv["length_m"].sum()), "length_m": _quantiles(iv["length_m"]),
"one_cell": int((iv["n_positive_cells"] == 1).sum()),
"one_activity": int((iv["n_activities"] == 1).sum()),
"activities": int(iv["n_activities"].sum()), "hours": round(float(iv["hours"].sum()), 2),
"entirely_above_own_hole_top": int((iv["md_bottom"] <= top).sum()),
"by_wellbore": {w: int(n) for w, n in iv.groupby("wellbore").size().items()},
"by_merge_gap_cells": {str(g): int(len(L.t3_intervals(cells, t3a, d, cfg, merge_gap_cells=g)))
for g in (0, 1, 2)}}
ep = episodes[d]
out[f"episodes_{d}"] = {"n": int(len(ep)), "with_in_hole_depth": int((ep["n_in_hole"] > 0).sum()),
"hours": _quantiles(ep["hours"]), "activities": _quantiles(ep["n_activities"]),
"spanning_reports": int((ep["n_reports"] > 1).sum())}
return out
def coverage_summary(t1r: pd.DataFrame, t1a: pd.DataFrame, t2: pd.DataFrame, cells: pd.DataFrame,
intervals: dict, activities: pd.DataFrame, reports: pd.DataFrame) -> dict:
live = t1r[t1r["status"].ne("placeholder_date")]
drilling = live[live["scope"].eq("drilling_day")]
frames = {
"t1_section_drilling_day": (drilling, "section"), "t1_section_all_days": (live, "section"),
"t1_phase_drilling_day": (drilling, "phase"), "t1_phase_all_days": (live, "phase"),
"t1_op_class": (t1a, "op_class"), "t1_op_group": (t1a, "op_group"), "t1_op_sub": (t1a, "op_sub"),
"t1_day_op_class": (live, "day_op_class"),
}
for d in L.NPT_DEFINITIONS:
npt = t2[t2[f"npt_{d}"]]
frames[f"t2_npt_{d}"] = (t2.assign(**{f"npt_{d}": t2[f"npt_{d}"].map({True: "npt", False: "not_npt"})}),
f"npt_{d}")
frames[f"t2_cause_{d}"] = (npt, f"cause_{d}")
frames[f"t2_cause_fine_{d}"] = (npt, "cause_fine")
frames[f"t3_cell_{d}"] = (cells.assign(**{f"label_{d}": cells[f"label_{d}"].map({True: "trouble",
False: "no_trouble"})}),
f"label_{d}")
frames[f"t3_interval_{d}"] = (intervals[d].assign(interval="interval"), "interval")
coverage, distributions, rare = {}, {}, []
for name, (frame, column) in frames.items():
cov = L.class_coverage(frame, column, rare=RARE)
coverage[name] = _records(cov.drop(columns="label"))
if name != "t1_op_sub":
distributions[name] = {"by_wellbore": L.distribution(frame, column, "wellbore"),
"by_well": L.distribution(frame, column, "well")}
flagged = cov[cov["rare"] | cov["single_wellbore"] | cov["single_well"]]
rare += [{"label": name, "class": r["class"], "n": int(r["n"]), "n_wellbores": int(r["n_wellbores"]),
"n_wells": int(r["n_wells"]), "rare": bool(r["rare"])} for _, r in flagged.iterrows()]
wells = t1r.groupby("well")["wellbore"].agg(lambda s: sorted(set(s))).to_dict()
return {
"note": "n_wellbores / n_wells = groups that contain the class; a class in one group cannot be in both the "
"training and the test side of a grouped split. top_*_share = largest share held by one group.",
"wells": wells, "n_wells": len(wells), "n_wellbores": int(t1r["wellbore"].nunique()),
"reports_by_wellbore": {w: int(n) for w, n in t1r.groupby("wellbore").size().items()},
"activities_by_wellbore": {w: int(n) for w, n in t1a.groupby("wellbore").size().items()},
"activities_by_well": {w: int(n) for w, n in t1a.groupby("well").size().items()},
"split_facts": split_facts(activities, reports, t1r, cells),
"classes": coverage, "flagged_classes": rare, "distributions": distributions,
}
def split_facts(activities: pd.DataFrame, reports: pd.DataFrame, t1r: pd.DataFrame, cells: pd.DataFrame) -> dict:
"""What wellbores of one well share, for the choice between a split by wellbore and a split by well:
report days that two wellbores of a well both report, activity comments that occur verbatim in another wellbore
of the same well (against the same in another well), and trouble cells in the hole shared with the parent."""
live = t1r[t1r["status"].ne("placeholder_date")].merge(reports[["report_id", "sum24Hr"]], on="report_id")
days = live.groupby(["well", "file_date"]).agg(n=("wellbore", "nunique"), texts=("sum24Hr", "nunique"))
shared = days[days["n"] > 1]
text = activities["comments"].fillna("").str.lower().str.replace(r"\s+", " ", regex=True).str.strip()
g = pd.DataFrame({"text": text, "wellbore": activities["wellbore"], "well": activities["wellbore"].map(L.well_of)})
out = {"report_days_shared_by_two_wellbores_of_a_well": int(len(shared)),
"of_which_same_sum24Hr": int((shared["texts"] == 1).sum()),
"wells_with_shared_days": sorted(shared.index.get_level_values(0).unique())}
for name, sel in (("all_comments", g), ("comments_of_40_chars_or_more", g[g["text"].str.len() >= 40])):
in_well = sel.groupby(["text", "well"])["wellbore"].nunique()
wells = sel.groupby("text")["well"].nunique()
twin_same_well = pd.MultiIndex.from_frame(sel[["text", "well"]]).map(in_well).to_numpy() > 1
twin_other_well = sel["text"].map(wells).to_numpy() > 1
multi = sel["well"].map(sel.groupby("well")["wellbore"].nunique()).to_numpy() > 1
out[name] = {"n": int(len(sel)),
"verbatim_in_another_wellbore_of_the_same_well": int(twin_same_well.sum()),
"verbatim_in_another_well": int(twin_other_well.sum()),
"n_in_wells_with_several_wellbores": int(multi.sum()),
"share_same_well_among_those": round(float(twin_same_well[multi].mean()), 4),
"share_other_well": round(float(twin_other_well.mean()), 4)}
for d in L.NPT_DEFINITIONS:
pos = cells[cells[f"label_{d}"]]
out[f"t3_positive_cells_{d}_above_own_hole_top"] = int((~pos["in_own_hole"]).sum())
return out
def expected_counts(t1r, t1a, t2, t3a, cells, intervals, episodes) -> dict:
live = t1r[t1r["status"].ne("placeholder_date")]
got = {
"report_status": _counts(t1r["status"]),
"t1_scope": _counts(t1r["scope"]),
"t1_filled_by": _counts(live["filled_by"]),
"t1_section": _counts(live["section"]),
"t1_section_drilling_day": _counts(live.loc[live["scope"].eq("drilling_day"), "section"]),
"t1_phase": _counts(live["phase"]),
"t1_op_class": _counts(t1a["op_class"]),
"t3_depth_class": _counts(t3a["depth_class"]),
"t3_cells": int(len(cells)),
}
for d in L.NPT_DEFINITIONS:
got[f"t2_npt_{d}"] = int(t2[f"npt_{d}"].sum())
got[f"t2_cause_{d}"] = _counts(t2.loc[t2[f"npt_{d}"], f"cause_{d}"])
got[f"t3_npt_in_hole_{d}"] = int((t3a[f"npt_{d}"] & t3a["depth_class"].eq("in_hole")).sum())
got[f"t3_positive_cells_{d}"] = int(cells[f"label_{d}"].sum())
got[f"t3_intervals_{d}"] = int(len(intervals[d]))
got[f"t3_episodes_{d}"] = int(len(episodes[d]))
return got
def analysis_md(summary: dict) -> str:
"""The short analysis for the protocol author, written from summary.json (same numbers, readable form)."""
t1, t2, t3, cov = summary["t1"], summary["t2"], summary["t3"], summary["coverage"]
lines = ["# Volve-DIA labels T1-T3: analysis for the evaluation protocol", "",
"Generated by scripts/07_labels.py from outputs/ddr and configs/labels.yaml "
f"(sha256 {summary['labels_yaml']['sha256'][:12]}). Every number is in summary.json.", ""]
lines += ["## T1 fill rule: recovery of masked diaHole", "",
"| rule | " + " | ".join(f"{s} recovered / coverage" for s in L.MASK_SCHEMES) + " |",
"| --- |" + " ---: |" * len(L.MASK_SCHEMES)]
rows = {(r["rule"], r["scheme"]): r for r in t1["fill_evaluation"]["overall"]}
for rule in L.FILL_RULES:
cells = [f"{rows[(rule, s)]['recovered']:.4f} / {rows[(rule, s)]['coverage']:.4f}" for s in L.MASK_SCHEMES]
lines.append(f"| {rule} | " + " | ".join(cells) + " |")
masked = {s: rows[("ffill", s)]["n_masked"] for s in L.MASK_SCHEMES}
lines += ["", f"Masked reports per scheme: {masked}.", "",
"On the reports that really lack diaHole (nothing masked):", "",
"| rule | subset | n | answered | text names a size | both | agree with text | bit record | both | "
"agree with bit |", "| --- | --- | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: |"]
for r in t1["fill_evaluation"]["on_reports_without_diaHole"]:
lines.append(f"| {r['rule']} | {r['subset']} | {r['n']} | {r['n_answered']} | {r['n_text']} | {r['n_both']} | "
f"{r['n_agree_text']} | {r['n_bit']} | {r['n_both_bit']} | {r['n_agree_bit']} |")
lines += ["", f"Position of the reports without diaHole: {t1['missing_position']}.",
f"Sections after filling (all days): {t1['section']['all']}; "
f"drilling days: {t1['section']['drilling_day']}.",
f"Filled by: {t1['filled_by']}.", ""]
lines += ["## T2: NPT and cause groups", "", "| cause group | (a) interruption only | (b) union |",
"| --- | ---: | ---: |"]
causes = sorted(set(t2["npt_a"]["cause"]) | set(t2["npt_b"]["cause"]))
for c in causes:
lines.append(f"| {c} | {t2['npt_a']['cause'].get(c, 0)} | {t2['npt_b']['cause'].get(c, 0)} |")
lines += [f"| **total** | {t2['npt_a']['n']} | {t2['npt_b']['n']} |", "",
f"NPT hours: (a) {t2['npt_a']['hours']} h ({t2['npt_a']['hours_share']:.2%} of the reported hours), "
f"(b) {t2['npt_b']['hours']} h ({t2['npt_b']['hours_share']:.2%}).", ""]
lines += ["## T3: trouble intervals and what activities.md allows", "",
f"Depth class of all activities: {t3['depth_class']['all']}.",
f"NPT rows located in the hole: (a) {t3['depth_class']['npt_a']['located_share']:.2%} of rows, "
f"{t3['depth_class']['npt_a']['located_hours_share']:.2%} of hours; "
f"(b) {t3['depth_class']['npt_b']['located_share']:.2%} of rows, "
f"{t3['depth_class']['npt_b']['located_hours_share']:.2%} of hours.",
f"Cells: {t3['cells']['n']} ({t3['cells']['without_activity']} without any activity); positive "
f"(a) {t3['cells']['positive_a']}, (b) {t3['cells']['positive_b']}.",
f"Intervals: (a) {t3['intervals_a']['n']} in {t3['intervals_a']['wellbores']} wellbores, "
f"(b) {t3['intervals_b']['n']} in {t3['intervals_b']['wellbores']} wellbores; by merge gap "
f"(a) {t3['intervals_a']['by_merge_gap_cells']}, (b) {t3['intervals_b']['by_merge_gap_cells']}.",
f"Checks: {t3['md_checks']}.", ""]
lines += ["## Classes that a grouped split cannot evaluate, or that are rare", "",
"| label | class | n | wellbores | wells | fewer than 20 |", "| --- | --- | ---: | ---: | ---: | --- |"]
for r in cov["flagged_classes"]:
if r["label"] != "t1_op_sub":
lines.append(f"| {r['label']} | {r['class']} | {r['n']} | {r['n_wellbores']} | {r['n_wells']} | "
f"{'yes' if r['rare'] else ''} |")
lines += ["", f"What wellbores of one well share: {cov['split_facts']}."]
lines += ["", "## Number of wellbores and wells per class (T2 cause, T1 section and operation)", "",
"| label | class | n | wellbores (of 26) | wells (of 11) | top wellbore (share) | top well (share) |",
"| --- | --- | ---: | ---: | ---: | --- | --- |"]
for name in ("t2_cause_a", "t2_cause_b", "t1_section_drilling_day", "t1_phase_drilling_day", "t1_op_class"):
for r in cov["classes"][name]:
lines.append(f"| {name} | {r['class']} | {r['n']} | {r['n_wellbores']} | {r['n_wells']} | "
f"{r['top_wellbore']} ({r['top_wellbore_share']:.2f}) | {r['top_well']} "
f"({r['top_well_share']:.2f}) |")
lines += ["", "## Free text naming the label (comment only)", "",
"| target | definition | positives | recall | false-positive rate | precision |",
"| --- | --- | ---: | ---: | ---: | ---: |"]
for r in summary["text"]["lexicon"]:
if r["scope"] == "comment":
lines.append(f"| {r['target']} | {r['definition']} | {r['n_pos']} | {r['recall']} | {r['fpr']} | "
f"{r['precision']} |")
return "\n".join(lines) + "\n"
def main() -> int:
ddr = paths.outputs_dir() / "ddr"
out = paths.outputs_dir() / "labels"
out.mkdir(parents=True, exist_ok=True)
names = ("reports", "activities", "bits", "casings", "equip_failures")
missing = [n for n in names if not (ddr / f"{n}.parquet").is_file()]
if missing:
print(f"missing {ddr}/{{{','.join(missing)}}}.parquet: run scripts/02_parse_ddr.py first")
return 1
src = {n: pd.read_parquet(ddr / f"{n}.parquet") for n in names}
reports, activities = src["reports"], src["activities"]
config_path = paths.REPO_ROOT / "configs" / "labels.yaml"
cfg = L.load_config(config_path)
diff = L.check_code_counts(activities, cfg)
if diff:
print("configs/labels.yaml differs from the data (written, found):", diff)
return 1
tl = L.timeline(reports, activities, cfg)
feat = L.fill_features(tl, activities, src["bits"], src["casings"], cfg)
ev = L.evaluate_fill_rules(feat)
ops = L.operation_classes(activities, cfg)
t1r = L.attach_witsml_section(L.t1_reports(feat, ops, activities, cfg), None)
t1a = L.t1_activities(ops, t1r)
t2 = L.t2_labels(activities, cfg)
t2in = L.t2_inputs(activities, reports, cfg)
lexicon = L.text_rates(activities, reports, t2, cfg)
literal = L.code_sub_literal(activities)
t3a = L.t3_activities(activities, t2, reports, cfg)
episodes = {d: L.t3_episodes(t3a, d) for d in L.NPT_DEFINITIONS}
cells = L.t3_cells(t3a, reports, cfg)
intervals = {d: L.t3_intervals(cells, t3a, d, cfg) for d in L.NPT_DEFINITIONS}
cells = L.attach_intervals(cells, intervals)
code_map = pd.DataFrame([{"proprietaryCode": c, "n": r["n"], "op_group": c.split(" -- ")[0],
"op_sub": c.split(" -- ")[1], "op_class": r["op_class"], "cause": r["cause"]}
for c, r in cfg["codes"].items()])
tables = {
"code_map": code_map, "t1_reports": t1r, "t1_activities": t1a, "t2_labels": t2, "t2_inputs": t2in,
"t3_activities": t3a, "t3_episodes": pd.concat(episodes.values(), ignore_index=True), "t3_cells": cells,
"t3_intervals": pd.concat(intervals.values(), ignore_index=True), "fill_eval": ev,
"text_lexicon_rates": lexicon, "text_code_sub_literal": literal,
}
for name, df in tables.items():
df.to_parquet(out / f"{name}.parquet", index=False)
db, tmp = out / "volve_labels.duckdb", out / "volve_labels.duckdb.tmp"
tmp.unlink(missing_ok=True)
with duckdb.connect(str(tmp)) as con:
for name in tables:
con.execute(f"CREATE TABLE {name} AS SELECT * FROM read_parquet('{out / name}.parquet')")
os.replace(tmp, db)
got = expected_counts(t1r, t1a, t2, t3a, cells, intervals, episodes)
summary = {
"labels_yaml": {"version": cfg["version"], "sha256": hashlib.sha256(config_path.read_bytes()).hexdigest()},
"counts": got,
"tables": {name: {"rows": len(df), "columns": df.shape[1]} for name, df in tables.items()},
"decisions": {
"placeholder_report": t1r.loc[t1r["status"].eq("placeholder_date"), "report_id"].tolist(),
"reports_without_activities": t1r.loc[t1r["status"].eq("no_activities"), "report_id"].tolist(),
"note": "placeholder: no section, no row in T2/T3, outside the timeline; no_activities: section label "
"kept (T1 report-day), no operation label, no row in T2/T3",
},
"t1": t1_summary(t1r, t1a, feat, ev, cfg),
"t2": t2_summary(t2, activities, src),
"t3": t3_summary(t3a, cells, intervals, episodes, activities, reports, t1r, cfg),
"text": {"note": "analysis only: how often the free text names the label; never a label source",
"lexicon": _records(lexicon), "code_sub_literal": _records(literal)},
"coverage": coverage_summary(t1r, t1a, t2, cells, intervals, activities, reports),
}
(out / "summary.json").write_text(json.dumps(summary, indent=1, ensure_ascii=False) + "\n", encoding="utf-8")
(out / "analysis.md").write_text(analysis_md(summary), encoding="utf-8")
print(json.dumps({"counts": got, "tables": summary["tables"]}, indent=1, ensure_ascii=False))
diff = {k: (EXPECTED.get(k), got.get(k)) for k in sorted(set(EXPECTED) | set(got)) if EXPECTED.get(k) != got.get(k)}
if diff:
print("counts differ from EXPECTED (expected, got):", diff)
return 1
return 0
if __name__ == "__main__":
sys.exit(main())