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

642
tests/test_labels.py Normal file
View File

@@ -0,0 +1,642 @@
"""volve_dia.labels: every rule of T1-T3 on small synthetic frames, then the locked counts on the Volve tables
(`data` marker; skipped without outputs/ddr or the DDR XML folder)."""
import importlib.util
import numpy as np
import pandas as pd
import pytest
from volve_dia import labels as L
from volve_dia import paths
CFG = L.load_config()
# ---------------------------------------------------------------------------------------------------------------
# Synthetic frames
# ---------------------------------------------------------------------------------------------------------------
def _ts(day: int, hour: float = 0.0) -> pd.Timestamp:
return pd.Timestamp("2010-01-01", tz="UTC") + pd.Timedelta(days=day, hours=hour)
def _reports(rows: list[dict]) -> pd.DataFrame:
"""One report per row, one day each; defaults for every column the label code reads."""
out = []
for i, row in enumerate(rows):
day = row.pop("day", i)
wellbore = row.pop("wellbore", "15/9-F-1")
base = {"report_id": f"{wellbore}#{day:03d}", "wellbore": wellbore, "file_date": str(_ts(day + 1).date()),
"start_utc": _ts(day), "end_utc": _ts(day + 1), "dTimSpud": "2010-01-01T00:00:00+00:00",
"diaHole": np.nan, "diaPilot": np.nan, "mdDiaHoleStart": np.nan, "mdCsgLast": np.nan, "md": np.nan,
"tvd": np.nan, "distDrill": np.nan, "waterDepth": 91.0, "elevKelly": 54.9, "reportNo": day + 1,
"sum24Hr": "None", "forecast24Hr": "None", "rigAlias_NPD_Name": "RIG", "operator": "OP",
"drillContractor": "DC"}
out.append({**base, **row})
return pd.DataFrame(out)
def _activities(rows: list[tuple]) -> pd.DataFrame:
"""(report_id, wellbore, start hour within the series, hours, md, code, state, detail, comment)."""
out, seq = [], {}
for report_id, wellbore, start, hours, md, code, state, detail, comment in rows:
n = seq[report_id] = seq.get(report_id, -1) + 1
main, sub = code.split(" -- ")
out.append({"report_id": report_id, "wellbore": wellbore, "seq": n, "act_id": f"{report_id}:{n:03d}",
"md": md, "phase": "fixed", "proprietaryCode": code, "code_main": main, "code_sub": sub,
"state": state, "stateDetailActivity": detail, "comments": comment,
"start_utc": _ts(0, start), "end_utc": _ts(0, start + hours), "duration_h": float(hours)})
return pd.DataFrame(out)
EMPTY_BITS = pd.DataFrame({"report_id": [], "wellbore": [], "diaBit": []})
EMPTY_CASINGS = pd.DataFrame({"report_id": [], "wellbore": [], "od": [], "mdBottom": []})
W = "15/9-F-1"
def _one_activity_per_report(reports: pd.DataFrame, code: str = "drilling -- drill") -> pd.DataFrame:
return _activities([(r.report_id, r.wellbore, 24.0 * i, 24.0, 500.0, code, "ok", "success", "x")
for i, r in enumerate(reports.itertuples())])
# ---------------------------------------------------------------------------------------------------------------
# Configuration
# ---------------------------------------------------------------------------------------------------------------
def test_config_maps_all_64_codes_to_declared_classes():
assert CFG["version"] == 1 and len(CFG["codes"]) == 64
assert sum(r["n"] for r in CFG["codes"].values()) == 23447
assert {r["op_class"] for r in CFG["codes"].values()} == set(CFG["t1"]["op_classes"])
interruption = {c: r for c, r in CFG["codes"].items() if c.startswith("interruption -- ")}
assert len(interruption) == 10 and {r["op_class"] for r in interruption.values()} == {"interruption"}
assert sum(r["n"] for r in interruption.values()) == 3577
assert all(r["cause"] == "detail" for c, r in CFG["codes"].items() if c not in interruption)
assert sum(r["n"] for r in CFG["t1"]["hole_sizes"].values()) == 769
@pytest.mark.parametrize("old, new, message", [
("op_class: trip,", "op_class: tripping,", "op_class"),
("cause: weather}", "cause: storm}", "cause"),
("version: 1", "version: 2", "version"),
('"drilling -- drill": {n: 1822, op_class: drill_ream, cause: detail}',
'"drilling -- drill": {n: 1822, op_class: drill_ream, cause: weather}',
"only interruption codes"),
])
def test_config_rejects_undeclared_classes(tmp_path, old, new, message):
text = (paths.REPO_ROOT / "configs" / "labels.yaml").read_text(encoding="utf-8")
assert old in text
bad = tmp_path / "labels.yaml"
bad.write_text(text.replace(old, new, 1), encoding="utf-8")
with pytest.raises(ValueError, match=message):
L.load_config(bad)
def test_check_code_counts_reports_every_difference():
a = _activities([("r", W, 0, 1, 0.0, "drilling -- drill", "ok", "success", "x")])
diff = L.check_code_counts(a, CFG)
assert diff["drilling -- drill"] == (1822, 1) and diff["drilling -- trip"] == (1430, None)
assert diff["state=ok"] == (22967, 1) and diff["stateDetailActivity=success"] == (20802, 1)
# ---------------------------------------------------------------------------------------------------------------
# T1: text sizes, masks, fill rules
# ---------------------------------------------------------------------------------------------------------------
@pytest.mark.parametrize("text, expected", [
('Drilled 12 1/4" hole from 2842 m to 2872 m MD', [12.25]),
("DRILLED 8-1/2\" HOLE", [8.5]),
("Drilled 8½\" hole and 17 ½\" section", [8.5, 17.5]),
("Drilled 17,5\" hole; drilled 12.25 in hole", [17.5, 12.25]),
('OPENED 9 7/8" PILOTHOLE TO 26" HOLE FROM 170 M', [9.875, 26.0]),
('Ran 9 5/8" casing. Made up 8 1/2" BHA. POOH with 5 1/2" DP', []), # not a hole size wording
('Drilled 16" hole', []), # not a size of this field
('pressure tested to 345 bar / 12 1/4" hole', [12.25]),
(None, []),
])
def test_hole_sizes_in_text(text, expected):
sizes = tuple(float(s) for s in CFG["t1"]["hole_sizes"])
assert L.hole_sizes_in_text(text, sizes) == expected
def test_known_runs_and_masks():
dia = np.array([np.nan, 36, 36, 26, 26, 26, 26, np.nan, 26, 17.5])
assert [r.tolist() for r in L.known_runs(dia)] == [[1, 2], [3, 4, 5, 6], [8], [9]]
assert [m.tolist() for m in L.fill_masks(dia, "single")] == [[1], [2], [3], [4], [5], [6], [8], [9]]
assert [m.tolist() for m in L.fill_masks(dia, "tail_half")] == [[2], [5, 6]]
assert [m.tolist() for m in L.fill_masks(dia, "head_half")] == [[1], [3, 4]]
assert [m.tolist() for m in L.fill_masks(dia, "whole_run")] == [[1, 2], [3, 4, 5, 6], [8], [9]]
with pytest.raises(ValueError):
L.fill_masks(dia, "random")
def _wellbore_frame() -> pd.DataFrame:
"""Ten days: lead-in, 36" (2 days), 26" (3 days), two days without diaHole, 17.5" (2 days)."""
dia = [np.nan, 36, 36, 26, 26, 26, np.nan, np.nan, 17.5, 17.5]
return pd.DataFrame({
"dia": dia, "start_utc": [_ts(i) for i in range(10)],
"mdDiaHoleStart": [0, 145, 145, 200, 200, 200, 1400, 1400, 1405, 1405],
"mdCsgLast": [np.nan, np.nan, 195, 195, 195, 1390, 1390, 1390, 1390, 1390],
"md": [0, 180, 200, 800, 1400, 1400, 1400, 1400, 1900, 2500],
"bit_dia": [np.nan, 36, np.nan, 26, np.nan, np.nan, np.nan, 17.5, np.nan, np.nan],
"casing_hole": [np.nan, np.nan, 26, 26, 26, 17.5, 17.5, 17.5, 17.5, 17.5],
"text_dia": [np.nan, 36, np.nan, np.nan, 26, np.nan, np.nan, np.nan, 17.5, np.nan]})
def test_fill_rules_on_one_wellbore():
g = _wellbore_frame()
nan = np.nan
np.testing.assert_array_equal(L.FILL_RULES["ffill"](g), [nan, 36, 36, 26, 26, 26, 26, 26, 17.5, 17.5])
np.testing.assert_array_equal(L.FILL_RULES["bfill"](g), [36, 36, 36, 26, 26, 26, 17.5, 17.5, 17.5, 17.5])
np.testing.assert_array_equal(L.FILL_RULES["ffill_bfill"](g), [36, 36, 36, 26, 26, 26, 26, 26, 17.5, 17.5])
# day 6 is one day after 26" and two before 17.5"; day 7 is two after and one before
np.testing.assert_array_equal(L.FILL_RULES["nearest"](g), [36, 36, 36, 26, 26, 26, 26, 17.5, 17.5, 17.5])
# the header opens a new record (1400 m) on the days without diaHole: no known report shares it
np.testing.assert_array_equal(L.FILL_RULES["hole_start"](g), [nan, 36, 36, 26, 26, 26, nan, nan, 17.5, 17.5])
# shoe at 195 m is shared by one 36" day and two 26" days; shoe at 1390 m by one 26" day and two 17.5" days
np.testing.assert_array_equal(L.FILL_RULES["csg_last"](g), [nan, nan, 26, 26, 26, 17.5, 17.5, 17.5, 17.5, 17.5])
# md 1400 lies in the 26" range [800, 1400] only; md 0 in none; 200 m in the 36" range [180, 200]
np.testing.assert_array_equal(L.FILL_RULES["depth_range"](g), [nan, 36, 36, 26, 26, 26, 26, 26, 17.5, 17.5])
np.testing.assert_array_equal(L.FILL_RULES["bit_ffill"](g), [nan, 36, 36, 26, 26, 26, 26, 17.5, 17.5, 17.5])
np.testing.assert_array_equal(L.FILL_RULES["casing_program"](g), g["casing_hole"])
np.testing.assert_array_equal(L.FILL_RULES["text"](g), g["text_dia"])
def test_evaluate_fill_rules_counts_masked_answered_correct():
g = _wellbore_frame().assign(wellbore=W, status="ok")
ev = L.evaluate_fill_rules(g, rules=("ffill", "bfill", "bit_report"))
s = L.summarise_fill_eval(ev).set_index(["rule", "scheme"])
# single: 7 known days; ffill misses the first day of each of the three runs (one of them unanswered)
assert tuple(s.loc[("ffill", "single"), ["n_masked", "n_answered", "n_correct"]]) == (7, 6, 4)
assert tuple(s.loc[("bfill", "single"), ["n_masked", "n_answered", "n_correct"]]) == (7, 6, 4)
# tail_half masks days 2, 5 and 9: the head of each run stays visible
assert tuple(s.loc[("ffill", "tail_half"), ["n_masked", "n_correct"]]) == (3, 3)
assert tuple(s.loc[("bfill", "tail_half"), ["n_masked", "n_answered", "n_correct"]]) == (3, 2, 0)
assert tuple(s.loc[("bfill", "head_half"), ["n_masked", "n_correct"]]) == (3, 3)
assert tuple(s.loc[("ffill", "whole_run"), ["n_masked", "n_answered", "n_correct"]]) == (7, 5, 0)
# a rule that does not read diaHole answers the same under every scheme
assert tuple(s.loc[("bit_report", "single"), ["n_masked", "n_answered", "n_correct"]]) == (7, 2, 2)
assert s.loc[("ffill", "single"), "recovered"] == round(4 / 7, 4)
assert s.loc[("ffill", "single"), "coverage"] == round(6 / 7, 4)
assert s.loc[("bit_report", "single"), "precision"] == 1.0
def test_fill_on_missing_compares_with_text_and_bit():
g = _wellbore_frame().assign(wellbore=W, status="ok", n_drilling_activities=[0, 1, 1, 1, 1, 1, 1, 0, 1, 1])
g.loc[7, "text_dia"] = 26.0
m = L.fill_on_missing(g, rules=("ffill", "bfill")).set_index(["rule", "subset"])
row = m.loc[("ffill", "all_missing")]
assert (row["n"], row["n_answered"], row["n_text"], row["n_both"], row["n_agree_text"]) == (3, 2, 1, 1, 1)
assert (row["n_bit"], row["n_both_bit"], row["n_agree_bit"]) == (1, 1, 0) # bit says 17.5 on day 7
assert m.loc[("bfill", "all_missing"), "n_agree_bit"] == 1
assert m.loc[("ffill", "missing_drilling_day"), "n"] == 1
# ---------------------------------------------------------------------------------------------------------------
# T1 labels
# ---------------------------------------------------------------------------------------------------------------
def test_timeline_status_and_placeholder_rule():
r = _reports([{"day": -6000, "sum24Hr": "None"}, {"day": 0}, {"day": 1}, {"day": -200}])
a = _activities([(r.report_id[1], W, 0, 24, 0.0, "drilling -- drill", "ok", "success", "x"),
(r.report_id[1], W, 0, 1, 0.0, "moving -- skid", "ok", "success", "x"),
(r.report_id[3], W, 0, 24, 0.0, "moving -- skid", "ok", "success", "x")])
tl = L.timeline(r, a, CFG).set_index("report_id")
assert tl.loc[r.report_id[0], "status"] == "placeholder_date" # no activity, 16 years before spud
assert tl.loc[r.report_id[2], "status"] == "no_activities" # no activity, real date
assert tl.loc[r.report_id[3], "status"] == "ok" # before spud but with activities
assert tl.loc[r.report_id[1], ["n_activities", "n_drilling_activities"]].tolist() == [2, 1]
assert tl["well"].eq("15/9-F-1").all() and tl.index.tolist() == [r.report_id[i] for i in (0, 3, 1, 2)]
def test_t1_reports_fill_provenance_and_phase():
r = _reports([{"day": -6000}, # placeholder
{"day": 0}, {"day": 1}, # before the first section
{"day": 2, "diaHole": 8.5, "diaPilot": 8.5}, # pilot
{"day": 3, "diaHole": 26.0},
{"day": 4}, {"day": 9}, # after the 26" section
{"day": 10, "diaHole": 12.25},
{"day": 11, "wellbore": "15/9-F-1 A", "diaHole": 6.0},
{"day": 12, "wellbore": "15/9-F-1 A"}])
a = _one_activity_per_report(r.iloc[[1, 3, 4, 5, 7, 8, 9]])
a.loc[a["report_id"].eq(r.report_id[9]), ["proprietaryCode", "code_main", "code_sub"]] = [
"completion -- perforate", "completion", "perforate"]
feat = L.fill_features(L.timeline(r, a, CFG), a, EMPTY_BITS, EMPTY_CASINGS, CFG)
ops = L.operation_classes(a, CFG)
t = L.t1_reports(feat, ops, a, CFG).set_index("report_id")
ids = r.report_id.tolist()
assert t.loc[ids[0], ["status", "filled_by", "scope"]].tolist() == ["placeholder_date", "none", "excluded"]
assert pd.isna(t.loc[ids[0], "section"]) and pd.isna(t.loc[ids[0], "phase"])
# leading days take the first section and inherit its pilot flag
assert t.loc[ids[1], ["section", "phase", "filled_by", "section_rule"]].tolist() == [
"8.5", "pilot", "bfill_leading", "T1.S3"]
assert t.loc[ids[1], "fill_source_report_id"] == ids[3] and t.loc[ids[1], "fill_gap_reports"] == 2
assert t.loc[ids[2], "scope"] == "no_activities" and t.loc[ids[2], "section"] == "8.5"
assert t.loc[ids[3], ["section", "phase", "filled_by", "phase_rule"]].tolist() == [
"8.5", "pilot", "diaHole", "T1.P2"]
assert t.loc[ids[4], ["section", "phase", "filled_by", "section_rule", "phase_rule"]].tolist() == [
"26", "surface", "diaHole", "T1.S1", "T1.P1"]
assert pd.isna(t.loc[ids[4], "fill_gap_days"]) or t.loc[ids[4], "fill_gap_days"] == 0
# forward fill, with the distance to the source report
assert t.loc[ids[5], ["section", "filled_by", "fill_source_report_id", "section_rule"]].tolist() == [
"26", "ffill", ids[4], "T1.S2"]
assert t.loc[ids[6], ["fill_gap_reports", "fill_gap_days"]].tolist() == [2, 6.0]
assert t.loc[ids[7], ["section", "phase"]].tolist() == ["12.25", "production"]
# the fill never crosses to another wellbore; 6" shares the reservoir phase
assert t.loc[ids[9], ["section", "phase", "filled_by", "scope"]].tolist() == [
"6", "reservoir", "ffill", "other_day"]
assert t.loc[ids[8], ["day_op_group", "day_op_class", "day_op_class_share"]].tolist() == [
"drilling", "drill_ream", 1.0]
assert t["section_witsml"].isna().all() and t["section_agree"].isna().all()
def test_day_operation_is_the_class_with_most_hours():
r = _reports([{"day": 0, "diaHole": 26.0}])
rid = r.report_id[0]
a = _activities([(rid, W, 0, 5, 300.0, "drilling -- drill", "ok", "success", "x"),
(rid, W, 5, 4, 300.0, "drilling -- trip", "ok", "success", "x"),
(rid, W, 9, 4, 300.0, "plug abandon -- trip", "ok", "success", "x"),
(rid, W, 13, 7, 0.0, "interruption -- repair", "ok", "equipment failure", "x")])
feat = L.fill_features(L.timeline(r, a, CFG), a, EMPTY_BITS, EMPTY_CASINGS, CFG)
t = L.t1_reports(feat, L.operation_classes(a, CFG), a, CFG).iloc[0]
assert (t["day_op_class"], t["day_op_class_share"]) == ("trip", 0.4) # 8 h in two main groups
assert (t["day_op_group"], t["day_op_group_share"]) == ("drilling", 0.45)
assert t["scope"] == "drilling_day"
def test_fill_features_bits_casings_text():
r = _reports([{"day": 0, "mdCsgLast": 1390.0, "sum24Hr": 'Drilled 17 1/2" hole to 1500 m'},
{"day": 1, "mdCsgLast": 1390.0}, {"day": 2, "mdCsgLast": 2500.0}, {"day": 3}])
ids = r.report_id.tolist()
a = _activities([(ids[0], W, 0, 24, 1500.0, "drilling -- drill", "ok", "success", 'Drilled 17 1/2" hole'),
(ids[1], W, 24, 12, 0.0, "drilling -- trip", "ok", "success", 'POOH with 17 1/2" BHA'),
(ids[1], W, 36, 12, 0.0, "completion -- other", "ok", "success", 'Drilled 8 1/2" hole'),
(ids[2], W, 48, 24, 0.0, "drilling -- drill", "ok", "success", '12 1/4" hole and 8 1/2" hole'),
(ids[3], W, 72, 24, 0.0, "drilling -- drill", "ok", "success", "x")])
bits = pd.DataFrame({"report_id": [ids[0], ids[0], ids[1]], "wellbore": W, "diaBit": [17.5, 36.0, -999.0]})
casings = pd.DataFrame({"report_id": [ids[0], ids[0]], "wellbore": ["15/9-F-1", "15/9-F-1 A"],
"od": [20.0, 13.375], "mdBottom": [1388.9, 2520.0]})
f = L.fill_features(L.timeline(r, a, CFG), a, bits, casings, CFG).set_index("report_id")
np.testing.assert_array_equal(f["bit_dia"], [36.0, np.nan, np.nan, np.nan]) # largest valid bit
# 20" shoe 1.1 m away -> 17.5"; the shoe of the sidetrack of the same well is 20 m away: out of tolerance
np.testing.assert_array_equal(f["casing_hole"], [17.5, 17.5, np.nan, np.nan])
# only drilling-group comments and sum24Hr are read; a tie between two sizes gives no answer
np.testing.assert_array_equal(f["text_dia"], [17.5, np.nan, np.nan, np.nan])
def test_operation_classes_cover_every_code_and_reject_unknown():
a = _activities([("r", W, i, 1, 0.0, code, "ok", "success", "x") for i, code in enumerate(CFG["codes"])])
ops = L.operation_classes(a, CFG)
assert ops["op_class"].tolist() == [r["op_class"] for r in CFG["codes"].values()]
assert ops["op_group"].nunique() == 7 and ops["op_sub"].nunique() == 41 and ops["op_class"].nunique() == 15
by_code = dict(zip(a["proprietaryCode"], ops["op_class"]))
assert by_code["plug abandon -- trip"] == by_code["formation evaluation -- trip"] == "trip"
assert by_code["plug abandon -- other"] == by_code["drilling -- other"] == "other"
assert by_code["interruption -- other"] == by_code["interruption -- waiting on weather"] == "interruption"
bad = a.assign(proprietaryCode="drilling -- fly")
with pytest.raises(ValueError, match="drilling -- fly"):
L.operation_classes(bad, CFG)
def test_t1_activities_inherit_the_section_of_the_day():
r = _reports([{"day": 0, "diaHole": 26.0}, {"day": 1}])
a = _one_activity_per_report(r)
feat = L.fill_features(L.timeline(r, a, CFG), a, EMPTY_BITS, EMPTY_CASINGS, CFG)
ops = L.operation_classes(a, CFG)
t = L.t1_activities(ops, L.t1_reports(feat, ops, a, CFG))
assert t["act_id"].tolist() == a["act_id"].tolist()
assert t[["section", "phase", "filled_by", "op_class", "op_rule"]].values.tolist() == [
["26", "surface", "diaHole", "drill_ream", "T1.O1"], ["26", "surface", "ffill", "drill_ream", "T1.O1"]]
def test_witsml_section_hook():
r = _reports([{"day": 0, "diaHole": 26.0}, {"day": 1, "diaHole": 26.0}, {"day": 2}])
a = _one_activity_per_report(r)
feat = L.fill_features(L.timeline(r, a, CFG), a, EMPTY_BITS, EMPTY_CASINGS, CFG)
t1 = L.t1_reports(feat, L.operation_classes(a, CFG), a, CFG)
assert L.attach_witsml_section(t1, None) is t1
w = pd.DataFrame({"wellbore": W, "start_utc": [_ts(0), _ts(1, 6)], "end_utc": [_ts(1, 6), _ts(2)],
"section_in": [26.0, 17.5]})
t = L.attach_witsml_section(t1, w)
assert t["section_witsml"].tolist()[:2] == [26.0, 17.5] and pd.isna(t["section_witsml"][2])
assert t["section_agree"].tolist()[:2] == [True, False] and pd.isna(t["section_agree"][2])
# ---------------------------------------------------------------------------------------------------------------
# T2
# ---------------------------------------------------------------------------------------------------------------
T2_ROWS = [
# code, state, detail -> npt_a, npt_b, cause, rule, conflict
("drilling -- drill", "ok", "success", False, False, "none", None, False),
("interruption -- repair", "ok", "success", True, True, "equipment", "T2.C1", False),
("interruption -- maintain", "ok", "operation failed", True, True, "equipment", "T2.C1", True),
("interruption -- waiting on weather", "ok", "success", True, True, "weather", "T2.C1", False),
("interruption -- wait", "ok", "success", True, True, "waiting", "T2.C1", False),
("interruption -- fish", "fail", "stuck equipment", True, True, "stuck_fishing", "T2.C1", False),
("interruption -- well control", "ok", "circulation loss", True, True, "well_control", "T2.C1", True),
("interruption -- sidetrack", "ok", "success", True, True, "sidetrack", "T2.C1", False),
("interruption -- lost circulation", "fail", "success", True, True, "lost_circulation", "T2.C1", False),
("interruption -- other", "ok", "equipment failure", True, True, "equipment", "T2.C2", False),
("interruption -- other", "ok", "mud loss", True, True, "lost_circulation", "T2.C2", False),
("interruption -- rig up/down", "ok", "operation failed", True, True, "operation_failed", "T2.C2", False),
("interruption -- other", "ok", "success", True, True, "unspecified", "T2.C3", False),
("drilling -- casing", "ok", "equipment failure", False, True, "equipment", "T2.C2", False),
("plug abandon -- other", "fail", "stuck equipment", False, True, "stuck_fishing", "T2.C2", False),
("drilling -- ream", "ok", "circulation loss", False, True, "lost_circulation", "T2.C2", False),
("drilling -- casing", "ok", "injury", False, True, "hse", "T2.C2", False),
("formation evaluation -- log", "fail", "success", False, True, "unspecified", "T2.C3", False),
("drilling -- wait", "ok", "success", False, False, "none", None, False),
]
def test_t2_labels_rules():
a = _activities([("r", W, i, 1, 0.0, code, state, detail, "x")
for i, (code, state, detail, *_) in enumerate(T2_ROWS)])
t = L.t2_labels(a, CFG)
for row, (code, state, detail, npt_a, npt_b, cause, rule, conflict) in zip(t.itertuples(), T2_ROWS):
case = (code, state, detail)
assert (row.npt_a, row.npt_b) == (npt_a, npt_b), case
assert row.cause_group == row.cause_b == cause, case
assert row.cause_a == (cause if npt_a else "none"), case
assert (row.cause_rule == rule if rule else pd.isna(row.cause_rule)) and row.cause_conflict == conflict, case
by_case = {(c, d): r for r, (c, _, d, *_) in zip(t.itertuples(), T2_ROWS)}
wc = by_case[("interruption -- well control", "circulation loss")]
assert (wc.cause_from_code, wc.cause_from_detail, wc.cause_fine) == (
"well_control", "lost_circulation", "well_control")
assert by_case[("interruption -- other", "equipment failure")].cause_fine == "equipment_failure"
assert by_case[("interruption -- waiting on weather", "success")].cause_fine == "waiting_on_weather"
assert by_case[("interruption -- other", "success")].cause_fine == "unspecified"
assert by_case[("drilling -- drill", "success")].cause_fine == "none"
assert pd.isna(by_case[("drilling -- drill", "success")].cause_from_code)
assert t["wait_code_outside_interruption"].tolist() == [False] * 18 + [True]
assert t["is_state_fail"].sum() == 4 and t["is_detail_nonsuccess"].sum() == 10
assert set(t["cause_group"]) - {"none"} <= set(CFG["t2"]["cause_groups"])
def test_t2_precedence_can_be_reversed():
cfg = {**CFG, "t2": {**CFG["t2"], "precedence": ["detail", "code", "default"]}}
a = _activities([("r", W, 0, 1, 0.0, "interruption -- well control", "ok", "circulation loss", "x"),
("r", W, 1, 1, 0.0, "interruption -- repair", "ok", "success", "x")])
t = L.t2_labels(a, cfg)
assert t["cause_group"].tolist() == ["lost_circulation", "equipment"]
assert t["cause_rule"].tolist() == ["T2.C2", "T2.C1"]
def test_t2_inputs_hide_every_code_column():
r = _reports([{"day": 0, "diaHole": 26.0, "sum24Hr": "Drilled.", "forecast24Hr": "Drill."}])
a = _activities([(r.report_id[0], W, 0, 24, 300.0, "interruption -- repair", "fail", "equipment failure", "text")])
view = L.t2_inputs(a, r, CFG)
assert not set(view.columns) & set(L.MASKED)
assert not any("interruption" in str(v) or "equipment failure" in str(v) or v == "fail" for v in view.iloc[0])
row = view.iloc[0]
assert (row["comments"], row["sum24Hr"], row["forecast24Hr"], row["rig_phase"]) == (
"text", "Drilled.", "Drill.", "fixed")
assert (row["well"], row["report_diaHole"], row["md"]) == ("15/9-F-1", 26.0, 300.0)
leaky = {**CFG, "t2": {**CFG["t2"], "input_activity_columns": ["act_id", "report_id", "wellbore", "state"]}}
with pytest.raises(ValueError, match="masked columns"):
L.t2_inputs(a, r, leaky)
def test_text_rates_and_literal_sub_codes():
r = _reports([{"day": 0, "sum24Hr": "Waited on weather all day."}, {"day": 1, "sum24Hr": "None"}])
ids = r.report_id.tolist()
wow, trip = "interruption -- waiting on weather", "drilling -- trip"
a = _activities([(ids[0], W, 0, 6, 0.0, wow, "ok", "success", "WOW. Wind 45 knots."),
(ids[0], W, 6, 6, 0.0, wow, "ok", "success", "Serviced TDS."),
(ids[0], W, 12, 12, 0.0, trip, "ok", "success", "POOH. Tripping speed 300 m/hr."),
(ids[1], W, 24, 12, 0.0, trip, "ok", "success", "RIH."),
(ids[1], W, 36, 12, 0.0, "interruption -- fish", "ok", "stuck equipment", "Pipe stuck at 3558.")])
t2 = L.t2_labels(a, CFG)
rates = L.text_rates(a, r, t2, CFG).set_index(["target", "definition", "scope"])
w = rates.loc[("weather", "a", "comment")]
assert (w["n_pos"], w["hit_pos"], w["n_neg"], w["hit_neg"]) == (2, 1, 3, 0)
assert (w["recall"], w["fpr"], w["precision"]) == (0.5, 0.0, 1.0)
w = rates.loc[("weather", "a", "comment+sum24Hr")] # the summary names the weather for the whole day
assert (w["hit_pos"], w["hit_neg"]) == (2, 1)
assert rates.loc[("stuck_fishing", "b", "comment"), "recall"] == 1.0
assert rates.loc[("npt", "a", "comment"), "hit_pos"] == 2 # "wow", "stuck"
assert len(rates) == len(CFG["text_lexicon"]) * 2 * 2
lit = L.code_sub_literal(a).set_index("code_sub")
assert lit.loc["trip", ["n", "hit", "rate"]].tolist() == [2, 1, 0.5]
assert lit.loc["waiting on weather", "rate"] == 0.0 and lit.loc["fish", "rate_other_rows"] == 0.0
# ---------------------------------------------------------------------------------------------------------------
# T3
# ---------------------------------------------------------------------------------------------------------------
def _t3_case():
"""One wellbore, mud line 145.9 m. (hour, md) of the rows: drill (0, 300), repair (1, 305), repair (2, 318),
drill (3, 400), repair (4, 0), repair (5, 100), failed trip (6, 334), drill (7, 500), weather (40, 505)."""
r = _reports([{"day": 0, "diaHole": 26.0, "mdDiaHoleStart": 200.0, "md": 600.0}])
rid = r.report_id[0]
drill, repair = "drilling -- drill", "interruption -- repair"
rows = [(0, 300.0, drill, "ok", "success"), (1, 305.0, repair, "ok", "success"),
(2, 318.0, repair, "ok", "equipment failure"), (3, 400.0, drill, "ok", "success"),
(4, 0.0, repair, "ok", "success"), (5, 100.0, repair, "ok", "success"),
(6, 334.0, "drilling -- trip", "fail", "stuck equipment"), (7, 500.0, drill, "ok", "success"),
(40, 505.0, "interruption -- waiting on weather", "ok", "success")]
a = _activities([(rid, W, h, 1, md, code, state, detail, "x") for h, md, code, state, detail in rows])
return r, a
def test_mudline_and_own_hole_top():
r = _reports([{"day": 0, "elevKelly": 0.0, "waterDepth": 91.0, "diaHole": 26.0, "mdDiaHoleStart": 300.0},
{"day": 1, "diaHole": 17.5, "mdDiaHoleStart": 1400.0}, {"day": 2, "mdDiaHoleStart": 5.0},
{"day": 3, "wellbore": "15/9-19 A", "waterDepth": 84.0, "elevKelly": 25.0}])
assert L.mudline(r).to_dict() == {"15/9-19 A": 109.0, "15/9-F-1": 145.9} # elevKelly 0 is not used
assert L.own_hole_top(r).to_dict() == {"15/9-F-1": 300.0}
def test_t3_depth_classes_cells_and_episodes():
r, a = _t3_case()
t = L.t3_activities(a, L.t2_labels(a, CFG), r, CFG)
assert t["depth_class"].tolist() == ["in_hole"] * 4 + ["zero", "above_mudline"] + ["in_hole"] * 3
assert t["cell"].tolist() == [30, 30, 31, 40, pd.NA, pd.NA, 33, 50, 50]
stem = "15_9_F_1"
# (a): hours 1-2, hours 4-5, hour 40; the drilling row at hour 3 and the 33 h gap end an episode
assert t["episode_a"].fillna("").tolist() == ["", f"{stem}:a:E0001", f"{stem}:a:E0001", "", f"{stem}:a:E0002",
f"{stem}:a:E0002", "", "", f"{stem}:a:E0003"]
# (b): the failed trip at hour 6 continues the episode of hours 4-5
assert t["episode_b"].tolist()[4:7] == [f"{stem}:b:E0002"] * 3
ea, eb = L.t3_episodes(t, "a"), L.t3_episodes(t, "b")
assert ea["n_activities"].tolist() == [2, 2, 1] and eb["n_activities"].tolist() == [2, 3, 1]
assert ea.loc[0, ["md_min", "md_max", "n_in_hole", "hours", "causes"]].tolist() == [
305.0, 318.0, 2, 2.0, "equipment"]
assert ea.loc[1, "n_in_hole"] == 0 and pd.isna(ea.loc[1, "md_min"]) # at surface: not located
assert eb.loc[1, ["md_min", "md_max", "causes"]].tolist() == [334.0, 334.0, "equipment|stuck_fishing"]
assert ea.loc[2, "act_ids"] == [a["act_id"].iloc[8]]
def test_t3_episode_gap_is_configurable():
r, a = _t3_case()
cfg = {**CFG, "t3": {**CFG["t3"], "episode_max_gap_h": 0.0}}
a.loc[2, ["start_utc", "end_utc"]] = [_ts(0, 2.5), _ts(0, 3.5)] # half an hour after the row before
t = L.t3_activities(a, L.t2_labels(a, CFG), r, cfg)
assert t["episode_a"].tolist()[1:3] == ["15_9_F_1:a:E0001", "15_9_F_1:a:E0002"]
def test_t3_cells_and_intervals():
r, a = _t3_case()
t = L.t3_activities(a, L.t2_labels(a, CFG), r, CFG)
cells = L.t3_cells(t, r, CFG)
assert cells["cell"].tolist() == list(range(14, 61)) # mud line 145.9 m to report md 600 m
c = cells.set_index("cell")
assert c.loc[14, ["md_top", "md_bottom", "in_own_hole"]].tolist() == [140.0, 150.0, False]
assert c.loc[20, "in_own_hole"] and not c.loc[19, "in_own_hole"] # own hole starts at 200 m
assert c.loc[30, ["n_activities", "n_npt_a", "n_npt_b", "label_a", "label_b"]].tolist() == [2, 1, 1, True, True]
assert c.loc[33, ["n_npt_a", "n_npt_b", "label_a", "label_b", "causes_b"]].tolist() == [0, 1, False, True,
"stuck_fishing"]
assert c.loc[40, ["n_activities", "label_a", "label_b"]].tolist() == [1, False, False]
assert c.loc[35, ["n_activities", "hours", "label_b"]].tolist() == [0, 0.0, False]
assert c.loc[31, "act_ids_a"] == [a["act_id"].iloc[2]] and c.loc[31, "first_npt_start_a"] == _ts(0, 2)
assert cells["label_a"].sum() == 3 and cells["label_b"].sum() == 4
ia, ib = L.t3_intervals(cells, t, "a", CFG), L.t3_intervals(cells, t, "b", CFG)
# touching cells 30-31 merge; 33 (b only) and 50 stand alone with the default gap of 0
assert ia[["cell_first", "cell_last", "md_top", "md_bottom", "length_m", "n_activities"]].values.tolist() == [
[30, 31, 300.0, 320.0, 20.0, 2], [50, 50, 500.0, 510.0, 10.0, 1]]
assert ib["interval_id"].tolist() == ["15_9_F_1:b:I001", "15_9_F_1:b:I002", "15_9_F_1:b:I003"]
assert ib[["cell_first", "cell_last"]].values.tolist() == [[30, 31], [33, 33], [50, 50]]
assert ia.loc[0, ["hours", "n_episodes", "causes", "first_start_utc"]].tolist() == [2.0, 1, "equipment", _ts(0, 1)]
# one empty cell (32) may lie between two positive cells when the gap is 1
wide = L.t3_intervals(cells, t, "b", CFG, merge_gap_cells=1)
assert wide[["cell_first", "cell_last", "n_positive_cells", "length_m"]].values.tolist() == [
[30, 33, 3, 40.0], [50, 50, 1, 10.0]]
out = L.attach_intervals(cells, {"a": ia, "b": ib}).set_index("cell")
assert out.loc[[30, 31], "interval_id_a"].tolist() == ["15_9_F_1:a:I001"] * 2
assert pd.isna(out.loc[33, "interval_id_a"]) and out.loc[33, "interval_id_b"] == "15_9_F_1:b:I002"
assert out["interval_id_b"].notna().sum() == 4
def test_t3_wellbores_do_not_merge():
r = _reports([{"day": 0, "md": 400.0}, {"day": 0, "wellbore": "15/9-F-1 A", "md": 400.0}])
a = _activities([(r.report_id[0], "15/9-F-1", 0, 1, 305.0, "interruption -- repair", "ok", "success", "x"),
(r.report_id[1], "15/9-F-1 A", 1, 1, 312.0, "interruption -- repair", "ok", "success", "x")])
t = L.t3_activities(a, L.t2_labels(a, CFG), r, CFG)
assert t["episode_a"].tolist() == ["15_9_F_1:a:E0001", "15_9_F_1_A:a:E0001"]
iv = L.t3_intervals(L.t3_cells(t, r, CFG), t, "a", CFG)
assert iv[["wellbore", "cell_first", "cell_last"]].values.tolist() == [["15/9-F-1", 30, 30], ["15/9-F-1 A", 31, 31]]
assert iv["well"].tolist() == ["15/9-F-1", "15/9-F-1"]
# ---------------------------------------------------------------------------------------------------------------
# Analysis
# ---------------------------------------------------------------------------------------------------------------
def test_class_coverage_and_distribution():
f = pd.DataFrame({"wellbore": ["15/9-F-1", "15/9-F-1 A", "15/9-F-1 A", "15/9-F-4", "15/9-F-4"],
"well": ["15/9-F-1", "15/9-F-1", "15/9-F-1", "15/9-F-4", "15/9-F-4"],
"label": ["x", "x", "x", "y", None]})
cov = L.class_coverage(f, "label", rare=3).set_index("class")
assert cov.loc["x", ["n", "n_wellbores", "n_wells", "top_wellbore", "top_wellbore_share"]].tolist() == [
3, 2, 1, "15/9-F-1 A", 0.6667]
assert cov.loc["x", ["rare", "single_wellbore", "single_well"]].tolist() == [False, False, True]
assert cov.loc["y", ["n", "rare", "single_wellbore", "single_well"]].tolist() == [1, True, True, True]
assert L.distribution(f, "label", "well") == {"15/9-F-1": {"x": 3}, "15/9-F-4": {"y": 1}}
# ---------------------------------------------------------------------------------------------------------------
# The Volve tables: locked counts
# ---------------------------------------------------------------------------------------------------------------
DDR = paths.outputs_dir() / "ddr"
TABLES = ("reports", "activities", "bits", "casings")
HAVE_TABLES = all((DDR / f"{t}.parquet").is_file() for t in TABLES)
HAVE_XML = paths.ddr_xml_dir().is_dir()
needs_tables = pytest.mark.skipif(not (HAVE_TABLES or HAVE_XML), reason="missing the DDR tables and the DDR XML folder")
@pytest.fixture(scope="module")
def volve() -> dict:
if HAVE_TABLES:
src = {t: pd.read_parquet(DDR / f"{t}.parquet") for t in TABLES}
else:
from volve_dia.ddr.xml import parse_dir
src = parse_dir(paths.ddr_xml_dir())
reports, activities = src["reports"], src["activities"]
feat = L.fill_features(L.timeline(reports, activities, CFG), activities, src["bits"], src["casings"], CFG)
ops = L.operation_classes(activities, CFG)
t1r = L.t1_reports(feat, ops, activities, CFG)
t2 = L.t2_labels(activities, CFG)
t3a = L.t3_activities(activities, t2, reports, CFG)
cells = L.t3_cells(t3a, reports, CFG)
return {"reports": reports, "activities": activities, "feat": feat, "t1r": t1r, "t1a": L.t1_activities(ops, t1r),
"t2": t2, "t3a": t3a, "cells": cells,
"intervals": {d: L.t3_intervals(cells, t3a, d, CFG) for d in L.NPT_DEFINITIONS},
"episodes": {d: L.t3_episodes(t3a, d) for d in L.NPT_DEFINITIONS}}
def _script():
spec = importlib.util.spec_from_file_location("labels_07", paths.REPO_ROOT / "scripts" / "07_labels.py")
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
return module
@pytest.mark.data
@needs_tables
def test_labels_yaml_matches_the_data(volve):
assert L.check_code_counts(volve["activities"], CFG) == {}
published = volve["reports"]["diaHole"].value_counts().to_dict()
assert published == {float(k): v["n"] for k, v in CFG["t1"]["hole_sizes"].items()}
assert volve["reports"]["diaPilot"].notna().sum() == 19
@pytest.mark.data
@needs_tables
def test_locked_counts(volve):
script = _script()
got = script.expected_counts(volve["t1r"], volve["t1a"], volve["t2"], volve["t3a"], volve["cells"],
volve["intervals"], volve["episodes"])
assert got == script.EXPECTED
assert got["t2_npt_a"] == CFG["t2"]["npt_definitions"]["a"]["n"] == 3577
assert got["t2_npt_b"] == CFG["t2"]["npt_definitions"]["b"]["n"] == 4286
@pytest.mark.data
@needs_tables
def test_volve_reports_and_fill(volve):
t1r, feat = volve["t1r"], volve["feat"]
assert len(t1r) == 1759 and t1r["report_id"].is_unique
assert t1r.loc[t1r["status"].eq("placeholder_date"), "report_id"].tolist() == ["15_9_19_A_1980_01_01"]
assert t1r["status"].eq("no_activities").sum() == 8
live = t1r[t1r["status"].ne("placeholder_date")]
assert live["section"].notna().all() and live["phase"].notna().all() # every real report has a section
published = live[live["filled_by"].eq("diaHole")]
assert len(published) == 769 and (published["section_in"] == published["diaHole"]).all()
filled = live[live["diaHole"].isna()]
assert len(filled) == 989 and (filled["scope"] == "drilling_day").sum() == 260
assert filled["fill_source_report_id"].notna().all() and (filled["fill_gap_reports"] >= 1).all()
source = filled.merge(t1r[["report_id", "wellbore", "diaHole"]], left_on="fill_source_report_id",
right_on="report_id", suffixes=("", "_source"))
assert (source["wellbore"] == source["wellbore_source"]).all() # never across wellbores
assert (source["section_in"] == source["diaHole_source"]).all()
ev = L.evaluate_fill_rules(feat, rules=("ffill", "bfill"), schemes=("tail_half", "head_half"))
ev = L.summarise_fill_eval(ev).set_index(["rule", "scheme"])
assert ev.loc[("ffill", "tail_half"), ["n_masked", "n_correct"]].tolist() == [364, 364]
assert ev.loc[("bfill", "head_half"), ["n_masked", "n_correct"]].tolist() == [364, 364]
assert ev.loc[("ffill", "head_half"), "n_correct"] == 5 and ev.loc[("bfill", "tail_half"), "n_correct"] == 29
@pytest.mark.data
@needs_tables
def test_volve_t2_and_t3(volve):
t2, t3a, cells, activities = volve["t2"], volve["t3a"], volve["cells"], volve["activities"]
assert len(t2) == 23447 and t2["act_id"].tolist() == activities["act_id"].tolist()
assert (t2["npt_a"] <= t2["npt_b"]).all() and (t2["cause_group"].ne("none") == t2["npt_b"]).all()
assert t2["cause_conflict"].sum() == 192 and t2["wait_code_outside_interruption"].sum() == 79
view = L.t2_inputs(activities, volve["reports"], CFG)
assert len(view) == 23447 and not set(view.columns) & set(L.MASKED)
assert t2["well"].nunique() == 11 and t2["wellbore"].nunique() == 26
assert set(t3a["act_id"]) == set(activities["act_id"]) and t3a["md"].notna().all()
assert not cells.duplicated(["wellbore", "cell"]).any()
for d in L.NPT_DEFINITIONS:
located = t3a[t3a[f"npt_{d}"] & t3a["depth_class"].eq("in_hole")]
iv = volve["intervals"][d]
assert cells[f"n_npt_{d}"].sum() == len(located) == iv["n_activities"].sum()
assert iv["n_positive_cells"].sum() == cells[f"label_{d}"].sum()
assert sorted(a for ids in iv["act_ids"] for a in ids) == sorted(located["act_id"])
assert (iv["length_m"] >= iv["n_positive_cells"] * CFG["t3"]["grid_m"]).all()
assert volve["episodes"][d]["n_activities"].sum() == t3a[f"npt_{d}"].sum()