Files
Volve-DIA/scripts/06_parse_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

651 lines
40 KiB
Python

"""Parse the WITSML real-time objects and the formation tops into tables.
python scripts/06_parse_witsml.py [--workers 8]
python scripts/06_parse_witsml.py --match F-15S # a subset, for testing: written to outputs/witsml_subset/,
# no EXPECTED check, no cross-source checks
Writes outputs/witsml/ (needs outputs/ddr/volve_ddr.duckdb from 02 for the cross-source checks):
time_log/<wellbore>.parquet, depth_log/<wellbore>.parquet long log tables, one file per wellbore, sorted by
(mnemonic, index); zstd
<table>.parquet every other table
volve_witsml.duckdb the small tables, and views over the parquet files
for the log data (`time_log`, `depth_log`, their
`_dedup` versions, `drill_depth`)
summary.json counts, duplicates, sentinels, cross-source checks
and outputs/tops/{well_picks,shared_trunk_picks}.parquet (also tables `formation_tops`, `formation_tops_shared`
and the view `formation_tops_all` of volve_witsml.duckdb).
Fails if a count differs from EXPECTED, so a parser change that loses or adds rows is caught, and if the hole
depth of a WITSML wellbore agrees better with another DDR wellbore than with the one it is mapped to.
"""
from __future__ import annotations
import argparse
import collections
import json
import os
import shutil
import sys
import time
import warnings
from concurrent.futures import ProcessPoolExecutor
from pathlib import Path
import duckdb
import numpy as np
import pandas as pd
import pyarrow as pa
from volve_dia import paths, tops, witsml
warnings.filterwarnings("ignore", message=".*inplace keyword.*") # raised inside duckdb's .df() by pandas 3.1
#: Counts of the run of 17/11/2026 (2,047 logs in 7,150 files; 33 wellbore folders -> 21 DDR wellbores).
#: `log_values` are the rows of time_log and depth_log; `log_values_dropped_in_log` the repeats removed inside a
#: log; `log_values_ranked` the rows with dup_rank > 0 (the same mnemonic and index in another log of the wellbore).
EXPECTED = {
"log_files": 7150,
"logs": {"depth": 960, "time": 1087},
"log_rows": {"depth": 2740760, "time": 53301664},
"log_values": {"depth": 45436597, "time": 2249583611},
"log_values_dropped_in_log": {"depth": 1311, "time": 2904492},
"log_values_ranked": {"depth": 7543003, "time": 107353349},
"log_bad_rows": 0,
"wellbores_with_logs": 21,
"trajectories": 63, "trajectory_stations": 5561,
"messages": 11134, "bha_runs": 161,
"mudlogs": 8, "mudlog_intervals": 2882, "mudlog_lithology": 3617, "mudlog_qualifiers": 2951,
"sentinels_replaced": 3703,
"formation_tops": 409, "formation_tops_wellbores": 35, "formation_tops_ddr_wellbores": 24,
"formation_tops_shared": 6,
}
HEADER_FIELDS = ["uidWell", "uidWellbore", "uid", "nameWell", "nameWellbore", "name", "serviceCompany",
"runNumber", "bhaRunNumber", "pass", "creationDate", "description", "objectGrowing", "indexType",
"indexCurve", "direction", "nullValue", "startIndex", "endIndex", "startDateTimeIndex",
"endDateTimeIndex", "commonData_sourceName", "commonData_dTimCreation",
"commonData_dTimLastChange"]
CURVE_FIELDS = ["unit", "typeLogData", "nullValue", "classWitsml", "curveDescription", "dataSource", "mnemAlias",
"alternateIndex"]
CURVE_COUNTS = ["n_values", "n_text", "n_not_number", "n_nan", "n_null_value", "n_dup_same", "n_dup_conflict",
"n_out_of_order", "n_ranked"]
#: A DDR depth and a WITSML depth are compared when the WITSML value is at most this old at the report end.
MAX_AGE = "1 hour"
#: A DDR survey station and a WITSML trajectory station are the same station when their MD differ by at most this.
SURVEY_MD_TOLERANCE = 0.5
# --------------------------------------------------------------------------------------------------------------
# logs: one worker per wellbore
# --------------------------------------------------------------------------------------------------------------
def log_tasks(root: Path, out: Path, match: str | None) -> list[tuple]:
"""Logs grouped by DDR wellbore (the header of the first chunk file names it), largest wellbore first."""
groups: dict[str, list] = collections.defaultdict(list)
for log_id, (folder, wb_dir, directory, files) in enumerate(witsml.find_logs(root)):
if match and match not in str(directory):
continue
h = witsml.read_log_file(files[0], header_only=True).header
wellbore, _ = witsml.wellbore_name(h.get("nameWell", ""), h.get("nameWellbore", ""), h.get("uidWellbore"))
groups[wellbore].append((log_id, folder, wb_dir, directory, files))
size = {wb: sum(f.stat().st_size for log in logs for f in log[4]) for wb, logs in groups.items()}
return [(wb, groups[wb], root, out) for wb in sorted(groups, key=lambda wb: -size[wb])]
def one_thread() -> None:
"""Worker initialiser: Arrow would otherwise start one thread per core in every worker."""
pa.set_cpu_count(1)
pa.set_io_thread_count(1)
def process_wellbore(task) -> dict:
"""Parse every log of one wellbore, write its two long tables, return the catalog rows."""
wellbore, logs, root, out = task
catalog, curve_rows = [], {}
curves: dict[str, dict[str, list]] = {"time": collections.defaultdict(list),
"depth": collections.defaultdict(list)}
hours: set[int] = set()
for log_id, folder, wb_dir, directory, files in logs:
t0 = time.time()
log = witsml.parse_log(files)
h = log.header
name_well, name_wellbore = h.get("nameWell", ""), h.get("nameWellbore", "")
_, source = witsml.wellbore_name(name_well, name_wellbore, h.get("uidWellbore"))
settings = h.get("name") in witsml.SETTINGS_LOGS
cat = {"log_id": log_id, "wellbore": wellbore, "wellbore_source": source,
"wellbore_witsml": witsml.published_wellbore(name_well, name_wellbore)[0], "folder": folder,
"wb_dir": wb_dir, "path": directory.relative_to(root).as_posix(), "kind": log.kind,
"log_class": "settings" if settings else "data", "n_files": len(files),
"bytes": sum(f.stat().st_size for f in files)}
cat.update({k: h.get(k) for k in HEADER_FIELDS})
cat["index_unit"] = log.index_unit
ist = log.index_stats()
cat.update(n_rows=log.counts["rows"], n_bad_rows=log.counts["bad_rows"],
n_index_distinct=ist.get("n_index_distinct", 0), n_index_backwards=ist.get("n_index_backwards", 0),
step_median=ist.get("step_median"), step_p10=ist.get("step_p10"), step_p90=ist.get("step_p90"),
n_curves_declared=len(log.curve_info))
index_key = "time" if log.kind == "time" else "md"
if ist["n_index_values"]:
cat[f"{index_key}_min"], cat[f"{index_key}_max"] = ist["index_min"], ist["index_max"]
if log.kind == "time" and not settings:
hours.update(np.unique(np.concatenate(log.index_values) // 3_600_000).tolist())
declared = dict(log.curve_info)
n_values = n_with_data = 0
for c in log.curves(log_id):
info = declared.pop(c.mnemonic)
row = {"log_id": log_id, "wellbore": wellbore, "kind": log.kind, "mnemonic": c.mnemonic,
"is_index": False, "undeclared": bool(info.get("undeclared"))}
row.update({k: info.get(k) for k in CURVE_FIELDS})
row.update({k: v for k, v in c.stats.items()})
row[f"{index_key}_min"], row[f"{index_key}_max"] = c.index[0], c.index[-1]
curve_rows[(log_id, c.mnemonic)] = row
curves[log.kind][c.mnemonic].append(c)
n_values += len(c.index)
n_with_data += 1
for name, info in declared.items(): # declared, without a value in any chunk file
row = {"log_id": log_id, "wellbore": wellbore, "kind": log.kind, "mnemonic": name,
"is_index": name == h.get("indexCurve"), "undeclared": False, "n_values": 0}
row.update({k: info.get(k) for k in CURVE_FIELDS})
curve_rows[(log_id, name)] = row
cat.update(n_curves_with_data=n_with_data, n_values=n_values, seconds=round(time.time() - t0, 2))
catalog.append(cat)
del log
overlaps, written = [], {}
for kind, by_mnemonic in curves.items():
if not by_mnemonic:
continue
target = out / f"{kind}_log" / f"{witsml.wellbore_dir(wellbore)}.parquet"
writer = witsml.LongWriter(target, kind, wellbore, list(by_mnemonic))
for mnemonic in sorted(by_mnemonic):
log_id, index, value, text, chunk, rank, pairs = witsml.merge_curve(by_mnemonic[mnemonic])
by_mnemonic[mnemonic] = None # free the per-log arrays
writer.write(mnemonic, log_id, index, value, text, chunk, rank)
for p in pairs:
overlaps.append({"wellbore": wellbore, "kind": kind, "mnemonic": mnemonic, **p})
if pairs:
ids, counts = np.unique(log_id[rank > 0], return_counts=True)
for i, n in zip(ids.tolist(), counts.tolist()):
curve_rows[(i, mnemonic)]["n_ranked"] = n
writer.close()
written[kind] = {"file": target.relative_to(out).as_posix(), "rows": writer.rows,
"bytes": target.stat().st_size}
return {"wellbore": wellbore, "catalog": catalog, "curves": list(curve_rows.values()), "overlaps": overlaps,
"written": written, "hours": sorted(hours)}
def log_tables(results: list[dict]) -> dict[str, pd.DataFrame]:
cat = pd.DataFrame([c for r in results for c in r["catalog"]]).sort_values("log_id", ignore_index=True)
cur = pd.DataFrame([c for r in results for c in r["curves"]]).sort_values(["log_id", "mnemonic"],
ignore_index=True)
for c in CURVE_COUNTS:
cur[c] = cur[c].fillna(0).astype("int64") if c in cur else 0
stat_cols = sorted(c for c in cur.columns if c.startswith(("suspect:", "sentinel:")))
stats = cur.melt(id_vars=["log_id", "wellbore", "kind", "mnemonic"], value_vars=stat_cols, var_name="stat",
value_name="n")
stats = stats[stats["n"] > 0].astype({"n": "int64"})
stats[["stat", "value"]] = stats["stat"].str.split(":", n=1, expand=True) if len(stats) else None
suspects = stats.loc[stats["stat"] == "suspect", ["log_id", "wellbore", "kind", "mnemonic", "value", "n"]]
removed = [{"table": f"{r.kind}_log", "column": r.mnemonic, "value": float(r.value), "n": r.n,
"kind": "sentinel"} for r in stats[stats["stat"] == "sentinel"].itertuples()]
removed += [{"table": f"{r.kind}_log", "column": r.mnemonic, "value": float(r.nullValue), "n": r.n_null_value,
"kind": "nullValue"} for r in cur[cur["n_null_value"] > 0].itertuples()]
cur = cur.drop(columns=stat_cols)
for df in (cat, cur):
for c in ("time_min", "time_max"):
if c in df:
df[c] = pd.to_datetime(df[c], unit="ms", utc=True)
counts = cur.groupby("log_id")[["n_dup_same", "n_dup_conflict", "n_out_of_order", "n_ranked", "n_text"]].sum()
cat = cat.join(counts, on="log_id")
cat[counts.columns] = cat[counts.columns].fillna(0).astype("int64")
ov = pd.DataFrame([o for r in results for o in r["overlaps"]],
columns=["wellbore", "kind", "mnemonic", "log_id", "other_log_id", "n", "n_same",
"n_rounding", "n_conflict", "max_abs_diff"])
hours = pd.DataFrame([(r["wellbore"], h) for r in results for h in r["hours"]], columns=["wellbore", "hour"])
hours["hour"] = pd.to_datetime(hours["hour"] * 3600, unit="s", utc=True)
sent = pd.DataFrame(removed, columns=["table", "column", "value", "n", "kind"])
if len(sent):
sent = sent.groupby(["table", "column", "value", "kind"], as_index=False)["n"].sum()
units = cur[cur["n_values"] > 0].groupby(["kind", "mnemonic", "unit"], dropna=False).agg(
n=("n_values", "sum"), n_logs=("log_id", "count")).reset_index()
units = pd.DataFrame({"table": units["kind"] + "_log", "column": units["mnemonic"], "uom": units["unit"],
"n": units["n"], "uom_stored": units["unit"], "factor": 1.0, "n_logs": units["n_logs"]})
return {"log_catalog": cat, "log_curves": cur, "log_overlaps": ov, "log_hours": hours,
"log_suspects": suspects.sort_values(["log_id", "mnemonic", "value"], ignore_index=True),
"_sentinels": sent, "_units": units}
def wellbores_table(t: dict[str, pd.DataFrame], ddr_wellbores: set[str]) -> pd.DataFrame:
"""One row per WITSML wellbore (well folder + numbered subfolder): names, DDR wellbore, object counts."""
key = ["folder", "wb_dir", "uidWellbore", "nameWell", "nameWellbore", "wellbore_witsml", "wellbore",
"wellbore_source"]
parts = []
cat = t["log_catalog"]
for kind in ("time", "depth"):
part = cat[cat["kind"] == kind].groupby(key, dropna=False).agg(
n=("log_id", "count"), n_values=("n_values", "sum")).reset_index()
parts.append(part.rename(columns={"n": f"n_{kind}_logs", "n_values": f"n_{kind}_values"}))
for table, column in (("trajectory_catalog", "n_trajectories"), ("messages", "n_messages"),
("bha_runs", "n_bha_runs"), ("mudlog_catalog", "n_mudlogs")):
df = t[table].assign(wb_dir=t[table]["path"].str.split("/").str[1])
parts.append(df.groupby(key, dropna=False).size().rename(column).reset_index())
out = parts[0]
for p in parts[1:]:
out = out.merge(p, on=key, how="outer")
counts = [c for c in out.columns if c.startswith("n_")]
out[counts] = out[counts].fillna(0).astype("int64")
out["in_ddr"] = out["wellbore"].isin(ddr_wellbores)
return out.sort_values(["wellbore", "folder", "wb_dir"], ignore_index=True)
# --------------------------------------------------------------------------------------------------------------
# DuckDB and the cross-source checks
# --------------------------------------------------------------------------------------------------------------
def build_db(out: Path, tables: dict[str, pd.DataFrame], ddr_db: Path, workers: int) -> duckdb.DuckDBPyConnection:
db = out / "volve_witsml.duckdb.tmp"
db.unlink(missing_ok=True)
con = duckdb.connect(str(db))
con.execute(f"SET threads = {workers}")
con.execute("SET memory_limit = '32GB'")
for name in tables:
con.execute(f"CREATE TABLE {name} AS SELECT * FROM read_parquet('{out / name}.parquet')")
for name, sql in witsml.view_sql(out.resolve()).items():
con.execute(f"CREATE VIEW {name} AS {sql}")
con.execute("CREATE VIEW formation_tops_all AS SELECT *, NULL::VARCHAR AS inherited_from, NULL::DOUBLE AS "
"md_kickoff FROM formation_tops UNION ALL SELECT * FROM formation_tops_shared")
con.execute(f"ATTACH '{ddr_db}' AS ddr (READ_ONLY)")
return con
def _quantiles(s: pd.Series, digits: int = 3) -> dict:
if not len(s):
return {"n": 0}
q = s.quantile([0.05, 0.25, 0.5, 0.75, 0.95])
return {"n": int(len(s)), "p05": round(float(q[0.05]), digits), "p25": round(float(q[0.25]), digits),
"median": round(float(q[0.5]), digits), "p75": round(float(q[0.75]), digits),
"p95": round(float(q[0.95]), digits), "max_abs": round(float(s.abs().max()), digits)}
def check_identity(con) -> tuple[pd.DataFrame, list[str]]:
"""Hole depth of every WITSML wellbore at the end of the DDR report periods of every DDR wellbore of its
slot. A WITSML wellbore must agree best with the DDR wellbore it is mapped to."""
con.execute(f"""
CREATE TEMP TABLE hole_uid AS
SELECT c.uidWellbore, any_value(c.wellbore) AS wellbore, any_value(c.wellbore_witsml) AS wellbore_witsml,
d.time, first(d.value ORDER BY c.n_values DESC, c.log_id) AS md
FROM time_log d JOIN log_catalog c USING (log_id)
WHERE d.mnemonic IN ({', '.join(repr(m) for m in witsml.HOLE_DEPTH)}) AND d.value IS NOT NULL
AND ({witsml.depth_filter(witsml.HOLE_DEPTH)})
GROUP BY c.uidWellbore, d.time""")
df = con.execute(f"""
WITH u AS (SELECT DISTINCT uidWellbore, wellbore, wellbore_witsml FROM hole_uid),
r AS (SELECT u.*, p.wellbore AS ddr_wellbore, p.end_utc, p.md AS ddr_md
FROM ddr.reports p JOIN u ON split_part(p.wellbore, ' ', 1) = split_part(u.wellbore, ' ', 1)
WHERE p.md IS NOT NULL)
SELECT r.uidWellbore, r.wellbore_witsml, r.wellbore AS mapped, r.ddr_wellbore, count(*) AS n_reports,
round(median(abs(h.md - r.ddr_md)), 3) AS median_abs_diff_m,
sum((abs(h.md - r.ddr_md) <= 5)::INT) AS n_within_5m
FROM r ASOF JOIN hole_uid h ON h.uidWellbore = r.uidWellbore AND r.end_utc >= h.time
WHERE r.end_utc - h.time <= INTERVAL {MAX_AGE}
GROUP BY ALL ORDER BY r.wellbore_witsml, r.uidWellbore, r.ddr_wellbore""").df()
best = df.sort_values(["n_within_5m", "n_reports"], ascending=False).groupby("uidWellbore").head(1)
mapped = df[df["mapped"] == df["ddr_wellbore"]].set_index("uidWellbore")["n_within_5m"]
wrong = [f"{r.uidWellbore} ({r.wellbore_witsml}) is mapped to {r.mapped} but agrees best with {r.ddr_wellbore}"
for r in best.itertuples() if r.n_within_5m > mapped.get(r.uidWellbore, 0)]
return df, wrong
def check_depth(con) -> tuple[pd.DataFrame, dict]:
"""WITSML hole depth and bit depth at the end of every DDR report period against `md` of the DDR."""
con.execute("CREATE TEMP TABLE dd AS SELECT * FROM drill_depth")
df = con.execute(f"""
WITH r AS (SELECT report_id, wellbore, end_utc, md AS ddr_md,
md - lag(md) OVER (PARTITION BY wellbore ORDER BY end_utc) AS ddr_md_change
FROM ddr.reports),
h AS (SELECT r.report_id, d.md AS hole_md, d.time AS hole_time, d.log_id AS hole_log_id
FROM r ASOF JOIN (SELECT * FROM dd WHERE depth = 'hole') d
ON d.wellbore = r.wellbore AND r.end_utc >= d.time
WHERE r.end_utc - d.time <= INTERVAL {MAX_AGE}),
b AS (SELECT r.report_id, d.md AS bit_md, d.time AS bit_time
FROM r ASOF JOIN (SELECT * FROM dd WHERE depth = 'bit') d
ON d.wellbore = r.wellbore AND r.end_utc >= d.time
WHERE r.end_utc - d.time <= INTERVAL {MAX_AGE})
SELECT r.*, h.hole_md, h.hole_time, h.hole_log_id, c.serviceCompany, b.bit_md, b.bit_time,
h.hole_md - r.ddr_md AS hole_diff, b.bit_md - r.ddr_md AS bit_diff
FROM r LEFT JOIN h USING (report_id) LEFT JOIN b USING (report_id)
LEFT JOIN log_catalog c ON c.log_id = h.hole_log_id
ORDER BY r.wellbore, r.end_utc""").df()
both = df[df["ddr_md"].notna() & df["hole_md"].notna()]
d = both["hole_diff"]
def share(s: pd.Series) -> dict:
return {"n": int(len(s)), "within_1m": int((s.abs() <= 1).sum()), "within_5m": int((s.abs() <= 5).sum()),
"within_50m": int((s.abs() <= 50).sum()), "beyond_50m": int((s.abs() > 50).sum()),
**{k: v for k, v in _quantiles(s).items() if k != "n"}}
far = both[d.abs() > 50]
summary = {
"max_age": MAX_AGE,
"ddr_reports": int(len(df)), "ddr_reports_with_md": int(df["ddr_md"].notna().sum()),
"reports_with_witsml_hole_depth": int(df["hole_md"].notna().sum()),
"reports_with_both": int(len(both)),
"hole_minus_ddr_m": share(d),
"hole_minus_ddr_m_by_company": {k: share(g["hole_diff"]) for k, g in both.groupby("serviceCompany")},
"hole_minus_ddr_m_when_ddr_md_increased": share(both.loc[both["ddr_md_change"] > 0, "hole_diff"]),
"hole_minus_ddr_m_when_ddr_md_did_not_increase": share(both.loc[~(both["ddr_md_change"] > 0), "hole_diff"]),
"beyond_50m": {"witsml_deeper": int((far["hole_diff"] > 0).sum()),
"witsml_shallower": int((far["hole_diff"] < 0).sum()),
"witsml_hole_depth_is_0": int((far["hole_md"] == 0).sum()),
"per_wellbore": {k: int(v) for k, v in far.groupby("wellbore").size().items()}},
"bit_minus_ddr_m": share(df.loc[df["ddr_md"].notna() & df["bit_md"].notna(), "bit_diff"]),
"reports_per_wellbore": {k: int(v) for k, v in both.groupby("wellbore").size().items()},
}
return df, summary
def check_coverage(con) -> tuple[pd.DataFrame, dict]:
"""Hours with time-log data inside every DDR report period, and the WITSML time range against the DDR's."""
df = con.execute("""
SELECT r.report_id, r.wellbore, r.start_utc, r.end_utc,
date_diff('hour', r.start_utc, r.end_utc) AS period_h, count(h.hour) AS hours_with_data
FROM ddr.reports r LEFT JOIN log_hours h
ON h.wellbore = r.wellbore AND h.hour >= r.start_utc AND h.hour < r.end_utc
GROUP BY ALL ORDER BY r.wellbore, r.end_utc""").df()
per = con.execute("""
WITH w AS (SELECT wellbore, min(hour) AS witsml_first, max(hour) AS witsml_last, count(*) AS witsml_hours
FROM log_hours GROUP BY ALL),
d AS (SELECT wellbore, min(start_utc) AS ddr_first, max(end_utc) AS ddr_last, count(*) AS ddr_reports
FROM ddr.reports WHERE start_utc >= TIMESTAMPTZ '1990-01-01' GROUP BY ALL),
inside AS (SELECT h.wellbore, count(DISTINCT h.hour) AS witsml_hours_in_ddr_periods
FROM log_hours h JOIN ddr.reports r
ON r.wellbore = h.wellbore AND h.hour >= r.start_utc AND h.hour < r.end_utc
GROUP BY ALL)
SELECT * FROM d FULL JOIN w USING (wellbore) LEFT JOIN inside USING (wellbore) ORDER BY wellbore""").df()
agg = df.groupby("wellbore").agg(reports=("report_id", "count"),
with_data=("hours_with_data", lambda s: (s > 0).sum()),
full=("hours_with_data", lambda s: (s >= 23).sum()))
per = per.merge(agg.reset_index(), on="wellbore", how="left")
has = per[per["witsml_hours"].notna()]
summary = {
"ddr_wellbores": int(per["ddr_reports"].notna().sum()),
"ddr_wellbores_with_time_logs": int((per["ddr_reports"].notna() & per["witsml_hours"].notna()).sum()),
"ddr_wellbores_without_time_logs": sorted(per.loc[per["witsml_hours"].isna(), "wellbore"]),
"witsml_wellbores_without_ddr": sorted(per.loc[per["ddr_reports"].isna(), "wellbore"]),
"ddr_reports_on_wellbores_with_time_logs": int(has["reports"].sum()),
"ddr_reports_with_any_hour_of_data": int((df["hours_with_data"] > 0).sum()),
"ddr_reports_with_23h_or_more": int((df["hours_with_data"] >= 23).sum()),
"witsml_hours_with_data": int(has["witsml_hours"].sum()),
"witsml_hours_inside_a_ddr_period_of_the_wellbore": int(has["witsml_hours_in_ddr_periods"].fillna(0).sum()),
"per_wellbore": json.loads(per.assign(
**{c: per[c].dt.strftime("%Y-%m-%dT%H:%MZ") for c in
("ddr_first", "ddr_last", "witsml_first", "witsml_last")}).to_json(orient="records")),
}
return df, summary
def check_surveys(con) -> tuple[pd.DataFrame, dict]:
"""DDR survey stations against the nearest WITSML trajectory station (actual trajectories) of the wellbore."""
df = con.execute(f"""
WITH s AS (SELECT DISTINCT wellbore, md, tvd, incl, azi FROM ddr.surveys WHERE md IS NOT NULL),
t AS (SELECT t.wellbore, t.md, t.tvd, t.incl, t.azi, t.path, t.seq, c.aziRef, c.serviceCompany
FROM trajectory t JOIN trajectory_catalog c USING (path) WHERE c.kind = 'actual'),
m AS (SELECT s.*, t.md AS w_md, t.tvd AS w_tvd, t.incl AS w_incl, t.azi AS w_azi, t.path, t.aziRef,
row_number() OVER (PARTITION BY s.wellbore, s.md, s.tvd, s.incl, s.azi
ORDER BY abs(t.md - s.md), abs(t.incl - s.incl), t.path, t.seq) AS k
FROM s JOIN t ON t.wellbore = s.wellbore AND abs(t.md - s.md) <= {SURVEY_MD_TOLERANCE})
SELECT s.*, s.wellbore IN (SELECT wellbore FROM t) AS has_trajectory, m.w_md, m.w_tvd, m.w_incl, m.w_azi,
m.path, m.aziRef, m.w_md - s.md AS md_diff, m.w_tvd - s.tvd AS tvd_diff, m.w_incl - s.incl AS incl_diff,
((m.w_azi - s.azi + 540) % 360) - 180 AS azi_diff
FROM s LEFT JOIN (SELECT * FROM m WHERE k = 1) m
ON m.wellbore = s.wellbore AND m.md = s.md AND m.tvd IS NOT DISTINCT FROM s.tvd
AND m.incl IS NOT DISTINCT FROM s.incl AND m.azi IS NOT DISTINCT FROM s.azi
ORDER BY s.wellbore, s.md""").df()
hit = df[df["w_md"].notna()]
steep = hit[hit["incl"] >= 5] # azimuth is ill-defined in a near-vertical hole
summary = {
"md_tolerance_m": SURVEY_MD_TOLERANCE,
"ddr_survey_stations_distinct": int(len(df)),
"on_wellbores_with_witsml_trajectory": int(df["has_trajectory"].sum()),
"matched": int(len(hit)),
"matched_per_wellbore": {k: int(v) for k, v in hit.groupby("wellbore").size().items()},
"incl_diff_deg": {**_quantiles(hit["incl_diff"]), "within_0.1": int((hit["incl_diff"].abs() <= 0.1).sum())},
"tvd_diff_m": {**_quantiles(hit["tvd_diff"].dropna()), "within_1m": int((hit["tvd_diff"].abs() <= 1).sum())},
"azi_diff_deg_incl_ge_5": {**_quantiles(steep["azi_diff"].dropna()),
"within_0.5": int((steep["azi_diff"].abs() <= 0.5).sum())},
"azi_diff_deg_incl_ge_5_by_aziRef": {str(k): _quantiles(g["azi_diff"].dropna())
for k, g in steep.groupby("aziRef", dropna=False)},
}
return df, summary
def check_tops(con) -> dict:
per = con.execute("""
WITH d AS (SELECT wellbore, max(md) AS ddr_md_max FROM ddr.reports GROUP BY ALL),
p AS (SELECT wellbore, count(*) FILTER (inherited_from IS NULL) AS picks,
count(*) FILTER (inherited_from IS NOT NULL) AS picks_shared, max(md) AS pick_md_max
FROM formation_tops_all WHERE wellbore IS NOT NULL GROUP BY ALL)
SELECT d.wellbore, coalesce(p.picks, 0) AS picks, coalesce(p.picks_shared, 0) AS picks_shared,
p.pick_md_max, d.ddr_md_max
FROM d LEFT JOIN p USING (wellbore) ORDER BY 1""").df()
# DDR `stratInfo` tops against the picks of the same formation ("Hugin Fm" ~ "Hugin Fm. VOLVE Top")
strat = con.execute(r"""
SELECT s.wellbore, s.description, s.mdTop AS ddr_md, p.surface, p.md AS pick_md, p.md - s.mdTop AS diff
FROM (SELECT DISTINCT wellbore, description, mdTop FROM ddr.strat WHERE mdTop IS NOT NULL) s
JOIN formation_tops p ON p.wellbore = s.wellbore AND p.track = 'main' AND p.boundary = 'Top' AND p.obs = 1
AND p.unit NOT LIKE '%Sand%'
AND lower(regexp_replace(p.unit, '\s+(Fm|GP)\b.*$', ''))
= lower(regexp_replace(s.description, '\s+(Fm|Gp)\b.*$', ''))""").df()
return {
"ddr_wellbores_with_own_picks": int((per["picks"] > 0).sum()),
"ddr_wellbores_with_shared_picks_only": sorted(
per.loc[(per["picks"] == 0) & (per["picks_shared"] > 0), "wellbore"]),
"ddr_wellbores_without_picks": sorted(per.loc[(per["picks"] == 0) & (per["picks_shared"] == 0), "wellbore"]),
"picks_below_ddr_md_max": json.loads(per[per["pick_md_max"] > per["ddr_md_max"]].to_json(orient="records")),
"ddr_strat_tops_matched_by_name": int(len(strat)),
"pick_minus_ddr_strat_m": {**_quantiles(strat["diff"]), "within_5m": int((strat["diff"].abs() <= 5).sum())},
"per_wellbore": json.loads(per.to_json(orient="records")),
}
# --------------------------------------------------------------------------------------------------------------
def du(path: Path) -> int:
return sum(f.stat().st_size for f in path.rglob("*") if f.is_file())
def main() -> int:
ap = argparse.ArgumentParser()
ap.add_argument("--workers", type=int, default=8)
ap.add_argument("--match", default=None, help="only logs whose path contains this text (for testing)")
args = ap.parse_args()
t_start = time.time()
root = paths.witsml_dir()
out = paths.outputs_dir() / ("witsml_subset" if args.match else "witsml")
out.mkdir(parents=True, exist_ok=True)
ddr_db = paths.outputs_dir() / "ddr" / "volve_ddr.duckdb"
if not ddr_db.is_file():
print(f"missing {ddr_db}: run scripts/02_parse_ddr.py first")
return 1
with duckdb.connect(str(ddr_db), read_only=True) as con:
ddr_wellbores = {w for (w,) in con.execute("SELECT DISTINCT wellbore FROM reports").fetchall()}
for stale in ("time_log", "depth_log", "log_time", "log_depth"):
shutil.rmtree(out / stale, ignore_errors=True)
# logs
tasks = log_tasks(root, out, args.match)
results = []
with ProcessPoolExecutor(max_workers=args.workers, initializer=one_thread) as ex:
for r in ex.map(process_wellbore, tasks, chunksize=1):
results.append(r)
print(f"[{time.time() - t_start:6.0f} s] {r['wellbore']}: {len(r['catalog'])} logs, " + ", ".join(
f"{k} {v['rows']:,} values {v['bytes'] / 1e6:.0f} MB" for k, v in r["written"].items()), flush=True)
tables = log_tables(results)
# trajectory, message, bhaRun, mudLog
objects, flat = witsml.parse_objects(root)
tc = objects["trajectory_catalog"]
tc["kind"] = np.where(tc["name"].str.contains("Plan Traj"), "plan", "actual")
tables.update(objects)
tables["sentinels"] = pd.concat([witsml.sentinels_table(flat), tables.pop("_sentinels")], ignore_index=True)
tables["units"] = pd.concat([witsml.units_table(flat), tables.pop("_units")], ignore_index=True)
tables["units"]["n_logs"] = tables["units"]["n_logs"].astype("Int64") # empty for the object tables
tables["wellbores"] = wellbores_table(tables, ddr_wellbores)
# formation tops
picks = tops.parse_picks(paths.well_picks_file(), ddr_wellbores)
tables["formation_tops"], tables["formation_tops_shared"] = picks, tops.shared_trunk_picks(picks)
tops_dir = paths.outputs_dir() / ("tops_subset" if args.match else "tops")
tops_dir.mkdir(parents=True, exist_ok=True)
picks.to_parquet(tops_dir / "well_picks.parquet", index=False)
tables["formation_tops_shared"].to_parquet(tops_dir / "shared_trunk_picks.parquet", index=False)
for name, df in tables.items():
df.to_parquet(out / f"{name}.parquet", index=False, compression="zstd")
print(f"[{time.time() - t_start:6.0f} s] tables written", flush=True)
con = build_db(out, tables, ddr_db, args.workers)
checks: dict = {}
wrong: list[str] = []
if not args.match:
identity, wrong = check_identity(con)
depth, checks["depth_vs_ddr"] = check_depth(con)
coverage, checks["time_coverage_vs_ddr"] = check_coverage(con)
surveys, checks["trajectory_vs_ddr_surveys"] = check_surveys(con)
checks["formation_tops_vs_ddr"] = check_tops(con)
for name, df in (("check_wellbore_identity", identity), ("check_depth", depth),
("check_coverage", coverage), ("check_surveys", surveys)):
df.to_parquet(out / f"{name}.parquet", index=False, compression="zstd")
con.execute(f"CREATE TABLE {name} AS SELECT * FROM read_parquet('{out / name}.parquet')")
tables[name] = df
checks["wellbore_identity"] = json.loads(identity.to_json(orient="records"))
checks["wellbore_identity_wrong"] = wrong
con.execute("DETACH ddr")
con.close()
os.replace(out / "volve_witsml.duckdb.tmp", out / "volve_witsml.duckdb")
cat, cur, ov, wb = tables["log_catalog"], tables["log_curves"], tables["log_overlaps"], tables["wellbores"]
data = cat[cat["log_class"] == "data"]
by_kind = {k: g for k, g in cat.groupby("kind")}
gen = data[data["name"] == "GenTime"]
slb = data[(data["kind"] == "time") & (data["serviceCompany"] == "Schlumberger")]
time_data = data[data["kind"] == "time"]
got = {
"log_files": int(cat["n_files"].sum()),
"logs": {k: int(len(g)) for k, g in by_kind.items()},
"log_rows": {k: int(g["n_rows"].sum()) for k, g in by_kind.items()},
"log_values": {k: int(g["n_values"].sum()) for k, g in by_kind.items()},
"log_values_dropped_in_log": {k: int(g["n_dup_same"].sum() + g["n_dup_conflict"].sum())
for k, g in by_kind.items()},
"log_values_ranked": {k: int(g["n_ranked"].sum()) for k, g in by_kind.items()},
"log_bad_rows": int(cat["n_bad_rows"].sum()),
"wellbores_with_logs": int(cat["wellbore"].nunique()),
"trajectories": len(tables["trajectory_catalog"]), "trajectory_stations": len(tables["trajectory"]),
"messages": len(tables["messages"]), "bha_runs": len(tables["bha_runs"]),
"mudlogs": len(tables["mudlog_catalog"]), "mudlog_intervals": len(tables["mudlog_intervals"]),
"mudlog_lithology": len(tables["mudlog_lithology"]), "mudlog_qualifiers": len(tables["mudlog_qualifiers"]),
"sentinels_replaced": int(tables["sentinels"]["n"].sum()),
"formation_tops": len(picks), "formation_tops_wellbores": int(picks["wellbore_picks"].nunique()),
"formation_tops_ddr_wellbores": int(picks["wellbore"].nunique()),
"formation_tops_shared": len(tables["formation_tops_shared"]),
}
summary = {
"counts": got,
"tables": {name: {"rows": len(df), "columns": df.shape[1], "bytes": (out / f"{name}.parquet").stat().st_size}
for name, df in tables.items()},
"log_data_files": {r["wellbore"]: r["written"] for r in sorted(results, key=lambda r: r["wellbore"])},
"disk_bytes": {"time_log": du(out / "time_log"), "depth_log": du(out / "depth_log"),
"witsml_total": du(out), "tops": du(tops_dir)},
"wellbores": {
"witsml_well_folders": sum(p.is_dir() for p in root.iterdir()),
"witsml_well_folders_with_objects": int(wb["folder"].nunique()),
"witsml_wellbore_folders": int(len(wb)),
"witsml_wellbore_names_as_published": int(wb["wellbore_witsml"].nunique()),
"wellbores": int(wb["wellbore"].nunique()),
"ddr_wellbores_with_any_object": sorted(set(wb.loc[wb["in_ddr"], "wellbore"])),
"ddr_wellbores_with_time_logs": sorted(set(time_data["wellbore"]) & ddr_wellbores),
"ddr_wellbores_without_any_object": sorted(ddr_wellbores - set(wb["wellbore"])),
"not_in_ddr": sorted(set(wb.loc[~wb["in_ddr"], "wellbore"])),
"renamed": json.loads(wb.loc[wb["wellbore_source"] == "uidWellbore", [
"uidWellbore", "nameWellbore", "wellbore_witsml", "wellbore"]].to_json(orient="records")),
"named_from_nameWell": json.loads(wb.loc[wb["wellbore_source"] == "nameWell", [
"folder", "nameWellbore", "wellbore"]].to_json(orient="records")),
},
"channels": {
"distinct_mnemonics": {k: int(g["mnemonic"].nunique())
for k, g in cur[cur["n_values"] > 0].groupby("kind")},
"time_logs_by_service_company": {str(k): int(v) for k, v in
time_data.groupby("serviceCompany", dropna=False).size().items()},
"GenTime": {"logs": int(len(gen)), "wellbores": int(gen["wellbore"].nunique()),
"curves_with_data": sorted({int(v) for v in gen["n_curves_with_data"]}),
"curves_declared_incl_index": sorted({int(v) for v in gen["n_curves_declared"]}),
"step_median_s": sorted({float(v) for v in gen["step_median"].dropna()}),
"values": int(gen["n_values"].sum())},
"Schlumberger_time_logs": {"logs": int(len(slb)), "wellbores": int(slb["wellbore"].nunique()),
"curves_with_data": _quantiles(slb["n_curves_with_data"], 0),
"step_median_s": _quantiles(slb["step_median"].dropna()),
"values": int(slb["n_values"].sum())},
"time_log_step_median_s_weighted_by_rows": {
str(k): int(v) for k, v in time_data.assign(step=time_data["step_median"].round())
.groupby("step")["n_rows"].sum().sort_values(ascending=False).head(8).items()},
},
"values": {
"empty_cells_are_not_counted": True,
"null_value_replaced": int(cur["n_null_value"].sum()),
"sentinels_by_table": {k: int(v) for k, v in tables["sentinels"].groupby("table")["n"].sum().items()},
"text_values": {k: int(g["n_text"].sum()) for k, g in cur.groupby("kind")},
"not_a_number_in_numeric_curves": {k: int(g["n_not_number"].sum()) for k, g in cur.groupby("kind")},
"suspect_values_kept": {str(k): int(v) for k, v in
tables["log_suspects"].groupby("value")["n"].sum().items()},
"mudlog_intervals_tadi_implausible": int(tables["mudlog_intervals"]["tadi_implausible"].sum()),
"unit_conversions": int(tables["units"].loc[tables["units"]["factor"] != 1.0, "n"].sum()),
},
"trajectories": {
"by_kind": {k: {"trajectories": int(len(g)), "stations": int(g["n_stations"].sum())}
for k, g in tables["trajectory_catalog"].groupby("kind")},
"by_azi_ref": {str(k): int(v) for k, v in
tables["trajectory_catalog"].groupby("aziRef", dropna=False).size().items()},
"distinct_actual_stations": int(len(
tables["trajectory"].merge(tables["trajectory_catalog"].loc[
tables["trajectory_catalog"]["kind"] == "actual", ["path"]], on="path")
.round({"md": 2, "incl": 2, "azi": 2}).drop_duplicates(["wellbore", "md", "incl", "azi"]))),
},
"duplicates": {
"in_log_same_value": {k: int(g["n_dup_same"].sum()) for k, g in by_kind.items()},
"in_log_conflict": {k: int(g["n_dup_conflict"].sum()) for k, g in by_kind.items()},
"in_log_logs_affected": int(((cat["n_dup_same"] + cat["n_dup_conflict"]) > 0).sum()),
"in_log_values_out_of_order": {k: int(g["n_out_of_order"].sum()) for k, g in by_kind.items()},
"between_logs": {k: {"ranked_rows": int(g["n"].sum()), "same": int(g["n_same"].sum()),
"rounding": int(g["n_rounding"].sum()), "conflict": int(g["n_conflict"].sum()),
"log_pairs": int(len(g.drop_duplicates(["log_id", "other_log_id"]))),
"wellbore_mnemonics": int(len(g.drop_duplicates(["wellbore", "mnemonic"])))}
for k, g in ov.groupby("kind")},
"between_logs_top_mnemonics": json.loads(
ov.groupby(["kind", "mnemonic"])[["n", "n_same", "n_rounding", "n_conflict"]].sum()
.sort_values("n", ascending=False).head(12).reset_index().to_json(orient="records")),
},
"checks": checks,
"seconds": round(time.time() - t_start, 1),
}
(out / "summary.json").write_text(json.dumps(summary, indent=1, ensure_ascii=False) + "\n", encoding="utf-8")
short = {k: v for k, v in summary.items() if k not in ("tables", "log_data_files", "checks")}
short["checks"] = {k: v for k, v in checks.items() if k != "wellbore_identity"}
for part in ("time_coverage_vs_ddr", "formation_tops_vs_ddr"):
if part in short["checks"]:
short["checks"][part] = {k: v for k, v in short["checks"][part].items() if k != "per_wellbore"}
print(json.dumps(short, indent=1, ensure_ascii=False))
if args.match:
return 0
if wrong:
print("wellbore identity:", *wrong, sep="\n ")
return 1
diff = {k: (EXPECTED.get(k), got[k]) for k in got if EXPECTED.get(k) != got[k]}
if diff:
print("counts differ from EXPECTED (expected, got):", diff)
return 1
return 0
if __name__ == "__main__":
sys.exit(main())