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:
39
tests/test_audit.py
Normal file
39
tests/test_audit.py
Normal file
@@ -0,0 +1,39 @@
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
import pytest
|
||||
|
||||
from volve_dia import audit
|
||||
|
||||
|
||||
def test_allocate_minimum_then_sqrt_share():
|
||||
a = audit.allocate({"big": 1600, "mid": 100, "tiny": 1}, 20, 2)
|
||||
assert sum(a.values()) == 20 and a["tiny"] == 1 and a["mid"] >= 2 and a["big"] > a["mid"]
|
||||
assert audit.allocate({"x": 3, "y": 3}, 10, 2) == {"x": 3, "y": 3} # never more than a stratum holds
|
||||
with pytest.raises(ValueError):
|
||||
audit.allocate({s: 10 for s in "abcdef"}, 5, 1)
|
||||
|
||||
|
||||
def test_draw_weights_and_spread_over_wells():
|
||||
f = pd.DataFrame({"act_id": range(400), "well": np.repeat(list("ABCD"), 100),
|
||||
"zone": ["a"] * 100 + ["none"] * 300, "stratum": ["a/x"] * 100 + ["none/y"] * 300})
|
||||
s = audit.draw(f, {"a": 8, "none": 8}, 2, seed=1)
|
||||
assert len(s) == 16 and s["act_id"].is_unique
|
||||
assert set(s.loc[s["zone"] == "none", "well"]) == {"B", "C", "D"} # spread over the wells of the stratum
|
||||
assert s.groupby("stratum")["weight"].first().to_dict() == {"a/x": 12.5, "none/y": 37.5}
|
||||
assert audit.draw(f, {"a": 8, "none": 8}, 2, seed=1)["act_id"].tolist() == s["act_id"].tolist()
|
||||
|
||||
|
||||
def test_cohen_kappa():
|
||||
a = pd.Series(list("yynnyn"))
|
||||
assert audit.cohen_kappa(a, a) == pytest.approx(1.0)
|
||||
b = pd.Series(list("ynynyn"))
|
||||
po, pe = 4 / 6, 0.5 * 0.5 + 0.5 * 0.5
|
||||
assert audit.cohen_kappa(a, b) == pytest.approx((po - pe) / (1 - pe))
|
||||
w = pd.Series([1, 1, 1, 1, 1, 1.0])
|
||||
assert audit.cohen_kappa(a, b, w) == pytest.approx(audit.cohen_kappa(a, b))
|
||||
assert audit.cohen_kappa(pd.Series(["y", "y"]), pd.Series(["y", "y"])) is None # pe = 1
|
||||
|
||||
|
||||
def test_zone():
|
||||
z = audit.zone(pd.Series([True, False, False]), pd.Series([True, True, False]))
|
||||
assert z.tolist() == ["a", "b_only", "none"]
|
||||
642
tests/test_labels.py
Normal file
642
tests/test_labels.py
Normal 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()
|
||||
75
tests/test_ocr_hub.py
Normal file
75
tests/test_ocr_hub.py
Normal file
@@ -0,0 +1,75 @@
|
||||
import numpy as np
|
||||
|
||||
from volve_dia import ocr, ocr_hub
|
||||
|
||||
|
||||
def test_page_content_parses_like_a_service_answer():
|
||||
cats = {1: "Section Header", 3: "Table", 7: "Image"}
|
||||
anns = [
|
||||
{"id": 1, "category_id": 1, "bbox": [165.3, 233.9, 330.6, 23.39], "text": "<p><b>Operations</b></p>"},
|
||||
{"id": 2, "category_id": 3, "bbox": [0, 0, 1653, 2339],
|
||||
"text": "<table><tr><td>Start</td><td>End</td></tr><tr><td>00:00</td><td>06:00</td></tr></table>"},
|
||||
{"id": 3, "category_id": 7, "bbox": [10, 10, 5, 5], "text": ""},
|
||||
]
|
||||
blocks = ocr.html_blocks(ocr_hub.page_content(anns, cats, 1653, 2339), 2)
|
||||
assert [(b.raw_label, b.label) for b in blocks] == [("Section Header", "section_header"), ("Table", "table")]
|
||||
assert blocks[0].bbox == [100.0, 100.0, 300.0, 110.0]
|
||||
assert blocks[1].bbox == [0.0, 0.0, 1000.0, 1000.0]
|
||||
assert blocks[1].text == "Start | End\n00:00 | 06:00"
|
||||
assert all(b.page == 2 for b in blocks)
|
||||
|
||||
|
||||
def test_tokens_keep_dates_depths_and_names_whole():
|
||||
assert ocr_hub.tokens("<p>Period: 2009-01-16 00:00</p> Wellbore: 15/9-F-15 B, 3.5 m") == [
|
||||
"period", "2009-01-16", "00:00", "wellbore", "15/9-f-15", "b", "3.5", "m"]
|
||||
|
||||
|
||||
def test_text_candidates_rank_the_right_page_first():
|
||||
pages = [ocr_hub.tokens(t) for t in ("period 2009-01-16 drill 8.5 hole to 3000 m",
|
||||
"period 2009-01-17 drill 8.5 hole to 3100 m",
|
||||
"")]
|
||||
images = [ocr_hub.tokens(t) for t in ("period 2009-01-17 drill 8.5 hole to 3100 m",
|
||||
"", "period 2009-01-16 drill 8.5 hole to 3000 m")]
|
||||
cands = ocr_hub.text_candidates(pages, images, prefilter=3, top_k=2)
|
||||
assert cands[0][0] == (2, 1.0)
|
||||
assert cands[1][0] == (0, 1.0)
|
||||
assert cands[2] == [(1, 1.0)] # a page with no text layer: the images with no text
|
||||
|
||||
|
||||
def test_correlation():
|
||||
rng = np.random.default_rng(0)
|
||||
a = rng.integers(0, 255, (40, 30), dtype=np.uint8)
|
||||
assert ocr_hub.correlation(a, a) == 1.0
|
||||
assert ocr_hub.correlation(a, np.pad(a, ((0, 1), (0, 1)))) == 1.0 # one pixel larger: common area
|
||||
assert abs(ocr_hub.correlation(a, rng.integers(0, 255, (40, 30), dtype=np.uint8))) < 0.1
|
||||
blank = np.full((40, 30), 255, np.uint8)
|
||||
assert ocr_hub.correlation(blank, blank) == 1.0
|
||||
|
||||
|
||||
def test_select_breaks_image_ties_by_text():
|
||||
# Two reports that differ only in a date: equal correlation, the text decides.
|
||||
assert ocr_hub.select([(0.978, 0.93, 1), (0.978, 0.99, 2), (0.95, 1.0, 3)], 0.9, 0.01) == (0.978, 0.99, 2)
|
||||
# Outside the tie window the image decides, whatever the text says.
|
||||
assert ocr_hub.select([(0.99, 0.80, 1), (0.95, 1.0, 2)], 0.9, 0.01) == (0.99, 0.80, 1)
|
||||
assert ocr_hub.select([(0.85, 1.0, 1)], 0.9, 0.01) is None
|
||||
assert ocr_hub.select([], 0.9, 0.01) is None
|
||||
|
||||
|
||||
def test_select_text_floor_rejects_same_layout_other_report():
|
||||
# A first page of another day: same layout (corr 0.92) but other text (F1 0.36); with a floor it is no match.
|
||||
assert ocr_hub.select([(0.921, 0.364, 1)], 0.9, 0.01) == (0.921, 0.364, 1)
|
||||
assert ocr_hub.select([(0.921, 0.364, 1)], 0.9, 0.01, 0.7) is None
|
||||
assert ocr_hub.select([(0.95, 0.5, 1), (0.93, 0.95, 2)], 0.9, 0.01, 0.7) == (0.93, 0.95, 2)
|
||||
|
||||
|
||||
def test_coarse_dot_is_a_correlation():
|
||||
rng = np.random.default_rng(1)
|
||||
a = rng.integers(0, 255, (585, 413), dtype=np.uint8)
|
||||
assert abs(float(ocr_hub.coarse(a) @ ocr_hub.coarse(a)) - 1) < 1e-5
|
||||
assert ocr_hub.coarse(a).shape == (ocr_hub.COARSE[0] * ocr_hub.COARSE[1],)
|
||||
assert float(ocr_hub.coarse(np.full((585, 413), 255, np.uint8)) @ ocr_hub.coarse(a)) == 0.0
|
||||
|
||||
|
||||
def test_iso_dates():
|
||||
assert ocr_hub.iso_dates("Period: 1997-09-04 00:00 - 1997-09-05 00:00, created 2018-05-03; 12345-01-01") == {
|
||||
"1997-09-04", "1997-09-05", "2018-05-03"}
|
||||
437
tests/test_t4.py
Normal file
437
tests/test_t4.py
Normal file
@@ -0,0 +1,437 @@
|
||||
"""volve_dia.t4: template instantiation, drop rules, sampling, the scorer; and, with the data, the locked counts and
|
||||
the agreement of the SQL answers with the pandas implementation."""
|
||||
|
||||
import copy
|
||||
import importlib.util
|
||||
import json
|
||||
|
||||
import duckdb
|
||||
import pytest
|
||||
|
||||
from volve_dia import paths, t4
|
||||
from volve_dia.names import well_of
|
||||
|
||||
CONFIG = paths.REPO_ROOT / "configs" / "t4_templates.yaml"
|
||||
DDR = paths.REPO_ROOT / "outputs" / "ddr"
|
||||
needs_db = pytest.mark.skipif(not (DDR / "volve_ddr.duckdb").is_file(), reason="missing outputs/ddr/volve_ddr.duckdb")
|
||||
|
||||
# ----------------------------------------------------------------------------------------------------------------------
|
||||
# A small database and four templates: a header value with a missing case, a list, a tie, a sampled sum.
|
||||
# ----------------------------------------------------------------------------------------------------------------------
|
||||
|
||||
MINI = {
|
||||
"seed": 7,
|
||||
"templates": [
|
||||
{
|
||||
"id": "T1_deepest", "family": "lookup", "tadi": {"category": 1},
|
||||
"questions": ["Deepest depth of {wellbore}?", "How deep is {wellbore}?"],
|
||||
"slots": {"wellbore": {"type": "wellbore"}},
|
||||
"slots_sql": "SELECT DISTINCT wellbore FROM reports ORDER BY 1",
|
||||
"answer_sql": "SELECT max(md) AS answer FROM reports WHERE wellbore = $wellbore",
|
||||
"evidence_sql": "SELECT 'reports' AS \"table\", report_id, NULL AS seq FROM reports WHERE wellbore = "
|
||||
"$wellbore AND md = (SELECT max(md) FROM reports WHERE wellbore = $wellbore)",
|
||||
"evidence_mode": "any", "on_null": "not_reported",
|
||||
"answer": {"type": "number", "unit": "m", "round": 1, "tolerance": {"abs": 1.0}},
|
||||
"source": ["reports.md"],
|
||||
},
|
||||
{
|
||||
"id": "T2_holes", "family": "lookup", "tadi": {"category": 1},
|
||||
"questions": ["Hole sizes of {wellbore}?"],
|
||||
"slots": {"wellbore": {"type": "wellbore"}},
|
||||
"slots_sql": "SELECT DISTINCT wellbore FROM reports WHERE diaHole IS NOT NULL ORDER BY 1",
|
||||
"answer_sql": "SELECT DISTINCT diaHole AS answer FROM reports WHERE wellbore = $wellbore "
|
||||
"AND diaHole IS NOT NULL ORDER BY 1 DESC",
|
||||
"evidence_sql": "SELECT 'reports' AS \"table\", report_id, NULL AS seq, diaHole AS grp FROM reports "
|
||||
"WHERE wellbore = $wellbore AND diaHole IS NOT NULL",
|
||||
"evidence_mode": "group",
|
||||
"answer": {"type": "list", "item_type": "number", "unit": "in", "tolerance": {"abs": 0.01}},
|
||||
"source": ["reports.diaHole"],
|
||||
},
|
||||
{
|
||||
"id": "T3_top_code", "family": "aggregation", "tadi": {"category": 2},
|
||||
"questions": ["Which code has the most hours in {wellbore}?"],
|
||||
"slots": {"wellbore": {"type": "wellbore"}},
|
||||
"slots_sql": "SELECT DISTINCT wellbore FROM activities ORDER BY 1",
|
||||
"answer_sql": "WITH h AS (SELECT code, sum(duration_h) AS h FROM activities WHERE wellbore = $wellbore "
|
||||
"GROUP BY 1) SELECT min(code) AS answer, CASE WHEN count(*) > 1 THEN 'tie' END AS "
|
||||
"drop_reason FROM h WHERE h = (SELECT max(h) FROM h)",
|
||||
"evidence_sql": "SELECT 'activities' AS \"table\", report_id, seq FROM activities WHERE wellbore = "
|
||||
"$wellbore AND code = (SELECT code FROM activities WHERE wellbore = $wellbore GROUP BY 1 "
|
||||
"ORDER BY sum(duration_h) DESC LIMIT 1)",
|
||||
"evidence_mode": "all",
|
||||
"answer": {"type": "enumeration", "choices": {"sql": "SELECT DISTINCT code FROM activities ORDER BY 1"}},
|
||||
"source": ["activities.code"],
|
||||
},
|
||||
{
|
||||
"id": "T4_hours", "family": "aggregation", "tadi": {"category": 2},
|
||||
"questions": ["Hours of '{code}' in {wellbore}?"],
|
||||
"slots": {"wellbore": {"type": "wellbore"}, "code": {"type": "string"}},
|
||||
"slots_sql": "SELECT DISTINCT wellbore, code FROM activities ORDER BY 1, 2",
|
||||
"answer_sql": "SELECT sum(duration_h) AS answer FROM activities WHERE wellbore = $wellbore "
|
||||
"AND code = $code",
|
||||
"evidence_sql": "SELECT 'activities' AS \"table\", report_id, seq FROM activities WHERE wellbore = "
|
||||
"$wellbore AND code = $code",
|
||||
"evidence_mode": "all", "sample": {"by": ["wellbore"], "n": 1},
|
||||
"answer": {"type": "number", "unit": "h", "round": 2, "tolerance": {"abs": 0.25}},
|
||||
"source": ["activities.duration_h"],
|
||||
},
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
@pytest.fixture()
|
||||
def con():
|
||||
c = duckdb.connect(":memory:")
|
||||
c.execute("CREATE TABLE reports (report_id VARCHAR, wellbore VARCHAR, md DOUBLE, diaHole DOUBLE)")
|
||||
c.execute("""INSERT INTO reports VALUES
|
||||
('15_9_F_1_2013_08_01', '15/9-F-1', 1000.0, 17.5), ('15_9_F_1_2013_08_02', '15/9-F-1', 2500.5, 12.25),
|
||||
('15_9_F_1_2013_08_03', '15/9-F-1', 2500.5, 12.25), ('15_9_F_1_A_2013_08_24', '15/9-F-1 A', 3000.0, NULL),
|
||||
('15_9_F_4_2008_02_19', '15/9-F-4', NULL, NULL)""")
|
||||
c.execute("CREATE TABLE activities (report_id VARCHAR, wellbore VARCHAR, seq BIGINT, code VARCHAR, "
|
||||
"duration_h DOUBLE)")
|
||||
c.execute("""INSERT INTO activities VALUES
|
||||
('15_9_F_1_2013_08_01', '15/9-F-1', 0, 'drilling -- drill', 10.0),
|
||||
('15_9_F_1_2013_08_01', '15/9-F-1', 1, 'interruption -- repair', 2.5),
|
||||
('15_9_F_1_2013_08_02', '15/9-F-1', 0, 'drilling -- drill', 4.0),
|
||||
('15_9_F_1_A_2013_08_24', '15/9-F-1 A', 0, 'drilling -- drill', 6.0),
|
||||
('15_9_F_1_A_2013_08_24', '15/9-F-1 A', 1, 'drilling -- trip', 6.0)""")
|
||||
yield c
|
||||
c.close()
|
||||
|
||||
|
||||
@pytest.fixture()
|
||||
def mini():
|
||||
cfg = copy.deepcopy(MINI)
|
||||
for t in cfg["templates"]:
|
||||
t4.validate_template(t)
|
||||
return cfg
|
||||
|
||||
|
||||
def by_template(questions):
|
||||
out = {}
|
||||
for q in questions:
|
||||
out.setdefault(q["template_id"], []).append(q)
|
||||
return out
|
||||
|
||||
|
||||
def test_instantiation(con, mini):
|
||||
questions, outcomes, summary = t4.build(con, mini)
|
||||
q = by_template(questions)
|
||||
deepest = {x["wellbore"]: x for x in q["T1_deepest"]}
|
||||
assert deepest["15/9-F-1"]["answer"] == 2500.5 and deepest["15/9-F-1"]["answer_text"] == "2500.5 m"
|
||||
assert deepest["15/9-F-1"]["question"] in ("Deepest depth of 15/9-F-1?", "How deep is 15/9-F-1?")
|
||||
assert (deepest["15/9-F-1"]["unit"], deepest["15/9-F-1"]["tolerance_abs"]) == ("m", 1.0)
|
||||
assert deepest["15/9-F-1 A"]["well"] == "15/9-F-1" and deepest["15/9-F-1 A"]["wells"] == ["15/9-F-1"]
|
||||
# evidence mode any: the two reports that state the deepest depth are one group
|
||||
assert [(e["report_id"], e["seq"], e["group"]) for e in deepest["15/9-F-1"]["evidence"]] == [
|
||||
("15_9_F_1_2013_08_02", None, 0), ("15_9_F_1_2013_08_03", None, 0)]
|
||||
# the stored SQL is the executed SQL, literals written in
|
||||
assert deepest["15/9-F-1 A"]["sql"] == "SELECT max(md) AS answer FROM reports WHERE wellbore = '15/9-F-1 A'"
|
||||
assert con.execute(deepest["15/9-F-1 A"]["sql"]).fetchone()[0] == 3000.0
|
||||
# no depth in any report of 15/9-F-4: an unanswerable question, without evidence
|
||||
assert deepest["15/9-F-4"]["answer"] == t4.NOT_REPORTED and not deepest["15/9-F-4"]["answerable"]
|
||||
assert deepest["15/9-F-4"]["evidence"] == []
|
||||
# a list answer with one evidence group per element
|
||||
holes = q["T2_holes"][0]
|
||||
assert holes["answer"] == [17.5, 12.25] and holes["answer_text"] == "17.5, 12.25 in"
|
||||
assert holes["n_evidence"] == 3 and holes["n_evidence_groups"] == 2
|
||||
assert summary["questions"] == len(questions) and summary["unanswerable"] == 1
|
||||
assert len({x["id"] for x in questions}) == len(questions)
|
||||
|
||||
|
||||
def test_drops_and_sampling(con, mini):
|
||||
questions, outcomes, summary = t4.build(con, mini)
|
||||
q = by_template(questions)
|
||||
# 15/9-F-1 A: two codes with 6 h each, a tie, dropped and counted
|
||||
assert [x["wellbore"] for x in q["T3_top_code"]] == ["15/9-F-1"]
|
||||
assert q["T3_top_code"][0]["answer"] == "drilling -- drill"
|
||||
assert q["T3_top_code"][0]["choices"] == ["drilling -- drill", "drilling -- trip", "interruption -- repair"]
|
||||
assert summary["per_template"]["T3_top_code"]["dropped"] == {"tie": 1}
|
||||
assert summary["dropped"] == {"tie": 1} and summary["dropped_total"] == 1
|
||||
# four (wellbore, code) candidates, one kept per wellbore, the same ones on every run
|
||||
hours = summary["per_template"]["T4_hours"]
|
||||
assert (hours["candidates"], hours["questions"], hours["not_sampled"]["answerable"]) == (4, 2, 2)
|
||||
again, _, _ = t4.build(con, mini)
|
||||
assert [x["id"] for x in again] == [x["id"] for x in questions]
|
||||
# every answerable question has evidence rows; the sums are over all rows of the code
|
||||
assert all(x["evidence"] for x in questions if x["answerable"])
|
||||
for x in q["T4_hours"]:
|
||||
rows = con.execute(x["evidence_sql"]).fetchall()
|
||||
assert len(rows) == x["n_evidence"] == x["n_evidence_groups"]
|
||||
|
||||
|
||||
def test_null_answer_is_dropped_without_on_null(con, mini):
|
||||
del mini["templates"][0]["on_null"]
|
||||
_, outcomes, summary = t4.build(con, mini)
|
||||
assert summary["per_template"]["T1_deepest"]["dropped"] == {"null_answer": 1}
|
||||
assert [o.status for o in outcomes["T1_deepest"]] == ["ok", "ok", "drop"]
|
||||
|
||||
|
||||
def test_rendering():
|
||||
assert t4.format_inch(12.25) == '12 1/4" (12.25 in)' and t4.format_inch(36.0) == '36"'
|
||||
assert t4.format_inch(13.375) == '13 3/8" (13.375 in)' and t4.format_inch(9.875) == '9 7/8" (9.875 in)'
|
||||
assert t4.format_number(3520.0) == "3520" and t4.format_number(1.48) == "1.48"
|
||||
sql = t4.render_sql("SELECT 1 WHERE w = $w AND d = $d AND x = $x", {"w": "15/9-F-1 A", "d": 12.25, "x": "o'k"})
|
||||
assert sql == "SELECT 1 WHERE w = '15/9-F-1 A' AND d = 12.25 AND x = 'o''k'"
|
||||
assert t4.evidence_id("activities", "15_9_F_4_2008_02_19", 10) == "activities:15_9_F_4_2008_02_19:10"
|
||||
assert t4.evidence_id("reports", "15_9_F_4_2008_02_19") == "reports:15_9_F_4_2008_02_19"
|
||||
|
||||
|
||||
def test_validate_template(mini):
|
||||
t = copy.deepcopy(mini["templates"][0])
|
||||
t["questions"] = ["Depth of {well}?"]
|
||||
with pytest.raises(t4.TemplateError, match="undeclared slots"):
|
||||
t4.validate_template(t)
|
||||
t = copy.deepcopy(mini["templates"][0])
|
||||
t["answer"] = {"type": "number", "unit": "m"}
|
||||
with pytest.raises(t4.TemplateError, match="tolerance"):
|
||||
t4.validate_template(t)
|
||||
t = copy.deepcopy(mini["templates"][0])
|
||||
t["answer_sql"] = "SELECT max(md) AS answer FROM reports WHERE wellbore = $name"
|
||||
with pytest.raises(t4.TemplateError, match="undeclared parameters"):
|
||||
t4.validate_template(t)
|
||||
t = copy.deepcopy(mini["templates"][3])
|
||||
t["negatives"] = {"n": 2}
|
||||
with pytest.raises(t4.TemplateError, match="on_null"):
|
||||
t4.validate_template(t)
|
||||
|
||||
|
||||
# ----------------------------------------------------------------------------------------------------------------------
|
||||
# Scorer
|
||||
# ----------------------------------------------------------------------------------------------------------------------
|
||||
|
||||
def gold(answer, kind, evidence=(), **kw):
|
||||
q = {"answer": answer, "answer_type": kind, "answerable": True, "evidence": list(evidence), "unit": None,
|
||||
"tolerance_abs": None, "tolerance_rel": None, "tolerance_days": 0, "item_type": None}
|
||||
q.update(kw)
|
||||
return q
|
||||
|
||||
|
||||
def test_tolerance():
|
||||
assert t4.within_tolerance(3520.9, 3520.0, abs_tol=1.0) and not t4.within_tolerance(3521.1, 3520.0, abs_tol=1.0)
|
||||
assert t4.within_tolerance(13.7, 13.45, rel_tol=0.02) and not t4.within_tolerance(13.8, 13.45, rel_tol=0.02)
|
||||
assert t4.within_tolerance(11, 11, abs_tol=0) and not t4.within_tolerance(12, 11, abs_tol=0)
|
||||
assert t4.within_tolerance(1.0, 0.5, abs_tol=0.5, rel_tol=0.01) # the larger of the two limits applies
|
||||
|
||||
|
||||
def test_score_number():
|
||||
q = gold(3520.0, "number", unit="m", tolerance_abs=1.0)
|
||||
assert t4.score(3520.4, q)["correct"] and t4.score("3,520 m", q)["correct"] and t4.score("3520,4", q)["correct"]
|
||||
assert not t4.score(3522, q)["correct"] and not t4.score("deep", q)["correct"]
|
||||
assert t4.score({"answer": 11548.6, "unit": "ft"}, q)["correct"] # 3520.0 m
|
||||
assert t4.score("11548.6 ft", q)["correct"] and t4.score("3520 metres", q)["correct"]
|
||||
assert not t4.score({"answer": 3520, "unit": "ft"}, q)["correct"] and not t4.score("3520 ft", q)["correct"]
|
||||
assert not t4.score({"answer": 3520, "unit": "h"}, q)["correct"] # another dimension
|
||||
rop = gold(13.45, "number", unit="m/h", tolerance_rel=0.02)
|
||||
assert t4.score("13.6 m/h", rop)["correct"] and not t4.score(14.0, rop)["correct"]
|
||||
count = gold(11.0, "number", unit="reports", tolerance_abs=0)
|
||||
assert t4.score({"answer": 11, "unit": "days"}, count)["correct"] and not t4.score(12, count)["correct"]
|
||||
size = gold(12.25, "number", unit="in", tolerance_abs=0.01)
|
||||
assert t4.score('12 1/4"', size)["correct"] and t4.score("12.25 in", size)["correct"]
|
||||
|
||||
|
||||
def test_score_date_string_boolean():
|
||||
d = gold("1997-11-27", "date")
|
||||
assert t4.score("1997-11-27", d)["correct"] and t4.score("27.11.1997", d)["correct"]
|
||||
assert t4.score("27 November 1997", d)["correct"] and t4.score("1997-11-27T14:00:00+01:00", d)["correct"]
|
||||
assert not t4.score("1997-11-28", d)["correct"] and not t4.score("November", d)["correct"]
|
||||
assert t4.score("1997-11-28", gold("1997-11-27", "date", tolerance_days=1))["correct"]
|
||||
rig = gold("MÆRSK INSPIRER", "string")
|
||||
assert t4.score("Mærsk Inspirer.", rig)["correct"] and not t4.score("Byford Dolphin", rig)["correct"]
|
||||
wb = gold("15/9-F-1 B", "enumeration", choices=["15/9-F-1", "15/9-F-1 B"])
|
||||
assert t4.score("NO 15/9-F-1 B", wb)["correct"] and t4.score("15_9_F_1_B", wb)["correct"]
|
||||
assert not t4.score("15/9-F-1", wb)["correct"]
|
||||
code = gold("interruption -- fish", "enumeration")
|
||||
assert t4.score("Interruption - fish", code)["correct"] and not t4.score("interruption -- repair", code)["correct"]
|
||||
yes, no = gold(True, "boolean"), gold(False, "boolean")
|
||||
assert t4.score("Yes, on 2008-11-14.", yes)["correct"] and t4.score(True, yes)["correct"]
|
||||
assert not t4.score("no", yes)["correct"] and not t4.score("maybe", yes)["correct"]
|
||||
s = t4.score("No such activity is recorded.", no) # a 'no', not an abstention
|
||||
assert s["correct"] and not s["abstained"]
|
||||
assert t4.score("n/a", no)["abstained"] and not t4.score("n/a", no)["correct"]
|
||||
|
||||
|
||||
def test_score_list():
|
||||
q = gold([36.0, 26.0, 17.5], "list", item_type="number", unit="in", tolerance_abs=0.01)
|
||||
s = t4.score([17.5, 36, 26], q)
|
||||
assert s["correct"] and s["list_precision"] == s["list_recall"] == 1.0
|
||||
assert t4.score('36", 26", 17 1/2"', q)["correct"]
|
||||
s = t4.score([36, 26], q)
|
||||
assert not s["correct"] and s["list_precision"] == 1.0 and s["list_recall"] == pytest.approx(2 / 3)
|
||||
s = t4.score([36, 26, 17.5, 12.25], q)
|
||||
assert not s["correct"] and s["list_precision"] == 0.75 and s["list_recall"] == 1.0
|
||||
assert not t4.score([36, 36, 26], q)["correct"] # a gold element is matched once
|
||||
|
||||
|
||||
def test_score_unanswerable():
|
||||
q = gold(t4.NOT_REPORTED, "date", answerable=False)
|
||||
for pred in (None, "", "Not reported", "N/A", "no such activity in the reports", "unknown"):
|
||||
s = t4.score(pred, q)
|
||||
assert s["correct"] and s["abstained"] and not s["fabricated"]
|
||||
s = t4.score("1997-11-27", q)
|
||||
assert not s["correct"] and s["fabricated"] and not s["abstained"]
|
||||
answerable = gold(3520.0, "number", unit="m", tolerance_abs=1.0)
|
||||
s = t4.score("not reported", answerable)
|
||||
assert not s["correct"] and s["abstained"] and not s["fabricated"]
|
||||
|
||||
|
||||
def test_score_citations():
|
||||
def rows(*specs):
|
||||
return [{"table": t, "report_id": r, "seq": s, "group": g} for t, r, s, g in specs]
|
||||
|
||||
rid = "15_9_F_4_2008_02_19"
|
||||
need_all = rows(("activities", rid, 10, 0), ("activities", rid, 11, 1), ("reports", rid, None, 2))
|
||||
s = t4.score_citations([f"activities:{rid}:10", f"{rid}:011", {"table": "reports", "report_id": rid}], need_all)
|
||||
assert s == {"n_cited": 3, "citation_precision": 1.0, "citation_recall": 1.0}
|
||||
s = t4.score_citations([f"activities:{rid}:10", f"activities:{rid}:99"], need_all)
|
||||
assert s["citation_precision"] == 0.5 and s["citation_recall"] == pytest.approx(1 / 3)
|
||||
any_one = rows(("reports", rid, None, 0), ("reports", "15_9_F_4_2008_02_20", None, 0))
|
||||
assert t4.score_citations([f"reports:{rid}"], any_one)["citation_recall"] == 1.0
|
||||
assert t4.score_citations([rid], any_one)["citation_precision"] == 1.0 # a bare report id
|
||||
grouped = rows(("casings", rid, 0, 0), ("casings", rid, 1, 0), ("casings", rid, 2, 1))
|
||||
assert t4.score_citations([f"casings:{rid}:1"], grouped)["citation_recall"] == 0.5
|
||||
none = t4.score_citations([], need_all)
|
||||
assert none == {"n_cited": 0, "citation_precision": None, "citation_recall": 0.0}
|
||||
assert t4.score_citations([f"reports:{rid}"], [])["citation_precision"] == 0.0
|
||||
assert t4.score_citations([f"reports:{rid}"], [])["citation_recall"] is None
|
||||
assert t4.score_citations(["not a citation"], need_all)["citation_precision"] == 0.0
|
||||
# report level: any row of the report counts
|
||||
s = t4.score_citations([f"fluids:{rid}:0"], need_all, level="report")
|
||||
assert s["citation_precision"] == 1.0 and s["citation_recall"] == 1.0
|
||||
q = gold(3245.0, "number", evidence=need_all[:1], unit="m", tolerance_abs=1.0)
|
||||
s = t4.score({"answer": "3245 m", "citations": [f"{rid}:010"]}, q)
|
||||
assert s["correct"] and s["citation_precision"] == 1.0 and s["citation_recall"] == 1.0
|
||||
|
||||
|
||||
# ----------------------------------------------------------------------------------------------------------------------
|
||||
# The configuration, and the build on the DDR tables
|
||||
# ----------------------------------------------------------------------------------------------------------------------
|
||||
|
||||
def test_config_is_valid():
|
||||
from volve_dia import t4_pandas
|
||||
|
||||
cfg = t4.load_config(CONFIG)
|
||||
ids = [t["id"] for t in cfg["templates"]]
|
||||
assert len(ids) == len(set(ids)) == 39
|
||||
assert {t["family"] for t in cfg["templates"]} == set(t4.FAMILIES)
|
||||
assert {t["answer"]["type"] for t in cfg["templates"]} == set(t4.ANSWER_TYPES)
|
||||
assert set(ids) == set(t4_pandas.TEMPLATES) # every template has its pandas twin
|
||||
assert [t["id"] for t in cfg["disabled"]] == [
|
||||
"W01_rop_section_witsml", "W02_max_inclination_trajectory", "W03_formation_at_first_event_picks",
|
||||
"W04_best_bha_run", "W05_parameters_in_formation"]
|
||||
for t in cfg["templates"]:
|
||||
assert t["tadi"].get("fit") in ("direct", "partial", "none") and t.get("caveats")
|
||||
assert t["tadi"].get("category") in (None, 1, 2, 3, 4, 5, 6)
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def built():
|
||||
from volve_dia import t4_pandas
|
||||
|
||||
cfg = t4.load_config(CONFIG)
|
||||
with t4.connect(DDR / "volve_ddr.duckdb") as con:
|
||||
questions, outcomes, summary = t4.build(con, cfg)
|
||||
return cfg, questions, outcomes, summary, t4_pandas.Tables(DDR)
|
||||
|
||||
|
||||
def script():
|
||||
spec = importlib.util.spec_from_file_location("t4_questions", paths.REPO_ROOT / "scripts" / "08_t4_questions.py")
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(module)
|
||||
return module
|
||||
|
||||
|
||||
@pytest.mark.data
|
||||
@needs_db
|
||||
def test_locked_counts(built):
|
||||
_, questions, _, summary, _ = built
|
||||
expected = script().EXPECTED
|
||||
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()}
|
||||
assert got == expected
|
||||
assert len(questions) == 1662 and len({q["id"] for q in questions}) == 1662
|
||||
assert len({q["question"] for q in questions}) == 1662
|
||||
|
||||
|
||||
@pytest.mark.data
|
||||
@needs_db
|
||||
def test_questions_are_well_formed(built):
|
||||
_, questions, _, _, _ = built
|
||||
for q in questions:
|
||||
if q["scope"] != "field":
|
||||
assert q["well"] == well_of(q["wellbore"]) and q["wellbore"] in q["wellbores"]
|
||||
assert q["wells"] == sorted({well_of(w) for w in q["wellbores"]})
|
||||
assert "{" not in q["question"] and "$" not in q["sql"] and "$" not in q["evidence_sql"]
|
||||
if not q["answerable"]:
|
||||
assert q["answer"] == t4.NOT_REPORTED and not q["evidence"]
|
||||
elif not (q["answer_type"] == "boolean" and q["answer"] is False):
|
||||
assert q["evidence"], q["id"]
|
||||
if q["answer_type"] == "enumeration" and q["answerable"]:
|
||||
assert q["answer"] in q["choices"]
|
||||
assert sum(q["scope"] == "pair" for q in questions) == 92
|
||||
assert all(len(q["wells"]) == 1 for q in questions if q["scope"] == "pair") # same-well pairs only
|
||||
assert all(len(q["wells"]) == 11 and len(q["wellbores"]) == 26 for q in questions if q["scope"] == "field")
|
||||
assert sum(not q["printed_in_render"] for q in questions) == 215
|
||||
|
||||
|
||||
@pytest.mark.data
|
||||
@needs_db
|
||||
def test_stored_sql_reproduces_answers(built):
|
||||
cfg, questions, _, _, _ = built
|
||||
specs = {t["id"]: t for t in cfg["templates"]}
|
||||
with t4.connect(DDR / "volve_ddr.duckdb") as con:
|
||||
for q in questions[::7]:
|
||||
o = t4.run_instance(con, specs[q["template_id"]], q["slots"])
|
||||
assert o.sql == q["sql"] and o.answer == q["answer"] and o.evidence == q["evidence"]
|
||||
|
||||
|
||||
@pytest.mark.data
|
||||
@needs_db
|
||||
def test_sql_agrees_with_pandas(built):
|
||||
from volve_dia import t4_pandas
|
||||
|
||||
cfg, _, outcomes, _, tables = built
|
||||
check = t4_pandas.crosscheck(cfg, outcomes, tables)
|
||||
assert check["total"]["instances"] == 3915 and check["total"]["agree"] == 3915
|
||||
assert check["total"]["slot_differences"] == 0 and check["total"]["templates_in_full_agreement"] == 39
|
||||
|
||||
|
||||
@pytest.mark.data
|
||||
@needs_db
|
||||
def test_crosscheck_detects_a_wrong_template(built):
|
||||
"""The comparison is not vacuous: a template whose SQL takes the shallowest depth, or whose evidence SQL misses
|
||||
rows, disagrees with the pandas implementation."""
|
||||
from volve_dia import t4_pandas
|
||||
|
||||
cfg, _, _, _, tables = built
|
||||
wrong = copy.deepcopy(next(t for t in cfg["templates"] if t["id"] == "L03_deepest_md"))
|
||||
wrong["answer_sql"] = wrong["answer_sql"].replace("max(md)", "min(md)")
|
||||
loose = copy.deepcopy(next(t for t in cfg["templates"] if t["id"] == "A06_hours_per_code"))
|
||||
loose["evidence_sql"] += " AND seq > 0"
|
||||
with t4.connect(DDR / "volve_ddr.duckdb") as con:
|
||||
outcomes = {t["id"]: t4.run_template(con, t) for t in (wrong, loose)}
|
||||
check = t4_pandas.crosscheck({"templates": [wrong, loose]}, outcomes, tables)
|
||||
assert check["per_template"]["L03_deepest_md"]["answer"] > 0
|
||||
assert check["per_template"]["A06_hours_per_code"]["evidence"] > 0
|
||||
assert check["per_template"]["A06_hours_per_code"]["answer"] == 0
|
||||
|
||||
|
||||
@pytest.mark.data
|
||||
@needs_db
|
||||
def test_gold_answers_score_as_correct(built):
|
||||
_, questions, _, _, _ = built
|
||||
result = script().self_score(questions)
|
||||
assert result == {"questions": 1662, "correct": 1662, "wrong": []}
|
||||
|
||||
|
||||
@pytest.mark.data
|
||||
@needs_db
|
||||
def test_outputs_match_the_build(built):
|
||||
_, questions, _, summary, _ = built
|
||||
out = paths.REPO_ROOT / "outputs" / "t4"
|
||||
if not (out / "questions.jsonl").is_file():
|
||||
pytest.skip("outputs/t4 not built: run scripts/08_t4_questions.py")
|
||||
stored = t4.read_jsonl(out / "questions.jsonl")
|
||||
assert stored == json.loads(json.dumps(questions))
|
||||
assert json.loads((out / "summary.json").read_text(encoding="utf-8"))["questions"] == summary["questions"]
|
||||
|
||||
457
tests/test_witsml.py
Normal file
457
tests/test_witsml.py
Normal file
@@ -0,0 +1,457 @@
|
||||
"""volve_dia.witsml and volve_dia.tops: synthetic WITSML snippets (null values, sentinels, time and depth index,
|
||||
duplicates), then the Volve files and the tables of scripts/06_parse_witsml.py (skipped without them)."""
|
||||
|
||||
import importlib.util
|
||||
import io
|
||||
import json
|
||||
import xml.etree.ElementTree as ET
|
||||
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
import pyarrow.parquet as pq
|
||||
import pytest
|
||||
|
||||
from volve_dia import paths, tops, witsml
|
||||
from volve_dia.witsml import Curve, Flat, LongWriter, ParsedLog, dedup_curve, merge_curve, read_log_file
|
||||
|
||||
NSURI = "http://www.witsml.org/schemas/1series"
|
||||
|
||||
|
||||
def log_xml(index_type: str, index_curve: str, curves: list[tuple], rows: list[str], units: str | None = None,
|
||||
null_value: str | None = None, uid: str = "L1", name_wellbore: str = "NO 15/9-F-11 T2") -> io.BytesIO:
|
||||
"""A `<logs>` document. `curves`: (mnemonic, unit, typeLogData, nullValue or None)."""
|
||||
info = "".join(
|
||||
f'<logCurveInfo uid="{m}"><mnemonic>{m}</mnemonic><unit>{u}</unit>'
|
||||
+ (f"<nullValue>{nv}</nullValue>" if nv is not None else "") + f"<typeLogData>{t}</typeLogData></logCurveInfo>"
|
||||
for m, u, t, nv in curves)
|
||||
names = ",".join([index_curve] + [c[0] for c in curves if c[0] != index_curve])
|
||||
units = units if units is not None else ",".join(["m" if index_type == "measured depth" else ""]
|
||||
+ [c[1] for c in curves if c[0] != index_curve])
|
||||
data = "".join(f"<data>{r}</data>" for r in rows)
|
||||
return io.BytesIO((
|
||||
f'<?xml version="1.0" encoding="UTF-8"?><logs xmlns="{NSURI}" version="1.4.1.1">'
|
||||
f'<log uidWell="W1" uidWellbore="B1" uid="{uid}"><nameWell>NO 15/9-F-11</nameWell>'
|
||||
f"<nameWellbore>{name_wellbore}</nameWellbore><name>GenTime</name><indexType>{index_type}</indexType>"
|
||||
f"<direction>increasing</direction><indexCurve>{index_curve}</indexCurve>"
|
||||
+ (f"<nullValue>{null_value}</nullValue>" if null_value is not None else "") + info
|
||||
+ f"<logData><mnemonicList>{names}</mnemonicList><unitList>{units}</unitList>{data}</logData>"
|
||||
"<commonData><sourceName>X</sourceName><priv_userOwner>someone</priv_userOwner></commonData></log></logs>"
|
||||
).encode())
|
||||
|
||||
|
||||
TIME_CURVES = [("Time", "", "date time", None), ("HKLD", "N", "double", "-999.25"), ("RPM", "c/s", "double", None),
|
||||
("PASS", "unitless", "string", None), ("ARR", "unitless", "double", None)]
|
||||
|
||||
|
||||
def time_log(rows: list[str], **kw) -> io.BytesIO:
|
||||
return log_xml("date time", "Time", TIME_CURVES, rows, **kw)
|
||||
|
||||
|
||||
def parsed(*chunks: io.BytesIO) -> ParsedLog:
|
||||
log = ParsedLog()
|
||||
for i, c in enumerate(chunks, 1):
|
||||
log.add(read_log_file(c), i)
|
||||
return log
|
||||
|
||||
|
||||
def by_name(log: ParsedLog, log_id: int = 0) -> dict[str, Curve]:
|
||||
return {c.mnemonic: c for c in log.curves(log_id)}
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------------------------------------------
|
||||
# logs
|
||||
# ---------------------------------------------------------------------------------------------------------------
|
||||
|
||||
def test_read_log_file_header_and_curves():
|
||||
lf = read_log_file(time_log(["2013-04-08T01:45:28.000Z,1,2,Drilling,"], null_value="-999.25"))
|
||||
assert lf.header["uid"] == "L1" and lf.header["uidWellbore"] == "B1" and lf.header["indexType"] == "date time"
|
||||
assert lf.header["nullValue"] == "-999.25" and lf.header["commonData_sourceName"] == "X"
|
||||
assert "commonData_priv_userOwner" not in lf.header # people of the operator are not copied
|
||||
assert lf.mnemonics == ["Time", "HKLD", "RPM", "PASS", "ARR"] and lf.units[1:3] == ["N", "c/s"]
|
||||
assert [c["mnemonic"] for c in lf.curves] == lf.mnemonics and lf.curves[1]["nullValue"] == "-999.25"
|
||||
assert lf.rows == ["2013-04-08T01:45:28.000Z,1,2,Drilling,"]
|
||||
head = read_log_file(time_log(["2013-04-08T01:45:28.000Z,1,2,Drilling,"]), header_only=True)
|
||||
assert head.header["nameWellbore"] == "NO 15/9-F-11 T2" and not head.rows and not head.curves
|
||||
|
||||
|
||||
def test_time_log_nulls_sentinels_text():
|
||||
log = parsed(time_log([
|
||||
"2013-04-08T01:45:28.000Z,100.5,-9999,Drilling,1 2 3", # RPM: TADI sentinel; ARR: an array, not a number
|
||||
"2013-04-08T01:45:31.000Z,-999.25,2.5,,", # HKLD: its nullValue; PASS and ARR: empty
|
||||
"2013-04-08T01:45:34.500Z,,-999.25,TripIn,7", # HKLD: empty; RPM: the log-level null value
|
||||
"2013-04-08T01:45:37.000Z,9999,-999,Drilling,8", # suspect values are kept
|
||||
], null_value="-999.25"))
|
||||
assert log.kind == "time" and log.counts["rows"] == 4 and log.counts["bad_rows"] == 0
|
||||
c = by_name(log)
|
||||
t0 = pd.Timestamp("2013-04-08T01:45:28Z").value // 10**6
|
||||
assert c["HKLD"].index.tolist() == [t0, t0 + 9000] and c["HKLD"].value.tolist() == [100.5, 9999.0]
|
||||
assert c["HKLD"].stats["n_null_value"] == 1 and c["HKLD"].stats["suspect:9999"] == 1
|
||||
assert c["RPM"].value.tolist() == [2.5, -999.0]
|
||||
assert c["RPM"].stats["sentinel:-9999"] == 1 and c["RPM"].stats["n_null_value"] == 1
|
||||
assert c["RPM"].stats["suspect:-999"] == 1
|
||||
assert c["PASS"].text.tolist() == ["Drilling", "TripIn", "Drilling"] and np.isnan(c["PASS"].value).all()
|
||||
assert c["PASS"].index.tolist() == [t0, t0 + 6500, t0 + 9000] # milliseconds are kept
|
||||
assert c["ARR"].stats["n_not_number"] == 1 and c["ARR"].stats["n_text"] == 1
|
||||
assert c["ARR"].text.tolist() == ["1 2 3", None, None] and c["ARR"].value.tolist()[1:] == [7.0, 8.0]
|
||||
st = log.index_stats()
|
||||
assert (st["n_index_values"], st["n_index_distinct"], st["step_median"]) == (4, 4, 3.0)
|
||||
|
||||
|
||||
def test_time_index_must_be_utc():
|
||||
with pytest.raises(ValueError, match="does not end in 'Z'"):
|
||||
parsed(time_log(["2013-04-08T01:45:28.000+01:00,1,2,Drilling,"]))
|
||||
|
||||
|
||||
def test_chunk_boundary_duplicates_are_dropped_once():
|
||||
a = time_log(["2013-04-08T01:45:28.000Z,1,10,Drilling,", "2013-04-08T01:45:31.000Z,2,20,Drilling,"])
|
||||
b = time_log(["2013-04-08T01:45:31.000Z,2,21,Drilling,", "2013-04-08T01:45:34.000Z,3,30,Drilling,"])
|
||||
c = by_name(parsed(a, b))
|
||||
assert c["HKLD"].value.tolist() == [1.0, 2.0, 3.0] and c["HKLD"].chunk.tolist() == [1, 2, 2]
|
||||
assert (c["HKLD"].stats["n_dup_same"], c["HKLD"].stats["n_dup_conflict"]) == (1, 0)
|
||||
assert c["RPM"].value.tolist() == [10.0, 21.0, 30.0] # a conflict: the later file wins
|
||||
assert (c["RPM"].stats["n_dup_same"], c["RPM"].stats["n_dup_conflict"]) == (0, 1)
|
||||
assert c["PASS"].stats["n_dup_same"] == 1 and c["PASS"].text.tolist() == ["Drilling"] * 3
|
||||
|
||||
|
||||
def test_log_must_stay_one_log():
|
||||
a = time_log(["2013-04-08T01:45:28.000Z,1,10,Drilling,"])
|
||||
with pytest.raises(ValueError, match="uid changes"):
|
||||
parsed(a, time_log(["2013-04-08T01:45:31.000Z,1,10,Drilling,"], uid="L2"))
|
||||
with pytest.raises(ValueError, match="2 log elements"):
|
||||
doc = time_log(["2013-04-08T01:45:28.000Z,1,10,Drilling,"]).getvalue().decode()
|
||||
one = doc[doc.index("<log "):doc.index("</logs>")]
|
||||
read_log_file(io.BytesIO(doc.replace("</logs>", one + "</logs>").encode()))
|
||||
|
||||
|
||||
def test_bad_rows_are_counted_not_guessed():
|
||||
log = parsed(time_log(["2013-04-08T01:45:28.000Z,1,10,Drilling,", "2013-04-08T01:45:31.000Z,2,20,a,b,"]))
|
||||
assert log.counts["rows"] == 2 and log.counts["bad_rows"] == 1 and by_name(log)["HKLD"].value.tolist() == [1.0]
|
||||
|
||||
|
||||
def depth_log(rows: list[str], **kw) -> io.BytesIO:
|
||||
curves = [("Depth", "m", "double", None), ("GR", "gAPI", "double", "-999.25"),
|
||||
("Time", "unitless", "date time", None), ("CODE", "unitless", "long", None)]
|
||||
return log_xml("measured depth", "Depth", curves, rows, **kw)
|
||||
|
||||
|
||||
def test_depth_log_sorted_by_depth():
|
||||
log = parsed(depth_log(["231.5,40.1,2013-03-22T21:53:39.000Z,111", "231.2,-999.25,2013-03-22T21:50:00.000Z,112",
|
||||
"231.9,41,,113"]))
|
||||
assert log.kind == "depth" and log.index_unit == "m" and log.index_stats()["n_index_backwards"] == 1
|
||||
c = by_name(log)
|
||||
assert c["GR"].index.tolist() == [231.5, 231.9] and c["GR"].stats["n_null_value"] == 1
|
||||
assert c["CODE"].index.tolist() == [231.2, 231.5, 231.9] and c["CODE"].value.tolist() == [112.0, 111.0, 113.0]
|
||||
assert c["CODE"].stats["n_out_of_order"] == 2
|
||||
assert c["Time"].text.tolist() == ["2013-03-22T21:50:00.000Z", "2013-03-22T21:53:39.000Z"]
|
||||
with pytest.raises(ValueError, match="expected metres"):
|
||||
parsed(depth_log(["231.5,40.1,,111"], units="ft,gAPI,unitless,unitless"))
|
||||
with pytest.raises(ValueError, match="unsupported indexType"):
|
||||
parsed(log_xml("vertical depth", "Depth", [("Depth", "m", "double", None)], ["1"]))
|
||||
|
||||
|
||||
def test_dedup_curve_keeps_the_last_row():
|
||||
index = np.array([10, 20, 20, 30, 30, 30], dtype=np.int64)
|
||||
value = np.array([1.0, 2.0, 2.0, 3.0, 4.0, 4.0])
|
||||
chunk = np.array([1, 1, 2, 2, 3, 4], dtype=np.int16)
|
||||
i, v, t, c, n = dedup_curve(index, value, None, chunk)
|
||||
assert i.tolist() == [10, 20, 30] and v.tolist() == [1.0, 2.0, 4.0] and c.tolist() == [1, 2, 4] and t is None
|
||||
assert n == {"n_dup_same": 2, "n_dup_conflict": 1, "n_out_of_order": 0}
|
||||
text = np.array(["a", "b", "c", None, None, None], dtype=object)
|
||||
i, v, t, c, n = dedup_curve(index, np.full(6, np.nan), text, chunk) # NaN == NaN for text rows
|
||||
assert t.tolist() == ["a", "c", None] and n["n_dup_conflict"] == 1 and n["n_dup_same"] == 2
|
||||
|
||||
|
||||
def curve(log_id: int, index: list, value: list, text: list | None = None) -> Curve:
|
||||
return Curve(log_id, "BITDEP", np.array(index, dtype=np.int64), np.array(value, dtype=float),
|
||||
None if text is None else np.array(text, dtype=object), np.full(len(index), 1, dtype=np.int16), {})
|
||||
|
||||
|
||||
def test_merge_curve_ranks_and_keeps_every_row():
|
||||
main = curve(7, [10, 20, 30, 40, 45], [1.0, 2.0, 3.0, 4.0, 4.5]) # most values: the preferred log
|
||||
other = curve(3, [20, 30, 40, 50], [2.0, 3.00001, 9.0, 5.0]) # same, rounding, conflict, alone
|
||||
third = curve(9, [20], [2.0])
|
||||
log_id, index, value, text, chunk, rank, pairs = merge_curve([third, other, main])
|
||||
assert index.tolist() == [10, 20, 20, 20, 30, 30, 40, 40, 45, 50]
|
||||
assert log_id.tolist() == [7, 7, 3, 9, 7, 3, 7, 3, 7, 3] and rank.tolist() == [0, 0, 1, 2, 0, 1, 0, 1, 0, 0]
|
||||
assert value[rank == 0].tolist() == [1.0, 2.0, 3.0, 4.0, 4.5, 5.0] # one value per index, none lost
|
||||
p = {(r["log_id"], r["other_log_id"]): r for r in pairs}
|
||||
assert (p[(7, 3)]["n"], p[(7, 3)]["n_same"], p[(7, 3)]["n_rounding"], p[(7, 3)]["n_conflict"]) == (3, 1, 1, 1)
|
||||
assert p[(7, 3)]["max_abs_diff"] == 5.0 and p[(7, 9)]["n_same"] == 1
|
||||
# equal sizes: the lower log_id is preferred; a single log has no pairs
|
||||
assert merge_curve([curve(5, [1], [1.0]), curve(2, [1], [1.0])])[0].tolist() == [2, 5]
|
||||
assert merge_curve([main])[6] == [] and merge_curve([main, curve(1, [99], [0.0])])[6] == []
|
||||
|
||||
|
||||
def test_long_writer_round_trip(tmp_path):
|
||||
w = LongWriter(tmp_path / "time_log" / "15_9_F_11_T2.parquet", "time", "15/9-F-11 T2", ["HKLD", "PASS"])
|
||||
t0 = 1365385528000
|
||||
w.write("HKLD", np.array([1, 1, 2], dtype=np.int32), np.array([t0, t0 + 3000, t0 + 3000]),
|
||||
np.array([1.5, 2.5, 2.5]), None, np.array([1, 1, 4], dtype=np.int16), np.array([0, 0, 1], dtype=np.int8))
|
||||
w.write("PASS", np.array([1], dtype=np.int32), np.array([t0]), np.array([np.nan]),
|
||||
np.array(["Drilling"], dtype=object), np.array([1], dtype=np.int16), np.array([0], dtype=np.int8))
|
||||
w.close()
|
||||
df = pq.read_table(w.path).to_pandas()
|
||||
assert w.rows == 4 and list(df.columns) == ["wellbore", "log_id", "mnemonic", "time", "value", "text", "chunk",
|
||||
"dup_rank"]
|
||||
assert set(df["wellbore"]) == {"15/9-F-11 T2"} and df["mnemonic"].tolist() == ["HKLD"] * 3 + ["PASS"]
|
||||
assert df["time"].iloc[1] == pd.Timestamp("2013-04-08T01:45:31Z") and df["dup_rank"].tolist() == [0, 0, 1, 0]
|
||||
assert df["value"].isna().tolist() == [False, False, False, True] and df["text"].iloc[3] == "Drilling"
|
||||
assert not list(tmp_path.rglob("*.tmp"))
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------------------------------------------
|
||||
# wellbore names and the object tables
|
||||
# ---------------------------------------------------------------------------------------------------------------
|
||||
|
||||
@pytest.mark.parametrize("name_well, name_wellbore, uid, expected", [
|
||||
("NO 15/9-F-11", "NO 15/9-F-11 T2", "31f506a6", ("15/9-F-11 T2", "nameWellbore")),
|
||||
("15/9-F-15B", "15/9-F-15B - Main Wellbore", "B-854763", ("15/9-F-15 B", "nameWellbore")),
|
||||
("15/9-F-4", "EcoScope_Customer_Run5", "B-613073", ("15/9-F-4", "nameWell")),
|
||||
("15/9-F-15S", "15/9-F-15S - Main Wellbore", "B-744206", ("15/9-F-15", "uidWellbore")),
|
||||
("15/9-F-15", "15/9-F-15 - Main Wellbore", "B-826806", ("15/9-F-15 A", "uidWellbore")),
|
||||
("15/9-F-15A", "15/9-F-15A - Main Wellbore", "B-861401", ("15/9-F-15 C", "uidWellbore")),
|
||||
("NO 15/9-F-15", "NO 15/9-F-15 C", "9ab4989d", ("15/9-F-15 C", "nameWellbore")),
|
||||
])
|
||||
def test_wellbore_name(name_well, name_wellbore, uid, expected):
|
||||
assert witsml.wellbore_name(name_well, name_wellbore, uid) == expected
|
||||
|
||||
|
||||
def test_published_name_is_kept():
|
||||
assert witsml.published_wellbore("15/9-F-15S", "15/9-F-15S - Main Wellbore") == ("15/9-F-15 S", "nameWellbore")
|
||||
assert witsml.wellbore_dir("15/9-F-11 T2") == "15_9_F_11_T2"
|
||||
|
||||
|
||||
def element(xml: str) -> ET.Element:
|
||||
return ET.fromstring(f'<x xmlns="{NSURI}">{xml}</x>')
|
||||
|
||||
|
||||
def test_flat_sentinels_units_and_nesting():
|
||||
flat = Flat()
|
||||
st = element('<md uom="m">-999.25</md><tvd uom="m">145.9</tvd><incl uom="rad">0.5</incl>'
|
||||
'<dls uom="dega/m">0.1</dls><typeTrajStation>tie in point</typeTrajStation><empty uom="m"></empty>'
|
||||
'<corUsed><stnGridCorUsed uom="rad">999.25</stnGridCorUsed>'
|
||||
'<dirSensorOffset uom="m">0</dirSensorOffset></corUsed>'
|
||||
'<commonData><itemState>actual</itemState><priv_ipOwner>10.0.0.1</priv_ipOwner></commonData>'
|
||||
'<tubular uidRef="T1">string</tubular><p uid="a"><v>1</v></p><p uid="b"><v>2</v></p>')
|
||||
row = flat.leaves(st, {}, "trajectory")
|
||||
assert row["md"] is None and row["tvd"] == 145.9 and row["empty"] is None
|
||||
assert row["incl"] == pytest.approx(28.6478897565) and row["dls"] == pytest.approx(3.0)
|
||||
assert row["corUsed_stnGridCorUsed"] is None and row["corUsed_dirSensorOffset"] == 0.0
|
||||
assert row["commonData_itemState"] == "actual" and "commonData_priv_ipOwner" not in row
|
||||
assert row["tubular"] == "string" and row["tubular_uidRef"] == "T1"
|
||||
assert (row["p_uid"], row["p_v"], row["p2_uid"], row["p2_v"]) == ("a", "1", "b", "2")
|
||||
assert flat.sentinels == {("trajectory", "md", -999.25): 1, ("trajectory", "corUsed_stnGridCorUsed", 999.25): 1}
|
||||
units = witsml.units_table(flat).set_index("column")
|
||||
assert (units.loc["incl", "uom"], units.loc["incl", "uom_stored"]) == ("rad", "dega")
|
||||
assert units.loc["dls", "uom_stored"] == "dega/30m" and units.loc["dls", "factor"] == 30.0
|
||||
assert "md" not in units.index # a sentinel is not a value in a unit
|
||||
assert witsml.sentinels_table(flat)["n"].sum() == 2
|
||||
with pytest.raises(ValueError, match="repeated leaf"):
|
||||
Flat().leaves(element('<md uom="m">1</md><md uom="m">2</md>'), {}, "trajectory")
|
||||
# 999.25 is a sentinel only where it cannot be a value; -999 only in the mudLog gas readings
|
||||
assert Flat().leaves(element('<md uom="m">999.25</md>'), {}, "trajectory")["md"] == 999.25
|
||||
gas = Flat().leaves(element('<chromatograph><methAv uom="ppm">-999</methAv><methMx uom="ppm">999</methMx>'
|
||||
'</chromatograph><ropAv uom="m/s">-999</ropAv>'), {}, "mudlog_intervals")
|
||||
assert gas == {"chromatograph_methAv": None, "chromatograph_methMx": 999.0, "ropAv": -999.0}
|
||||
|
||||
|
||||
def test_units_table_refuses_two_stored_units():
|
||||
flat = Flat()
|
||||
flat.units.update({("trajectory", "md", "m"): 1, ("trajectory", "md", "ft"): 1})
|
||||
with pytest.raises(ValueError, match="more than one unit"):
|
||||
witsml.units_table(flat)
|
||||
|
||||
|
||||
def test_view_sql_names_the_depth_channels(tmp_path):
|
||||
views = witsml.view_sql(tmp_path)
|
||||
assert list(views) == ["time_log", "time_log_dedup", "depth_log", "depth_log_dedup", "drill_depth"]
|
||||
assert f"{tmp_path.as_posix()}/time_log/*.parquet" in views["time_log"]
|
||||
assert "dup_rank = 0" in views["depth_log_dedup"]
|
||||
assert "(d.mnemonic = 'DMEA') OR (d.mnemonic = 'Depth' AND c.name = 'GenTime')" in views["drill_depth"]
|
||||
assert "(d.mnemonic = 'DBTM') OR (d.mnemonic = 'BITDEP' AND c.name = 'GenTime')" in views["drill_depth"]
|
||||
|
||||
|
||||
def test_tadi_filters_only_flag():
|
||||
df = pd.DataFrame({"ropAv": [0.01, 0.06, None], "rpmAv": [2.0, 2.0, 6.0], "wobAv": [1e5, 1e5, 1e5]})
|
||||
assert witsml.tadi_implausible(df).tolist() == [False, True, True] # 0.06 m/s = 216 m/h; 6 c/s = 360 rpm
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------------------------------------------
|
||||
# formation tops
|
||||
# ---------------------------------------------------------------------------------------------------------------
|
||||
|
||||
WIDTHS = [24, 40, 5, 3, 8, 8, 8, 8, 6, 6, 9, 9, 5] # the dash line of the picks file
|
||||
|
||||
|
||||
def picks_line(*cells) -> str:
|
||||
return " " + " ".join(str(c).ljust(w) for c, w in zip(cells, WIDTHS))
|
||||
|
||||
|
||||
def picks_block(well: str, rows: list[tuple]) -> str:
|
||||
head = [f"Well {well}", picks_line(*tops.COLUMNS), picks_line(*("-" * w for w in WIDTHS))]
|
||||
return "\n".join(head + [picks_line(well, *r, "STAT") for r in rows]) + "\n\n"
|
||||
|
||||
|
||||
PICKS = "# Qlf column\n# NL: Not logged\n\n" + picks_block("NO 15/9-19 SR", [
|
||||
("Seabed", 1, "", "106.00", "106.00", "-81.00", "81.08", "", "", "437506.0", "6477887.5"),
|
||||
("HORDALAND GP. Top", 1, "NL", "1107.50", "1057.14", "-1032.14", "998.00", "", "", "437313.9", "6477939.3"),
|
||||
("Hugin Fm. VOLVE Base", 2, "", "4340.00", "2904.66", "-2879.66", "2566.01", "1.27", "3.00", "434734.9",
|
||||
"6478413.8"),
|
||||
]) + picks_block("NO 15/9-F-12 pilot", [
|
||||
("Utsira Fm. Top", 1, "", "882.45", "882.42", "-827.52", "900.57", "", "", "435055.3", "6478564.5"),
|
||||
]) + picks_block("NO 15/5-7 A", [("Sleipner Fm. Top", 1, "", "4098.10", "", "", "", "", "", "", "")])
|
||||
|
||||
|
||||
def test_parse_picks(tmp_path):
|
||||
f = tmp_path / "picks.dat"
|
||||
f.write_text(PICKS, encoding="ascii")
|
||||
p = tops.parse_picks(f, {"15/9-19 S", "15/9-19 ST2", "15/9-F-12"})
|
||||
assert len(p) == 5 and p["wellbore_picks"].tolist() == ["15/9-19 SR"] * 3 + ["15/9-F-12 pilot", "15/5-7 A"]
|
||||
assert p["wellbore"].tolist()[:4] == ["15/9-19 ST2"] * 3 + ["15/9-F-12"] and pd.isna(p["wellbore"].iloc[4])
|
||||
assert p["track"].tolist() == ["main"] * 3 + ["pilot", "main"]
|
||||
hugin = p.iloc[2]
|
||||
assert (hugin["surface"], hugin["unit"], hugin["boundary"], hugin["obs"]) == (
|
||||
"Hugin Fm. VOLVE Base", "Hugin Fm. VOLVE", "Base", 2)
|
||||
assert (hugin["md"], hugin["tvdss"], hugin["dip"], hugin["azi"], hugin["northing"]) == (
|
||||
4340.0, -2879.66, 1.27, 3.0, 6478413.8)
|
||||
assert p.iloc[0]["boundary"] is None or pd.isna(p.iloc[0]["boundary"]) # "Seabed" has no Top/Base
|
||||
assert p.iloc[1]["qlf"] == "NL" and pd.isna(p.iloc[0]["qlf"]) and pd.isna(p.iloc[4]["tvd"])
|
||||
assert p["line"].tolist() == [7, 8, 9, 14, 19]
|
||||
shared = tops.shared_trunk_picks(p) # above the kick-off at 1493 m
|
||||
assert shared["wellbore"].tolist() == ["15/9-19 S"] * 2 and shared["md"].tolist() == [106.0, 1107.5]
|
||||
assert set(shared["inherited_from"]) == {"15/9-19 SR"} and set(shared["md_kickoff"]) == {1493.0}
|
||||
|
||||
|
||||
def test_parse_picks_rejects_a_broken_file(tmp_path):
|
||||
f = tmp_path / "picks.dat"
|
||||
f.write_text(PICKS.replace("NO 15/9-F-12 pilot Utsira", "NO 15/9-F-12 Utsira"),
|
||||
encoding="ascii")
|
||||
with pytest.raises(ValueError, match="in the block of"):
|
||||
tops.parse_picks(f)
|
||||
f.write_text(PICKS.replace(" NL 1107.50", " XX 1107.50"), encoding="ascii")
|
||||
with pytest.raises(ValueError, match="unknown qualifiers"):
|
||||
tops.parse_picks(f)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------------------------------------------
|
||||
# the Volve files
|
||||
# ---------------------------------------------------------------------------------------------------------------
|
||||
|
||||
ROOT = paths.witsml_dir()
|
||||
OUT = paths.outputs_dir() / "witsml"
|
||||
needs_data = pytest.mark.skipif(not ROOT.is_dir(), reason="missing the WITSML folder")
|
||||
needs_picks = pytest.mark.skipif(not paths.well_picks_file().is_file(), reason="missing the well picks file")
|
||||
needs_tables = pytest.mark.skipif(not (OUT / "summary.json").is_file(),
|
||||
reason="missing outputs/witsml: run scripts/06_parse_witsml.py")
|
||||
|
||||
|
||||
@pytest.mark.data
|
||||
@needs_data
|
||||
def test_find_logs_and_wellbores():
|
||||
logs = witsml.find_logs(ROOT)
|
||||
assert len(logs) == 2047 and sum(len(files) for *_, files in logs) == 7150
|
||||
assert sum(1 for _ in ROOT.rglob("log/**/*.xml")) == 7150 # no log file outside the layout
|
||||
names = {}
|
||||
for folder, wb_dir, directory, files in logs:
|
||||
h = read_log_file(files[0], header_only=True).header
|
||||
wellbore, _ = witsml.wellbore_name(h["nameWell"], h["nameWellbore"], h["uidWellbore"])
|
||||
names.setdefault((folder, wb_dir), (h["uidWellbore"], h["nameWellbore"], wellbore))
|
||||
assert len(names) == 33 # wellbore folders with logs
|
||||
wellbores = {wb for *_, wb in names.values()}
|
||||
assert len(wellbores) == 21 and "15/9-F-15 S" not in wellbores
|
||||
assert names[("Norway-StatoilHydro-15_$47$_9-F-15S", "1")] == (
|
||||
"B-744206", "15/9-F-15S - Main Wellbore", "15/9-F-15")
|
||||
assert names[("Norway-StatoilHydro-15_$47$_9-F-15", "1")][2] == "15/9-F-15 A"
|
||||
assert names[("Norway-StatoilHydro-15_$47$_9-F-15A", "1")][2] == "15/9-F-15 C"
|
||||
assert names[("Norway-StatoilHydro-15_$47$_9-F-15B", "1")][2] == "15/9-F-15 B"
|
||||
# a well folder holds several wellbores: the folder name is not the wellbore
|
||||
assert {names[("Norway-Statoil-NO 15_$47$_9-F-11", n)][2] for n in "1234"} == {
|
||||
"15/9-F-11", "15/9-F-11 A", "15/9-F-11 B", "15/9-F-11 T2"}
|
||||
assert {names[("Norway-Statoil-NO 15_$47$_9-F-15", n)][2] for n in "12"} == {"15/9-F-15 C", "15/9-F-15 D"}
|
||||
|
||||
|
||||
@pytest.mark.data
|
||||
@needs_data
|
||||
def test_parse_one_log():
|
||||
directory = ROOT / "Norway-StatoilHydro-15_$47$_9-F-15B" / "1" / "log" / "2" / "1" / "1"
|
||||
log = witsml.parse_log(sorted(directory.glob("*.xml")))
|
||||
curves = log.curves()
|
||||
assert (log.header["uid"], log.header["name"], log.kind) == ("L-854765-MD", "8.5in section - MD Log", "depth")
|
||||
assert log.counts["rows"] == 650 and log.counts["bad_rows"] == 0 and len(log.curve_info) == 386
|
||||
assert len(curves) == 385 and sum(len(c.index) for c in curves) == 12898
|
||||
assert all((np.diff(c.index) > 0).all() for c in curves)
|
||||
|
||||
|
||||
@pytest.mark.data
|
||||
@needs_data
|
||||
def test_parse_objects_counts():
|
||||
t, flat = witsml.parse_objects(ROOT)
|
||||
assert {k: len(v) for k, v in t.items()} == {
|
||||
"trajectory_catalog": 63, "trajectory": 5561, "messages": 11134, "bha_runs": 161, "mudlog_catalog": 8,
|
||||
"mudlog_intervals": 2882, "mudlog_lithology": 3617, "mudlog_qualifiers": 2951}
|
||||
assert sum(flat.sentinels.values()) == 3703
|
||||
assert flat.sentinels[("trajectory", "corUsed_stnGridCorUsed", 999.25)] == 2123
|
||||
traj = t["trajectory"]
|
||||
assert traj["incl"].between(0, 180).all() and traj["azi"].dropna().between(0, 360).all() # degrees
|
||||
assert set(t["trajectory_catalog"].loc[t["trajectory_catalog"]["wellbore_source"] == "uidWellbore",
|
||||
"wellbore"]) == {"15/9-F-15", "15/9-F-15 A", "15/9-F-15 C"}
|
||||
assert t["mudlog_intervals"]["wellbore"].nunique() == 8 and t["messages"]["wellbore"].nunique() == 16
|
||||
assert witsml.units_table(flat).groupby(["table", "column"])["uom_stored"].nunique().max() == 1
|
||||
|
||||
|
||||
@pytest.mark.data
|
||||
@needs_picks
|
||||
def test_well_picks():
|
||||
p = tops.parse_picks(paths.well_picks_file())
|
||||
assert len(p) == 409 and p["wellbore_picks"].nunique() == 35 and p["md"].notna().all()
|
||||
assert set(p.loc[p["wellbore_picks"] == "15/9-19 SR", "wellbore"]) == {"15/9-19 ST2"}
|
||||
assert set(p.loc[p["wellbore_picks"] == "15/9-F-12 pilot", "wellbore"]) == {"15/9-F-12"}
|
||||
assert (p["wellbore_picks"] == "15/9-19 SR").sum() == 15 and (p["track"] == "pilot").sum() == 3
|
||||
shared = tops.shared_trunk_picks(p)
|
||||
assert shared.groupby("wellbore").size().to_dict() == {"15/9-19 S": 4, "15/9-F-9 A": 2}
|
||||
assert shared["md"].max() == 1107.5
|
||||
|
||||
|
||||
def _script():
|
||||
spec = importlib.util.spec_from_file_location("parse_witsml", paths.REPO_ROOT / "scripts" / "06_parse_witsml.py")
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(module)
|
||||
return module
|
||||
|
||||
|
||||
@pytest.mark.data
|
||||
@needs_tables
|
||||
def test_locked_counts():
|
||||
summary = json.loads((OUT / "summary.json").read_text(encoding="utf-8"))
|
||||
assert summary["counts"] == _script().EXPECTED
|
||||
assert summary["checks"]["wellbore_identity_wrong"] == []
|
||||
assert summary["duplicates"]["in_log_conflict"] == {"depth": 0, "time": 0}
|
||||
assert summary["counts"]["log_bad_rows"] == 0
|
||||
|
||||
|
||||
@pytest.mark.data
|
||||
@needs_tables
|
||||
def test_tables_keys_and_mapping():
|
||||
with witsml.connect(OUT) as con:
|
||||
def one(sql: str):
|
||||
return con.execute(sql).fetchone()[0]
|
||||
|
||||
assert one("SELECT count(*) FROM log_catalog") == 2047
|
||||
assert one("SELECT count(DISTINCT wellbore) FROM log_catalog") == 21
|
||||
assert one("SELECT count(*) FROM log_catalog WHERE wellbore = '15/9-F-15 S'") == 0
|
||||
assert con.execute("SELECT DISTINCT wellbore_witsml, wellbore FROM log_catalog WHERE wellbore_source = "
|
||||
"'uidWellbore' ORDER BY 1").fetchall() == [
|
||||
("15/9-F-15", "15/9-F-15 A"), ("15/9-F-15 A", "15/9-F-15 C"), ("15/9-F-15 S", "15/9-F-15")]
|
||||
# the long table of a small wellbore: values = catalog, one row per (log, mnemonic, time), dedup view unique
|
||||
wb = "15/9-F-15 B"
|
||||
n = one(f"SELECT count(*) FROM time_log WHERE wellbore = '{wb}'")
|
||||
assert n == one(f"SELECT sum(n_values) FROM log_catalog WHERE wellbore = '{wb}' AND kind = 'time'")
|
||||
assert n == one(f"SELECT count(*) FROM (SELECT DISTINCT log_id, mnemonic, time FROM time_log "
|
||||
f"WHERE wellbore = '{wb}')")
|
||||
kept = one(f"SELECT count(*) FROM time_log_dedup WHERE wellbore = '{wb}'")
|
||||
assert kept == one(f"SELECT count(*) FROM (SELECT DISTINCT mnemonic, time FROM time_log "
|
||||
f"WHERE wellbore = '{wb}')")
|
||||
assert n - kept == one(f"SELECT sum(n_ranked) FROM log_curves WHERE wellbore = '{wb}' AND kind = 'time'")
|
||||
assert one("SELECT count(*) FROM formation_tops") == 409
|
||||
assert one("SELECT count(*) FROM formation_tops_all") == 415
|
||||
assert one("SELECT count(DISTINCT wellbore) FROM formation_tops_all WHERE wellbore IS NOT NULL") == 26
|
||||
Reference in New Issue
Block a user