Files
Volve-DIA/tests/test_witsml.py
lamlvh 17916650a5 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>
2026-11-17 08:34:35 +00:00

458 lines
26 KiB
Python

"""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