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:
98
volve_dia/audit.py
Normal file
98
volve_dia/audit.py
Normal file
@@ -0,0 +1,98 @@
|
||||
"""Blind audit of the activity labels: stratified sample, masked rating sheet, agreement.
|
||||
|
||||
The rater sees what a model sees (the masked input view `t2_inputs`, plus the comments of the activities before and
|
||||
after in the same report) and never the codes or the labels. The key (item -> act_id, stratum, weight, labels) is
|
||||
written to a separate file. Agreement is Cohen's kappa, unweighted and weighted back to the population by the
|
||||
inverse inclusion probability of each stratum.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import math
|
||||
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
|
||||
#: Values the rater may choose (labels.yaml t2.cause_groups without hse, t1.op_classes without interruption).
|
||||
CAUSES = ("equipment", "weather", "waiting", "stuck_fishing", "lost_circulation", "well_control", "sidetrack",
|
||||
"operation_failed", "unspecified")
|
||||
OP_CLASSES = ("drill_ream", "trip", "casing_cement", "circulate", "bop_wellhead", "formation_evaluation", "completion",
|
||||
"perforate", "wireline", "plug_abandon", "rig_move", "rig_up_down", "wait", "other")
|
||||
|
||||
|
||||
def allocate(sizes: dict[str, int], k: int, minimum: int) -> dict[str, int]:
|
||||
"""Split k items over strata: `minimum` each (or the whole stratum if smaller), the rest proportional to the
|
||||
square root of the stratum size, by largest remainder, never more than a stratum holds."""
|
||||
sizes = {s: int(n) for s, n in sizes.items() if n > 0}
|
||||
out = {s: min(minimum, n) for s, n in sizes.items()}
|
||||
if sum(out.values()) > k:
|
||||
raise ValueError(f"{len(sizes)} strata x minimum {minimum} > {k} items")
|
||||
while sum(out.values()) < k:
|
||||
room = {s: n - out[s] for s, n in sizes.items() if n > out[s]}
|
||||
if not room:
|
||||
break
|
||||
left = k - sum(out.values())
|
||||
w = {s: math.sqrt(sizes[s]) for s in room}
|
||||
share = {s: left * w[s] / sum(w.values()) for s in room}
|
||||
add = {s: min(room[s], int(share[s])) for s in room}
|
||||
if sum(add.values()) == 0: # hand out single items by largest remainder
|
||||
for s in sorted(room, key=lambda s: (-(share[s] - int(share[s])), s))[:left]:
|
||||
add[s] = 1
|
||||
for s, a in add.items():
|
||||
out[s] += a
|
||||
return out
|
||||
|
||||
|
||||
def spread_sample(frame: pd.DataFrame, k: int, by: str, rng: np.random.Generator) -> pd.DataFrame:
|
||||
"""k rows of `frame`, spread over the values of `by` (round robin over a random order of the groups)."""
|
||||
if k >= len(frame):
|
||||
return frame
|
||||
f = frame.sample(frac=1.0, random_state=rng.integers(2**31))
|
||||
order = {g: i for i, g in enumerate(rng.permutation(f[by].unique()))}
|
||||
f = f.assign(_rank=f.groupby(by).cumcount(), _g=f[by].map(order))
|
||||
return f.sort_values(["_rank", "_g"]).head(k).drop(columns=["_rank", "_g"])
|
||||
|
||||
|
||||
def zone(npt_a: pd.Series, npt_b: pd.Series) -> pd.Series:
|
||||
"""a = NPT under both definitions, b_only = only under the union, none = neither."""
|
||||
return pd.Series(np.where(npt_a, "a", np.where(npt_b, "b_only", "none")), index=npt_a.index)
|
||||
|
||||
|
||||
def draw(frame: pd.DataFrame, plan: dict[str, int], minimum: int, seed: int) -> pd.DataFrame:
|
||||
"""Stratified sample. `frame` has act_id, well, zone, stratum (zone/class). `plan` gives the items per zone.
|
||||
Returns the sampled rows with n_stratum, k_stratum and weight = n_stratum / k_stratum."""
|
||||
rng = np.random.default_rng(seed)
|
||||
parts = []
|
||||
for z, k in plan.items():
|
||||
fz = frame[frame["zone"] == z]
|
||||
alloc = allocate(fz["stratum"].value_counts().to_dict(), k, minimum)
|
||||
for s, ks in sorted(alloc.items()):
|
||||
fs = fz[fz["stratum"] == s]
|
||||
parts.append(spread_sample(fs, ks, "well", rng).assign(n_stratum=len(fs), k_stratum=ks))
|
||||
out = pd.concat(parts, ignore_index=True)
|
||||
out["weight"] = out["n_stratum"] / out["k_stratum"]
|
||||
return out.sample(frac=1.0, random_state=seed).reset_index(drop=True)
|
||||
|
||||
|
||||
def cohen_kappa(a: pd.Series, b: pd.Series, weight: pd.Series | None = None) -> float | None:
|
||||
"""Cohen's kappa of two label series (optionally with item weights). None if undefined."""
|
||||
m = a.notna() & b.notna()
|
||||
a, b = a[m].astype(str), b[m].astype(str)
|
||||
w = pd.Series(1.0, index=a.index) if weight is None else weight[m].astype(float)
|
||||
if w.sum() == 0:
|
||||
return None
|
||||
po = float(w[a == b].sum() / w.sum())
|
||||
pa = w.groupby(a).sum() / w.sum()
|
||||
pb = w.groupby(b).sum() / w.sum()
|
||||
pe = float(sum(pa.get(c, 0.0) * pb.get(c, 0.0) for c in set(pa.index) | set(pb.index)))
|
||||
return None if pe >= 1.0 else (po - pe) / (1.0 - pe)
|
||||
|
||||
|
||||
def agreement(a: pd.Series, b: pd.Series, weight: pd.Series | None = None) -> dict:
|
||||
m = a.notna() & b.notna()
|
||||
w = pd.Series(1.0, index=a.index) if weight is None else weight.astype(float)
|
||||
k = cohen_kappa(a, b, weight)
|
||||
return {"n": int(m.sum()),
|
||||
"agreement": (round(float(w[m & (a.astype(str) == b.astype(str))].sum() / w[m].sum()), 4)
|
||||
if m.any() else None),
|
||||
"kappa": None if k is None else round(k, 4)}
|
||||
768
volve_dia/labels.py
Normal file
768
volve_dia/labels.py
Normal file
@@ -0,0 +1,768 @@
|
||||
"""Deterministic labels T1-T3 of Volve-DIA, from the DDR XML tables (volve_dia.ddr.xml) and configs/labels.yaml.
|
||||
|
||||
Every function is pure: DataFrames in, a label table out, no file access except `load_config`. Every label row
|
||||
carries its provenance: the source row (`report_id` or `act_id`), the rule (`*_rule`, ids below) and the source
|
||||
columns. Nothing here reads HTML, PDF or OCR text, and no label is taken from free text.
|
||||
|
||||
Sources (tables of outputs/ddr/): `reports` (diaHole, diaPilot, mdDiaHoleStart, mdCsgLast, md, dTimSpud, waterDepth,
|
||||
elevKelly, sum24Hr, forecast24Hr), `activities` (proprietaryCode, code_main, code_sub, state, stateDetailActivity,
|
||||
md, comments, start_utc, end_utc, duration_h), `bits` (diaBit) and `casings` (od, mdBottom); the last two are used
|
||||
only by candidate fill rules.
|
||||
|
||||
Rules
|
||||
T1.S1 section = reports.diaHole of the report itself.
|
||||
T1.S2 no diaHole: forward fill, the last known diaHole of an earlier report of the same wellbore.
|
||||
T1.S3 no earlier known diaHole: the first known diaHole of the wellbore (`bfill_leading`).
|
||||
T1.P1 phase = nominal phase of the hole size (labels.yaml t1.hole_sizes); T1.P2: `pilot` when diaPilot is set.
|
||||
T1.O1 operation class = op_class of the proprietaryCode (labels.yaml codes).
|
||||
T2.Na NPT (a) = interruption group. T2.Nb NPT (b) = (a) or state == fail or stateDetailActivity != success.
|
||||
T2.C1 cause named by the interruption sub-code. T2.C2 cause from stateDetailActivity. T2.C3 unspecified.
|
||||
T3.D1 depth class of activities.md against the mud line. T3.G1 cell = floor(md / grid).
|
||||
T3.E1 episode = run of consecutive NPT activities in time. T3.M1 interval = run of touching positive cells.
|
||||
|
||||
Activity codes are label sources, so they are masked in model inputs: `t2_inputs` builds the masked view and raises
|
||||
if a column of `MASKED` is in it. The free text is the legitimate input; `text_rates` only measures how often it
|
||||
names the label.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from pathlib import Path
|
||||
from typing import Callable
|
||||
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
import yaml
|
||||
|
||||
from .names import stem, well_of
|
||||
from .paths import REPO_ROOT
|
||||
|
||||
#: Columns a model must never read for T2 and T3 (they are the label sources).
|
||||
MASKED = ("proprietaryCode", "code_main", "code_sub", "state", "stateDetailActivity")
|
||||
NPT_DEFINITIONS = ("a", "b")
|
||||
MASK_SCHEMES = ("single", "tail_half", "head_half", "whole_run")
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------------------------------------------
|
||||
# Configuration
|
||||
# ---------------------------------------------------------------------------------------------------------------
|
||||
|
||||
def load_config(path: Path | None = None) -> dict:
|
||||
"""configs/labels.yaml, checked for internal consistency (classes used are classes declared)."""
|
||||
cfg = yaml.safe_load((path or REPO_ROOT / "configs" / "labels.yaml").read_text(encoding="utf-8"))
|
||||
if cfg.get("version") != 1:
|
||||
raise ValueError(f"labels.yaml version {cfg.get('version')!r}, expected 1")
|
||||
ops, causes = set(cfg["t1"]["op_classes"]), set(cfg["t2"]["cause_groups"])
|
||||
for code, row in cfg["codes"].items():
|
||||
if " -- " not in code:
|
||||
raise ValueError(f"not a proprietaryCode: {code!r}")
|
||||
if row["op_class"] not in ops:
|
||||
raise ValueError(f"{code}: op_class {row['op_class']!r} is not declared in t1.op_classes")
|
||||
if row["cause"] != "detail" and row["cause"] not in causes:
|
||||
raise ValueError(f"{code}: cause {row['cause']!r} is not declared in t2.cause_groups")
|
||||
if row["cause"] != "detail" and not code.startswith("interruption -- "):
|
||||
raise ValueError(f"{code}: only interruption codes may name a cause")
|
||||
for detail, row in cfg["t2"]["cause_from_detail"].items():
|
||||
if row["cause"] is not None and row["cause"] not in causes:
|
||||
raise ValueError(f"stateDetailActivity {detail!r}: cause {row['cause']!r} is not declared")
|
||||
if cfg["t2"]["default_cause"] not in causes:
|
||||
raise ValueError("t2.default_cause is not declared in t2.cause_groups")
|
||||
if set(cfg["t2"]["masked_columns"]) != set(MASKED):
|
||||
raise ValueError("t2.masked_columns differs from labels.MASKED")
|
||||
if cfg["t1"]["fill"]["rule"] not in FILL_RULES or cfg["t1"]["fill"]["leading"] not in FILL_RULES:
|
||||
raise ValueError("t1.fill names an unknown rule")
|
||||
return cfg
|
||||
|
||||
|
||||
def check_code_counts(activities: pd.DataFrame, cfg: dict) -> dict:
|
||||
"""Differences between the counts written in labels.yaml and the data: {} when the file matches the source."""
|
||||
diff: dict = {}
|
||||
got = activities["proprietaryCode"].value_counts().to_dict()
|
||||
want = {code: row["n"] for code, row in cfg["codes"].items()}
|
||||
for code in sorted(set(got) | set(want)):
|
||||
if got.get(code) != want.get(code):
|
||||
diff[code] = (want.get(code), got.get(code))
|
||||
for column, table in (("stateDetailActivity", cfg["t2"]["cause_from_detail"]), ("state", cfg["t2"]["state"])):
|
||||
got = activities[column].value_counts().to_dict()
|
||||
for value in sorted(set(got) | set(table)):
|
||||
if got.get(value) != table.get(value, {}).get("n"):
|
||||
diff[f"{column}={value}"] = (table.get(value, {}).get("n"), got.get(value))
|
||||
return diff
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------------------------------------------
|
||||
# Report timeline
|
||||
# ---------------------------------------------------------------------------------------------------------------
|
||||
|
||||
def timeline(reports: pd.DataFrame, activities: pd.DataFrame, cfg: dict) -> pd.DataFrame:
|
||||
"""One row per report, ordered by wellbore and time, with `well`, the activity counts and `status`:
|
||||
`ok`, `no_activities` (a real day without activity rows) or `placeholder_date` (see labels.yaml reports)."""
|
||||
r = reports.copy()
|
||||
r["well"] = r["wellbore"].map(well_of)
|
||||
a = activities.assign(_drill=activities["code_main"].eq("drilling"))
|
||||
per = a.groupby("report_id").agg(n_activities=("act_id", "size"), n_drilling_activities=("_drill", "sum"),
|
||||
hours_activities=("duration_h", "sum"))
|
||||
r = r.merge(per, on="report_id", how="left")
|
||||
r[["n_activities", "n_drilling_activities"]] = r[["n_activities", "n_drilling_activities"]].fillna(0).astype(int)
|
||||
r["hours_activities"] = r["hours_activities"].fillna(0.0)
|
||||
spud = pd.to_datetime(r["dTimSpud"], utc=True, format="ISO8601")
|
||||
days = pd.Timedelta(days=cfg["reports"]["placeholder_days_before_spud"])
|
||||
placeholder = r["n_activities"].eq(0) & spud.notna() & (r["end_utc"] < spud - days)
|
||||
r["status"] = np.select([placeholder, r["n_activities"].eq(0)], ["placeholder_date", "no_activities"], "ok")
|
||||
return r.sort_values(["wellbore", "start_utc", "report_id"], kind="stable").reset_index(drop=True)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------------------------------------------
|
||||
# T1: hole size in the text (cross-check only) and candidate fill rules
|
||||
# ---------------------------------------------------------------------------------------------------------------
|
||||
|
||||
_FRACTIONS = {"½": 0.5, "¼": 0.25, "¾": 0.75}
|
||||
_HOLE_SIZE = re.compile(
|
||||
r"(?<![\d/.,])(\d{1,2})(?:\s*[- ]\s*(\d)\s*/\s*(\d)|[.,](\d{1,3})|\s*([½¼¾]))?"
|
||||
r"\s*(?:\"|''|”|in\b\.?|inch(?:es)?\b)\s*(?:pilot\s*)?(?:hole|section|open\s*hole|pilothole|oh\b)", re.I)
|
||||
|
||||
|
||||
def hole_sizes_in_text(text: str | None, sizes: tuple[float, ...]) -> list[float]:
|
||||
"""Hole sizes named in `text` as '<size>" hole|section|pilot hole|open hole' (12 1/4", 12.25", 12¼", 8-1/2in),
|
||||
kept only when they are one of `sizes`. One entry per mention."""
|
||||
out = []
|
||||
for whole, num, den, dec, glyph in _HOLE_SIZE.findall(text or ""):
|
||||
v = float(whole)
|
||||
if num and den and den != "0":
|
||||
v += int(num) / int(den)
|
||||
elif dec:
|
||||
v += float("0." + dec)
|
||||
elif glyph:
|
||||
v += _FRACTIONS[glyph]
|
||||
if any(abs(v - s) < 1e-6 for s in sizes):
|
||||
out.append(v)
|
||||
return out
|
||||
|
||||
|
||||
def _most_frequent(values: list[float]) -> float:
|
||||
"""The most frequent value; NaN when there is none or the top count is tied."""
|
||||
if not values:
|
||||
return np.nan
|
||||
counts = pd.Series(values).value_counts()
|
||||
if len(counts) > 1 and counts.iloc[0] == counts.iloc[1]:
|
||||
return np.nan
|
||||
return float(counts.index[0])
|
||||
|
||||
|
||||
def fill_features(tl: pd.DataFrame, activities: pd.DataFrame, bits: pd.DataFrame, casings: pd.DataFrame,
|
||||
cfg: dict) -> pd.DataFrame:
|
||||
"""`tl` (from `timeline`) plus the columns the candidate fill rules read:
|
||||
`dia` (reports.diaHole; unknown on placeholder reports), `bit_dia` (largest valid bits.diaBit of the report),
|
||||
`casing_hole` (next hole size after the last casing, from casings.od at the shoe nearest to mdCsgLast) and
|
||||
`text_dia` (hole size named most often in sum24Hr and the drilling-group comments; cross-check only)."""
|
||||
f = tl.copy()
|
||||
f["dia"] = f["diaHole"].where(f["status"].ne("placeholder_date"))
|
||||
sizes = tuple(float(s) for s in cfg["t1"]["hole_sizes"])
|
||||
|
||||
valid = bits[bits["diaBit"] > 0] if len(bits) else bits
|
||||
f["bit_dia"] = f["report_id"].map(valid.groupby("report_id")["diaBit"].max() if len(valid) else {}).astype(float)
|
||||
|
||||
fill = cfg["t1"]["fill"]
|
||||
next_hole = {round(float(k), 3): float(v) for k, v in fill["casing_od_to_next_hole"].items()}
|
||||
shoes: dict[str, np.ndarray] = {}
|
||||
if len(casings):
|
||||
c = casings.dropna(subset=["od", "mdBottom"]).assign(well=lambda d: d["wellbore"].map(well_of))
|
||||
shoes = {w: g[["mdBottom", "od"]].to_numpy(float) for w, g in c.groupby("well")}
|
||||
casing_hole = np.full(len(f), np.nan)
|
||||
for i, (w, shoe) in enumerate(zip(f["well"], f["mdCsgLast"])):
|
||||
if w in shoes and pd.notna(shoe):
|
||||
dist = np.abs(shoes[w][:, 0] - shoe)
|
||||
j = int(dist.argmin())
|
||||
if dist[j] <= fill["casing_shoe_tolerance_m"]:
|
||||
casing_hole[i] = next_hole.get(round(float(shoes[w][j, 1]), 3), np.nan)
|
||||
f["casing_hole"] = casing_hole
|
||||
|
||||
drill = activities[activities["code_main"].eq("drilling")]
|
||||
comments = drill.groupby("report_id")["comments"].agg(lambda s: "\n".join(s.dropna()))
|
||||
text = f["sum24Hr"].fillna("") + "\n" + f["report_id"].map(comments).fillna("")
|
||||
f["text_dia"] = [_most_frequent(hole_sizes_in_text(t, sizes)) for t in text]
|
||||
return f
|
||||
|
||||
|
||||
def _ffill(g: pd.DataFrame) -> np.ndarray:
|
||||
return g["dia"].ffill().to_numpy(float)
|
||||
|
||||
|
||||
def _bfill(g: pd.DataFrame) -> np.ndarray:
|
||||
return g["dia"].bfill().to_numpy(float)
|
||||
|
||||
|
||||
def _ffill_bfill(g: pd.DataFrame) -> np.ndarray:
|
||||
return g["dia"].ffill().bfill().to_numpy(float)
|
||||
|
||||
|
||||
def _nearest(g: pd.DataFrame) -> np.ndarray:
|
||||
"""Known diaHole of the report nearest in time; the earlier one on a tie."""
|
||||
t = g["start_utc"].astype("int64").astype(float)
|
||||
known = g["dia"].notna()
|
||||
before, after = t.where(known).ffill(), t.where(known).bfill()
|
||||
prev, nxt = g["dia"].ffill(), g["dia"].bfill()
|
||||
use_prev = nxt.isna() | (prev.notna() & ((t - before) <= (after - t)))
|
||||
return np.where(use_prev, prev, nxt).astype(float)
|
||||
|
||||
|
||||
def _by_key(column: str) -> Callable[[pd.DataFrame], np.ndarray]:
|
||||
"""diaHole that the known reports of the wellbore with the same value of `column` carry most often (ties: the
|
||||
smaller size)."""
|
||||
def rule(g: pd.DataFrame) -> np.ndarray:
|
||||
k = g.loc[g["dia"].notna() & g[column].notna(), [column, "dia"]]
|
||||
if k.empty:
|
||||
return np.full(len(g), np.nan)
|
||||
table = k.groupby(column)["dia"].agg(lambda s: s.value_counts().sort_index().idxmax())
|
||||
return g[column].map(table).to_numpy(float)
|
||||
return rule
|
||||
|
||||
|
||||
def _depth_range(g: pd.DataFrame) -> np.ndarray:
|
||||
"""Section whose depth range [min md, max md] over the known reports of the wellbore contains the report md
|
||||
(1 m tolerance); the smaller size when several do."""
|
||||
k = g.loc[g["dia"].notna() & g["md"].notna()]
|
||||
out = np.full(len(g), np.nan)
|
||||
if k.empty:
|
||||
return out
|
||||
spans = k.groupby("dia")["md"].agg(["min", "max"]).sort_index()
|
||||
for i, md in enumerate(g["md"].to_numpy(float)):
|
||||
if not np.isnan(md):
|
||||
hit = spans.index[(spans["min"] - 1 <= md) & (md <= spans["max"] + 1)]
|
||||
if len(hit):
|
||||
out[i] = hit[0]
|
||||
return out
|
||||
|
||||
|
||||
#: Candidate fill rules: frame of one wellbore in time order (columns of `fill_features`, `dia` NaN where unknown
|
||||
#: or masked) -> predicted hole size per report (NaN = no answer).
|
||||
FILL_RULES: dict[str, Callable[[pd.DataFrame], np.ndarray]] = {
|
||||
"ffill": _ffill,
|
||||
"bfill": _bfill,
|
||||
"ffill_bfill": _ffill_bfill,
|
||||
"nearest": _nearest,
|
||||
"hole_start": _by_key("mdDiaHoleStart"),
|
||||
"csg_last": _by_key("mdCsgLast"),
|
||||
"depth_range": _depth_range,
|
||||
"bit_report": lambda g: g["bit_dia"].to_numpy(float),
|
||||
"bit_ffill": lambda g: g["bit_dia"].ffill().to_numpy(float),
|
||||
"casing_program": lambda g: g["casing_hole"].to_numpy(float),
|
||||
"text": lambda g: g["text_dia"].to_numpy(float),
|
||||
}
|
||||
#: Rules that do not read `dia`: masking cannot change their answer.
|
||||
_DIA_FREE = ("bit_report", "bit_ffill", "casing_program", "text")
|
||||
|
||||
|
||||
def known_runs(dia: np.ndarray) -> list[np.ndarray]:
|
||||
"""Maximal runs of consecutive reports with the same known hole size, as position arrays."""
|
||||
runs, start = [], None
|
||||
for i in range(len(dia) + 1):
|
||||
same = i < len(dia) and start is not None and not np.isnan(dia[i]) and dia[i] == dia[start]
|
||||
if start is not None and not same:
|
||||
runs.append(np.arange(start, i))
|
||||
start = None
|
||||
if start is None and i < len(dia) and not np.isnan(dia[i]):
|
||||
start = i
|
||||
return runs
|
||||
|
||||
|
||||
def fill_masks(dia: np.ndarray, scheme: str) -> list[np.ndarray]:
|
||||
"""Sets of positions to mask together under `scheme`. `single`: every known report alone; `tail_half` /
|
||||
`head_half`: the last / first n // 2 reports of every run of n >= 2; `whole_run`: every run."""
|
||||
runs = known_runs(dia)
|
||||
if scheme == "single":
|
||||
return [np.array([i]) for run in runs for i in run]
|
||||
if scheme == "whole_run":
|
||||
return runs
|
||||
if scheme == "tail_half":
|
||||
return [run[len(run) - len(run) // 2:] for run in runs if len(run) >= 2]
|
||||
if scheme == "head_half":
|
||||
return [run[:len(run) // 2] for run in runs if len(run) >= 2]
|
||||
raise ValueError(f"unknown masking scheme {scheme!r}")
|
||||
|
||||
|
||||
def evaluate_fill_rules(feat: pd.DataFrame, rules: tuple[str, ...] | None = None,
|
||||
schemes: tuple[str, ...] = MASK_SCHEMES) -> pd.DataFrame:
|
||||
"""Mask known hole sizes and count how often each rule recovers them.
|
||||
|
||||
One row per (rule, scheme, wellbore): `n_masked`, `n_answered` (the rule gave a value) and `n_correct`.
|
||||
Each mask set is evaluated alone, with every other known value visible."""
|
||||
rules = rules or tuple(FILL_RULES)
|
||||
rows = []
|
||||
live = feat[feat["status"].ne("placeholder_date")]
|
||||
for wellbore, g in live.groupby("wellbore", sort=True):
|
||||
g = g.reset_index(drop=True)
|
||||
truth = g["dia"].to_numpy(float)
|
||||
fixed = {name: FILL_RULES[name](g) for name in rules if name in _DIA_FREE}
|
||||
for scheme in schemes:
|
||||
tally = {name: np.zeros(3, dtype=int) for name in rules}
|
||||
for mask in fill_masks(truth, scheme):
|
||||
masked = g.assign(dia=g["dia"].mask(g.index.isin(mask)))
|
||||
for name in rules:
|
||||
pred = (fixed[name] if name in fixed else FILL_RULES[name](masked))[mask]
|
||||
tally[name] += (len(mask), int(np.sum(~np.isnan(pred))), int(np.sum(pred == truth[mask])))
|
||||
rows += [{"rule": name, "scheme": scheme, "wellbore": wellbore, "n_masked": int(t[0]),
|
||||
"n_answered": int(t[1]), "n_correct": int(t[2])} for name, t in tally.items()]
|
||||
return pd.DataFrame(rows)
|
||||
|
||||
|
||||
def summarise_fill_eval(ev: pd.DataFrame, by_wellbore: bool = False) -> pd.DataFrame:
|
||||
"""`recovered` = correct / masked, `coverage` = answered / masked, `precision` = correct / answered."""
|
||||
keys = ["rule", "scheme"] + (["wellbore"] if by_wellbore else [])
|
||||
s = ev.groupby(keys, sort=False)[["n_masked", "n_answered", "n_correct"]].sum().reset_index()
|
||||
s["recovered"] = (s["n_correct"] / s["n_masked"]).round(4)
|
||||
s["coverage"] = (s["n_answered"] / s["n_masked"]).round(4)
|
||||
s["precision"] = (s["n_correct"] / s["n_answered"].where(s["n_answered"] > 0)).round(4)
|
||||
return s
|
||||
|
||||
|
||||
def fill_on_missing(feat: pd.DataFrame, rules: tuple[str, ...] | None = None) -> pd.DataFrame:
|
||||
"""The rules on the reports that really lack diaHole (nothing masked): how many they answer, and how often the
|
||||
answer agrees with two independent readings of the same report where those exist: the hole size named in the
|
||||
text (`text_dia`) and the bit record of the report (`bit_dia`). Rows: (rule, subset) for `all_missing` and
|
||||
`missing_drilling_day` (at least one drilling-group activity)."""
|
||||
rules = rules or tuple(FILL_RULES)
|
||||
live = feat[feat["status"].ne("placeholder_date")]
|
||||
preds = {name: [] for name in rules}
|
||||
parts = []
|
||||
for _, g in live.groupby("wellbore", sort=True):
|
||||
g = g.reset_index(drop=True)
|
||||
parts.append(g)
|
||||
for name in rules:
|
||||
preds[name].append(FILL_RULES[name](g))
|
||||
allr = pd.concat(parts, ignore_index=True)
|
||||
missing = allr["dia"].isna().to_numpy()
|
||||
subsets = {"all_missing": missing, "missing_drilling_day": missing & (allr["n_drilling_activities"] > 0).to_numpy()}
|
||||
text, bit = allr["text_dia"].to_numpy(float), allr["bit_dia"].to_numpy(float)
|
||||
rows = []
|
||||
for name in rules:
|
||||
pred = np.concatenate(preds[name])
|
||||
for subset, sel in subsets.items():
|
||||
answered = sel & ~np.isnan(pred)
|
||||
with_text, with_bit = answered & ~np.isnan(text), answered & ~np.isnan(bit)
|
||||
rows.append({"rule": name, "subset": subset, "n": int(sel.sum()), "n_answered": int(answered.sum()),
|
||||
"n_text": int((sel & ~np.isnan(text)).sum()), "n_both": int(with_text.sum()),
|
||||
"n_agree_text": int((with_text & (pred == text)).sum()),
|
||||
"n_bit": int((sel & ~np.isnan(bit)).sum()), "n_both_bit": int(with_bit.sum()),
|
||||
"n_agree_bit": int((with_bit & (pred == bit)).sum())})
|
||||
return pd.DataFrame(rows)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------------------------------------------
|
||||
# T1 labels
|
||||
# ---------------------------------------------------------------------------------------------------------------
|
||||
|
||||
def operation_classes(activities: pd.DataFrame, cfg: dict) -> pd.DataFrame:
|
||||
"""T1 operation label of every activity: `op_group` (main code), `op_sub` (sub-code), `op_class` (labels.yaml)."""
|
||||
codes = cfg["codes"]
|
||||
unknown = sorted(set(activities["proprietaryCode"].dropna()) - set(codes))
|
||||
if unknown or activities["proprietaryCode"].isna().any():
|
||||
raise ValueError(f"proprietaryCode missing or not in labels.yaml: {unknown}")
|
||||
out = activities[["act_id", "report_id", "wellbore"]].copy()
|
||||
out["well"] = out["wellbore"].map(well_of)
|
||||
out["op_group"] = activities["code_main"].to_numpy()
|
||||
out["op_sub"] = activities["code_sub"].to_numpy()
|
||||
out["op_class"] = activities["proprietaryCode"].map({c: row["op_class"] for c, row in codes.items()}).to_numpy()
|
||||
out["op_rule"] = "T1.O1"
|
||||
out["op_source"] = "activities.proprietaryCode"
|
||||
return out
|
||||
|
||||
|
||||
def _seconds(times: pd.Series) -> np.ndarray:
|
||||
"""UTC timestamps as seconds since 1970 (float), whatever the resolution of the column."""
|
||||
return (times - pd.Timestamp("1970-01-01", tz="UTC")).dt.total_seconds().to_numpy(float)
|
||||
|
||||
|
||||
def _section_name(cfg: dict) -> tuple[dict, dict]:
|
||||
sizes = cfg["t1"]["hole_sizes"]
|
||||
return ({float(k): str(v["section"]) for k, v in sizes.items()},
|
||||
{float(k): str(v["phase"]) for k, v in sizes.items()})
|
||||
|
||||
|
||||
def _dominant(frame: pd.DataFrame, column: str) -> pd.DataFrame:
|
||||
"""Per report: the value of `column` with the most hours (ties: alphabetical) and its share of the hours."""
|
||||
h = frame.groupby(["report_id", column])["duration_h"].sum().reset_index()
|
||||
h = h.sort_values(["report_id", "duration_h", column], ascending=[True, False, True], kind="stable")
|
||||
top = h.drop_duplicates("report_id").set_index("report_id")
|
||||
total = h.groupby("report_id")["duration_h"].sum()
|
||||
return pd.DataFrame({column: top[column], "share": (top["duration_h"] / total).round(4)})
|
||||
|
||||
|
||||
def t1_reports(feat: pd.DataFrame, ops: pd.DataFrame, activities: pd.DataFrame, cfg: dict) -> pd.DataFrame:
|
||||
"""T1 per report-day: hole section and phase (published, or filled with provenance), scope, day-level operation.
|
||||
|
||||
`scope`: `drilling_day` (at least one drilling-group activity), `other_day`, `no_activities`, `excluded`.
|
||||
|
||||
`feat` is `fill_features` (or `timeline` with a `dia` column). `filled_by` is `diaHole` (published), `ffill` or
|
||||
`bfill_leading`; `fill_source_report_id` is the report the value comes from (the report itself when published),
|
||||
`fill_gap_reports` and `fill_gap_days` the distance to it."""
|
||||
fill = cfg["t1"]["fill"]
|
||||
if fill["rule"] != "ffill" or fill["leading"] != "bfill":
|
||||
raise ValueError("t1_reports implements t1.fill.rule = ffill with leading = bfill")
|
||||
names, phases = _section_name(cfg)
|
||||
parts = []
|
||||
for _, g in feat.groupby("wellbore", sort=False):
|
||||
g = g.reset_index(drop=True)
|
||||
live = g["status"].ne("placeholder_date").to_numpy()
|
||||
dia = g["dia"].to_numpy(float) if "dia" in g else g["diaHole"].where(live).to_numpy(float)
|
||||
pos = np.arange(len(g), dtype=float)
|
||||
known = ~np.isnan(dia)
|
||||
src_main = pd.Series(np.where(known, pos, np.nan)).ffill().to_numpy()
|
||||
src_lead = pd.Series(np.where(known, pos, np.nan)).bfill().to_numpy()
|
||||
src = np.where(np.isnan(src_main), src_lead, src_main)
|
||||
by = np.select([known, ~np.isnan(src_main), ~np.isnan(src_lead)], ["diaHole", "ffill", "bfill_leading"], "none")
|
||||
src[~live], by[~live] = np.nan, "none"
|
||||
has = ~np.isnan(src)
|
||||
idx = src[has].astype(int)
|
||||
section_in = np.full(len(g), np.nan)
|
||||
section_in[has] = dia[idx]
|
||||
pilot = np.zeros(len(g), dtype=bool)
|
||||
pilot[has] = g["diaPilot"].notna().to_numpy()[idx]
|
||||
source_id = np.full(len(g), None, dtype=object)
|
||||
source_id[has] = g["report_id"].to_numpy()[idx]
|
||||
gap_reports = np.full(len(g), np.nan)
|
||||
gap_reports[has] = np.abs(pos[has] - idx)
|
||||
gap_days = np.full(len(g), np.nan)
|
||||
start = _seconds(g["start_utc"])
|
||||
gap_days[has] = np.abs(start[has] - start[idx]) / 86400.0
|
||||
out = g[["report_id", "wellbore", "well", "file_date", "start_utc", "end_utc", "status", "diaHole", "diaPilot",
|
||||
"n_activities", "n_drilling_activities", "hours_activities"]].copy()
|
||||
out["section_in"] = section_in
|
||||
out["is_pilot"] = pilot
|
||||
out["filled_by"] = by
|
||||
out["fill_source_report_id"] = source_id
|
||||
out["fill_gap_reports"] = gap_reports
|
||||
out["fill_gap_days"] = np.round(gap_days, 3)
|
||||
parts.append(out)
|
||||
t = pd.concat(parts, ignore_index=True)
|
||||
t["section"] = t["section_in"].map(names)
|
||||
t["phase"] = t["section_in"].map(phases).mask(t["is_pilot"] & t["section_in"].notna(), cfg["t1"]["pilot_phase"])
|
||||
t["section_rule"] = t["filled_by"].map({"diaHole": "T1.S1", "ffill": "T1.S2", "bfill_leading": "T1.S3"})
|
||||
t["phase_rule"] = np.where(t["section_in"].isna(), None, np.where(t["is_pilot"], "T1.P2", "T1.P1"))
|
||||
t["section_source"] = np.where(t["section_in"].isna(), None, "reports.diaHole,reports.diaPilot")
|
||||
t["scope"] = np.select([t["status"].eq("placeholder_date"), t["status"].eq("no_activities"),
|
||||
t["n_drilling_activities"] > 0], ["excluded", "no_activities", "drilling_day"], "other_day")
|
||||
|
||||
hours = ops[["report_id", "op_group", "op_class"]].assign(duration_h=activities["duration_h"].to_numpy())
|
||||
for column, name in (("op_group", "day_op_group"), ("op_class", "day_op_class")):
|
||||
top = _dominant(hours, column)
|
||||
t[name] = t["report_id"].map(top[column])
|
||||
t[name + "_share"] = t["report_id"].map(top["share"])
|
||||
t["section_witsml"] = pd.Series(np.nan, index=t.index, dtype=float)
|
||||
t["section_agree"] = pd.Series(pd.NA, index=t.index, dtype="boolean")
|
||||
return t
|
||||
|
||||
|
||||
def attach_witsml_section(t1: pd.DataFrame, witsml_sections: pd.DataFrame | None) -> pd.DataFrame:
|
||||
"""Hook for a hole section derived from WITSML (labels.yaml t1.witsml_section).
|
||||
|
||||
`witsml_sections` has one row per (wellbore, time interval): `wellbore`, `start_utc`, `end_utc`, `section_in`.
|
||||
A report-day takes the section with the longest overlap with its period; `section_agree` compares it with the
|
||||
DDR section. With None the table is returned unchanged (both columns stay NULL)."""
|
||||
if witsml_sections is None or witsml_sections.empty:
|
||||
return t1
|
||||
t = t1.copy()
|
||||
best = np.full(len(t), np.nan)
|
||||
day_start, day_end = _seconds(t["start_utc"]), _seconds(t["end_utc"])
|
||||
for wellbore, w in witsml_sections.groupby("wellbore"):
|
||||
w_start, w_end, w_size = _seconds(w["start_utc"]), _seconds(w["end_utc"]), w["section_in"].to_numpy(float)
|
||||
for i in np.flatnonzero((t["wellbore"] == wellbore).to_numpy()):
|
||||
overlap = np.minimum(w_end, day_end[i]) - np.maximum(w_start, day_start[i])
|
||||
if len(overlap) and overlap.max() > 0:
|
||||
best[i] = w_size[int(overlap.argmax())]
|
||||
t["section_witsml"] = best
|
||||
agree = pd.Series(best == t["section_in"].to_numpy(float), index=t.index, dtype="boolean")
|
||||
t["section_agree"] = agree.mask(np.isnan(best) | t["section_in"].isna().to_numpy())
|
||||
return t
|
||||
|
||||
|
||||
def t1_activities(ops: pd.DataFrame, t1: pd.DataFrame) -> pd.DataFrame:
|
||||
"""T1 per activity: its operation label and the section label of its report-day."""
|
||||
day = t1[["report_id", "section_in", "section", "phase", "is_pilot", "filled_by", "section_rule", "scope"]]
|
||||
return ops.merge(day, on="report_id", how="left", validate="many_to_one")
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------------------------------------------
|
||||
# T2 labels, masked inputs, text rates
|
||||
# ---------------------------------------------------------------------------------------------------------------
|
||||
|
||||
def _snake(s: pd.Series) -> pd.Series:
|
||||
return s.str.replace(r"\W+", "_", regex=True).str.strip("_")
|
||||
|
||||
|
||||
def t2_labels(activities: pd.DataFrame, cfg: dict) -> pd.DataFrame:
|
||||
"""T2 per activity: NPT under definitions (a) and (b), cause group with both candidate sources and the rule."""
|
||||
t2 = cfg["t2"]
|
||||
a = activities
|
||||
out = a[["act_id", "report_id", "wellbore"]].copy()
|
||||
out["well"] = out["wellbore"].map(well_of)
|
||||
out["duration_h"] = a["duration_h"].to_numpy()
|
||||
out["is_interruption"] = a["code_main"].eq("interruption").to_numpy()
|
||||
out["is_state_fail"] = a["state"].map({k: v["npt"] for k, v in t2["state"].items()}).astype(bool).to_numpy()
|
||||
out["is_detail_nonsuccess"] = a["stateDetailActivity"].ne("success").to_numpy()
|
||||
out["npt_a"] = out["is_interruption"]
|
||||
out["npt_b"] = out["is_interruption"] | out["is_state_fail"] | out["is_detail_nonsuccess"]
|
||||
|
||||
code_cause = {c: (None if r["cause"] == "detail" else r["cause"]) for c, r in cfg["codes"].items()}
|
||||
detail_cause = {d: r["cause"] for d, r in t2["cause_from_detail"].items()}
|
||||
from_code = np.array([code_cause[c] for c in a["proprietaryCode"]], dtype=object)
|
||||
from_detail = np.array([detail_cause[d] for d in a["stateDetailActivity"]], dtype=object)
|
||||
has_code = np.array([c is not None for c in from_code])
|
||||
has_detail = np.array([d is not None for d in from_detail])
|
||||
order = {"code": (has_code, from_code, "T2.C1"), "detail": (has_detail, from_detail, "T2.C2")}
|
||||
cause = np.full(len(a), t2["default_cause"], dtype=object)
|
||||
rule = np.full(len(a), "T2.C3", dtype=object)
|
||||
for source in reversed([s for s in t2["precedence"] if s != "default"]):
|
||||
has, values, rule_id = order[source]
|
||||
cause[has], rule[has] = values[has], rule_id
|
||||
npt = out["npt_b"].to_numpy()
|
||||
out["cause_from_code"] = np.where(npt, from_code, None)
|
||||
out["cause_from_detail"] = np.where(npt, from_detail, None)
|
||||
out["cause_group"] = np.where(npt, cause, "none")
|
||||
out["cause_rule"] = np.where(npt, rule, None)
|
||||
fine = np.where(rule == "T2.C1", _snake(a["code_sub"]).to_numpy(object),
|
||||
np.where(rule == "T2.C2", _snake(a["stateDetailActivity"]).to_numpy(object), t2["default_cause"]))
|
||||
out["cause_fine"] = np.where(npt, fine, "none")
|
||||
out["cause_conflict"] = npt & has_code & has_detail & (from_code != from_detail)
|
||||
out["cause_a"] = np.where(out["npt_a"], out["cause_group"], "none")
|
||||
out["cause_b"] = out["cause_group"]
|
||||
out["wait_code_outside_interruption"] = (a["code_sub"].eq("wait") & ~a["code_main"].eq("interruption")).to_numpy()
|
||||
out["npt_rule_a"], out["npt_rule_b"] = "T2.Na", "T2.Nb"
|
||||
out["source_columns"] = "activities.proprietaryCode,activities.state,activities.stateDetailActivity"
|
||||
return out
|
||||
|
||||
|
||||
def t2_inputs(activities: pd.DataFrame, reports: pd.DataFrame, cfg: dict) -> pd.DataFrame:
|
||||
"""The masked model-input view for T2 and T3: activity text and depth, report text and header metadata, and no
|
||||
activity-code column. Raises if a column of `MASKED` would be in the view."""
|
||||
t2 = cfg["t2"]
|
||||
acts = activities[t2["input_activity_columns"]].rename(columns={"phase": "rig_phase"})
|
||||
rep = reports[["report_id"] + t2["input_report_columns"]].rename(
|
||||
columns={c: f"report_{c}" for c in ("md", "tvd", "distDrill", "diaHole", "mdDiaHoleStart", "mdCsgLast")})
|
||||
view = acts.merge(rep, on="report_id", how="left", validate="many_to_one")
|
||||
view.insert(3, "well", view["wellbore"].map(well_of))
|
||||
leaked = sorted(set(view.columns) & set(MASKED))
|
||||
if leaked:
|
||||
raise ValueError(f"masked columns in the model-input view: {leaked}")
|
||||
return view
|
||||
|
||||
|
||||
def text_rates(activities: pd.DataFrame, reports: pd.DataFrame, labels: pd.DataFrame, cfg: dict) -> pd.DataFrame:
|
||||
"""How often the free text names the label, for the lexicon of labels.yaml (analysis only).
|
||||
|
||||
One row per (target, definition, scope): scope `comment` searches activities.comments, `comment+sum24Hr` adds
|
||||
the 24 h summary of the report. `recall` = share of positive rows the lexicon hits, `fpr` = share of negative
|
||||
rows it hits, `precision` = positives among the hits."""
|
||||
lex = {k: re.compile("|".join(f"(?:{alt})" for alt in v), re.I) for k, v in cfg["text_lexicon"].items()}
|
||||
comment = activities["comments"].fillna("")
|
||||
summary = activities["report_id"].map(reports.set_index("report_id")["sum24Hr"]).fillna("")
|
||||
texts = {"comment": comment, "comment+sum24Hr": comment + "\n" + summary.where(summary.ne("None"), "")}
|
||||
rows = []
|
||||
for scope, text in texts.items():
|
||||
hits = {k: np.fromiter((rx.search(s) is not None for s in text), dtype=bool, count=len(text))
|
||||
for k, rx in lex.items()}
|
||||
for d in NPT_DEFINITIONS:
|
||||
npt = labels[f"npt_{d}"].to_numpy()
|
||||
cause = labels[f"cause_{d}"].to_numpy()
|
||||
for target, hit in hits.items():
|
||||
pos = npt if target == "npt" else cause == target
|
||||
n_pos, n_neg = int(pos.sum()), int((~pos).sum())
|
||||
tp, fp = int((hit & pos).sum()), int((hit & ~pos).sum())
|
||||
rows.append({"target": target, "definition": d, "scope": scope, "n_pos": n_pos, "hit_pos": tp,
|
||||
"n_neg": n_neg, "hit_neg": fp,
|
||||
"recall": round(tp / n_pos, 4) if n_pos else None,
|
||||
"fpr": round(fp / n_neg, 4) if n_neg else None,
|
||||
"precision": round(tp / (tp + fp), 4) if tp + fp else None})
|
||||
return pd.DataFrame(rows)
|
||||
|
||||
|
||||
def code_sub_literal(activities: pd.DataFrame) -> pd.DataFrame:
|
||||
"""Per sub-code: the share of its rows whose comment contains the sub-code literally (case-insensitive), and
|
||||
the share of all other rows that do (so "drill" in "drill pipe" is visible as a high background rate)."""
|
||||
comment = activities["comments"].fillna("").str.lower()
|
||||
rows = []
|
||||
for sub, n in activities["code_sub"].value_counts().items():
|
||||
hit = comment.str.contains(sub.lower(), regex=False).to_numpy()
|
||||
own = activities["code_sub"].eq(sub).to_numpy()
|
||||
rows.append({"code_sub": sub, "n": int(n), "hit": int((hit & own).sum()),
|
||||
"rate": round(float((hit & own).sum() / n), 4),
|
||||
"rate_other_rows": round(float((hit & ~own).sum() / max(int((~own).sum()), 1)), 4)})
|
||||
return pd.DataFrame(rows)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------------------------------------------
|
||||
# T3: depth classes, episodes, cells, intervals
|
||||
# ---------------------------------------------------------------------------------------------------------------
|
||||
|
||||
def mudline(reports: pd.DataFrame) -> pd.Series:
|
||||
"""Mud line per wellbore in m MD: median of waterDepth + elevKelly over the reports with elevKelly > 0."""
|
||||
ok = reports[reports["elevKelly"] > 0]
|
||||
return (ok["waterDepth"] + ok["elevKelly"]).groupby(ok["wellbore"]).median().rename("mudline_md")
|
||||
|
||||
|
||||
def own_hole_top(reports: pd.DataFrame) -> pd.Series:
|
||||
"""Top of the hole a wellbore drilled itself: the smallest mdDiaHoleStart among its reports with a diaHole."""
|
||||
ok = reports[reports["diaHole"].notna() & reports["mdDiaHoleStart"].notna()]
|
||||
return ok.groupby("wellbore")["mdDiaHoleStart"].min().rename("own_hole_top_md")
|
||||
|
||||
|
||||
def t3_activities(activities: pd.DataFrame, labels: pd.DataFrame, reports: pd.DataFrame, cfg: dict) -> pd.DataFrame:
|
||||
"""Per activity: depth class (T3.D1), grid cell (T3.G1, in-hole rows only), NPT flags and episode ids (T3.E1).
|
||||
Rows are in time order within the wellbore."""
|
||||
grid = float(cfg["t3"]["grid_m"])
|
||||
t = activities[["act_id", "report_id", "wellbore", "seq", "start_utc", "end_utc", "duration_h", "md"]].copy()
|
||||
t = t.merge(labels[["act_id", "well", "npt_a", "npt_b", "cause_group"]], on="act_id", validate="one_to_one")
|
||||
t["mudline_md"] = t["wellbore"].map(mudline(reports))
|
||||
if t["mudline_md"].isna().any():
|
||||
raise ValueError("no mud line for: " + ", ".join(sorted(t.loc[t["mudline_md"].isna(), "wellbore"].unique())))
|
||||
md = t["md"]
|
||||
t["depth_class"] = np.select([md.isna(), md <= 0, md < t["mudline_md"]], ["missing", "zero", "above_mudline"],
|
||||
"in_hole")
|
||||
t["cell"] = np.floor(md / grid).where(t["depth_class"].eq("in_hole")).astype("Int64")
|
||||
t = t.sort_values(["wellbore", "start_utc", "end_utc", "report_id", "seq"], kind="stable").reset_index(drop=True)
|
||||
max_gap = pd.Timedelta(hours=float(cfg["t3"]["episode_max_gap_h"]))
|
||||
same = t["wellbore"].eq(t["wellbore"].shift())
|
||||
near = (t["start_utc"] - t["end_utc"].shift()) <= max_gap
|
||||
for d in NPT_DEFINITIONS:
|
||||
npt = t[f"npt_{d}"]
|
||||
first = npt & ~(npt.shift(fill_value=False) & same & near)
|
||||
number = first.groupby(t["wellbore"]).cumsum()
|
||||
ids = t["wellbore"].map(stem) + f":{d}:E" + number.astype(str).str.zfill(4)
|
||||
t[f"episode_{d}"] = ids.where(npt, None)
|
||||
return t
|
||||
|
||||
|
||||
def t3_episodes(t3a: pd.DataFrame, definition: str) -> pd.DataFrame:
|
||||
"""One row per NPT episode under `definition`: time span, hours, depth span of its in-hole rows, causes, rows."""
|
||||
col = f"episode_{definition}"
|
||||
e = t3a[t3a[col].notna()]
|
||||
hole = e["md"].where(e["depth_class"].eq("in_hole"))
|
||||
g = e.assign(_md=hole).groupby(col, sort=False)
|
||||
out = g.agg(wellbore=("wellbore", "first"), well=("well", "first"), n_activities=("act_id", "size"),
|
||||
start_utc=("start_utc", "min"), end_utc=("end_utc", "max"), hours=("duration_h", "sum"),
|
||||
n_in_hole=("_md", "count"), md_min=("_md", "min"), md_max=("_md", "max"),
|
||||
causes=("cause_group", lambda s: "|".join(sorted(set(s)))),
|
||||
n_reports=("report_id", "nunique"), act_ids=("act_id", list)).reset_index()
|
||||
out = out.rename(columns={col: "episode_id"})
|
||||
out.insert(1, "definition", definition)
|
||||
out["rule"] = "T3.E1"
|
||||
return out
|
||||
|
||||
|
||||
def _cell_universe(t3a: pd.DataFrame, reports: pd.DataFrame, grid: float) -> pd.DataFrame:
|
||||
hole = t3a[t3a["depth_class"].eq("in_hole")]
|
||||
deepest = pd.concat([hole.groupby("wellbore")["md"].max(), reports.groupby("wellbore")["md"].max()],
|
||||
axis=1).max(axis=1)
|
||||
mud = mudline(reports)
|
||||
frames = []
|
||||
for wellbore in sorted(deepest.index):
|
||||
if pd.isna(deepest[wellbore]) or deepest[wellbore] < mud[wellbore]:
|
||||
continue
|
||||
cells = np.arange(int(np.floor(mud[wellbore] / grid)), int(np.floor(deepest[wellbore] / grid)) + 1)
|
||||
frames.append(pd.DataFrame({"wellbore": wellbore, "cell": cells}))
|
||||
return pd.concat(frames, ignore_index=True)
|
||||
|
||||
|
||||
def t3_cells(t3a: pd.DataFrame, reports: pd.DataFrame, cfg: dict) -> pd.DataFrame:
|
||||
"""One row per (wellbore, cell) from the mud line to the deepest depth of the wellbore: exposure (all in-hole
|
||||
activities in the cell), NPT counts, hours, label, first NPT time, causes and source rows under (a) and (b)."""
|
||||
grid = float(cfg["t3"]["grid_m"])
|
||||
cells = _cell_universe(t3a, reports, grid)
|
||||
cells["well"] = cells["wellbore"].map(well_of)
|
||||
cells["md_top"] = cells["cell"] * grid
|
||||
cells["md_bottom"] = (cells["cell"] + 1) * grid
|
||||
top = cells["wellbore"].map(own_hole_top(reports)).fillna(cells["wellbore"].map(mudline(reports)))
|
||||
cells["own_hole_top_md"] = top
|
||||
cells["in_own_hole"] = cells["md_bottom"] > top
|
||||
hole = t3a[t3a["depth_class"].eq("in_hole")].assign(cell=lambda d: d["cell"].astype(int))
|
||||
keys = ["wellbore", "cell"]
|
||||
exposure = hole.groupby(keys).agg(n_activities=("act_id", "size"), hours=("duration_h", "sum")).reset_index()
|
||||
cells = cells.merge(exposure, on=keys, how="left")
|
||||
for d in NPT_DEFINITIONS:
|
||||
npt = hole[hole[f"npt_{d}"]]
|
||||
agg = npt.groupby(keys).agg(**{
|
||||
f"n_npt_{d}": ("act_id", "size"), f"hours_npt_{d}": ("duration_h", "sum"),
|
||||
f"first_npt_start_{d}": ("start_utc", "min"),
|
||||
f"causes_{d}": ("cause_group", lambda s: "|".join(sorted(set(s)))),
|
||||
f"act_ids_{d}": ("act_id", list)}).reset_index()
|
||||
cells = cells.merge(agg, on=keys, how="left")
|
||||
cells[f"label_{d}"] = cells[f"n_npt_{d}"].notna()
|
||||
for c in ["n_activities"] + [f"n_npt_{d}" for d in NPT_DEFINITIONS]:
|
||||
cells[c] = cells[c].fillna(0).astype(int)
|
||||
for c in ["hours"] + [f"hours_npt_{d}" for d in NPT_DEFINITIONS]:
|
||||
cells[c] = cells[c].fillna(0.0)
|
||||
cells["rule"] = "T3.D1,T3.G1"
|
||||
cells["source_columns"] = "activities.md,reports.waterDepth,reports.elevKelly"
|
||||
return cells.sort_values(keys, kind="stable").reset_index(drop=True)
|
||||
|
||||
|
||||
def t3_intervals(cells: pd.DataFrame, t3a: pd.DataFrame, definition: str, cfg: dict,
|
||||
merge_gap_cells: int | None = None) -> pd.DataFrame:
|
||||
"""Trouble intervals under `definition` (T3.M1): runs of positive cells of one wellbore with at most
|
||||
`merge_gap_cells` negative cells between two positive ones, as [md_top, md_bottom) with the NPT rows inside."""
|
||||
grid = float(cfg["t3"]["grid_m"])
|
||||
gap = cfg["t3"]["merge_gap_cells"] if merge_gap_cells is None else merge_gap_cells
|
||||
pos = cells.loc[cells[f"label_{definition}"], ["wellbore", "well", "cell"]].sort_values(["wellbore", "cell"])
|
||||
new = pos["wellbore"].ne(pos["wellbore"].shift()) | (pos["cell"].diff() > gap + 1)
|
||||
pos = pos.assign(number=new.groupby(pos["wellbore"]).cumsum())
|
||||
pos["interval_id"] = pos["wellbore"].map(stem) + f":{definition}:I" + pos["number"].astype(str).str.zfill(3)
|
||||
out = pos.groupby("interval_id", sort=False).agg(
|
||||
wellbore=("wellbore", "first"), well=("well", "first"), cell_first=("cell", "min"), cell_last=("cell", "max"),
|
||||
n_positive_cells=("cell", "size")).reset_index()
|
||||
out.insert(1, "definition", definition)
|
||||
out["md_top"] = out["cell_first"] * grid
|
||||
out["md_bottom"] = (out["cell_last"] + 1) * grid
|
||||
out["length_m"] = out["md_bottom"] - out["md_top"]
|
||||
npt = t3a[t3a[f"npt_{definition}"] & t3a["depth_class"].eq("in_hole")].assign(cell=lambda d: d["cell"].astype(int))
|
||||
npt = npt.merge(pos[["wellbore", "cell", "interval_id"]], on=["wellbore", "cell"], validate="many_to_one")
|
||||
agg = npt.groupby("interval_id").agg(
|
||||
n_activities=("act_id", "size"), hours=("duration_h", "sum"), first_start_utc=("start_utc", "min"),
|
||||
last_end_utc=("end_utc", "max"), causes=("cause_group", lambda s: "|".join(sorted(set(s)))),
|
||||
n_episodes=(f"episode_{definition}", "nunique"), act_ids=("act_id", list)).reset_index()
|
||||
out = out.merge(agg, on="interval_id", validate="one_to_one")
|
||||
out["merge_gap_cells"] = gap
|
||||
out["rule"] = "T3.M1"
|
||||
return out
|
||||
|
||||
|
||||
def attach_intervals(cells: pd.DataFrame, intervals: dict[str, pd.DataFrame]) -> pd.DataFrame:
|
||||
"""Add `interval_id_a` / `interval_id_b` to the cell table (NULL outside an interval)."""
|
||||
out = cells.copy()
|
||||
for d, iv in intervals.items():
|
||||
ids = np.full(len(out), None, dtype=object)
|
||||
index = {w: g for w, g in out.groupby("wellbore").indices.items()}
|
||||
cell = out["cell"].to_numpy()
|
||||
for row in iv.itertuples():
|
||||
rows = index[row.wellbore]
|
||||
inside = rows[(cell[rows] >= row.cell_first) & (cell[rows] <= row.cell_last)]
|
||||
ids[inside] = row.interval_id
|
||||
out[f"interval_id_{d}"] = ids
|
||||
return out
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------------------------------------------
|
||||
# Analysis for the protocol
|
||||
# ---------------------------------------------------------------------------------------------------------------
|
||||
|
||||
def class_coverage(frame: pd.DataFrame, column: str, rare: int = 20) -> pd.DataFrame:
|
||||
"""Per class of `column`: instances, number of wellbores and wells that contain it, the largest share held by
|
||||
one wellbore and by one well, and the flags `rare` (fewer than `rare` instances), `single_wellbore` and
|
||||
`single_well` (a class in one group can never be in both the training and the test side of a grouped split)."""
|
||||
f = frame[frame[column].notna()]
|
||||
rows = []
|
||||
for value, g in f.groupby(column, sort=True):
|
||||
by_wellbore, by_well = g["wellbore"].value_counts(), g["well"].value_counts()
|
||||
rows.append({"label": column, "class": str(value), "n": len(g),
|
||||
"n_wellbores": len(by_wellbore), "n_wells": len(by_well),
|
||||
"top_wellbore": by_wellbore.index[0], "top_wellbore_share": round(by_wellbore.iloc[0] / len(g), 4),
|
||||
"top_well": by_well.index[0], "top_well_share": round(by_well.iloc[0] / len(g), 4),
|
||||
"rare": len(g) < rare, "single_wellbore": len(by_wellbore) == 1, "single_well": len(by_well) == 1})
|
||||
return pd.DataFrame(rows)
|
||||
|
||||
|
||||
def distribution(frame: pd.DataFrame, column: str, by: str) -> dict:
|
||||
"""{group: {class: n}} of `column` per value of `by` (wellbore or well)."""
|
||||
f = frame[frame[column].notna()]
|
||||
table = f.groupby([by, column]).size()
|
||||
return {str(g): {str(k): int(v) for k, v in table[g].items()} for g in table.index.get_level_values(0).unique()}
|
||||
281
volve_dia/ocr_hub.py
Normal file
281
volve_dia/ocr_hub.py
Normal file
@@ -0,0 +1,281 @@
|
||||
"""Import an OCR of the Volve PDF pages that was run outside this repository and exported from the internal Dataset
|
||||
Hub as one COCO file (`configs/ocr_hub.yaml`).
|
||||
|
||||
The export holds one PNG per distinct page image and, per image, chandra's blocks: category (= chandra's own label),
|
||||
pixel box ``[x, y, w, h]``, inner HTML (`text`) and `attributes.reading_order`. It does not say which PDF and page an
|
||||
image is: images are named by the sha256 of the PNG, identical PNGs are stored once (a blank page, or a second page
|
||||
that holds the same rows in two reports), and the renderer is not PyMuPDF, so no pixel or hash matches ours.
|
||||
|
||||
Each PDF page is therefore matched to an image by content, in two stages:
|
||||
|
||||
1. text: the PDF text layer and the OCR text are split into tokens (dates and depths kept whole), every image is
|
||||
scored by a hashed TF-IDF cosine, and the best `prefilter` images are re-scored by an idf-weighted token F1. The
|
||||
best `top_k` are the candidates. A page with no text layer gets the images with no text as candidates;
|
||||
2. image: the page is rendered at `thumb_dpi` in grey and correlated with each candidate image shrunk by
|
||||
2**`thumb_shrink`. A candidate shows the page if the correlation reaches `min_corr`; among those within `tie_eps`
|
||||
of the best correlation the highest text F1 wins (`select`), because two reports that differ only in a date
|
||||
correlate equally. A DDR page with no such candidate (short pages whose OCR text differs from the text layer) is
|
||||
searched by image against every image of the export (coarse correlation, best `fallback_top_k` re-scored) and
|
||||
is `missing` if that fails too.
|
||||
|
||||
A check that does not take part in the choice: every ISO date of the page's text layer (the period of page 1) must
|
||||
occur in the chosen OCR text.
|
||||
|
||||
The winner is written in chandra's page format (``<div data-bbox="x0 y0 x1 y1" data-label="...">``, box normalised
|
||||
to 0-1000) to ``outputs/ocr/hub/pages/<doc sha256[:16]>/pNNNN.json`` with its provenance and match scores, so the
|
||||
blocks parse with `ocr.html_blocks` exactly as a page read through the service. Hub pages are kept apart from the
|
||||
service cache because the prompt, renderer and settings that produced them are not recorded in the export.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import collections
|
||||
import hashlib
|
||||
import json
|
||||
import re
|
||||
import zlib
|
||||
from dataclasses import dataclass
|
||||
from html import unescape
|
||||
from pathlib import Path
|
||||
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
import yaml
|
||||
|
||||
from . import ocr
|
||||
from .paths import REPO_ROOT, outputs_dir
|
||||
|
||||
CONFIG = REPO_ROOT / "configs" / "ocr_hub.yaml"
|
||||
_TAG = re.compile(r"<[^>]+>")
|
||||
_TOKEN = re.compile(r"[A-Za-z0-9]+(?:[-:./][A-Za-z0-9]+)*")
|
||||
_DATE = re.compile(r"\b(?:19|20)\d\d-[01]\d-[0-3]\d\b")
|
||||
_DIM = 1 << 14
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class HubConfig:
|
||||
dir: Path
|
||||
prefilter: int
|
||||
top_k: int
|
||||
thumb_dpi: int
|
||||
thumb_shrink: int
|
||||
min_corr: float
|
||||
tie_eps: float
|
||||
fallback_top_k: int
|
||||
min_text_f1: float
|
||||
f1_min_tokens: int
|
||||
|
||||
|
||||
def load_config(path: Path = CONFIG) -> HubConfig:
|
||||
raw = yaml.safe_load(path.read_text(encoding="utf-8"))
|
||||
raw["dir"] = REPO_ROOT / raw["dir"]
|
||||
return HubConfig(**raw)
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- the export
|
||||
|
||||
@dataclass
|
||||
class Export:
|
||||
file: Path # the COCO json
|
||||
sha256: str
|
||||
images: dict[int, dict] # id -> {file_name, width, height}
|
||||
blocks: dict[int, list[dict]] # image id -> annotations in reading order
|
||||
categories: dict[int, str]
|
||||
orphans: list[str] # PNG files with no image record
|
||||
|
||||
|
||||
def load_export(hub_dir: Path) -> Export:
|
||||
files = sorted((hub_dir / "annotations").rglob("*.json"))
|
||||
if len(files) != 1:
|
||||
raise FileNotFoundError(f"expected one COCO json under {hub_dir / 'annotations'}, found {len(files)}")
|
||||
data = json.loads(files[0].read_text(encoding="utf-8"))
|
||||
cats = {c["id"]: c["name"] for c in data["categories"]}
|
||||
images = {im["id"]: im for im in data["images"]}
|
||||
blocks: dict[int, list[dict]] = collections.defaultdict(list)
|
||||
for a in data["annotations"]:
|
||||
blocks[a["image_id"]].append(a)
|
||||
for v in blocks.values():
|
||||
v.sort(key=lambda a: ((a.get("attributes") or {}).get("reading_order", 0), a["id"]))
|
||||
named = {im["file_name"] for im in images.values()}
|
||||
orphans = sorted(f"images/{p.name}" for p in (hub_dir / "images").glob("*.png") if f"images/{p.name}" not in named)
|
||||
return Export(files[0], ocr.sha256_file(files[0]), images, dict(blocks), cats, orphans)
|
||||
|
||||
|
||||
def page_content(anns: list[dict], cats: dict[int, str], width: float, height: float) -> str:
|
||||
"""chandra's page answer for the blocks of one image: one ``<div>`` per block, box normalised to 0-1000."""
|
||||
out = []
|
||||
for a in anns:
|
||||
x, y, w, h = a["bbox"]
|
||||
box = " ".join(str(round(v)) for v in (1000 * x / width, 1000 * y / height,
|
||||
1000 * (x + w) / width, 1000 * (y + h) / height))
|
||||
out.append(f'<div data-bbox="{box}" data-label="{cats[a["category_id"]]}">\n{a.get("text") or ""}\n</div>')
|
||||
return "\n".join(out)
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- text stage
|
||||
|
||||
def tokens(text: str) -> list[str]:
|
||||
return _TOKEN.findall(unescape(_TAG.sub(" ", text)).lower())
|
||||
|
||||
|
||||
def iso_dates(text: str) -> set[str]:
|
||||
return set(_DATE.findall(text))
|
||||
|
||||
|
||||
def _hashed_tfidf(docs: list[list[str]], idf: np.ndarray) -> np.ndarray:
|
||||
m = np.zeros((len(docs), _DIM), np.float32)
|
||||
for i, toks in enumerate(docs):
|
||||
for h, n in collections.Counter(zlib.crc32(t.encode()) % _DIM for t in toks).items():
|
||||
m[i, h] = (1 + np.log(n)) * idf[h]
|
||||
norm = np.linalg.norm(m, axis=1)
|
||||
norm[norm == 0] = 1
|
||||
return m / norm[:, None]
|
||||
|
||||
|
||||
class TextIndex:
|
||||
"""Token statistics of the pages (document frequencies) and the images, for the text stage."""
|
||||
|
||||
def __init__(self, page_toks: list[list[str]], image_toks: list[list[str]]):
|
||||
n = self.n = len(page_toks)
|
||||
df_hash = collections.Counter()
|
||||
self.df_tok = collections.Counter()
|
||||
for toks in page_toks:
|
||||
df_hash.update({zlib.crc32(t.encode()) % _DIM for t in toks})
|
||||
self.df_tok.update(set(toks))
|
||||
idf = np.full(_DIM, np.log(n + 1) + 1, np.float32)
|
||||
for h, c in df_hash.items():
|
||||
idf[h] = np.log((n + 1) / (c + 1)) + 1
|
||||
self.sim = _hashed_tfidf(page_toks, idf) @ _hashed_tfidf(image_toks, idf).T
|
||||
self.page_counts = [collections.Counter(t) for t in page_toks]
|
||||
self.img_counts = [collections.Counter(t) for t in image_toks]
|
||||
self.page_weight = [self._weight(c) for c in self.page_counts]
|
||||
self.img_weight = [self._weight(c) for c in self.img_counts]
|
||||
self.empty = [i for i, t in enumerate(image_toks) if not t]
|
||||
|
||||
def _weight(self, c: collections.Counter) -> float:
|
||||
return sum(k * (np.log((self.n + 1) / (self.df_tok.get(t, 0) + 1)) + 1) for t, k in c.items())
|
||||
|
||||
def f1(self, j: int, i: int) -> float:
|
||||
"""idf-weighted token-multiset F1 of page j and image i (1 if both have no text)."""
|
||||
den = self.page_weight[j] + self.img_weight[i]
|
||||
return 2 * self._weight(self.page_counts[j] & self.img_counts[i]) / den if den else 1.0
|
||||
|
||||
def candidates(self, j: int, prefilter: int, top_k: int) -> list[tuple[int, float]]:
|
||||
if not self.page_counts[j]:
|
||||
return [(i, 1.0) for i in self.empty][:top_k]
|
||||
scored = [(int(i), self.f1(j, int(i))) for i in np.argsort(-self.sim[j])[:prefilter]]
|
||||
scored.sort(key=lambda s: -s[1])
|
||||
return scored[:top_k]
|
||||
|
||||
|
||||
def text_candidates(page_toks: list[list[str]], image_toks: list[list[str]], prefilter: int,
|
||||
top_k: int) -> list[list[tuple[int, float]]]:
|
||||
"""For every page, up to `top_k` (image index, idf-weighted token F1), best first."""
|
||||
ix = TextIndex(page_toks, image_toks)
|
||||
return [ix.candidates(j, prefilter, top_k) for j in range(len(page_toks))]
|
||||
|
||||
|
||||
def select(scored: list[tuple[float, float, int]], min_corr: float, tie_eps: float,
|
||||
min_f1: float = 0.0) -> tuple[float, float, int] | None:
|
||||
"""Pick the image of a page from its candidates (corr, text F1, image index).
|
||||
|
||||
The image correlation decides whether a candidate shows the page at all; it cannot tell apart two reports that
|
||||
differ only in a date or a number (their thumbnails correlate equally). So among the candidates that reach
|
||||
`min_corr` and `min_f1` and lie within `tie_eps` of the best correlation, the one with the highest text F1 wins
|
||||
(then the higher correlation). `min_f1` keeps a page with a text layer from taking the image of another report
|
||||
with the same layout (a first page of another day). None if no candidate passes."""
|
||||
ok = [s for s in scored if s[0] >= min_corr and s[1] >= min_f1]
|
||||
if not ok:
|
||||
return None
|
||||
top = max(s[0] for s in ok)
|
||||
return max((s for s in ok if s[0] >= top - tie_eps), key=lambda s: (s[1], s[0]))
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- image stage
|
||||
|
||||
def _grey(pix) -> np.ndarray:
|
||||
import pymupdf
|
||||
|
||||
if pix.n != 1 or pix.alpha:
|
||||
pix = pymupdf.Pixmap(pymupdf.csGRAY, pix)
|
||||
return np.frombuffer(pix.samples, np.uint8).reshape(pix.h, pix.stride)[:, : pix.w].copy()
|
||||
|
||||
|
||||
def image_thumb(path: Path, shrink: int) -> np.ndarray:
|
||||
import pymupdf
|
||||
|
||||
pix = pymupdf.Pixmap(str(path))
|
||||
if pix.alpha:
|
||||
pix = pymupdf.Pixmap(pix, 0)
|
||||
pix.shrink(shrink)
|
||||
return _grey(pix)
|
||||
|
||||
|
||||
def page_thumb(doc, page: int, dpi: int) -> np.ndarray:
|
||||
import pymupdf
|
||||
|
||||
return _grey(doc[page - 1].get_pixmap(dpi=dpi, colorspace=pymupdf.csGRAY))
|
||||
|
||||
|
||||
COARSE = (146, 103) # a 50 dpi A4 page, or a 1653 x 2339 image shrunk by 4, averaged over 4 x 4 blocks
|
||||
|
||||
|
||||
def coarse(a: np.ndarray, f: int = 4) -> np.ndarray:
|
||||
"""A thumbnail averaged over f x f blocks into the fixed shape COARSE (cropped or padded with white), flattened,
|
||||
centred and scaled to unit norm, so that a dot product of two is their correlation."""
|
||||
h, w = COARSE[0] * f, COARSE[1] * f
|
||||
b = np.full((h, w), 255, np.float32)
|
||||
b[: min(h, a.shape[0]), : min(w, a.shape[1])] = a[:h, :w]
|
||||
v = b.reshape(COARSE[0], f, COARSE[1], f).mean(axis=(1, 3)).ravel()
|
||||
v -= v.mean()
|
||||
n = float(np.linalg.norm(v))
|
||||
return v / n if n > 0 else v
|
||||
|
||||
|
||||
def correlation(a: np.ndarray, b: np.ndarray) -> float:
|
||||
"""Pearson correlation of two grey thumbnails over their common top-left area (sizes differ by a pixel)."""
|
||||
h, w = min(a.shape[0], b.shape[0]), min(a.shape[1], b.shape[1])
|
||||
x = a[:h, :w].astype(np.float32).ravel()
|
||||
y = b[:h, :w].astype(np.float32).ravel()
|
||||
x -= x.mean()
|
||||
y -= y.mean()
|
||||
den = float(np.sqrt((x @ x) * (y @ y)))
|
||||
return float(x @ y / den) if den > 0 else float(np.array_equal(a[:h, :w], b[:h, :w]))
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- page records
|
||||
|
||||
def cache_dir() -> Path:
|
||||
return outputs_dir() / "ocr" / "hub" / "pages"
|
||||
|
||||
|
||||
def page_file(doc_sha256: str, page: int) -> Path:
|
||||
return cache_dir() / doc_sha256[:16] / f"p{page:04d}.json"
|
||||
|
||||
|
||||
def write_page(rec: dict) -> None:
|
||||
f = page_file(rec["doc_sha256"], rec["page"])
|
||||
f.parent.mkdir(parents=True, exist_ok=True)
|
||||
tmp = f.with_suffix(".tmp")
|
||||
tmp.write_text(json.dumps(rec, ensure_ascii=False, indent=1), encoding="utf-8")
|
||||
tmp.replace(f)
|
||||
|
||||
|
||||
def load_blocks(doc_sha256: str, n_pages: int) -> tuple[list[ocr.Block], list[dict]]:
|
||||
"""Blocks of a document from the hub import, in page and reading order, like `ocr.load_blocks`."""
|
||||
blocks: list[ocr.Block] = []
|
||||
records = []
|
||||
for page in range(1, n_pages + 1):
|
||||
f = page_file(doc_sha256, page)
|
||||
if not f.is_file():
|
||||
records.append({"page": page, "status": "missing"})
|
||||
continue
|
||||
rec = json.loads(f.read_text(encoding="utf-8"))
|
||||
records.append({k: v for k, v in rec.items() if k != "content"})
|
||||
if rec["status"] == "ok":
|
||||
blocks += ocr.html_blocks(rec["content"], page)
|
||||
return blocks, records
|
||||
|
||||
|
||||
def content_sha256(content: str) -> str:
|
||||
return hashlib.sha256(content.encode("utf-8")).hexdigest()
|
||||
@@ -55,3 +55,8 @@ def outputs_dir() -> Path:
|
||||
p = Path(env) if env else REPO_ROOT / "outputs"
|
||||
p.mkdir(parents=True, exist_ok=True)
|
||||
return p
|
||||
|
||||
|
||||
def well_picks_file() -> Path:
|
||||
"""Formation tops of the Volve wells (409 picks, 35 wellbores), fixed-width text."""
|
||||
return volve_root() / "Geophysical_Interpretations" / "Wells" / "Well_picks_Volve_v1.dat"
|
||||
|
||||
791
volve_dia/t4.py
Normal file
791
volve_dia/t4.py
Normal file
@@ -0,0 +1,791 @@
|
||||
"""T4: evidence-grounded question answering over the Volve daily drilling reports (DDR).
|
||||
|
||||
Source of every answer: the DDR tables that `scripts/02_parse_ddr.py` builds from the DDR XML files
|
||||
(`outputs/ddr/volve_ddr.duckdb`). Nothing is taken from the HTML or PDF renders, and no language model is involved.
|
||||
|
||||
Rules (plan §4.3, AGENTS.md):
|
||||
|
||||
* a question is a deterministic template (`configs/t4_templates.yaml`) filled with slot values that a SQL query
|
||||
enumerates from the data;
|
||||
* the gold answer is the result of the template's answer SQL, and the evidence is the set of rows (table, report_id,
|
||||
seq) that the template's evidence SQL returns. Both queries are stored with the question, with the slot values
|
||||
written in as literals, so each can be re-run as is;
|
||||
* an instance is dropped, and counted with its reason, when the answer is missing, ambiguous (several published
|
||||
values, a tie) or flagged by the template itself (`drop_reason` column of the answer SQL). A template with
|
||||
`on_null: not_reported` keeps instances without an answer as unanswerable questions (gold answer "not reported");
|
||||
* trouble and NPT questions are phrased on the published codes (`proprietaryCode`, `stateDetailActivity`), never on
|
||||
the NPT definition of T2, which is not locked yet;
|
||||
* each question carries its wellbore(s) and well(s), the groups of the evaluation split.
|
||||
|
||||
Evidence modes. `all`: every row is needed (sums, counts). `any`: every row states the answer by itself (a header
|
||||
value repeated in each report). `group`: the rows fall into groups and one row per group is enough (a list answer:
|
||||
one group per element). Citation recall is the share of groups with at least one cited row; citation precision is
|
||||
the share of cited rows that are evidence rows.
|
||||
|
||||
`score(prediction, gold)` compares a predicted answer with the gold answer by answer type, within the tolerance of
|
||||
the template, and computes citation precision and recall. An independent pandas implementation of every template is
|
||||
in `volve_dia/t4_pandas.py`; `scripts/08_t4_questions.py` compares the two on every candidate instance.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import datetime as dt
|
||||
import hashlib
|
||||
import json
|
||||
import math
|
||||
import re
|
||||
import unicodedata
|
||||
from dataclasses import dataclass, field
|
||||
from fractions import Fraction
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
import yaml
|
||||
|
||||
from .names import canonical, well_of
|
||||
|
||||
NOT_REPORTED = "not reported"
|
||||
ANSWER_TYPES = ("number", "date", "string", "enumeration", "boolean", "list")
|
||||
EVIDENCE_MODES = ("all", "any", "group")
|
||||
SLOT_TYPES = ("wellbore", "inch", "number", "date", "string")
|
||||
FAMILIES = ("lookup", "aggregation", "temporal_event", "comparison", "multi_hop")
|
||||
SCOPES = ("single", "pair", "field")
|
||||
#: Reasons the engine itself assigns; a template may add its own through the `drop_reason` column.
|
||||
DROP_NULL, DROP_DUPLICATE, DROP_NO_EVIDENCE = "null_answer", "duplicate", "no_evidence"
|
||||
_PARAM = re.compile(r"\$([A-Za-z_][A-Za-z0-9_]*)")
|
||||
_FIELD = re.compile(r"\{([A-Za-z_][A-Za-z0-9_]*)\}")
|
||||
|
||||
|
||||
# ----------------------------------------------------------------------------------------------------------------------
|
||||
# Templates
|
||||
# ----------------------------------------------------------------------------------------------------------------------
|
||||
|
||||
class TemplateError(ValueError):
|
||||
"""A template of the configuration is malformed, or its SQL returned something the rules do not allow."""
|
||||
|
||||
|
||||
def load_config(path: Path | str) -> dict:
|
||||
"""Read and validate `configs/t4_templates.yaml`. Returns the configuration with only the enabled templates in
|
||||
`templates`; disabled ones (the WITSML and formation-tops proposals) are kept in `disabled`."""
|
||||
cfg = yaml.safe_load(Path(path).read_text(encoding="utf-8"))
|
||||
templates = cfg.get("templates") or []
|
||||
ids = [t.get("id") for t in templates]
|
||||
if len(set(ids)) != len(ids):
|
||||
raise TemplateError(f"duplicate template ids: {sorted(i for i in set(ids) if ids.count(i) > 1)}")
|
||||
for t in templates:
|
||||
validate_template(t)
|
||||
cfg["disabled"] = [t for t in templates if not t.get("enabled", True)] + list(cfg.get("planned") or [])
|
||||
cfg["templates"] = [t for t in templates if t.get("enabled", True)]
|
||||
return cfg
|
||||
|
||||
|
||||
def validate_template(t: dict) -> None:
|
||||
tid = t.get("id", "?")
|
||||
|
||||
def need(cond: bool, msg: str) -> None:
|
||||
if not cond:
|
||||
raise TemplateError(f"template {tid}: {msg}")
|
||||
|
||||
for key in ("id", "family", "tadi", "questions", "slots", "slots_sql", "answer_sql", "evidence_sql",
|
||||
"evidence_mode", "answer", "source"):
|
||||
need(key in t, f"missing key {key!r}")
|
||||
need(t["family"] in FAMILIES, f"unknown family {t['family']!r}")
|
||||
need(t.get("scope", "single") in SCOPES, f"unknown scope {t.get('scope')!r}")
|
||||
need(t["evidence_mode"] in EVIDENCE_MODES, f"unknown evidence_mode {t['evidence_mode']!r}")
|
||||
need(t.get("on_null", "drop") in ("drop", "not_reported"), "on_null must be drop or not_reported")
|
||||
need(isinstance(t["questions"], list) and t["questions"], "questions must be a non-empty list")
|
||||
answer = t["answer"]
|
||||
need(answer.get("type") in ANSWER_TYPES, f"unknown answer type {answer.get('type')!r}")
|
||||
if answer["type"] == "list":
|
||||
need(answer.get("item_type") in ("number", "string"), "a list answer needs item_type number or string")
|
||||
if answer["type"] == "number" or answer.get("item_type") == "number":
|
||||
tol = answer.get("tolerance") or {}
|
||||
need("unit" in answer, "a numeric answer needs a unit (null for a pure count is not allowed: name what "
|
||||
"is counted)")
|
||||
need("abs" in tol or "rel" in tol, "a numeric answer needs tolerance.abs and/or tolerance.rel")
|
||||
slots = t["slots"]
|
||||
for name, spec in slots.items():
|
||||
need(spec.get("type") in SLOT_TYPES, f"slot {name}: unknown type {spec.get('type')!r}")
|
||||
if t.get("scope", "single") != "field":
|
||||
need(any(s["type"] == "wellbore" for s in slots.values()), "a single or pair template needs a wellbore slot")
|
||||
for pattern in t["questions"]:
|
||||
unknown = set(_FIELD.findall(pattern)) - set(slots)
|
||||
need(not unknown, f"question uses undeclared slots {sorted(unknown)}")
|
||||
for key in ("answer_sql", "evidence_sql"):
|
||||
unknown = set(_PARAM.findall(t[key])) - set(slots)
|
||||
need(not unknown, f"{key} uses undeclared parameters {sorted(unknown)}")
|
||||
for spec_key in ("sample", "negatives"):
|
||||
if spec_key in t:
|
||||
cap = t[spec_key]
|
||||
need(isinstance(cap.get("n"), int) and cap["n"] > 0, f"{spec_key}.n must be a positive int")
|
||||
need(set(cap.get("by", [])) <= set(slots) | {"answer"}, f"{spec_key}.by must name slots or 'answer'")
|
||||
need("negatives" not in t or t.get("on_null") == "not_reported", "negatives needs on_null: not_reported")
|
||||
|
||||
|
||||
# ----------------------------------------------------------------------------------------------------------------------
|
||||
# Rendering
|
||||
# ----------------------------------------------------------------------------------------------------------------------
|
||||
|
||||
def sql_literal(value: Any) -> str:
|
||||
if value is None:
|
||||
return "NULL"
|
||||
if isinstance(value, bool):
|
||||
return "TRUE" if value else "FALSE"
|
||||
if isinstance(value, (int, float)):
|
||||
if isinstance(value, float) and not math.isfinite(value):
|
||||
raise TemplateError(f"not a finite number: {value!r}")
|
||||
return repr(value)
|
||||
return "'" + str(value).replace("'", "''") + "'"
|
||||
|
||||
|
||||
def render_sql(sql: str, slots: dict) -> str:
|
||||
"""The SQL with every `$slot` replaced by the literal of its value: what is executed and what is stored."""
|
||||
return _PARAM.sub(lambda m: sql_literal(slots[m.group(1)]), sql).strip()
|
||||
|
||||
|
||||
def format_number(x: float, decimals: int | None = None) -> str:
|
||||
"""'3520' for 3520.0, '1.48' for 1.48: how a number is written in a question or an answer text."""
|
||||
if decimals is not None:
|
||||
x = round(x, decimals)
|
||||
return str(int(x)) if float(x).is_integer() else repr(float(x))
|
||||
|
||||
|
||||
def format_inch(x: float) -> str:
|
||||
"""Hole, bit and casing sizes as the reports write them, with the decimal value: 12.25 -> '12 1/4" (12.25 in)'."""
|
||||
frac = Fraction(x).limit_denominator(16)
|
||||
if abs(float(frac) - x) > 1e-9:
|
||||
return f"{format_number(x)} in"
|
||||
whole, rest = divmod(frac, 1)
|
||||
if rest == 0:
|
||||
return f'{whole}"'
|
||||
return f'{whole} {rest.numerator}/{rest.denominator}" ({format_number(x)} in)'
|
||||
|
||||
|
||||
def display(slot_type: str, value: Any) -> str:
|
||||
if slot_type == "inch":
|
||||
return format_inch(float(value))
|
||||
if slot_type == "number":
|
||||
return format_number(float(value))
|
||||
return str(value)
|
||||
|
||||
|
||||
def render_question(pattern: str, slot_specs: dict, slots: dict) -> str:
|
||||
return pattern.format(**{k: display(slot_specs[k]["type"], v) for k, v in slots.items()})
|
||||
|
||||
|
||||
def evidence_id(table: str, report_id: str, seq: int | None = None) -> str:
|
||||
"""'activities:15_9_F_4_2008_02_19:10', 'reports:15_9_F_4_2008_02_19' (a report row has no sequence number)."""
|
||||
return f"{table}:{report_id}" if seq is None else f"{table}:{report_id}:{int(seq)}"
|
||||
|
||||
|
||||
def slot_key(template_id: str, slots: dict) -> str:
|
||||
return template_id + "|" + json.dumps(slots, sort_keys=True, ensure_ascii=False)
|
||||
|
||||
|
||||
def _rank(seed: int, key: str) -> str:
|
||||
return hashlib.sha256(f"{seed}|{key}".encode()).hexdigest()
|
||||
|
||||
|
||||
# ----------------------------------------------------------------------------------------------------------------------
|
||||
# Instantiation
|
||||
# ----------------------------------------------------------------------------------------------------------------------
|
||||
|
||||
@dataclass
|
||||
class Outcome:
|
||||
"""What one candidate instance (one row of the slot enumeration) of a template came to."""
|
||||
template_id: str
|
||||
slots: dict
|
||||
status: str # "ok", "not_reported" or "drop"
|
||||
reason: str | None = None # the drop reason
|
||||
answer: Any = None
|
||||
evidence: list[dict] = field(default_factory=list) # {"table", "report_id", "seq", "group"}
|
||||
sql: str = ""
|
||||
evidence_sql: str = ""
|
||||
|
||||
@property
|
||||
def key(self) -> str:
|
||||
return slot_key(self.template_id, self.slots)
|
||||
|
||||
def evidence_partition(self) -> frozenset[frozenset[str]]:
|
||||
"""The evidence as a set of groups of row ids: the form in which two implementations are compared."""
|
||||
groups: dict[int, set[str]] = {}
|
||||
for e in self.evidence:
|
||||
groups.setdefault(e["group"], set()).add(evidence_id(e["table"], e["report_id"], e["seq"]))
|
||||
return frozenset(frozenset(g) for g in groups.values())
|
||||
|
||||
|
||||
def _py(value: Any) -> Any:
|
||||
"""DuckDB and numpy scalars as plain Python values (None for NULL and NaN)."""
|
||||
if value is None:
|
||||
return None
|
||||
if hasattr(value, "item"):
|
||||
value = value.item()
|
||||
if isinstance(value, float) and math.isnan(value):
|
||||
return None
|
||||
if isinstance(value, (dt.datetime, dt.date)):
|
||||
return value.isoformat()[:10]
|
||||
return value
|
||||
|
||||
|
||||
def coerce_answer(spec: dict, values: list[Any]) -> Any:
|
||||
"""The answer SQL's `answer` column as the gold answer of the template's type."""
|
||||
kind = spec["type"]
|
||||
|
||||
def one(v: Any, item_kind: str) -> Any:
|
||||
if item_kind == "number":
|
||||
v = float(v)
|
||||
return round(v, spec["round"]) if "round" in spec else v
|
||||
if item_kind == "boolean":
|
||||
return bool(v)
|
||||
return str(v)
|
||||
|
||||
if kind == "list":
|
||||
return [one(v, spec["item_type"]) for v in values]
|
||||
return one(values[0], kind if kind in ("number", "boolean") else "string")
|
||||
|
||||
|
||||
def group_evidence(mode: str, rows: list[dict]) -> list[dict]:
|
||||
"""Evidence rows with their group number: one group per row (`all`), one group (`any`) or the `grp` column."""
|
||||
rows = sorted(rows, key=lambda r: (r["table"], r["report_id"], -1 if r["seq"] is None else r["seq"]))
|
||||
seen, out = set(), []
|
||||
labels: dict[Any, int] = {}
|
||||
for r in rows:
|
||||
rid = evidence_id(r["table"], r["report_id"], r["seq"])
|
||||
if (rid, r.get("grp")) in seen:
|
||||
continue
|
||||
seen.add((rid, r.get("grp")))
|
||||
if mode == "all":
|
||||
group = len(out)
|
||||
elif mode == "any":
|
||||
group = 0
|
||||
else:
|
||||
group = labels.setdefault(r["grp"], len(labels))
|
||||
out.append({"table": r["table"], "report_id": r["report_id"], "seq": r["seq"], "group": group})
|
||||
return out
|
||||
|
||||
|
||||
def _rows(con, sql: str) -> list[dict]:
|
||||
cur = con.execute(sql)
|
||||
cols = [d[0] for d in cur.description]
|
||||
return [dict(zip(cols, (_py(v) for v in row))) for row in cur.fetchall()]
|
||||
|
||||
|
||||
def run_instance(con, tpl: dict, slots: dict) -> Outcome:
|
||||
"""Run the answer SQL and the evidence SQL of one candidate instance and apply the drop rules."""
|
||||
spec = tpl["answer"]
|
||||
sql, ev_sql = render_sql(tpl["answer_sql"], slots), render_sql(tpl["evidence_sql"], slots)
|
||||
out = Outcome(tpl["id"], slots, "drop", sql=sql, evidence_sql=ev_sql)
|
||||
rows = _rows(con, sql)
|
||||
if rows and "answer" not in rows[0]:
|
||||
raise TemplateError(f"template {tpl['id']}: the answer SQL has no `answer` column")
|
||||
reasons = [r["drop_reason"] for r in rows if r.get("drop_reason")]
|
||||
if reasons:
|
||||
out.reason = reasons[0]
|
||||
return out
|
||||
values = [r["answer"] for r in rows if r["answer"] is not None]
|
||||
if spec["type"] != "list" and len(rows) > 1:
|
||||
raise TemplateError(f"template {tpl['id']}: {len(rows)} answer rows for {slots} (a scalar answer needs one)")
|
||||
if not values:
|
||||
if tpl.get("on_null", "drop") == "not_reported":
|
||||
out.status, out.answer = "not_reported", NOT_REPORTED
|
||||
else:
|
||||
out.reason = DROP_NULL
|
||||
return out
|
||||
out.answer = coerce_answer(spec, values)
|
||||
ev_rows = _rows(con, ev_sql)
|
||||
for r in ev_rows:
|
||||
r.setdefault("seq", None)
|
||||
if tpl["evidence_mode"] == "group" and "grp" not in r:
|
||||
raise TemplateError(f"template {tpl['id']}: evidence_mode group needs a `grp` column")
|
||||
out.evidence = group_evidence(tpl["evidence_mode"], ev_rows)
|
||||
if not out.evidence and not (spec["type"] == "boolean" and out.answer is False):
|
||||
out.reason = DROP_NO_EVIDENCE # an answer that no row supports is not a benchmark item
|
||||
return out
|
||||
out.status = "ok"
|
||||
return out
|
||||
|
||||
|
||||
def run_template(con, tpl: dict) -> list[Outcome]:
|
||||
"""Every candidate instance of a template, in the order of its slot enumeration."""
|
||||
slot_names = list(tpl["slots"])
|
||||
cur = con.execute(tpl["slots_sql"])
|
||||
cols = [d[0] for d in cur.description]
|
||||
if cols != slot_names:
|
||||
raise TemplateError(f"template {tpl['id']}: slots_sql returns {cols}, the template declares {slot_names}")
|
||||
outcomes, seen = [], set()
|
||||
for row in cur.fetchall():
|
||||
slots = dict(zip(cols, (_py(v) for v in row)))
|
||||
if any(v is None for v in slots.values()):
|
||||
raise TemplateError(f"template {tpl['id']}: NULL slot value in {slots}")
|
||||
o = run_instance(con, tpl, slots)
|
||||
if o.key in seen:
|
||||
o.status, o.reason = "drop", DROP_DUPLICATE
|
||||
seen.add(o.key)
|
||||
outcomes.append(o)
|
||||
return outcomes
|
||||
|
||||
|
||||
def _sample(outcomes: list[Outcome], spec: dict | None, seed: int) -> tuple[list[Outcome], int]:
|
||||
"""At most `n` outcomes per group of `by` (slot names or 'answer'), chosen by a seeded hash of the instance key,
|
||||
so the choice does not depend on the order of the enumeration."""
|
||||
if not spec:
|
||||
return outcomes, 0
|
||||
groups: dict[tuple, list[Outcome]] = {}
|
||||
for o in outcomes:
|
||||
key = tuple(json.dumps(o.answer if b == "answer" else o.slots[b], sort_keys=True) for b in spec.get("by", []))
|
||||
groups.setdefault(key, []).append(o)
|
||||
kept = [o for g in groups.values() for o in sorted(g, key=lambda o: _rank(seed, o.key))[:spec["n"]]]
|
||||
return kept, len(outcomes) - len(kept)
|
||||
|
||||
|
||||
def select(tpl: dict, outcomes: list[Outcome], seed: int) -> tuple[list[Outcome], dict]:
|
||||
"""The instances that become questions: answerable ones (capped by `sample`) and, for `on_null: not_reported`,
|
||||
unanswerable ones (capped by `negatives`)."""
|
||||
ok, n_ok = _sample([o for o in outcomes if o.status == "ok"], tpl.get("sample"), seed)
|
||||
neg, n_neg = _sample([o for o in outcomes if o.status == "not_reported"], tpl.get("negatives"), seed)
|
||||
return ok + neg, {"answerable": n_ok, "unanswerable": n_neg}
|
||||
|
||||
|
||||
def _choices(con, tpl: dict, slots: dict) -> list[str] | None:
|
||||
spec = tpl["answer"].get("choices")
|
||||
if not spec:
|
||||
return None
|
||||
if "slots" in spec:
|
||||
return [str(slots[s]) for s in spec["slots"]]
|
||||
if "_choices" not in tpl:
|
||||
tpl["_choices"] = [str(r[0]) for r in con.execute(spec["sql"]).fetchall()]
|
||||
return tpl["_choices"]
|
||||
|
||||
|
||||
def answer_text(spec: dict, answer: Any) -> str:
|
||||
"""The gold answer as a reader would write it: '3520 m', '2007-08-26', '36, 26, 17.5 in', 'yes'."""
|
||||
unit = f" {spec['unit']}" if spec.get("unit") else ""
|
||||
if answer == NOT_REPORTED:
|
||||
return NOT_REPORTED
|
||||
if spec["type"] == "number":
|
||||
return format_number(answer) + unit
|
||||
if spec["type"] == "boolean":
|
||||
return "yes" if answer else "no"
|
||||
if spec["type"] == "list":
|
||||
items = [format_number(v) if spec["item_type"] == "number" else str(v) for v in answer]
|
||||
return ", ".join(items) + unit
|
||||
return str(answer)
|
||||
|
||||
|
||||
def make_question(con, tpl: dict, o: Outcome, all_wellbores: list[str], seed: int) -> dict:
|
||||
spec, tol = tpl["answer"], tpl["answer"].get("tolerance") or {}
|
||||
scope = tpl.get("scope", "single")
|
||||
if scope == "field":
|
||||
wellbores = list(all_wellbores)
|
||||
else:
|
||||
wellbores = [canonical(o.slots[k]) for k, s in tpl["slots"].items() if s["type"] == "wellbore"]
|
||||
wells = sorted({well_of(w) for w in wellbores})
|
||||
pattern_index = int(_rank(seed, "pattern|" + o.key), 16) % len(tpl["questions"])
|
||||
digest = hashlib.sha256(o.key.encode()).hexdigest()[:10]
|
||||
return {
|
||||
"id": f"T4-{tpl['id']}-{digest}",
|
||||
"template_id": tpl["id"],
|
||||
"family": tpl["family"],
|
||||
"tadi_category": tpl["tadi"].get("category"),
|
||||
"tadi_subcategory": tpl["tadi"].get("subcategory"),
|
||||
"scope": scope,
|
||||
"wellbore": None if scope == "field" else wellbores[0],
|
||||
"well": None if scope == "field" else well_of(wellbores[0]),
|
||||
"wellbores": wellbores,
|
||||
"wells": wells,
|
||||
"question": render_question(tpl["questions"][pattern_index], tpl["slots"], o.slots),
|
||||
"pattern_index": pattern_index,
|
||||
"slots": o.slots,
|
||||
"answer": o.answer,
|
||||
"answer_text": answer_text(spec, o.answer),
|
||||
"answer_type": spec["type"],
|
||||
"item_type": spec.get("item_type"),
|
||||
"unit": spec.get("unit"),
|
||||
"tolerance_abs": tol.get("abs"),
|
||||
"tolerance_rel": tol.get("rel"),
|
||||
"tolerance_days": tol.get("days", 0) if spec["type"] == "date" else None,
|
||||
"choices": _choices(con, tpl, o.slots),
|
||||
"answerable": o.status == "ok",
|
||||
"sql": o.sql,
|
||||
"evidence_sql": o.evidence_sql,
|
||||
"evidence": o.evidence,
|
||||
"evidence_mode": tpl["evidence_mode"],
|
||||
"printed_in_render": bool((tpl.get("render") or {}).get("printed", True)),
|
||||
"n_evidence": len(o.evidence),
|
||||
"n_evidence_groups": len({e["group"] for e in o.evidence}),
|
||||
"source": list(tpl["source"]),
|
||||
"caveats": list(tpl.get("caveats") or []),
|
||||
}
|
||||
|
||||
|
||||
def build(con, cfg: dict) -> tuple[list[dict], dict[str, list[Outcome]], dict]:
|
||||
"""All questions, the outcome of every candidate instance per template (for the cross-check) and the summary."""
|
||||
seed = int(cfg.get("seed", 0))
|
||||
all_wellbores = [r[0] for r in con.execute("SELECT DISTINCT wellbore FROM reports ORDER BY 1").fetchall()]
|
||||
questions, outcomes, per_template = [], {}, {}
|
||||
texts: dict[str, str] = {}
|
||||
for tpl in cfg["templates"]:
|
||||
outs = run_template(con, tpl)
|
||||
outcomes[tpl["id"]] = outs
|
||||
kept, not_sampled = select(tpl, outs, seed)
|
||||
drops: dict[str, int] = {}
|
||||
for o in outs:
|
||||
if o.status == "drop":
|
||||
drops[o.reason] = drops.get(o.reason, 0) + 1
|
||||
n_q = {"answerable": 0, "unanswerable": 0}
|
||||
for o in sorted(kept, key=lambda o: o.key):
|
||||
q = make_question(con, tpl, o, all_wellbores, seed)
|
||||
if q["question"] in texts: # the same text from two instances: keep the first only
|
||||
drops[DROP_DUPLICATE] = drops.get(DROP_DUPLICATE, 0) + 1
|
||||
continue
|
||||
texts[q["question"]] = q["id"]
|
||||
questions.append(q)
|
||||
n_q["answerable" if q["answerable"] else "unanswerable"] += 1
|
||||
per_template[tpl["id"]] = {
|
||||
"family": tpl["family"], "answer_type": tpl["answer"]["type"], "candidates": len(outs),
|
||||
"dropped": dict(sorted(drops.items())), "not_sampled": not_sampled,
|
||||
"questions": n_q["answerable"] + n_q["unanswerable"], **n_q,
|
||||
}
|
||||
if len({q["id"] for q in questions}) != len(questions):
|
||||
raise TemplateError("question ids are not unique")
|
||||
return questions, outcomes, summarise(questions, per_template)
|
||||
|
||||
|
||||
def summarise(questions: list[dict], per_template: dict) -> dict:
|
||||
def count(key) -> dict:
|
||||
out: dict[str, int] = {}
|
||||
for q in questions:
|
||||
k = key(q)
|
||||
out[k] = out.get(k, 0) + 1
|
||||
return dict(sorted(out.items()))
|
||||
|
||||
drops: dict[str, int] = {}
|
||||
for t in per_template.values():
|
||||
for reason, n in t["dropped"].items():
|
||||
drops[reason] = drops.get(reason, 0) + n
|
||||
sizes = sorted(q["n_evidence"] for q in questions if q["answerable"] and q["n_evidence"])
|
||||
return {
|
||||
"questions": len(questions),
|
||||
"answerable": sum(q["answerable"] for q in questions),
|
||||
"unanswerable": sum(not q["answerable"] for q in questions),
|
||||
"templates": len(per_template),
|
||||
"candidates": sum(t["candidates"] for t in per_template.values()),
|
||||
"dropped": dict(sorted(drops.items())),
|
||||
"dropped_total": sum(drops.values()),
|
||||
"not_sampled": {k: sum(t["not_sampled"][k] for t in per_template.values())
|
||||
for k in ("answerable", "unanswerable")},
|
||||
"per_family": count(lambda q: q["family"]),
|
||||
"per_answer_type": count(lambda q: q["answer_type"]),
|
||||
"per_scope": count(lambda q: q["scope"]),
|
||||
"per_tadi_category": count(lambda q: str(q["tadi_category"])),
|
||||
"per_wellbore": count(lambda q: q["wellbore"] or "(field)"),
|
||||
"per_well": count(lambda q: q["well"] or "(field)"),
|
||||
"evidence_rows": {"min": sizes[0], "median": sizes[len(sizes) // 2], "max": sizes[-1],
|
||||
"over_50": sum(s > 50 for s in sizes)} if sizes else {},
|
||||
"per_template": per_template,
|
||||
}
|
||||
|
||||
|
||||
def connect(db_path: Path | str):
|
||||
"""The DDR database, read-only, with the session time zone fixed so no result depends on the machine."""
|
||||
import duckdb
|
||||
|
||||
con = duckdb.connect(str(db_path), read_only=True)
|
||||
con.execute("SET TimeZone = 'UTC'")
|
||||
return con
|
||||
|
||||
|
||||
def write(questions: list[dict], out_dir: Path) -> None:
|
||||
"""questions.jsonl (native values) and questions.parquet (answer and slots as JSON text; evidence as a list of
|
||||
{table, report_id, seq, group} structs, seq NULL for a row of `reports`)."""
|
||||
import pyarrow as pa
|
||||
import pyarrow.parquet as pq
|
||||
|
||||
out_dir.mkdir(parents=True, exist_ok=True)
|
||||
with (out_dir / "questions.jsonl").open("w", encoding="utf-8") as f:
|
||||
for q in questions:
|
||||
f.write(json.dumps(q, ensure_ascii=False) + "\n")
|
||||
strings = pa.list_(pa.string())
|
||||
types = {
|
||||
"tadi_category": pa.int8(), "pattern_index": pa.int16(), "n_evidence": pa.int32(),
|
||||
"n_evidence_groups": pa.int32(), "tolerance_abs": pa.float64(), "tolerance_rel": pa.float64(),
|
||||
"tolerance_days": pa.int16(), "answerable": pa.bool_(), "printed_in_render": pa.bool_(),
|
||||
"wellbores": strings, "wells": strings, "choices": strings, "source": strings, "caveats": strings,
|
||||
"evidence": pa.list_(pa.struct([("table", pa.string()), ("report_id", pa.string()), ("seq", pa.int32()),
|
||||
("group", pa.int32())])),
|
||||
}
|
||||
as_json = ("answer", "slots")
|
||||
columns = list(questions[0]) if questions else []
|
||||
arrays = []
|
||||
for col in columns:
|
||||
values = [q[col] for q in questions]
|
||||
if col in as_json:
|
||||
values = [json.dumps(v, ensure_ascii=False, sort_keys=True) for v in values]
|
||||
arrays.append(pa.array(values, type=types.get(col, pa.string())))
|
||||
pq.write_table(pa.Table.from_arrays(arrays, names=columns), out_dir / "questions.parquet")
|
||||
|
||||
|
||||
def read_jsonl(path: Path | str) -> list[dict]:
|
||||
with Path(path).open(encoding="utf-8") as f:
|
||||
return [json.loads(line) for line in f if line.strip()]
|
||||
|
||||
|
||||
# ----------------------------------------------------------------------------------------------------------------------
|
||||
# Scoring
|
||||
# ----------------------------------------------------------------------------------------------------------------------
|
||||
|
||||
#: Factor from a unit to the reference unit of its dimension. A prediction in another unit of the same dimension is
|
||||
#: converted before the tolerance is applied; a unit of another dimension, or an unknown one, is a wrong answer.
|
||||
UNITS = {
|
||||
"m": ("length", 1.0), "ft": ("length", 0.3048), "km": ("length", 1000.0), "metres": ("length", 1.0),
|
||||
"meters": ("length", 1.0), "feet": ("length", 0.3048),
|
||||
"h": ("time", 1.0), "hr": ("time", 1.0), "hrs": ("time", 1.0), "hour": ("time", 1.0), "hours": ("time", 1.0),
|
||||
"min": ("time", 1 / 60), "d": ("time", 24.0), "day": ("time", 24.0), "days": ("time", 24.0),
|
||||
"g/cm3": ("density", 1.0), "sg": ("density", 1.0), "kg/l": ("density", 1.0), "kg/m3": ("density", 0.001),
|
||||
"ppg": ("density", 0.119826427),
|
||||
"m/h": ("rate", 1.0), "m/hr": ("rate", 1.0), "ft/h": ("rate", 0.3048), "ft/hr": ("rate", 0.3048),
|
||||
"deg": ("angle", 1.0), "dega": ("angle", 1.0), "degrees": ("angle", 1.0), "°": ("angle", 1.0),
|
||||
"in": ("size", 1.0), "inch": ("size", 1.0), "inches": ("size", 1.0), '"': ("size", 1.0),
|
||||
}
|
||||
_ABSTAIN = re.compile(r"^\W*(not\s+(reported|available|recorded|stated|found|applicable)|no\s+(such\s+)?(record|data|"
|
||||
r"information|event|activity|value)\w*(\s.*)?|unknown|n/?a|none|null|unanswerable|"
|
||||
r"cannot\s+be\s+(determined|answered).*)\W*$", re.I)
|
||||
_NUMBER = re.compile(r"[-+]?\d[\d,]*(?:\.\d+)?(?:[eE][-+]?\d+)?|[-+]?\.\d+")
|
||||
_REPORT_ID = re.compile(r"\d+_\d+_.+_\d{4}_\d{2}_\d{2}")
|
||||
_DATE_FORMATS = ("%Y-%m-%d", "%d.%m.%Y", "%d/%m/%Y", "%d-%m-%Y", "%d %B %Y", "%d %b %Y", "%B %d, %Y", "%b %d, %Y",
|
||||
"%B %d %Y", "%b %d %Y", "%Y/%m/%d")
|
||||
|
||||
|
||||
def is_abstention(answer: Any) -> bool:
|
||||
"""None, an empty string or a phrase such as 'not reported', 'N/A', 'no such event'."""
|
||||
if answer is None:
|
||||
return True
|
||||
if isinstance(answer, (list, tuple)):
|
||||
return len(answer) == 0
|
||||
if isinstance(answer, str):
|
||||
return not answer.strip() or bool(_ABSTAIN.match(answer.strip()))
|
||||
return False
|
||||
|
||||
|
||||
def parse_number(value: Any) -> float | None:
|
||||
"""A number from a number or from text ('3,520 m', '1,48', '12 1/4"'). The first number of the text is used;
|
||||
'1,48' is read as a decimal comma, '3,520' as a thousands separator."""
|
||||
if isinstance(value, bool):
|
||||
return None
|
||||
if isinstance(value, (int, float)):
|
||||
return float(value) if math.isfinite(value) else None
|
||||
if not isinstance(value, str):
|
||||
return None
|
||||
mixed = re.match(r'^\s*(\d+)\s+(\d+)/(\d+)\s*("|in\b|inch)?', value) # 12 1/4"
|
||||
if mixed and int(mixed.group(3)):
|
||||
return int(mixed.group(1)) + int(mixed.group(2)) / int(mixed.group(3))
|
||||
m = _NUMBER.search(value)
|
||||
if not m:
|
||||
return None
|
||||
text = m.group(0).rstrip(",")
|
||||
if "," in text:
|
||||
if re.fullmatch(r"[-+]?\d{1,3}(,\d{3})+(\.\d+)?", text):
|
||||
text = text.replace(",", "")
|
||||
elif text.count(",") == 1 and "." not in text:
|
||||
text = text.replace(",", ".")
|
||||
else:
|
||||
text = text.replace(",", "")
|
||||
try:
|
||||
return float(text)
|
||||
except ValueError:
|
||||
return None
|
||||
|
||||
|
||||
def parse_date(value: Any) -> dt.date | None:
|
||||
if isinstance(value, dt.datetime):
|
||||
return value.date()
|
||||
if isinstance(value, dt.date):
|
||||
return value
|
||||
if not isinstance(value, str):
|
||||
return None
|
||||
text = value.strip()
|
||||
m = re.match(r"\d{4}-\d{2}-\d{2}", text)
|
||||
if m:
|
||||
text = m.group(0)
|
||||
for fmt in _DATE_FORMATS:
|
||||
try:
|
||||
return dt.datetime.strptime(text, fmt).date()
|
||||
except ValueError:
|
||||
continue
|
||||
return None
|
||||
|
||||
|
||||
def parse_boolean(value: Any) -> bool | None:
|
||||
if isinstance(value, bool):
|
||||
return value
|
||||
if isinstance(value, (int, float)) and value in (0, 1):
|
||||
return bool(value)
|
||||
if isinstance(value, str):
|
||||
m = re.match(r"^\W*(yes|true|no|false)\b", value.strip(), re.I)
|
||||
if m:
|
||||
return m.group(1).lower() in ("yes", "true")
|
||||
return None
|
||||
|
||||
|
||||
def normalise_text(value: Any) -> str:
|
||||
"""Case, accents, punctuation and spacing removed: 'Mærsk Inspirer.' and 'MÆRSK INSPIRER' compare equal."""
|
||||
text = unicodedata.normalize("NFKD", str(value)).casefold()
|
||||
text = "".join(c for c in text if not unicodedata.combining(c))
|
||||
return re.sub(r"[^0-9a-zæøå]+", " ", text).strip()
|
||||
|
||||
|
||||
def _same_text(pred: Any, gold: str) -> bool:
|
||||
if normalise_text(pred) == normalise_text(gold):
|
||||
return True
|
||||
try: # wellbore names: 'NO 15/9-F-1 B', '15_9_F_1_B'
|
||||
return canonical(str(pred)) == canonical(gold)
|
||||
except ValueError:
|
||||
return False
|
||||
|
||||
|
||||
def convert_unit(value: float, unit: str | None, gold_unit: str | None) -> float | None:
|
||||
"""`value` in `unit` expressed in `gold_unit`; None if the two are not of the same known dimension. A prediction
|
||||
without a unit is taken to be in the gold unit. A gold unit that names what is counted ('reports', 'entries')
|
||||
is a label, not a physical unit: the predicted unit is then ignored."""
|
||||
if not unit or not gold_unit:
|
||||
return value
|
||||
u, g = unit.strip().lower().replace(" ", ""), gold_unit.strip().lower()
|
||||
if u == g or g not in UNITS:
|
||||
return value
|
||||
if u not in UNITS or UNITS[u][0] != UNITS[g][0]:
|
||||
return None
|
||||
return value * UNITS[u][1] / UNITS[g][1]
|
||||
|
||||
|
||||
def within_tolerance(pred: float, gold: float, abs_tol: float | None = None, rel_tol: float | None = None) -> bool:
|
||||
"""|pred - gold| <= max(abs_tol, rel_tol * |gold|), with a small allowance for floating-point noise."""
|
||||
limit = max(abs_tol or 0.0, (rel_tol or 0.0) * abs(gold))
|
||||
return abs(pred - gold) <= limit + 1e-9 * max(1.0, abs(gold))
|
||||
|
||||
|
||||
def inline_unit(text: Any) -> str | None:
|
||||
"""The unit written after the first number of a text answer ('11548.6 ft' -> 'ft'), if it is a known unit."""
|
||||
if not isinstance(text, str):
|
||||
return None
|
||||
m = _NUMBER.search(text)
|
||||
if not m:
|
||||
return None
|
||||
u = re.match(r"\s*([A-Za-z°\"][A-Za-z0-9/]*)", text[m.end():])
|
||||
return u.group(1).lower() if u and u.group(1).lower() in UNITS else None
|
||||
|
||||
|
||||
def _match_value(pred: Any, gold: Any, kind: str, q: dict, unit: str | None) -> bool:
|
||||
if kind == "number":
|
||||
p = parse_number(pred)
|
||||
if p is None:
|
||||
return False
|
||||
unit = unit or inline_unit(pred)
|
||||
p = convert_unit(p, unit, q.get("unit"))
|
||||
return p is not None and within_tolerance(p, float(gold), q.get("tolerance_abs"), q.get("tolerance_rel"))
|
||||
if kind == "date":
|
||||
p = parse_date(pred)
|
||||
return p is not None and abs((p - parse_date(gold)).days) <= (q.get("tolerance_days") or 0)
|
||||
if kind == "boolean":
|
||||
p = parse_boolean(pred)
|
||||
return p is not None and p == bool(gold)
|
||||
return _same_text(pred, gold)
|
||||
|
||||
|
||||
def parse_citation(c: Any) -> str | None:
|
||||
"""A citation as an evidence id. Accepted: {'table', 'report_id', 'seq'}, 'table:report_id:seq',
|
||||
'reports:report_id', an activity id as the DDR tables write it ('15_9_F_4_2008_02_19:010') and a bare report
|
||||
id ('15_9_F_4_2008_02_19', read as the row of `reports`)."""
|
||||
if isinstance(c, dict):
|
||||
if "act_id" in c and "table" not in c:
|
||||
return parse_citation(c["act_id"])
|
||||
if not c.get("table") or not c.get("report_id"):
|
||||
return None
|
||||
return evidence_id(c["table"], c["report_id"], c.get("seq"))
|
||||
if not isinstance(c, str):
|
||||
return None
|
||||
parts = c.strip().split(":")
|
||||
try:
|
||||
if len(parts) == 1 and _REPORT_ID.fullmatch(parts[0]):
|
||||
return evidence_id("reports", parts[0])
|
||||
if len(parts) == 3:
|
||||
return evidence_id(parts[0], parts[1], int(parts[2]))
|
||||
if len(parts) == 2 and parts[1].isdigit() and _REPORT_ID.fullmatch(parts[0]):
|
||||
return evidence_id("activities", parts[0], int(parts[1]))
|
||||
if len(parts) == 2:
|
||||
return evidence_id(parts[0], parts[1])
|
||||
except ValueError:
|
||||
return None
|
||||
return None
|
||||
|
||||
|
||||
def _report_level(eid: str) -> str:
|
||||
return "report:" + eid.split(":")[1]
|
||||
|
||||
|
||||
def score_citations(citations: list | None, evidence: list[dict], level: str = "row") -> dict:
|
||||
"""Citation precision (cited rows that are evidence rows / cited rows) and recall (evidence groups with a cited
|
||||
row / evidence groups). None where the ratio has no denominator: precision without citations, recall for a
|
||||
question without evidence rows. With `level="report"` a citation and an evidence row match when they are in the
|
||||
same report, whatever the table and row: the lenient reading for answers that cite a report rather than a row.
|
||||
A citation that cannot be parsed counts as a cited row that is not evidence."""
|
||||
if level not in ("row", "report"):
|
||||
raise ValueError(f"level must be 'row' or 'report', not {level!r}")
|
||||
parsed = [parse_citation(c) for c in (citations or [])]
|
||||
n_invalid = sum(c is None for c in parsed)
|
||||
cited = {c for c in parsed if c is not None}
|
||||
if level == "report":
|
||||
cited = {_report_level(c) for c in cited}
|
||||
groups: dict[int, set[str]] = {}
|
||||
for e in evidence:
|
||||
eid = evidence_id(e["table"], e["report_id"], e["seq"])
|
||||
groups.setdefault(e["group"], set()).add(_report_level(eid) if level == "report" else eid)
|
||||
gold_ids = set().union(*groups.values()) if groups else set()
|
||||
n_cited = len(cited) + n_invalid
|
||||
return {
|
||||
"n_cited": n_cited,
|
||||
"citation_precision": len(cited & gold_ids) / n_cited if n_cited else None,
|
||||
"citation_recall": sum(bool(g & cited) for g in groups.values()) / len(groups) if groups else None,
|
||||
}
|
||||
|
||||
|
||||
def score(prediction: Any, gold: dict, citation_level: str = "row") -> dict:
|
||||
"""Score one prediction against one question record (a row of questions.jsonl).
|
||||
|
||||
`prediction` is {"answer": ..., "unit": optional, "citations": optional list} or the bare answer. Returns
|
||||
`correct` (type-aware match within the tolerance of the template), `abstained` (the prediction gives no answer),
|
||||
`fabricated` (a concrete answer to a question whose gold answer is "not reported"), the citation scores and, for
|
||||
a list answer, `list_precision` and `list_recall`. An abstention is correct only for an unanswerable question.
|
||||
"""
|
||||
if not (isinstance(prediction, dict) and ("answer" in prediction or "citations" in prediction)):
|
||||
prediction = {"answer": prediction}
|
||||
pred, unit = prediction.get("answer"), prediction.get("unit")
|
||||
kind = gold["answer_type"]
|
||||
answerable = gold.get("answerable", True)
|
||||
abstained = is_abstention(pred)
|
||||
if answerable and kind == "boolean" and parse_boolean(pred) is not None:
|
||||
abstained = False # "No such activity is recorded" answers a yes/no question
|
||||
out = {"correct": False, "abstained": abstained, "fabricated": False}
|
||||
out.update(score_citations(prediction.get("citations"), gold.get("evidence") or [], citation_level))
|
||||
if not answerable:
|
||||
out["correct"] = out["abstained"]
|
||||
out["fabricated"] = not out["abstained"]
|
||||
return out
|
||||
if out["abstained"]:
|
||||
return out
|
||||
if kind == "list":
|
||||
items = pred if isinstance(pred, (list, tuple)) else re.split(r"\s*[;,]\s*|\s+and\s+", str(pred))
|
||||
items = [i for i in items if not (isinstance(i, str) and not i.strip())]
|
||||
left = list(gold["answer"])
|
||||
hits = 0
|
||||
for item in items:
|
||||
for g in left:
|
||||
if _match_value(item, g, gold["item_type"], gold, unit):
|
||||
left.remove(g)
|
||||
hits += 1
|
||||
break
|
||||
out["list_precision"] = hits / len(items) if items else 0.0
|
||||
out["list_recall"] = hits / len(gold["answer"])
|
||||
out["correct"] = hits == len(items) == len(gold["answer"])
|
||||
return out
|
||||
out["correct"] = _match_value(pred, gold["answer"], kind, gold, unit)
|
||||
return out
|
||||
728
volve_dia/t4_pandas.py
Normal file
728
volve_dia/t4_pandas.py
Normal file
@@ -0,0 +1,728 @@
|
||||
"""Second, independent implementation of every T4 template, in pandas on the parquet copies of the DDR tables.
|
||||
|
||||
Purpose: a gold answer that two code paths agree on. `volve_dia/t4.py` computes answers and evidence rows with the
|
||||
SQL of `configs/t4_templates.yaml` on DuckDB; this module computes the same things with pandas on
|
||||
`outputs/ddr/*.parquet`, from the published columns only. The columns that the DDR parser derives are derived again
|
||||
here, in another way:
|
||||
|
||||
wellbore of a row NPD wellbore alias of its report, joined on report_id (parser: `wellbore`)
|
||||
report date last ten characters of report_id (parser: `file_date`)
|
||||
activity start, end `dTimStart`, `dTimEnd` parsed with their UTC offsets (parser: `start_utc`, `end_utc`)
|
||||
activity duration end - start in hours (parser: `duration_h`)
|
||||
main code text before ' -- ' in `proprietaryCode` (parser: `code_main`)
|
||||
well text before the first space of the wellbore name (SQL: split_part)
|
||||
|
||||
Each template has `enumerate(tables) -> list of slot dicts` and `answer(tables, **slots) -> Result`. `crosscheck`
|
||||
compares, for every candidate instance, the slot enumeration, the status (answer, missing answer, drop reason), the
|
||||
answer and the evidence rows with their grouping. The rules themselves (what is a tie, what is dropped) are taken
|
||||
from the template definitions, so an error in a rule is not caught here; an error in its SQL is.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
from typing import Any, Callable
|
||||
|
||||
import pandas as pd
|
||||
|
||||
from .t4 import Outcome, evidence_id, slot_key
|
||||
|
||||
TABLES = ("reports", "activities", "bits", "casings", "surveys", "strat", "fluids", "equip_failures")
|
||||
EVENT_DETAILS = ("stuck equipment", "circulation loss", "mud loss")
|
||||
WOW, DRILL = "interruption -- waiting on weather", "drilling -- drill"
|
||||
PAIR_CODES = (WOW, "interruption -- repair")
|
||||
PRESENCE_CODES = ("interruption -- well control", "interruption -- lost circulation", "interruption -- sidetrack",
|
||||
"interruption -- fish")
|
||||
EXTRA_CODES = (DRILL, "drilling -- trip", "drilling -- casing")
|
||||
|
||||
|
||||
@dataclass
|
||||
class Result:
|
||||
status: str # "ok", "null" (no answer) or "drop"
|
||||
answer: Any = None
|
||||
evidence: frozenset = frozenset() # set of groups, each a frozenset of evidence ids
|
||||
reason: str | None = None
|
||||
|
||||
|
||||
NULL = Result("null")
|
||||
|
||||
|
||||
def dropped(reason: str) -> Result:
|
||||
return Result("drop", reason=reason)
|
||||
|
||||
|
||||
class Tables:
|
||||
"""The DDR tables with the derived columns of this module, split by wellbore."""
|
||||
|
||||
def __init__(self, ddr_dir: Path | str):
|
||||
ddr_dir = Path(ddr_dir)
|
||||
raw = {name: pd.read_parquet(ddr_dir / f"{name}.parquet") for name in TABLES}
|
||||
reports = raw["reports"].copy()
|
||||
reports["wb"] = reports["wellboreAlias_NPD_code"].astype(str)
|
||||
reports["date"] = reports["report_id"].str[-10:].str.replace("_", "-")
|
||||
wb_of, date_of = reports.set_index("report_id")["wb"], reports.set_index("report_id")["date"]
|
||||
self.all: dict[str, pd.DataFrame] = {"reports": reports}
|
||||
for name in TABLES[1:]:
|
||||
df = raw[name].copy()
|
||||
df["wb"] = df["report_id"].map(wb_of)
|
||||
df["date"] = df["report_id"].map(date_of)
|
||||
self.all[name] = df
|
||||
acts = self.all["activities"]
|
||||
acts["t0"] = pd.to_datetime(acts["dTimStart"], utc=True, format="ISO8601")
|
||||
acts["t1"] = pd.to_datetime(acts["dTimEnd"], utc=True, format="ISO8601")
|
||||
acts["dur"] = (acts["t1"] - acts["t0"]).dt.total_seconds() / 3600
|
||||
acts["main"] = acts["proprietaryCode"].str.split(" -- ").str[0]
|
||||
self.all["activities"] = acts.sort_values(["wb", "t0"]).reset_index(drop=True)
|
||||
self.wellbores = sorted(reports["wb"].unique())
|
||||
self._by_wb = {name: {wb: g for wb, g in df.groupby("wb", sort=False)} for name, df in self.all.items()}
|
||||
|
||||
def wb(self, table: str, wellbore: str) -> pd.DataFrame:
|
||||
"""The rows of one wellbore (an empty frame if it has none)."""
|
||||
return self._by_wb[table].get(wellbore, self.all[table].iloc[0:0])
|
||||
|
||||
|
||||
# ----------------------------------------------------------------------------------------------------------------------
|
||||
# Helpers
|
||||
# ----------------------------------------------------------------------------------------------------------------------
|
||||
|
||||
def ids(df: pd.DataFrame, table: str) -> list[str]:
|
||||
if table == "reports":
|
||||
return [evidence_id(table, r) for r in df["report_id"]]
|
||||
return [evidence_id(table, r, s) for r, s in zip(df["report_id"], df["seq"])]
|
||||
|
||||
|
||||
def ev_all(*id_lists: list[str]) -> frozenset:
|
||||
return frozenset(frozenset([i]) for lst in id_lists for i in lst)
|
||||
|
||||
|
||||
def ev_any(id_list: list[str]) -> frozenset:
|
||||
return frozenset([frozenset(id_list)]) if id_list else frozenset()
|
||||
|
||||
|
||||
def ev_groups(groups: dict[Any, list[str]]) -> frozenset:
|
||||
return frozenset(frozenset(v) for v in groups.values() if v)
|
||||
|
||||
|
||||
def well(wellbore: str) -> str:
|
||||
return wellbore.split(" ")[0]
|
||||
|
||||
|
||||
def unique_values(series: pd.Series) -> list:
|
||||
return sorted(series.dropna().unique().tolist())
|
||||
|
||||
|
||||
def single_value(df: pd.DataFrame, column: str, table: str, reason: str = "ambiguous_multiple_values") -> Result:
|
||||
"""The one published value of `column` in `df`; evidence: every row that states it (any one is enough)."""
|
||||
values = unique_values(df[column])
|
||||
if len(values) > 1:
|
||||
return dropped(reason)
|
||||
if not values:
|
||||
return NULL
|
||||
return Result("ok", values[0], ev_any(ids(df[df[column].notna()], table)))
|
||||
|
||||
|
||||
def density(rows: pd.DataFrame) -> Result:
|
||||
rows = rows[rows["density"].notna()]
|
||||
values = unique_values(rows["density"])
|
||||
if len(values) > 1:
|
||||
return dropped("ambiguous_multiple_values")
|
||||
if not values:
|
||||
return NULL
|
||||
if values[0] < 0.5 or values[0] > 3:
|
||||
return dropped("implausible_value")
|
||||
return Result("ok", values[0], ev_any(ids(rows, "fluids")))
|
||||
|
||||
|
||||
def first_event(t: Tables, wellbore: str, detail: str) -> pd.DataFrame:
|
||||
"""The activity (or activities, if tied) of a wellbore with the earliest start among those with the state
|
||||
detail."""
|
||||
e = t.wb("activities", wellbore)
|
||||
e = e[e["stateDetailActivity"] == detail]
|
||||
return e[e["t0"] == e["t0"].min()] if len(e) else e
|
||||
|
||||
|
||||
def section_rop(t: Tables, wellbore: str, hole: float) -> tuple[float | None, bool, list[str]]:
|
||||
"""Metres per hour coded 'drilling -- drill' over the reports of a hole size that state metres drilled.
|
||||
Returns (rop or None, True if a report has metres without drill hours, evidence ids)."""
|
||||
r = t.wb("reports", wellbore)
|
||||
r = r[(r["diaHole"] == hole) & (r["distDrill"] > 0)]
|
||||
if r.empty:
|
||||
return None, False, []
|
||||
a = t.wb("activities", wellbore)
|
||||
a = a[(a["proprietaryCode"] == DRILL) & a["report_id"].isin(set(r["report_id"]))]
|
||||
bad = bool(set(r["report_id"]) - set(a["report_id"]))
|
||||
hours = a["dur"].sum()
|
||||
rop = float(r["distDrill"].sum() / hours) if hours > 0 else None
|
||||
return rop, bad, ids(r, "reports") + ids(a, "activities")
|
||||
|
||||
|
||||
def code_hours(t: Tables, wellbore: str, code: str) -> tuple[float, pd.DataFrame]:
|
||||
a = t.wb("activities", wellbore)
|
||||
a = a[a["proprietaryCode"] == code]
|
||||
return round(float(a["dur"].sum()), 4), a
|
||||
|
||||
|
||||
def slots(df: pd.DataFrame, columns: dict[str, str]) -> list[dict]:
|
||||
"""Distinct rows of `df[columns]` as slot dicts, with the slot names of the template."""
|
||||
out = df[list(columns)].drop_duplicates().rename(columns=columns)
|
||||
return [{k: (v.item() if hasattr(v, "item") else v) for k, v in row.items()} for row in out.to_dict("records")]
|
||||
|
||||
|
||||
def every_wellbore(t: Tables) -> list[dict]:
|
||||
return [{"wellbore": w} for w in t.wellbores]
|
||||
|
||||
|
||||
def hole_slots(t: Tables) -> list[dict]:
|
||||
r = t.all["reports"]
|
||||
return slots(r[r["diaHole"].notna()], {"wb": "wellbore", "diaHole": "hole"})
|
||||
|
||||
|
||||
def event_slots(t: Tables) -> list[dict]:
|
||||
a = t.all["activities"]
|
||||
return slots(a[a["stateDetailActivity"].isin(EVENT_DETAILS)], {"wb": "wellbore", "stateDetailActivity": "detail"})
|
||||
|
||||
|
||||
def all_event_slots(t: Tables) -> list[dict]:
|
||||
return [{"wellbore": w, "detail": d} for w in t.wellbores for d in EVENT_DETAILS]
|
||||
|
||||
|
||||
def same_well_pairs(wellbores: list[str]) -> list[tuple[str, str]]:
|
||||
return [(a, b) for a in wellbores for b in wellbores if a < b and well(a) == well(b)]
|
||||
|
||||
|
||||
# ----------------------------------------------------------------------------------------------------------------------
|
||||
# Lookup
|
||||
# ----------------------------------------------------------------------------------------------------------------------
|
||||
|
||||
def L01_spud_date(t: Tables, wellbore: str) -> Result:
|
||||
r = t.wb("reports", wellbore).assign(spud=lambda d: d["dTimSpud"].str[:10])
|
||||
return single_value(r, "spud", "reports")
|
||||
|
||||
|
||||
def L02_drill_complete_date(t: Tables, wellbore: str) -> Result:
|
||||
r = t.wb("reports", wellbore).assign(done=lambda d: d["dateDrillComplete"].str[:10])
|
||||
return single_value(r, "done", "reports")
|
||||
|
||||
|
||||
def L03_deepest_md(t: Tables, wellbore: str) -> Result:
|
||||
r = t.wb("reports", wellbore)
|
||||
deepest = r["md"].max()
|
||||
if pd.isna(deepest):
|
||||
return NULL
|
||||
return Result("ok", float(deepest), ev_any(ids(r[r["md"] == deepest], "reports")))
|
||||
|
||||
|
||||
def L04_deepest_md_date(t: Tables, wellbore: str) -> Result:
|
||||
r = t.wb("reports", wellbore)
|
||||
at_depth = r[r["md"] == r["md"].max()].sort_values("date")
|
||||
if at_depth.empty:
|
||||
return NULL
|
||||
return Result("ok", at_depth["date"].iloc[0], ev_all(ids(at_depth.iloc[:1], "reports")))
|
||||
|
||||
|
||||
def L05_enumerate(t: Tables) -> list[dict]:
|
||||
return slots(t.all["casings"], {"wb": "wellbore", "od": "od"})
|
||||
|
||||
|
||||
def L05_casing_bottom_md(t: Tables, wellbore: str, od: float) -> Result:
|
||||
c = t.wb("casings", wellbore)
|
||||
c = c[c["od"] == od]
|
||||
deepest = c["mdBottom"].max()
|
||||
if pd.isna(deepest):
|
||||
return NULL
|
||||
return Result("ok", float(deepest), ev_any(ids(c[c["mdBottom"] == deepest], "casings")))
|
||||
|
||||
|
||||
def L06_casing_sizes(t: Tables, wellbore: str) -> Result:
|
||||
c = t.wb("casings", wellbore)
|
||||
sizes = sorted(unique_values(c["od"]), reverse=True)
|
||||
if not sizes:
|
||||
return NULL
|
||||
return Result("ok", sizes, ev_groups({s: ids(c[c["od"] == s], "casings") for s in sizes}))
|
||||
|
||||
|
||||
def L07_hole_sizes(t: Tables, wellbore: str) -> Result:
|
||||
r = t.wb("reports", wellbore)
|
||||
sizes = sorted(unique_values(r["diaHole"]), reverse=True)
|
||||
if not sizes:
|
||||
return NULL
|
||||
return Result("ok", sizes, ev_groups({s: ids(r[r["diaHole"] == s], "reports") for s in sizes}))
|
||||
|
||||
|
||||
def L08_hole_section_start_md(t: Tables, wellbore: str, hole: float) -> Result:
|
||||
r = t.wb("reports", wellbore)
|
||||
return single_value(r[r["diaHole"] == hole], "mdDiaHoleStart", "reports")
|
||||
|
||||
|
||||
def L09_hole_section_max_md(t: Tables, wellbore: str, hole: float) -> Result:
|
||||
r = t.wb("reports", wellbore)
|
||||
r = r[r["diaHole"] == hole]
|
||||
deepest = r["md"].max()
|
||||
if pd.isna(deepest):
|
||||
return NULL
|
||||
return Result("ok", float(deepest), ev_any(ids(r[r["md"] == deepest], "reports")))
|
||||
|
||||
|
||||
def L10_enumerate(t: Tables) -> list[dict]:
|
||||
s = t.all["surveys"]
|
||||
return slots(s[s["incl"].notna()], {"wb": "wellbore"})
|
||||
|
||||
|
||||
def L10_max_inclination(t: Tables, wellbore: str) -> Result:
|
||||
s = t.wb("surveys", wellbore)
|
||||
steepest = s["incl"].max()
|
||||
if pd.isna(steepest):
|
||||
return NULL
|
||||
return Result("ok", float(steepest), ev_any(ids(s[s["incl"] == steepest], "surveys")))
|
||||
|
||||
|
||||
def L11_max_inclination_md(t: Tables, wellbore: str) -> Result:
|
||||
s = t.wb("surveys", wellbore)
|
||||
top = s[s["incl"] == s["incl"].max()]
|
||||
depths = unique_values(top["md"])
|
||||
if len(depths) > 1:
|
||||
return dropped("tie")
|
||||
if not depths:
|
||||
return NULL
|
||||
return Result("ok", depths[0], ev_any(ids(top, "surveys")))
|
||||
|
||||
|
||||
def L12_enumerate(t: Tables) -> list[dict]:
|
||||
f = t.all["fluids"]
|
||||
return slots(f[f["density"].notna()], {"wb": "wellbore", "date": "date"})
|
||||
|
||||
|
||||
def L12_mud_density_on_date(t: Tables, wellbore: str, date: str) -> Result:
|
||||
f = t.wb("fluids", wellbore)
|
||||
return density(f[f["date"] == date])
|
||||
|
||||
|
||||
def L13_enumerate(t: Tables) -> list[dict]:
|
||||
f = t.all["fluids"]
|
||||
return slots(f[(f["md"] > 0) & f["density"].notna()], {"wb": "wellbore", "md": "md"})
|
||||
|
||||
|
||||
def L13_mud_density_at_depth(t: Tables, wellbore: str, md: float) -> Result:
|
||||
f = t.wb("fluids", wellbore)
|
||||
return density(f[f["md"] == md])
|
||||
|
||||
|
||||
def _formation(name: str) -> str:
|
||||
return name.rstrip(" .")
|
||||
|
||||
|
||||
def L14_enumerate(t: Tables) -> list[dict]:
|
||||
s = t.all["strat"].assign(fm=lambda d: d["description"].map(_formation))
|
||||
return slots(s, {"wb": "wellbore", "fm": "formation"})
|
||||
|
||||
|
||||
def L14_formation_top_md(t: Tables, wellbore: str, formation: str) -> Result:
|
||||
s = t.wb("strat", wellbore)
|
||||
return single_value(s[s["description"].map(_formation) == formation], "mdTop", "strat")
|
||||
|
||||
|
||||
def L15_rig_name(t: Tables, wellbore: str) -> Result:
|
||||
return single_value(t.wb("reports", wellbore), "rigAlias_NPD_Name", "reports")
|
||||
|
||||
|
||||
def L16_kickoff_md(t: Tables, wellbore: str) -> Result:
|
||||
return single_value(t.wb("reports", wellbore), "mdKickoff", "reports")
|
||||
|
||||
|
||||
# ----------------------------------------------------------------------------------------------------------------------
|
||||
# Aggregation
|
||||
# ----------------------------------------------------------------------------------------------------------------------
|
||||
|
||||
def A01_reports_per_hole_size(t: Tables, wellbore: str, hole: float) -> Result:
|
||||
r = t.wb("reports", wellbore)
|
||||
r = r[r["diaHole"] == hole]
|
||||
return Result("ok", float(len(r)), ev_all(ids(r, "reports"))) if len(r) else NULL
|
||||
|
||||
|
||||
def A02_enumerate(t: Tables) -> list[dict]:
|
||||
r = t.all["reports"]
|
||||
return slots(r[r["distDrill"] > 0], {"wb": "wellbore"})
|
||||
|
||||
|
||||
def A02_metres_drilled(t: Tables, wellbore: str) -> Result:
|
||||
r = t.wb("reports", wellbore)
|
||||
r = r[r["distDrill"] > 0]
|
||||
return Result("ok", float(r["distDrill"].sum()), ev_all(ids(r, "reports"))) if len(r) else NULL
|
||||
|
||||
|
||||
def A03_metres_drilled_section(t: Tables, wellbore: str, hole: float) -> Result:
|
||||
r = t.wb("reports", wellbore)
|
||||
r = r[(r["diaHole"] == hole) & (r["distDrill"] > 0)]
|
||||
return Result("ok", float(r["distDrill"].sum()), ev_all(ids(r, "reports"))) if len(r) else NULL
|
||||
|
||||
|
||||
def A04_rop_section(t: Tables, wellbore: str, hole: float) -> Result:
|
||||
rop, bad, evidence = section_rop(t, wellbore, hole)
|
||||
if bad:
|
||||
return dropped("inconsistent_source")
|
||||
return Result("ok", rop, ev_all(evidence)) if rop is not None else NULL
|
||||
|
||||
|
||||
def A05_enumerate(t: Tables) -> list[dict]:
|
||||
b = t.all["bits"]
|
||||
return slots(b[b["diaBit"] > 0], {"wb": "wellbore", "diaBit": "bit"})
|
||||
|
||||
|
||||
def A05_bit_run_rop_max(t: Tables, wellbore: str, bit: float) -> Result:
|
||||
b = t.wb("bits", wellbore)
|
||||
b = b[b["diaBit"] == bit]
|
||||
best = b["bitRun_ropAv"].max()
|
||||
if pd.isna(best):
|
||||
return NULL
|
||||
return Result("ok", float(best), ev_any(ids(b[b["bitRun_ropAv"] == best], "bits")))
|
||||
|
||||
|
||||
def A06_enumerate(t: Tables) -> list[dict]:
|
||||
a = t.all["activities"]
|
||||
return slots(a[(a["main"] == "interruption") | a["proprietaryCode"].isin(EXTRA_CODES)],
|
||||
{"wb": "wellbore", "proprietaryCode": "code"})
|
||||
|
||||
|
||||
def A06_hours_per_code(t: Tables, wellbore: str, code: str) -> Result:
|
||||
a = t.wb("activities", wellbore)
|
||||
a = a[a["proprietaryCode"] == code]
|
||||
return Result("ok", float(a["dur"].sum()), ev_all(ids(a, "activities"))) if len(a) else NULL
|
||||
|
||||
|
||||
def A07_enumerate(t: Tables) -> list[dict]:
|
||||
return slots(t.all["equip_failures"], {"wb": "wellbore"})
|
||||
|
||||
|
||||
def A07_equip_failure_count(t: Tables, wellbore: str) -> Result:
|
||||
e = t.wb("equip_failures", wellbore)
|
||||
return Result("ok", float(len(e)), ev_all(ids(e, "equip_failures"))) if len(e) else NULL
|
||||
|
||||
|
||||
def A08_enumerate(t: Tables) -> list[dict]:
|
||||
a = t.all["activities"]
|
||||
return slots(a[a["main"] == "interruption"], {"wb": "wellbore"})
|
||||
|
||||
|
||||
def A08_top_interruption_code(t: Tables, wellbore: str) -> Result:
|
||||
a = t.wb("activities", wellbore)
|
||||
a = a[a["main"] == "interruption"]
|
||||
if a.empty:
|
||||
return NULL
|
||||
hours = a.groupby("proprietaryCode")["dur"].sum().round(4)
|
||||
top = hours[hours == hours.max()].index.tolist()
|
||||
if len(top) > 1:
|
||||
return dropped("tie")
|
||||
return Result("ok", top[0], ev_all(ids(a[a["proprietaryCode"] == top[0]], "activities")))
|
||||
|
||||
|
||||
def wow_enumerate(t: Tables) -> list[dict]:
|
||||
a = t.all["activities"]
|
||||
return slots(a[a["proprietaryCode"] == WOW], {"wb": "wellbore"})
|
||||
|
||||
|
||||
def A09_wow_days(t: Tables, wellbore: str) -> Result:
|
||||
a = t.wb("activities", wellbore)
|
||||
a = a[a["proprietaryCode"] == WOW]
|
||||
if a.empty:
|
||||
return NULL
|
||||
groups = {rid: ids(g, "activities") for rid, g in a.groupby("report_id")}
|
||||
return Result("ok", float(len(groups)), ev_groups(groups))
|
||||
|
||||
|
||||
# ----------------------------------------------------------------------------------------------------------------------
|
||||
# Temporal and event
|
||||
# ----------------------------------------------------------------------------------------------------------------------
|
||||
|
||||
def E01_first_event_date(t: Tables, wellbore: str, detail: str) -> Result:
|
||||
e = first_event(t, wellbore, detail)
|
||||
if e.empty:
|
||||
return NULL
|
||||
if len(e) > 1:
|
||||
return dropped("tie")
|
||||
return Result("ok", e["dTimStart"].iloc[0][:10], ev_all(ids(e, "activities")))
|
||||
|
||||
|
||||
def E02_first_event_md(t: Tables, wellbore: str, detail: str) -> Result:
|
||||
e = first_event(t, wellbore, detail)
|
||||
if e.empty or pd.isna(e["md"].iloc[0]):
|
||||
return NULL
|
||||
if len(e) > 1:
|
||||
return dropped("tie")
|
||||
return Result("ok", float(e["md"].iloc[0]), ev_all(ids(e, "activities")))
|
||||
|
||||
|
||||
def E03_activity_before_first_event(t: Tables, wellbore: str, detail: str) -> Result:
|
||||
a = t.wb("activities", wellbore).reset_index(drop=True) # in time order
|
||||
hits = a.index[a["stateDetailActivity"] == detail]
|
||||
if len(hits) == 0 or hits[0] == 0:
|
||||
return NULL
|
||||
event, before = a.loc[hits[0]], a.loc[hits[0] - 1]
|
||||
if before["t1"] != event["t0"]:
|
||||
return dropped("not_contiguous")
|
||||
return Result("ok", before["proprietaryCode"], ev_all(ids(a.loc[[hits[0] - 1, hits[0]]], "activities")))
|
||||
|
||||
|
||||
def E04_first_episode_hours(t: Tables, wellbore: str, detail: str) -> Result:
|
||||
a = t.wb("activities", wellbore).reset_index(drop=True)
|
||||
hit = (a["stateDetailActivity"] == detail).tolist()
|
||||
if True not in hit:
|
||||
return NULL
|
||||
start = stop = hit.index(True)
|
||||
while stop < len(hit) and hit[stop]:
|
||||
stop += 1
|
||||
run = a.iloc[start:stop]
|
||||
return Result("ok", float(run["dur"].sum()), ev_all(ids(run, "activities")))
|
||||
|
||||
|
||||
def E05_max_wow_day(t: Tables, wellbore: str) -> Result:
|
||||
a = t.wb("activities", wellbore)
|
||||
a = a[a["proprietaryCode"] == WOW]
|
||||
if a.empty:
|
||||
return NULL
|
||||
per_day = a.groupby("date")["dur"].sum().round(4)
|
||||
days = per_day[per_day == per_day.max()].index.tolist()
|
||||
if len(days) > 1:
|
||||
return dropped("tie")
|
||||
return Result("ok", days[0], ev_all(ids(a[a["date"] == days[0]], "activities")))
|
||||
|
||||
|
||||
def E06_enumerate(t: Tables) -> list[dict]:
|
||||
return [{"wellbore": w, "code": c} for w in t.wellbores for c in PRESENCE_CODES]
|
||||
|
||||
|
||||
def E06_code_present(t: Tables, wellbore: str, code: str) -> Result:
|
||||
a = t.wb("activities", wellbore)
|
||||
a = a[a["proprietaryCode"] == code]
|
||||
return Result("ok", bool(len(a)), ev_any(ids(a, "activities")))
|
||||
|
||||
|
||||
# ----------------------------------------------------------------------------------------------------------------------
|
||||
# Comparison
|
||||
# ----------------------------------------------------------------------------------------------------------------------
|
||||
|
||||
def C01_enumerate(t: Tables) -> list[dict]:
|
||||
return [{"wellbore_a": a, "wellbore_b": b, "code": c} for a, b in same_well_pairs(t.wellbores) for c in PAIR_CODES]
|
||||
|
||||
|
||||
def C01_more_hours_pair(t: Tables, wellbore_a: str, wellbore_b: str, code: str) -> Result:
|
||||
(ha, rows_a), (hb, rows_b) = code_hours(t, wellbore_a, code), code_hours(t, wellbore_b, code)
|
||||
if ha == hb:
|
||||
return dropped("tie") if ha > 0 else NULL
|
||||
evidence = ev_all(ids(rows_a, "activities"), ids(rows_b, "activities"))
|
||||
return Result("ok", wellbore_a if ha > hb else wellbore_b, evidence)
|
||||
|
||||
|
||||
def C02_enumerate(t: Tables) -> list[dict]:
|
||||
r = t.all["reports"]
|
||||
have = {(s["wellbore"], s["hole"]) for s in slots(r[r["diaHole"].notna() & (r["distDrill"] > 0)],
|
||||
{"wb": "wellbore", "diaHole": "hole"})}
|
||||
return [{"wellbore_a": a, "wellbore_b": b, "hole": h} for a, b in same_well_pairs(t.wellbores)
|
||||
for h in sorted({h for w, h in have if w == a}) if (b, h) in have]
|
||||
|
||||
|
||||
def C02_faster_rop_pair(t: Tables, wellbore_a: str, wellbore_b: str, hole: float) -> Result:
|
||||
(ra, bad_a, ev_a), (rb, bad_b, ev_b) = section_rop(t, wellbore_a, hole), section_rop(t, wellbore_b, hole)
|
||||
if bad_a or bad_b:
|
||||
return dropped("inconsistent_source")
|
||||
if ra is None or rb is None:
|
||||
return NULL
|
||||
if abs(ra - rb) <= 0.02 * max(ra, rb):
|
||||
return dropped("tie")
|
||||
return Result("ok", wellbore_a if ra > rb else wellbore_b, ev_all(ev_a, ev_b))
|
||||
|
||||
|
||||
def C03_enumerate(t: Tables) -> list[dict]:
|
||||
a = t.all["activities"]
|
||||
return slots(a[a["main"] == "interruption"], {"proprietaryCode": "code"})
|
||||
|
||||
|
||||
def C03_field_most_hours(t: Tables, code: str) -> Result:
|
||||
a = t.all["activities"]
|
||||
a = a[a["proprietaryCode"] == code]
|
||||
if a.empty:
|
||||
return NULL
|
||||
hours = a.groupby("wb")["dur"].sum().round(4)
|
||||
top = hours[hours == hours.max()].index.tolist()
|
||||
if len(top) > 1:
|
||||
return dropped("tie")
|
||||
return Result("ok", top[0], ev_all(ids(a[a["wb"] == top[0]], "activities")))
|
||||
|
||||
|
||||
# ----------------------------------------------------------------------------------------------------------------------
|
||||
# Multi-hop
|
||||
# ----------------------------------------------------------------------------------------------------------------------
|
||||
|
||||
def _event_report(t: Tables, wellbore: str, detail: str) -> tuple[pd.DataFrame, pd.DataFrame]:
|
||||
"""The first activity with the state detail (earliest start; the first row if tied) and the row of its report."""
|
||||
e = first_event(t, wellbore, detail).iloc[:1]
|
||||
r = t.wb("reports", wellbore)
|
||||
return e, r[r["report_id"].isin(e["report_id"])]
|
||||
|
||||
|
||||
def M01_mud_density_at_first_event(t: Tables, wellbore: str, detail: str) -> Result:
|
||||
e, report = _event_report(t, wellbore, detail)
|
||||
f = t.wb("fluids", wellbore)
|
||||
res = density(f[f["report_id"].isin(report["report_id"])])
|
||||
if res.status != "ok":
|
||||
return res
|
||||
return Result("ok", res.answer, ev_all(ids(e, "activities")) | res.evidence)
|
||||
|
||||
|
||||
def _report_value(t: Tables, wellbore: str, detail: str, column: str) -> Result:
|
||||
e, report = _event_report(t, wellbore, detail)
|
||||
if report.empty or pd.isna(report[column].iloc[0]):
|
||||
return NULL
|
||||
return Result("ok", float(report[column].iloc[0]), ev_all(ids(e, "activities"), ids(report, "reports")))
|
||||
|
||||
|
||||
def M02_hole_size_at_first_event(t: Tables, wellbore: str, detail: str) -> Result:
|
||||
return _report_value(t, wellbore, detail, "diaHole")
|
||||
|
||||
|
||||
def M03_formation_at_first_event(t: Tables, wellbore: str, detail: str) -> Result:
|
||||
e, _ = _event_report(t, wellbore, detail)
|
||||
if e.empty or pd.isna(e["md"].iloc[0]):
|
||||
return NULL
|
||||
s = t.wb("strat", wellbore)
|
||||
above = s[s["mdTop"] <= e["md"].iloc[0]]
|
||||
if above.empty:
|
||||
return NULL
|
||||
top = above[above["mdTop"] == above["mdTop"].max()]
|
||||
names = sorted({_formation(d) for d in top["description"]})
|
||||
if len(names) > 1:
|
||||
return dropped("tie")
|
||||
return Result("ok", names[0], ev_all(ids(e, "activities")) | ev_any(ids(top, "strat")))
|
||||
|
||||
|
||||
def M04_last_casing_at_first_event(t: Tables, wellbore: str, detail: str) -> Result:
|
||||
return _report_value(t, wellbore, detail, "mdCsgLast")
|
||||
|
||||
|
||||
def M05_days_spud_to_deepest_md(t: Tables, wellbore: str) -> Result:
|
||||
r = t.wb("reports", wellbore)
|
||||
spud = unique_values(r["dTimSpud"].str[:10])
|
||||
at_depth = r[r["md"] == r["md"].max()].sort_values("date").iloc[:1]
|
||||
if len(spud) > 1:
|
||||
return dropped("ambiguous_multiple_values")
|
||||
if not spud or at_depth.empty:
|
||||
return NULL
|
||||
days = (pd.Timestamp(at_depth["date"].iloc[0]) - pd.Timestamp(spud[0])).days
|
||||
if days < 0:
|
||||
return dropped("implausible_value")
|
||||
evidence = ev_all(ids(at_depth, "reports")) | ev_any(ids(r[r["dTimSpud"].notna()], "reports"))
|
||||
return Result("ok", float(days), evidence)
|
||||
|
||||
|
||||
#: template id -> (slot enumeration, answer function)
|
||||
TEMPLATES: dict[str, tuple[Callable, Callable]] = {
|
||||
"L01_spud_date": (every_wellbore, L01_spud_date),
|
||||
"L02_drill_complete_date": (every_wellbore, L02_drill_complete_date),
|
||||
"L03_deepest_md": (every_wellbore, L03_deepest_md),
|
||||
"L04_deepest_md_date": (every_wellbore, L04_deepest_md_date),
|
||||
"L05_casing_bottom_md": (L05_enumerate, L05_casing_bottom_md),
|
||||
"L06_casing_sizes": (lambda t: slots(t.all["casings"], {"wb": "wellbore"}), L06_casing_sizes),
|
||||
"L07_hole_sizes": (lambda t: slots(t.all["reports"][t.all["reports"]["diaHole"].notna()], {"wb": "wellbore"}),
|
||||
L07_hole_sizes),
|
||||
"L08_hole_section_start_md": (hole_slots, L08_hole_section_start_md),
|
||||
"L09_hole_section_max_md": (hole_slots, L09_hole_section_max_md),
|
||||
"L10_max_inclination": (L10_enumerate, L10_max_inclination),
|
||||
"L11_max_inclination_md": (L10_enumerate, L11_max_inclination_md),
|
||||
"L12_mud_density_on_date": (L12_enumerate, L12_mud_density_on_date),
|
||||
"L13_mud_density_at_depth": (L13_enumerate, L13_mud_density_at_depth),
|
||||
"L14_formation_top_md": (L14_enumerate, L14_formation_top_md),
|
||||
"L15_rig_name": (every_wellbore, L15_rig_name),
|
||||
"L16_kickoff_md": (every_wellbore, L16_kickoff_md),
|
||||
"A01_reports_per_hole_size": (hole_slots, A01_reports_per_hole_size),
|
||||
"A02_metres_drilled": (A02_enumerate, A02_metres_drilled),
|
||||
"A03_metres_drilled_section": (hole_slots, A03_metres_drilled_section),
|
||||
"A04_rop_section": (hole_slots, A04_rop_section),
|
||||
"A05_bit_run_rop_max": (A05_enumerate, A05_bit_run_rop_max),
|
||||
"A06_hours_per_code": (A06_enumerate, A06_hours_per_code),
|
||||
"A07_equip_failure_count": (A07_enumerate, A07_equip_failure_count),
|
||||
"A08_top_interruption_code": (A08_enumerate, A08_top_interruption_code),
|
||||
"A09_wow_days": (wow_enumerate, A09_wow_days),
|
||||
"E01_first_event_date": (all_event_slots, E01_first_event_date),
|
||||
"E02_first_event_md": (event_slots, E02_first_event_md),
|
||||
"E03_activity_before_first_event": (event_slots, E03_activity_before_first_event),
|
||||
"E04_first_episode_hours": (all_event_slots, E04_first_episode_hours),
|
||||
"E05_max_wow_day": (wow_enumerate, E05_max_wow_day),
|
||||
"E06_code_present": (E06_enumerate, E06_code_present),
|
||||
"C01_more_hours_pair": (C01_enumerate, C01_more_hours_pair),
|
||||
"C02_faster_rop_pair": (C02_enumerate, C02_faster_rop_pair),
|
||||
"C03_field_most_hours": (C03_enumerate, C03_field_most_hours),
|
||||
"M01_mud_density_at_first_event": (event_slots, M01_mud_density_at_first_event),
|
||||
"M02_hole_size_at_first_event": (event_slots, M02_hole_size_at_first_event),
|
||||
"M03_formation_at_first_event": (event_slots, M03_formation_at_first_event),
|
||||
"M04_last_casing_at_first_event": (event_slots, M04_last_casing_at_first_event),
|
||||
"M05_days_spud_to_deepest_md": (every_wellbore, M05_days_spud_to_deepest_md),
|
||||
}
|
||||
|
||||
|
||||
# ----------------------------------------------------------------------------------------------------------------------
|
||||
# Comparison of the two implementations
|
||||
# ----------------------------------------------------------------------------------------------------------------------
|
||||
|
||||
def same_answer(spec: dict, sql_answer: Any, pd_answer: Any) -> bool:
|
||||
"""SQL answers are rounded to `round` decimals, pandas answers are not: a number agrees if it is within half a
|
||||
unit of the last decimal (1e-9 relative without rounding)."""
|
||||
def close(a: Any, b: Any) -> bool:
|
||||
limit = 0.5 * 10 ** -spec["round"] if "round" in spec else 0.0
|
||||
return abs(float(a) - float(b)) <= limit + 1e-9 * max(1.0, abs(float(a)))
|
||||
|
||||
if spec["type"] == "number":
|
||||
return close(sql_answer, pd_answer)
|
||||
if spec["type"] == "list":
|
||||
if len(sql_answer) != len(pd_answer):
|
||||
return False
|
||||
if spec["item_type"] == "number":
|
||||
return all(close(a, b) for a, b in zip(sql_answer, pd_answer))
|
||||
return list(sql_answer) == list(pd_answer)
|
||||
if spec["type"] == "boolean":
|
||||
return bool(sql_answer) == bool(pd_answer)
|
||||
return str(sql_answer) == str(pd_answer)
|
||||
|
||||
|
||||
def compare(tpl: dict, o: Outcome, res: Result) -> list[str]:
|
||||
"""What differs between the SQL outcome and the pandas result of one instance: 'status', 'answer', 'evidence'."""
|
||||
if o.status == "ok":
|
||||
if res.status != "ok":
|
||||
return ["status"]
|
||||
diff = [] if same_answer(tpl["answer"], o.answer, res.answer) else ["answer"]
|
||||
return diff + ([] if o.evidence_partition() == res.evidence else ["evidence"])
|
||||
if o.status == "not_reported" or o.reason == "null_answer":
|
||||
return [] if res.status == "null" else ["status"]
|
||||
return [] if (res.status, res.reason) == ("drop", o.reason) else ["status"]
|
||||
|
||||
|
||||
def crosscheck(cfg: dict, outcomes: dict[str, list[Outcome]], tables: Tables, examples: int = 5) -> dict:
|
||||
"""Agreement of the two implementations on every candidate instance of every template (duplicates excluded)."""
|
||||
per_template, total = {}, {"instances": 0, "agree": 0, "status": 0, "answer": 0, "evidence": 0}
|
||||
for tpl in cfg["templates"]:
|
||||
tid = tpl["id"]
|
||||
enumerate_fn, answer_fn = TEMPLATES[tid]
|
||||
outs = [o for o in outcomes[tid] if o.reason != "duplicate"]
|
||||
sql_keys = {o.key for o in outs}
|
||||
pd_keys = {slot_key(tid, {k: s[k] for k in tpl["slots"]}) for s in enumerate_fn(tables)}
|
||||
row = {"instances": len(outs), "agree": 0, "status": 0, "answer": 0, "evidence": 0,
|
||||
"slots_only_sql": len(sql_keys - pd_keys), "slots_only_pandas": len(pd_keys - sql_keys),
|
||||
"examples": []}
|
||||
for o in outs:
|
||||
diff = compare(tpl, o, answer_fn(tables, **o.slots))
|
||||
row["agree"] += not diff
|
||||
for d in diff:
|
||||
row[d] += 1
|
||||
if diff and len(row["examples"]) < examples:
|
||||
res = answer_fn(tables, **o.slots)
|
||||
row["examples"].append({"slots": o.slots, "differs": diff, "sql": [o.status, o.reason, o.answer],
|
||||
"pandas": [res.status, res.reason, res.answer]})
|
||||
for k in total:
|
||||
total[k] += row[k]
|
||||
per_template[tid] = row
|
||||
total["slot_differences"] = sum(r["slots_only_sql"] + r["slots_only_pandas"] for r in per_template.values())
|
||||
total["templates"] = len(per_template)
|
||||
total["templates_in_full_agreement"] = sum(
|
||||
r["agree"] == r["instances"] and not r["slots_only_sql"] and not r["slots_only_pandas"]
|
||||
for r in per_template.values())
|
||||
total["agreement"] = round(total["agree"] / total["instances"], 6) if total["instances"] else None
|
||||
return {"total": total, "per_template": per_template}
|
||||
136
volve_dia/tops.py
Normal file
136
volve_dia/tops.py
Normal file
@@ -0,0 +1,136 @@
|
||||
"""Formation tops of the Volve wells: `Geophysical_Interpretations/Wells/Well_picks_Volve_v1.dat` as a table.
|
||||
|
||||
The file is fixed-width text. Every well has a block: a `Well NO <name>` line, a header line, a line of dashes
|
||||
that gives the column positions, and one line per pick. `parse_picks` slices every pick line at the dash columns
|
||||
and checks it against the block header. The file states no units; depths agree with the DDR in metres.
|
||||
|
||||
Published columns: `Well name`, `Surface name`, `Obs#` (a surface crossed more than once is numbered), `Qlf`
|
||||
(ER eroded, FP faulted pick, FO faulted out, NL not logged, NR not reached), `MD`, `TVD`, `TVDSS`, `TWT`, `Dip`,
|
||||
`Azi`, `Easting`, `Northing`, `Intrp`. Added columns: `wellbore_picks` (the published name without "NO "),
|
||||
`wellbore` (the DDR wellbore the pick belongs to, see `PICKS_TO_DDR`; None when the well has no DDR), `track`,
|
||||
`unit` and `boundary` (the surface name split at its trailing "Top"/"Base").
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from pathlib import Path
|
||||
|
||||
import pandas as pd
|
||||
|
||||
from .names import canonical
|
||||
|
||||
COLUMNS = ["Well name", "Surface name", "Obs#", "Qlf", "MD", "TVD", "TVDSS", "TWT", "Dip", "Azi", "Easting",
|
||||
"Northing", "Intrp"]
|
||||
NUMERIC = ["MD", "TVD", "TVDSS", "TWT", "Dip", "Azi", "Easting", "Northing"]
|
||||
QUALIFIERS = {"ER": "eroded", "FP": "faulted pick", "FO": "faulted out", "NL": "not logged", "NR": "not reached"}
|
||||
|
||||
#: Names of the picks file that are not DDR wellbore names -> (DDR wellbore, track). Evidence:
|
||||
#:
|
||||
#: * `15/9-19 SR` is the NPD name of the 1993 re-entry of 15/9-19 S (NPD FactPages, wellbore 2105: entered
|
||||
#: 17.02.1993, TD 4641 m MD; its lithostratigraphy lists Shetland Gp 3827, Draupne Fm 4304, Skagerrak Fm 4340 m,
|
||||
#: the MD of the picks). NPD and the DDR cut the same hole differently. NPD: `15/9-19 S` is the first hole plus
|
||||
#: its technical sidetrack from 1493 m down to 3580 m (FactPages 2043), `15/9-19 SR` deepened it to 4641 m. DDR:
|
||||
#: `15/9-19 S` is the first hole only (49 reports to 19.12.1992, deepest 3353 m, stuck and plugged back) and
|
||||
#: `15/9-19 ST2` is everything drilled after the sidetrack (127 reports, 19.12.1992-26.07.1997, to 4641 m). The
|
||||
#: picks below the sidetrack point (3614-4579 m MD) lie below the deepest point of DDR `15/9-19 S` and inside
|
||||
#: `15/9-19 ST2`. Both DDR wellbores carry NPD number 2043; the DDR never uses the name SR.
|
||||
#: * `15/9-F-12 pilot` is the 8 1/2" pilot hole of F-12 (to 1353 m, 23.06-05.07.2007, then plugged). The DDR
|
||||
#: reports it under `15/9-F-12` (reports with diaPilot = 8.5), so its picks map to that wellbore, track "pilot".
|
||||
PICKS_TO_DDR = {
|
||||
"15/9-19 SR": ("15/9-19 ST2", "main"),
|
||||
"15/9-F-12 pilot": ("15/9-F-12", "pilot"),
|
||||
}
|
||||
#: DDR wellbores without a block of their own: (wellbore, block they share the upper hole with, MD of the
|
||||
#: kick-off in metres). Picks of that block above the kick-off lie in the shared hole and apply to both.
|
||||
#:
|
||||
#: * `15/9-19 S`: `15/9-19 ST2` was sidetracked from it at 1493 m (DDR activity 15_9_19_ST2_1992_12_19:000,
|
||||
#: "SIDETRACKED ... FROM 1493M"; NPD FactPages 2043: "plugging back and sidetracking from 1493 m").
|
||||
#: * `15/9-F-9 A` left F-9 through a window in the 13 3/8" casing; the DDR records parameters "above 13 3/8"
|
||||
#: casing window at 395 m" (activity 15_9_F_9_A_2009_07_05:011) and the WITSML trajectory of F-9 A starts at
|
||||
#: 420.4 m. The picks of F-9 are at 146, 146, 885 and 1071.2 m, so any kick-off between 146 and 885 m gives the
|
||||
#: same two shared picks; the DDR itself puts the Utsira Fm of F-9 A at 959 m against 885 m in F-9.
|
||||
SHARED_TRUNK = [
|
||||
("15/9-19 S", "15/9-19 SR", 1493.0),
|
||||
("15/9-F-9 A", "15/9-F-9", 395.0),
|
||||
]
|
||||
|
||||
_WELL = re.compile(r"^Well (NO .+?)\s*$")
|
||||
_BOUNDARY = re.compile(r"^(.*?)\s+(Top|Base)$")
|
||||
|
||||
|
||||
def picks_wellbore(name: str) -> str:
|
||||
"""'NO 15/9-F-12 pilot' -> '15/9-F-12 pilot'; names without a suffix word go through `canonical`."""
|
||||
s = re.sub(r"\s+", " ", name.strip())
|
||||
try:
|
||||
return canonical(s)
|
||||
except ValueError:
|
||||
return re.sub(r"^NO\s+", "", s)
|
||||
|
||||
|
||||
def parse_picks(path: Path, ddr_wellbores: set[str] | None = None) -> pd.DataFrame:
|
||||
"""One row per pick, in file order. `ddr_wellbores` (canonical names) decides the `wellbore` column: a pick
|
||||
gets a DDR wellbore only if its mapped name is one; with None every mapped name is kept."""
|
||||
rows = []
|
||||
well = spans = None
|
||||
lines = path.read_text(encoding="ascii").splitlines()
|
||||
for no, line in enumerate(lines, 1):
|
||||
m = _WELL.match(line)
|
||||
if m:
|
||||
well, spans = m.group(1), None
|
||||
continue
|
||||
if not line.strip() or line.startswith("#"):
|
||||
continue
|
||||
if well is None:
|
||||
raise ValueError(f"{path.name}:{no}: text before the first well block")
|
||||
if line.strip().startswith("Well name"):
|
||||
header = line
|
||||
continue
|
||||
if set(line.strip()) <= {"-", " "}:
|
||||
starts = [m.start() for m in re.finditer(r"-+", line)]
|
||||
if len(starts) != len(COLUMNS):
|
||||
raise ValueError(f"{path.name}:{no}: {len(starts)} columns, expected {len(COLUMNS)}")
|
||||
spans = list(zip(starts, starts[1:] + [None]))
|
||||
got = [header[a:b].strip() for a, b in spans]
|
||||
if got != COLUMNS:
|
||||
raise ValueError(f"{path.name}:{no}: header {got}")
|
||||
continue
|
||||
if spans is None:
|
||||
raise ValueError(f"{path.name}:{no}: pick line before the column line")
|
||||
cells = [line[a:b].strip() for a, b in spans]
|
||||
row = dict(zip(COLUMNS, cells))
|
||||
if row["Well name"] != well:
|
||||
raise ValueError(f"{path.name}:{no}: pick of {row['Well name']!r} in the block of {well!r}")
|
||||
row["line"] = no
|
||||
rows.append(row)
|
||||
df = pd.DataFrame(rows)
|
||||
for c in NUMERIC:
|
||||
df[c] = pd.to_numeric(df[c].replace("", None)) # raises on anything that is not a number
|
||||
df["Obs#"] = df["Obs#"].astype(int)
|
||||
df["Qlf"] = df["Qlf"].replace("", None)
|
||||
unknown = set(df["Qlf"].dropna()) - set(QUALIFIERS)
|
||||
if unknown:
|
||||
raise ValueError(f"unknown qualifiers: {unknown}")
|
||||
df["wellbore_picks"] = df["Well name"].map(picks_wellbore)
|
||||
mapped = df["wellbore_picks"].map(lambda w: PICKS_TO_DDR.get(w, (w, "main")))
|
||||
df["wellbore"] = [w if ddr_wellbores is None or w in ddr_wellbores else None for w, _ in mapped]
|
||||
df["track"] = [t for _, t in mapped]
|
||||
split = df["Surface name"].str.extract(_BOUNDARY)
|
||||
df["unit"] = split[0].fillna(df["Surface name"])
|
||||
df["boundary"] = split[1]
|
||||
return df[["wellbore", "wellbore_picks", "track", "Surface name", "unit", "boundary", "Obs#", "Qlf", "MD",
|
||||
"TVD", "TVDSS", "TWT", "Dip", "Azi", "Easting", "Northing", "Intrp", "line"]].rename(
|
||||
columns={"Surface name": "surface", "Obs#": "obs", "Qlf": "qlf", "MD": "md", "TVD": "tvd", "TVDSS": "tvdss",
|
||||
"TWT": "twt", "Dip": "dip", "Azi": "azi", "Easting": "easting", "Northing": "northing",
|
||||
"Intrp": "intrp"})
|
||||
|
||||
|
||||
def shared_trunk_picks(picks: pd.DataFrame) -> pd.DataFrame:
|
||||
"""Picks that a DDR wellbore without a block of its own shares with its mother bore (`SHARED_TRUNK`): the
|
||||
published rows above the kick-off, re-labelled with that wellbore and `inherited_from`."""
|
||||
out = []
|
||||
for wellbore, block, kickoff in SHARED_TRUNK:
|
||||
part = picks[(picks["wellbore_picks"] == block) & (picks["md"] < kickoff)].copy()
|
||||
part["wellbore"], part["inherited_from"], part["md_kickoff"] = wellbore, block, kickoff
|
||||
out.append(part)
|
||||
return pd.concat(out, ignore_index=True)
|
||||
826
volve_dia/witsml.py
Normal file
826
volve_dia/witsml.py
Normal file
@@ -0,0 +1,826 @@
|
||||
"""WITSML 1.4.1.1 real-time objects of Volve (`WITSML Realtime drilling data/`) as flat tables.
|
||||
|
||||
Layout of the source. A top folder is a *well* on one of two servers (Schlumberger-era folders such as
|
||||
`Norway-StatoilHydro-15_$47$_9-F-15A`, Baker-Hughes-era folders such as `Norway-Statoil-NO 15_$47$_9-F-11`); its
|
||||
numbered subfolders are the *wellbores* of that well (`NO 15/9-F-11` holds F-11, F-11 A, F-11 B and F-11 T2). The
|
||||
wellbore of an object is therefore read from the object (`nameWellbore`, `uidWellbore`), never from the folder.
|
||||
|
||||
<well>/<n>/log/<i>/<j>/<k>/NNNNN.xml one log (`<k>`) cut into consecutive chunk files
|
||||
<well>/<n>/{trajectory,message,bhaRun,mudLog}/N.xml
|
||||
|
||||
Parsed here: `log` (header, logCurveInfo, logData; time- and depth-indexed), `trajectory`, `message`, `bhaRun`,
|
||||
`mudLog`. Not parsed: `tubular`, `rig`, `wbGeometry`, `_wellInfo`, `_wellboreInfo`.
|
||||
|
||||
Column names are the WITSML element names (a nested element prefixes its leaves with its tag), so every value can
|
||||
be traced back to the schema. Values are stored as published, in the published unit. Log data are stored long:
|
||||
one row per published value `(wellbore, log_id, mnemonic, index, value | text, chunk)`, because the logs publish
|
||||
1,744 different mnemonics, of which the two service companies share 3 (HKLD, MWIN, DXC). `log_id` + `chunk` name the
|
||||
source file of every value. Normalisations, all counted, none silent:
|
||||
|
||||
* an empty log cell is "no value" and makes no row;
|
||||
* a log value equal to the `nullValue` of its curve (or of its log) becomes missing (`n_null_value`);
|
||||
* the sentinels -999.25 and -9999 become missing (TADI, arXiv:2605.00060, section 3.3 "Sentinel values");
|
||||
two more sentinels found in the object files are listed in `EXTRA_SENTINELS` with the reason;
|
||||
* a cell of a numeric curve that is not a number (array curves publish 16 space-separated values) is kept as
|
||||
text (`n_not_number`); curves of type string or date time are text;
|
||||
* trajectory angles and magnetic fields are published in two units (Schlumberger: dega, nT; Baker Hughes: rad, T):
|
||||
they are stored in the units of `STORED_UNITS` and the conversion is counted in the `units` table;
|
||||
* duplicates, see `dedup_curve` (inside one log: rows with the same index, one is kept) and `merge_curve`
|
||||
(between logs of one wellbore: rows with the same mnemonic and index are all kept and ranked, `dup_rank`);
|
||||
* three Schlumberger-server wellbores are renamed to their DDR name (`WELLBORE_BY_UID`).
|
||||
|
||||
Deviations from TADI (sections 3.2-3.3): TADI converts ROP to m/h, WOB to kN and RPM to 1/min and drops values it
|
||||
calls implausible (ROP > 200 m/h, RPM > 300, WOB > 500 kN). Here units stay as published (recorded per column and
|
||||
per curve) and no value is dropped for being large: `tadi_implausible` only flags mudLog intervals, and the values
|
||||
listed in `SUSPECT_VALUES` are only counted per curve, because a benchmark value must be the published one. TADI
|
||||
did not parse the `log` objects.
|
||||
|
||||
Times: log indexes are UTC timestamps (every published index ends in "Z", checked); other times stay ISO strings
|
||||
as published.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import collections
|
||||
import io
|
||||
import math
|
||||
import re
|
||||
import xml.etree.ElementTree as ET
|
||||
from dataclasses import dataclass, field
|
||||
from pathlib import Path
|
||||
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
import pyarrow as pa
|
||||
import pyarrow.compute as pc
|
||||
import pyarrow.csv as pacsv
|
||||
import pyarrow.parquet as pq
|
||||
|
||||
from .names import canonical, stem
|
||||
|
||||
NS = "{http://www.witsml.org/schemas/1series}"
|
||||
|
||||
#: TADI section 3.3: "WITSML uses -999.25 and -9999".
|
||||
SENTINELS = (-999.25, -9999.0)
|
||||
#: Sentinels of the object files that TADI does not list: (table, column prefix) -> value.
|
||||
#: * mudLog gas concentrations (ppm) are published as -999 where there is no reading; a concentration is never
|
||||
#: negative. (+999 also occurs, 5 times, but 999 ppm is a possible reading, so it is kept.)
|
||||
#: * `stnGridCorUsed` is 999.25 in 2,123 Baker Hughes stations: a grid convergence of 999.25 rad is not an angle.
|
||||
EXTRA_SENTINELS = {
|
||||
("mudlog_intervals", "chromatograph_"): -999.0,
|
||||
("mudlog_intervals", "mudGas_"): -999.0,
|
||||
("trajectory", "corUsed_stnGridCorUsed"): 999.25,
|
||||
}
|
||||
#: Log values that look like more sentinels. They are *kept* and counted per curve (`log_suspects`): none of them
|
||||
#: is a declared null value, and e.g. 9999 s is a possible off-bottom time.
|
||||
SUSPECT_VALUES = (-999.0, 999.25, -999.99, 9999.0, -99999.0, 99999.0, 1e30, -1e30)
|
||||
SUSPECT_HUGE = 1e15 # |value| above this is counted as "huge"
|
||||
#: Unit a column is stored in when the source publishes it in more than one unit: published unit -> (stored, factor).
|
||||
STORED_UNITS = {
|
||||
"rad": ("dega", 180.0 / math.pi),
|
||||
"T": ("nT", 1e9),
|
||||
"rad/m": ("dega/30m", 30.0 * 180.0 / math.pi),
|
||||
"dega/m": ("dega/30m", 30.0),
|
||||
}
|
||||
#: TADI section 3.3 quality filters in the published SI units; used only to flag (`tadi_implausible`).
|
||||
TADI_FILTERS = {"ropAv": 200.0 / 3600.0, "rpmAv": 300.0 / 60.0, "wobAv": 500.0e3} # m/s, c/s, N
|
||||
|
||||
#: commonData leaves that identify people and machines of the operator; not needed, not copied.
|
||||
DROPPED = {"priv_userOwner", "priv_userLastChange", "priv_ipOwner", "priv_ipLastChange"}
|
||||
#: WITSML `typeLogData` values stored as numbers; every other type is stored as text.
|
||||
NUMERIC_TYPES = {"double", "float", "long", "int", "short", "byte"}
|
||||
INDEX_KINDS = {"date time": "time", "measured depth": "depth"}
|
||||
#: Logs that hold display settings of the WITSML store (2 rows of text written on 22.09.2015 into every wellbore),
|
||||
#: not measurements. They are parsed like every log but excluded from time ranges and coverage.
|
||||
SETTINGS_LOGS = {"GlcSettingsLog"}
|
||||
#: Hole depth and bit depth of the time logs: Schlumberger `DMEA`/`DBTM`; Baker Hughes `Depth`/`BITDEP` of the
|
||||
#: `GenTime` log. (Every Baker Hughes log has a `Depth` curve: the reference depth of *that* log, which for an MWD
|
||||
#: log is the sensor depth. Only in `GenTime` is it the hole depth.)
|
||||
HOLE_DEPTH = {"DMEA": None, "Depth": "GenTime"} # mnemonic -> required log name (None: any)
|
||||
BIT_DEPTH = {"DBTM": None, "BITDEP": "GenTime"}
|
||||
|
||||
#: The Schlumberger server names three wellbores of slot F-15 differently from the DDR and from NPD: uidWellbore
|
||||
#: -> DDR wellbore. No DDR and no NPD wellbore is called F-15 S. Evidence, per uid (the first item is recomputed on
|
||||
#: every run by `scripts/06_parse_witsml.py`, which fails if a uid agrees better with another DDR wellbore):
|
||||
#: 1. hole depth `DMEA` at the end of the DDR report periods against `md` of the DDR (table
|
||||
#: `check_wellbore_identity`), for every DDR wellbore of the slot;
|
||||
#: 2. DDR survey stations found in the WITSML trajectories (MD within 0.5 m, inclination 0.1, azimuth 0.5 deg);
|
||||
#: 3. total depth in `_wellboreInfo` against the deepest `md` of the DDR and the TD of NPD FactPages;
|
||||
#: 4. dates of the time logs against the DDR reports and the NPD entry and completion dates.
|
||||
#:
|
||||
#: B-744206 "15/9-F-15S" = DDR 15/9-F-15: (1) 47 reports, median |diff| 0.12 m, 42 within 5 m; (2) 27 of its
|
||||
#: 27 distinct DDR stations; (3) 4090.0 m, DDR 4090 m; (4) logs 08.09-08.12.2008, NPD completed 05.12.2008.
|
||||
#: B-826806 "15/9-F-15" = DDR 15/9-F-15 A: (1) 15 reports, median 0.50 m, 13 within 5 m, while against DDR
|
||||
#: 15/9-F-15 all 3 reports are 2890 m off; (2) 53 stations of F-15 A, 0 of F-15; (3) 4096.5 m, DDR and
|
||||
#: NPD 4095 m; (4) logs 08.12.2008-12.01.2009, NPD 11.12.2008-10.01.2009.
|
||||
#: B-861401 "15/9-F-15A" = DDR 15/9-F-15 C: (1) 7 reports, median 0.12 m, 7 within 5 m, while against DDR
|
||||
#: 15/9-F-15 B both reports are about 960 m off; (2) 6 of the 6 stations of F-15 C, 1 of F-15 A;
|
||||
#: (3) 3232.1 m, DDR and NPD 3232 m; (4) logs 14.01-02.03.2009, NPD 18.01-15.02.2009.
|
||||
#: B-854763 "15/9-F-15B" keeps its name: (1) 2 reports within 0.6 m; (2) 8 of 9 stations; (3) 3497.6 m, NPD 3497 m.
|
||||
#: The Baker Hughes server (2013 onwards) uses the NPD names: its "NO 15/9-F-15 C" is DDR 15/9-F-15 C.
|
||||
WELLBORE_BY_UID = {
|
||||
"B-744206": "15/9-F-15",
|
||||
"B-826806": "15/9-F-15 A",
|
||||
"B-861401": "15/9-F-15 C",
|
||||
}
|
||||
|
||||
_MAIN = re.compile(r"\s*-\s*Main Wellbore$")
|
||||
|
||||
|
||||
def published_wellbore(name_well: str, name_wellbore: str) -> tuple[str, str]:
|
||||
"""(canonical wellbore as published, source). The name comes from `nameWellbore` ("15/9-F-15A - Main
|
||||
Wellbore", "NO 15/9-F-11 T2"); when that is not a wellbore name ("EcoScope_Customer_Run5", "test") it falls
|
||||
back to `nameWell` and says so."""
|
||||
try:
|
||||
return canonical(_MAIN.sub("", name_wellbore or "")), "nameWellbore"
|
||||
except ValueError:
|
||||
return canonical(name_well), "nameWell"
|
||||
|
||||
|
||||
def wellbore_name(name_well: str, name_wellbore: str, uid_wellbore: str | None = None) -> tuple[str, str]:
|
||||
"""(DDR wellbore, source): `WELLBORE_BY_UID` first, else the published name."""
|
||||
if uid_wellbore in WELLBORE_BY_UID:
|
||||
return WELLBORE_BY_UID[uid_wellbore], "uidWellbore"
|
||||
return published_wellbore(name_well, name_wellbore)
|
||||
|
||||
|
||||
def wellbore_dir(wellbore: str) -> str:
|
||||
"""File name of a wellbore in the parquet tree: '15/9-F-11 T2' -> '15_9_F_11_T2'."""
|
||||
return stem(wellbore)
|
||||
|
||||
|
||||
def _tag(e: ET.Element) -> str:
|
||||
return e.tag.replace(NS, "")
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------------------------------------------
|
||||
# log: reading
|
||||
# --------------------------------------------------------------------------------------------------------------
|
||||
|
||||
@dataclass
|
||||
class LogFile:
|
||||
"""One chunk file of a log: header leaves, logCurveInfo rows, and the raw comma-separated data rows."""
|
||||
header: dict
|
||||
curves: list[dict]
|
||||
mnemonics: list[str]
|
||||
units: list[str]
|
||||
rows: list[str]
|
||||
|
||||
|
||||
def read_log_file(source, header_only: bool = False) -> LogFile:
|
||||
"""Stream one `<logs><log>` file (path or binary file object). `logData/data` rows are kept as text.
|
||||
With `header_only` the parse stops at the first logCurveInfo (enough to name the wellbore)."""
|
||||
header: dict = {}
|
||||
curves: list[dict] = []
|
||||
mnemonics: list[str] = []
|
||||
units: list[str] = []
|
||||
rows: list[str] = []
|
||||
stack: list[str] = []
|
||||
n_logs = 0
|
||||
for event, e in ET.iterparse(source, events=("start", "end")):
|
||||
tag = _tag(e)
|
||||
if event == "start":
|
||||
stack.append(tag)
|
||||
if tag == "log":
|
||||
n_logs += 1
|
||||
header.update(e.attrib)
|
||||
elif header_only and tag in ("logCurveInfo", "logData"):
|
||||
return LogFile(header, curves, mnemonics, units, rows)
|
||||
continue
|
||||
stack.pop()
|
||||
parent = stack[-1] if stack else ""
|
||||
if tag == "data":
|
||||
rows.append(e.text or "")
|
||||
e.clear()
|
||||
elif tag == "logCurveInfo":
|
||||
c = {"uid": e.attrib.get("uid")}
|
||||
for child in e:
|
||||
c[_tag(child)] = (child.text or "").strip()
|
||||
if "uom" in child.attrib:
|
||||
c[_tag(child) + "_uom"] = child.attrib["uom"]
|
||||
curves.append(c)
|
||||
e.clear()
|
||||
elif tag == "mnemonicList":
|
||||
mnemonics = [m.strip() for m in (e.text or "").split(",")]
|
||||
elif tag == "unitList":
|
||||
units = [u.strip() for u in (e.text or "").split(",")]
|
||||
elif parent == "log" and len(e) == 0:
|
||||
header[tag] = (e.text or "").strip()
|
||||
if "uom" in e.attrib:
|
||||
header[tag + "_uom"] = e.attrib["uom"]
|
||||
elif parent == "commonData" and tag not in DROPPED:
|
||||
header["commonData_" + tag] = (e.text or "").strip()
|
||||
if n_logs != 1:
|
||||
raise ValueError(f"{source}: {n_logs} log elements, expected 1")
|
||||
return LogFile(header, curves, mnemonics, units, rows)
|
||||
|
||||
|
||||
def _split(rows: list[str], n_cols: int) -> tuple[pa.Table, int]:
|
||||
"""Comma-separated rows -> a table of string columns c0..cN. Rows with another field count are dropped and
|
||||
counted (WITSML 1.4.1 has no quoting, so a text value with a comma would break its row)."""
|
||||
bad = [0]
|
||||
|
||||
def on_invalid(row) -> str:
|
||||
bad[0] += 1
|
||||
return "skip"
|
||||
|
||||
data = "\n".join(r.replace("\n", " ").replace("\r", " ") for r in rows).encode("utf-8")
|
||||
names = [f"c{i}" for i in range(n_cols)]
|
||||
table = pacsv.read_csv(
|
||||
io.BytesIO(data),
|
||||
read_options=pacsv.ReadOptions(column_names=names, block_size=max(len(data) + 16, 1 << 20),
|
||||
use_threads=False),
|
||||
parse_options=pacsv.ParseOptions(delimiter=",", quote_char=False, escape_char=False,
|
||||
newlines_in_values=False, ignore_empty_lines=False,
|
||||
invalid_row_handler=on_invalid),
|
||||
convert_options=pacsv.ConvertOptions(column_types={n: pa.string() for n in names},
|
||||
strings_can_be_null=True, null_values=[""]),
|
||||
)
|
||||
return table, bad[0]
|
||||
|
||||
|
||||
def _objects(col: pa.ChunkedArray) -> np.ndarray:
|
||||
out = np.empty(len(col), dtype=object)
|
||||
out[:] = col.to_pylist()
|
||||
return out
|
||||
|
||||
|
||||
def _numbers(col: pa.ChunkedArray) -> tuple[np.ndarray, np.ndarray | None, int]:
|
||||
"""A string column -> (float64 values, NaN where missing; texts of the cells that are not numbers, or None;
|
||||
number of such cells)."""
|
||||
try:
|
||||
return pc.cast(col, pa.float64()).to_numpy(zero_copy_only=False), None, 0
|
||||
except pa.ArrowInvalid:
|
||||
raw = _objects(col)
|
||||
out = np.full(len(raw), np.nan)
|
||||
text = np.full(len(raw), None, dtype=object)
|
||||
bad = 0
|
||||
for i, s in enumerate(raw):
|
||||
if s is None:
|
||||
continue
|
||||
try:
|
||||
out[i] = float(s)
|
||||
except ValueError:
|
||||
text[i], bad = s, bad + 1
|
||||
return out, text, bad
|
||||
|
||||
|
||||
def parse_time_index(col: pa.ChunkedArray) -> np.ndarray:
|
||||
"""ISO 8601 strings ending in "Z" -> int64 milliseconds since the epoch (UTC). Raises on anything else."""
|
||||
if not pc.all(pc.ends_with(col, "Z")).as_py():
|
||||
raise ValueError("a time index value does not end in 'Z'")
|
||||
t = pd.to_datetime(col.to_pandas(), utc=True, format="ISO8601")
|
||||
return t.dt.as_unit("ms").astype("int64").to_numpy()
|
||||
|
||||
|
||||
def _float_or_none(s) -> float | None:
|
||||
try:
|
||||
return float(s) if s not in (None, "") else None
|
||||
except ValueError:
|
||||
return None
|
||||
|
||||
|
||||
@dataclass
|
||||
class CurveData:
|
||||
"""Values of one curve of one log, one list entry per chunk file, in file order."""
|
||||
index: list = field(default_factory=list) # int64 ms since the epoch, or float64 metres
|
||||
value: list = field(default_factory=list) # float64, NaN where the value is text
|
||||
text: list = field(default_factory=list) # object array or None
|
||||
chunk: list = field(default_factory=list) # int16 source file number
|
||||
has_text: bool = False
|
||||
stats: collections.Counter = field(default_factory=collections.Counter)
|
||||
|
||||
|
||||
@dataclass
|
||||
class Curve:
|
||||
"""One curve of one log after `dedup_curve`: sorted by index, one row per index value."""
|
||||
log_id: int
|
||||
mnemonic: str
|
||||
index: np.ndarray
|
||||
value: np.ndarray
|
||||
text: np.ndarray | None
|
||||
chunk: np.ndarray
|
||||
stats: dict
|
||||
|
||||
|
||||
class ParsedLog:
|
||||
"""All chunk files of one log merged: header, curve table, and the values of every curve in file order."""
|
||||
|
||||
def __init__(self) -> None:
|
||||
self.header: dict = {}
|
||||
self.kind: str | None = None # "time" | "depth"
|
||||
self.index_unit: str | None = None
|
||||
self.curve_info: dict[str, dict] = {} # mnemonic -> logCurveInfo of the first chunk that has it
|
||||
self.data: dict[str, CurveData] = {}
|
||||
self.counts: collections.Counter = collections.Counter()
|
||||
self.index_values: list[np.ndarray] = [] # the index column of every chunk, in file order
|
||||
|
||||
def add(self, lf: LogFile, chunk: int) -> None:
|
||||
h = lf.header
|
||||
if not self.header:
|
||||
self.header = dict(h)
|
||||
self.kind = INDEX_KINDS.get(h.get("indexType", ""))
|
||||
if self.kind is None:
|
||||
raise ValueError(f"unsupported indexType {h.get('indexType')!r}")
|
||||
else:
|
||||
for key in ("uid", "uidWellbore", "indexType", "indexCurve"):
|
||||
if h.get(key) != self.header.get(key):
|
||||
raise ValueError(f"chunk {chunk}: {key} changes inside one log: "
|
||||
f"{self.header.get(key)!r} -> {h.get(key)!r}")
|
||||
for c in lf.curves:
|
||||
known = self.curve_info.setdefault(c["mnemonic"], c)
|
||||
if known is not c and known.get("unit") != c.get("unit"):
|
||||
raise ValueError(f"chunk {chunk}: unit of {c['mnemonic']} changes inside one log")
|
||||
self.counts["files"] += 1
|
||||
self.counts["rows"] += len(lf.rows)
|
||||
if not lf.rows:
|
||||
return
|
||||
names = lf.mnemonics
|
||||
index_curve = h.get("indexCurve", "")
|
||||
if names.count(index_curve) != 1:
|
||||
raise ValueError(f"chunk {chunk}: index curve {index_curve!r} is not exactly once in mnemonicList")
|
||||
if len(set(names)) != len(names):
|
||||
raise ValueError(f"chunk {chunk}: repeated mnemonic in mnemonicList")
|
||||
table, bad = _split(lf.rows, len(names))
|
||||
self.counts["bad_rows"] += bad
|
||||
i_index = names.index(index_curve)
|
||||
icol = table.column(i_index)
|
||||
if icol.null_count:
|
||||
raise ValueError(f"chunk {chunk}: {icol.null_count} rows without an index value")
|
||||
if self.kind == "time":
|
||||
index = parse_time_index(icol)
|
||||
else:
|
||||
unit = lf.units[i_index] if i_index < len(lf.units) else ""
|
||||
if unit not in ("m", ""):
|
||||
raise ValueError(f"chunk {chunk}: depth index in {unit!r}, expected metres")
|
||||
self.index_unit = unit or self.index_unit
|
||||
index = pc.cast(icol, pa.float64()).to_numpy(zero_copy_only=False)
|
||||
self.index_values.append(index)
|
||||
log_null = _float_or_none(h.get("nullValue"))
|
||||
for j, name in enumerate(names):
|
||||
if j == i_index:
|
||||
continue
|
||||
col = table.column(j)
|
||||
n_valid = len(col) - col.null_count
|
||||
if n_valid == 0:
|
||||
continue
|
||||
info = self.curve_info.get(name)
|
||||
if info is None: # data for a curve without logCurveInfo
|
||||
info = self.curve_info.setdefault(name, {"mnemonic": name, "undeclared": True,
|
||||
"unit": lf.units[j] if j < len(lf.units) else None})
|
||||
cd = self.data.setdefault(name, CurveData())
|
||||
ltype = (info.get("typeLogData") or "").lower()
|
||||
if ltype in NUMERIC_TYPES or not ltype:
|
||||
values, text, n_bad = _numbers(col)
|
||||
cd.stats["n_not_number"] += n_bad
|
||||
keep = ~np.isnan(values)
|
||||
cd.stats["n_nan"] += int(n_valid - n_bad - keep.sum()) # the literal "NaN"
|
||||
null = _float_or_none(info.get("nullValue"))
|
||||
null = log_null if null is None else null
|
||||
if null is not None:
|
||||
hit = keep & (values == null)
|
||||
cd.stats["n_null_value"] += int(hit.sum())
|
||||
keep &= ~hit
|
||||
for s in SENTINELS:
|
||||
hit = keep & (values == s)
|
||||
if hit.any():
|
||||
cd.stats[f"sentinel:{s:g}"] += int(hit.sum())
|
||||
keep &= ~hit
|
||||
for s in SUSPECT_VALUES:
|
||||
n_hit = int((keep & (values == s)).sum())
|
||||
if n_hit:
|
||||
cd.stats[f"suspect:{s:g}"] += n_hit
|
||||
n_hit = int((keep & (np.abs(values) > SUSPECT_HUGE)).sum())
|
||||
if n_hit:
|
||||
cd.stats["suspect:huge"] += n_hit
|
||||
if text is not None:
|
||||
keep |= np.array([t is not None for t in text])
|
||||
cd.has_text = True
|
||||
cd.text.append(text[keep])
|
||||
else:
|
||||
cd.text.append(None)
|
||||
cd.value.append(values[keep])
|
||||
else:
|
||||
raw = _objects(col)
|
||||
keep = np.array([s is not None for s in raw])
|
||||
cd.has_text = True
|
||||
cd.text.append(raw[keep])
|
||||
cd.value.append(np.full(int(keep.sum()), np.nan))
|
||||
cd.index.append(index[keep])
|
||||
cd.chunk.append(np.full(int(keep.sum()), chunk, dtype=np.int16))
|
||||
|
||||
def index_stats(self) -> dict:
|
||||
"""Row-level statistics of the index column over all chunks, in file order. Steps are in seconds for a
|
||||
time log and metres for a depth log, between consecutive distinct index values."""
|
||||
if not self.index_values:
|
||||
return {"n_index_values": 0}
|
||||
idx = np.concatenate(self.index_values)
|
||||
uniq = np.unique(idx)
|
||||
ustep = np.diff(uniq) / (1000.0 if self.kind == "time" else 1.0)
|
||||
return {
|
||||
"n_index_values": int(len(idx)),
|
||||
"n_index_distinct": int(len(uniq)),
|
||||
"n_index_backwards": int((np.diff(idx) < 0).sum()),
|
||||
"index_min": idx.min(), "index_max": idx.max(),
|
||||
"step_median": float(np.median(ustep)) if len(ustep) else None,
|
||||
"step_p10": float(np.quantile(ustep, 0.1)) if len(ustep) else None,
|
||||
"step_p90": float(np.quantile(ustep, 0.9)) if len(ustep) else None,
|
||||
}
|
||||
|
||||
def curves(self, log_id: int = 0) -> list[Curve]:
|
||||
"""Every curve with data, de-duplicated on the index (`dedup_curve`) and sorted by it."""
|
||||
out = []
|
||||
for name in sorted(self.data):
|
||||
cd = self.data[name]
|
||||
index, value, chunk = np.concatenate(cd.index), np.concatenate(cd.value), np.concatenate(cd.chunk)
|
||||
text = None
|
||||
if cd.has_text:
|
||||
text = np.concatenate([t if t is not None else np.full(len(v), None, dtype=object)
|
||||
for t, v in zip(cd.text, cd.value)])
|
||||
index, value, text, chunk, dd = dedup_curve(index, value, text, chunk)
|
||||
stats = dict(cd.stats)
|
||||
stats.update(dd)
|
||||
stats["n_values"] = int(len(index))
|
||||
stats["n_text"] = int(sum(t is not None for t in text)) if text is not None else 0
|
||||
out.append(Curve(log_id, name, index, value, text, chunk, stats))
|
||||
return out
|
||||
|
||||
|
||||
def parse_log(files: list[Path]) -> ParsedLog:
|
||||
"""All chunk files of one log, in file-name order (00001.xml, 00002.xml, ...)."""
|
||||
log = ParsedLog()
|
||||
for f in sorted(files):
|
||||
log.add(read_log_file(f), int(f.stem))
|
||||
return log
|
||||
|
||||
|
||||
def find_logs(root: Path) -> list[tuple[str, str, Path, list[Path]]]:
|
||||
"""(well folder, wellbore subfolder, log directory, chunk files) of every log under `root`, sorted."""
|
||||
out = []
|
||||
for d in sorted(p for p in root.glob("*/*/log/*/*/*") if p.is_dir()):
|
||||
files = sorted(d.glob("*.xml"))
|
||||
if files:
|
||||
rel = d.relative_to(root).parts
|
||||
out.append((rel[0], rel[1], d, files))
|
||||
return out
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------------------------------------------
|
||||
# log: duplicates
|
||||
# --------------------------------------------------------------------------------------------------------------
|
||||
|
||||
def _same(value_a: np.ndarray, value_b: np.ndarray, text_a, text_b) -> np.ndarray:
|
||||
same = (value_a == value_b) | (np.isnan(value_a) & np.isnan(value_b))
|
||||
if text_a is not None:
|
||||
same &= text_a == text_b
|
||||
return same
|
||||
|
||||
|
||||
def dedup_curve(index: np.ndarray, value: np.ndarray, text: np.ndarray | None, chunk: np.ndarray):
|
||||
"""De-duplicate one curve of one log on its index. Rows are sorted by index (stable, so file order breaks
|
||||
ties). Among rows with the same index the *last* row in file order is kept and the others are dropped. A
|
||||
dropped row is counted in `n_dup_same` if the row after it has the same value, else in `n_dup_conflict` (a
|
||||
WITSML store appends corrections, so the later row is the one the server would return).
|
||||
|
||||
In the Volve logs every such row is a plain repeat (`n_dup_conflict` is 0 in all 2,047 logs): the last row of
|
||||
a chunk file is repeated as the first row of the next file, and one log was stored twice.
|
||||
|
||||
Returns (index, value, text, chunk, counts); `n_out_of_order` counts the rows that had to move."""
|
||||
n = len(index)
|
||||
order = np.argsort(index, kind="stable")
|
||||
moved = order != np.arange(n)
|
||||
if moved.any():
|
||||
index, value, chunk = index[order], value[order], chunk[order]
|
||||
text = text[order] if text is not None else None
|
||||
counts = {"n_dup_same": 0, "n_dup_conflict": 0, "n_out_of_order": int(moved.sum())}
|
||||
if n < 2:
|
||||
return index, value, text, chunk, counts
|
||||
same_index = index[1:] == index[:-1]
|
||||
if not same_index.any():
|
||||
return index, value, text, chunk, counts
|
||||
same_value = _same(value[1:], value[:-1], None if text is None else text[1:], None if text is None else text[:-1])
|
||||
keep = np.ones(n, dtype=bool)
|
||||
keep[:-1] = ~same_index # the last row of every run of equal index
|
||||
counts["n_dup_same"] = int((same_index & same_value).sum())
|
||||
counts["n_dup_conflict"] = int((same_index & ~same_value).sum())
|
||||
return index[keep], value[keep], text[keep] if text is not None else None, chunk[keep], counts
|
||||
|
||||
|
||||
#: Two colliding values that differ by at most this (relative to max(1, |value|)) are "rounding": memory logs
|
||||
#: publish 4-5 decimals where the real-time log publishes float32 values with all their digits.
|
||||
ROUNDING = 1e-4
|
||||
|
||||
|
||||
def merge_curve(curves: list[Curve]):
|
||||
"""All logs of one wellbore that publish the same mnemonic -> one series sorted by index, every row kept.
|
||||
|
||||
A mnemonic is only unique inside a log (the Baker Hughes `Depth` curve is the reference depth of its own
|
||||
log), so rows of different logs with the same index are *not* dropped. They are ranked: `dup_rank` is 0 for
|
||||
the row of the preferred log and 1, 2, ... for the others. The preferred log is the one with the most values
|
||||
of this curve in the wellbore (the main record; ties: lower log_id). Keeping `dup_rank = 0` gives at most one
|
||||
value per (wellbore, mnemonic, index).
|
||||
|
||||
Returns (log_id, index, value, text, chunk, dup_rank, overlaps); `overlaps` has one row per pair (preferred
|
||||
log, other log): colliding index values, how many values are identical, differ by rounding, or conflict, and
|
||||
the largest absolute difference."""
|
||||
curves = sorted(curves, key=lambda c: (-len(c.index), c.log_id))
|
||||
index = np.concatenate([c.index for c in curves])
|
||||
value = np.concatenate([c.value for c in curves])
|
||||
chunk = np.concatenate([c.chunk for c in curves])
|
||||
log_id = np.concatenate([np.full(len(c.index), c.log_id, dtype=np.int32) for c in curves])
|
||||
text = None
|
||||
if any(c.text is not None for c in curves):
|
||||
text = np.concatenate([c.text if c.text is not None else np.full(len(c.index), None, dtype=object)
|
||||
for c in curves])
|
||||
n = len(index)
|
||||
rank = np.zeros(n, dtype=np.int8)
|
||||
if len(curves) == 1:
|
||||
return log_id, index, value, text, chunk, rank, []
|
||||
order = np.argsort(index, kind="stable") # stable: the preferred log comes first in a tie
|
||||
index, value, chunk, log_id = index[order], value[order], chunk[order], log_id[order]
|
||||
text = text[order] if text is not None else None
|
||||
new_run = np.ones(n, dtype=bool)
|
||||
new_run[1:] = index[1:] != index[:-1]
|
||||
if new_run.all():
|
||||
return log_id, index, value, text, chunk, rank, []
|
||||
first = np.flatnonzero(new_run)[np.cumsum(new_run) - 1] # position of the preferred row
|
||||
position = np.arange(n) - first
|
||||
rank = np.minimum(position, 127).astype(np.int8)
|
||||
dup = position > 0
|
||||
va, vb = value[first[dup]], value[dup]
|
||||
same = _same(va, vb, None if text is None else text[first[dup]], None if text is None else text[dup])
|
||||
with np.errstate(invalid="ignore"):
|
||||
diff = np.abs(va - vb)
|
||||
rounding = ~same & (diff <= ROUNDING * np.maximum(1.0, np.abs(va)))
|
||||
pairs = pd.DataFrame({"log_id": log_id[first[dup]], "other_log_id": log_id[dup], "same": same,
|
||||
"rounding": rounding, "conflict": ~same & ~rounding, "diff": np.where(same, 0.0, diff)})
|
||||
g = pairs.groupby(["log_id", "other_log_id"], sort=True)
|
||||
overlaps = g.agg(n=("same", "size"), n_same=("same", "sum"), n_rounding=("rounding", "sum"),
|
||||
n_conflict=("conflict", "sum"), max_abs_diff=("diff", "max")).reset_index()
|
||||
return log_id, index, value, text, chunk, rank, overlaps.to_dict("records")
|
||||
|
||||
|
||||
def log_schema(kind: str) -> pa.Schema:
|
||||
index = ("time", pa.timestamp("ms", tz="UTC")) if kind == "time" else ("md", pa.float64())
|
||||
return pa.schema([("wellbore", pa.dictionary(pa.int32(), pa.string())), ("log_id", pa.int32()),
|
||||
("mnemonic", pa.dictionary(pa.int32(), pa.string())), index, ("value", pa.float64()),
|
||||
("text", pa.string()), ("chunk", pa.int16()), ("dup_rank", pa.int8())])
|
||||
|
||||
|
||||
class LongWriter:
|
||||
"""Writes the long log table of one wellbore, curve after curve (so the file is sorted by mnemonic, index).
|
||||
The time index is delta-encoded, so a regular sampling costs almost nothing; the file takes about one byte
|
||||
per value. Small curves are buffered into row groups of about a million rows."""
|
||||
|
||||
ROW_GROUP = 1 << 20
|
||||
|
||||
def __init__(self, path: Path, kind: str, wellbore: str, mnemonics: list[str]) -> None:
|
||||
self.path, self.kind, self.schema = path, kind, log_schema(kind)
|
||||
self.wellbores, self.mnemonics = pa.array([wellbore]), pa.array(sorted(mnemonics))
|
||||
self.codes = {m: i for i, m in enumerate(sorted(mnemonics))}
|
||||
self.buffer: list[pa.Table] = []
|
||||
self.buffered = self.rows = 0
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
self.tmp = path.with_suffix(".parquet.tmp")
|
||||
self.writer = pq.ParquetWriter(
|
||||
self.tmp, self.schema, compression="zstd", compression_level=9,
|
||||
use_dictionary=["wellbore", "mnemonic", "log_id", "chunk", "text", "dup_rank"],
|
||||
column_encoding={"time": "DELTA_BINARY_PACKED"} if kind == "time" else None)
|
||||
|
||||
def write(self, mnemonic: str, log_id, index, value, text, chunk, dup_rank) -> None:
|
||||
n = len(index)
|
||||
if n == 0:
|
||||
return
|
||||
zeros = pa.array(np.zeros(n, dtype=np.int32))
|
||||
idx = pa.array(index, type=pa.int64()).cast(pa.timestamp("ms", tz="UTC")) if self.kind == "time" \
|
||||
else pa.array(index, type=pa.float64())
|
||||
table = pa.Table.from_arrays([
|
||||
pa.DictionaryArray.from_arrays(zeros, self.wellbores), pa.array(log_id, type=pa.int32()),
|
||||
pa.DictionaryArray.from_arrays(pa.array(np.full(n, self.codes[mnemonic], dtype=np.int32)), self.mnemonics),
|
||||
idx, pa.array(value, mask=np.isnan(value)),
|
||||
pa.array(text, type=pa.string()) if text is not None else pa.nulls(n, pa.string()),
|
||||
pa.array(chunk, type=pa.int16()), pa.array(dup_rank, type=pa.int8())], schema=self.schema)
|
||||
self.buffer.append(table)
|
||||
self.buffered += n
|
||||
self.rows += n
|
||||
if self.buffered >= self.ROW_GROUP:
|
||||
self._flush()
|
||||
|
||||
def _flush(self) -> None:
|
||||
if self.buffer:
|
||||
self.writer.write_table(pa.concat_tables(self.buffer), row_group_size=self.ROW_GROUP)
|
||||
self.buffer, self.buffered = [], 0
|
||||
|
||||
def close(self) -> None:
|
||||
self._flush()
|
||||
self.writer.close()
|
||||
self.tmp.replace(self.path)
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------------------------------------------
|
||||
# trajectory, message, bhaRun, mudLog
|
||||
# --------------------------------------------------------------------------------------------------------------
|
||||
|
||||
class Flat:
|
||||
"""Flattens WITSML elements into rows and counts sentinels and units per (table, column)."""
|
||||
|
||||
def __init__(self) -> None:
|
||||
self.sentinels: collections.Counter = collections.Counter() # (table, column, value) -> n
|
||||
self.units: collections.Counter = collections.Counter() # (table, column, uom published) -> n
|
||||
|
||||
def value(self, e: ET.Element, table: str, column: str):
|
||||
text = (e.text or "").strip()
|
||||
if "uom" not in e.attrib:
|
||||
return text or None
|
||||
uom = e.attrib["uom"]
|
||||
if not text:
|
||||
return None
|
||||
v = float(text)
|
||||
extra = [s for (t, prefix), s in EXTRA_SENTINELS.items() if t == table and column.startswith(prefix)]
|
||||
if v in SENTINELS or v in extra:
|
||||
self.sentinels[(table, column, v)] += 1
|
||||
return None
|
||||
self.units[(table, column, uom)] += 1
|
||||
return v * STORED_UNITS[uom][1] if uom in STORED_UNITS else v
|
||||
|
||||
def leaves(self, elem: ET.Element, row: dict, table: str, prefix: str = "", skip: tuple[str, ...] = ()) -> dict:
|
||||
"""Leaves of `elem` into `row`; a nested element prefixes its leaves with its tag (numbered from the second
|
||||
occurrence on). `uid` and `uidRef` attributes become `<tag>_uid` and `<tag>_uidRef` columns."""
|
||||
seen: collections.Counter = collections.Counter()
|
||||
for child in elem:
|
||||
tag = _tag(child)
|
||||
if tag in skip or tag in DROPPED:
|
||||
continue
|
||||
if len(child) == 0:
|
||||
column = prefix + tag
|
||||
if column in row:
|
||||
raise ValueError(f"{table}: repeated leaf {column}")
|
||||
row[column] = self.value(child, table, column)
|
||||
if "uidRef" in child.attrib:
|
||||
row[column + "_uidRef"] = child.attrib["uidRef"]
|
||||
else:
|
||||
seen[tag] += 1
|
||||
nested = f"{prefix}{tag}{seen[tag] if seen[tag] > 1 else ''}_"
|
||||
if "uid" in child.attrib:
|
||||
row[nested + "uid"] = child.attrib["uid"]
|
||||
self.leaves(child, row, table, nested, skip)
|
||||
return row
|
||||
|
||||
|
||||
def _object(path: Path, plural: str, singular: str) -> ET.Element:
|
||||
root = ET.parse(path).getroot()
|
||||
if _tag(root) != plural or len(root) != 1 or _tag(root[0]) != singular:
|
||||
raise ValueError(f"{path}: expected one {singular} in {plural}")
|
||||
return root[0]
|
||||
|
||||
|
||||
def _ids(obj: ET.Element, path: Path, root: Path) -> dict:
|
||||
rel = path.relative_to(root)
|
||||
name_well, name_wellbore = obj.findtext(NS + "nameWell") or "", obj.findtext(NS + "nameWellbore") or ""
|
||||
wb, source = wellbore_name(name_well, name_wellbore, obj.attrib.get("uidWellbore"))
|
||||
return {"wellbore": wb, "wellbore_source": source,
|
||||
"wellbore_witsml": published_wellbore(name_well, name_wellbore)[0], "folder": rel.parts[0],
|
||||
"path": rel.as_posix(), "uidWell": obj.attrib.get("uidWell"),
|
||||
"uidWellbore": obj.attrib.get("uidWellbore"), "uid": obj.attrib.get("uid")}
|
||||
|
||||
|
||||
def _utc(s: pd.Series) -> pd.Series:
|
||||
return pd.to_datetime(s, utc=True, format="ISO8601")
|
||||
|
||||
|
||||
def parse_objects(root: Path) -> tuple[dict[str, pd.DataFrame], Flat]:
|
||||
"""trajectory, message, bhaRun and mudLog files under `root` -> tables `trajectory_catalog` (one row per
|
||||
trajectory), `trajectory` (stations), `messages`, `bha_runs`, `mudlog_catalog`, `mudlog_intervals`,
|
||||
`mudlog_lithology`, `mudlog_qualifiers`. UTC timestamps are added next to the published time strings."""
|
||||
flat = Flat()
|
||||
rows: dict[str, list[dict]] = {k: [] for k in (
|
||||
"trajectory_catalog", "trajectory", "messages", "bha_runs", "mudlog_catalog", "mudlog_intervals",
|
||||
"mudlog_lithology", "mudlog_qualifiers")}
|
||||
for path in sorted(root.glob("*/*/trajectory/*.xml")):
|
||||
obj = _object(path, "trajectorys", "trajectory")
|
||||
ids = _ids(obj, path, root)
|
||||
head = flat.leaves(obj, dict(ids), "trajectory_catalog", skip=("trajectoryStation",))
|
||||
stations = obj.findall(NS + "trajectoryStation")
|
||||
head["n_stations"] = len(stations)
|
||||
rows["trajectory_catalog"].append(head)
|
||||
for seq, st in enumerate(stations):
|
||||
row = {"wellbore": ids["wellbore"], "path": ids["path"], "traj_uid": ids["uid"],
|
||||
"traj_name": head.get("name"), "seq": seq, "uid": st.attrib.get("uid")}
|
||||
rows["trajectory"].append(flat.leaves(st, row, "trajectory"))
|
||||
for path in sorted(root.glob("*/*/message/*.xml")):
|
||||
obj = _object(path, "messages", "message")
|
||||
rows["messages"].append(flat.leaves(obj, _ids(obj, path, root), "messages"))
|
||||
for path in sorted(root.glob("*/*/bhaRun/*.xml")):
|
||||
obj = _object(path, "bhaRuns", "bhaRun")
|
||||
rows["bha_runs"].append(flat.leaves(obj, _ids(obj, path, root), "bha_runs"))
|
||||
for path in sorted(root.glob("*/*/mudLog/*.xml")):
|
||||
obj = _object(path, "mudLogs", "mudLog")
|
||||
ids = _ids(obj, path, root)
|
||||
head = flat.leaves(obj, dict(ids), "mudlog_catalog", skip=("geologyInterval",))
|
||||
intervals = obj.findall(NS + "geologyInterval")
|
||||
head["n_intervals"] = len(intervals)
|
||||
rows["mudlog_catalog"].append(head)
|
||||
for seq, gi in enumerate(intervals):
|
||||
base = {"wellbore": ids["wellbore"], "path": ids["path"], "mudlog_uid": ids["uid"], "seq": seq,
|
||||
"uid": gi.attrib.get("uid")}
|
||||
row = flat.leaves(gi, dict(base), "mudlog_intervals", skip=("lithology",))
|
||||
liths = gi.findall(NS + "lithology")
|
||||
row["n_lithology"] = len(liths)
|
||||
rows["mudlog_intervals"].append(row)
|
||||
for lseq, lith in enumerate(liths):
|
||||
lrow = {"wellbore": ids["wellbore"], "mudlog_uid": ids["uid"], "interval_uid": base["uid"],
|
||||
"interval_seq": seq, "seq": lseq, "uid": lith.attrib.get("uid")}
|
||||
rows["mudlog_lithology"].append(flat.leaves(lith, lrow, "mudlog_lithology", skip=("qualifier",)))
|
||||
for qseq, q in enumerate(lith.findall(NS + "qualifier")):
|
||||
qrow = {"wellbore": ids["wellbore"], "mudlog_uid": ids["uid"], "interval_uid": base["uid"],
|
||||
"lithology_uid": lrow["uid"], "seq": qseq, "uid": q.attrib.get("uid")}
|
||||
rows["mudlog_qualifiers"].append(flat.leaves(q, qrow, "mudlog_qualifiers"))
|
||||
tables = {name: pd.DataFrame(r) for name, r in rows.items()}
|
||||
for table, column in (("trajectory", "dTimStn"), ("messages", "dTim"), ("bha_runs", "dTimStart"),
|
||||
("bha_runs", "dTimStop"), ("mudlog_intervals", "dTim")):
|
||||
if column in tables[table]:
|
||||
tables[table][column + "_utc"] = _utc(tables[table][column])
|
||||
if len(tables["mudlog_intervals"]):
|
||||
tables["mudlog_intervals"]["tadi_implausible"] = tadi_implausible(tables["mudlog_intervals"])
|
||||
return tables, flat
|
||||
|
||||
|
||||
def tadi_implausible(intervals: pd.DataFrame) -> pd.Series:
|
||||
"""True where TADI (section 3.3) would drop a mudLog interval: ROP > 200 m/h, RPM > 300 or WOB > 500 kN.
|
||||
A flag only; the values stay as published."""
|
||||
out = pd.Series(False, index=intervals.index)
|
||||
for column, limit in TADI_FILTERS.items():
|
||||
if column in intervals:
|
||||
out |= intervals[column] > limit
|
||||
return out
|
||||
|
||||
|
||||
def units_table(flat: Flat) -> pd.DataFrame:
|
||||
"""(table, column, uom published, n values, uom stored, factor) for every measure of the object tables.
|
||||
Refuses a column that would be stored in more than one unit."""
|
||||
rows = []
|
||||
for (table, column, uom), n in sorted(flat.units.items()):
|
||||
stored, factor = STORED_UNITS.get(uom, (uom, 1.0))
|
||||
rows.append({"table": table, "column": column, "uom": uom, "n": n, "uom_stored": stored, "factor": factor})
|
||||
out = pd.DataFrame(rows, columns=["table", "column", "uom", "n", "uom_stored", "factor"])
|
||||
mixed = out.groupby(["table", "column"])["uom_stored"].nunique()
|
||||
if (mixed > 1).any():
|
||||
raise ValueError(f"columns stored in more than one unit: {mixed[mixed > 1].index.tolist()}")
|
||||
return out
|
||||
|
||||
|
||||
def sentinels_table(flat: Flat) -> pd.DataFrame:
|
||||
return pd.DataFrame([{"table": t, "column": c, "value": v, "n": n, "kind": "sentinel"}
|
||||
for (t, c, v), n in sorted(flat.sentinels.items())],
|
||||
columns=["table", "column", "value", "n", "kind"])
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------------------------------------------
|
||||
# DuckDB views over the long log tables
|
||||
# --------------------------------------------------------------------------------------------------------------
|
||||
|
||||
def depth_filter(channels: dict) -> str:
|
||||
return " OR ".join(f"(d.mnemonic = '{m}'" + (f" AND c.name = '{name}')" if name else ")")
|
||||
for m, name in channels.items())
|
||||
|
||||
|
||||
def view_sql(out: Path) -> dict[str, str]:
|
||||
"""SELECT statements of the views over `<out>/time_log/*.parquet` and `<out>/depth_log/*.parquet`:
|
||||
|
||||
`time_log`, `depth_log` every published value;
|
||||
`time_log_dedup`, `depth_log_dedup` one value per (wellbore, mnemonic, index): the rows with dup_rank = 0.
|
||||
Not for the Baker Hughes `Depth` curve, which is the reference
|
||||
depth of its own log (9.0 of its 15.0 million collisions between logs
|
||||
disagree): select it by log, or use `drill_depth`;
|
||||
`drill_depth` hole depth and bit depth against time (`HOLE_DEPTH`, `BIT_DEPTH`), one
|
||||
value per (wellbore, time, depth): the log with the most values wins.
|
||||
"""
|
||||
hole, bit = depth_filter(HOLE_DEPTH), depth_filter(BIT_DEPTH)
|
||||
mnemonics = ", ".join(repr(m) for m in (*HOLE_DEPTH, *BIT_DEPTH))
|
||||
views = {}
|
||||
for kind in ("time", "depth"):
|
||||
views[f"{kind}_log"] = f"SELECT * FROM read_parquet('{(Path(out) / f'{kind}_log').as_posix()}/*.parquet')"
|
||||
views[f"{kind}_log_dedup"] = f"SELECT * EXCLUDE (dup_rank) FROM {kind}_log WHERE dup_rank = 0"
|
||||
views["drill_depth"] = f"""
|
||||
SELECT wellbore, time, depth, first(value ORDER BY n_values DESC, log_id) AS md,
|
||||
first(log_id ORDER BY n_values DESC, log_id) AS log_id
|
||||
FROM (SELECT d.wellbore, d.time, d.value, d.log_id, c.n_values,
|
||||
CASE WHEN {hole} THEN 'hole' ELSE 'bit' END AS depth
|
||||
FROM time_log d JOIN log_catalog c USING (log_id)
|
||||
WHERE d.mnemonic IN ({mnemonics}) AND d.value IS NOT NULL AND ({hole} OR {bit}))
|
||||
GROUP BY wellbore, time, depth"""
|
||||
return views
|
||||
|
||||
|
||||
def connect(out: Path | None = None):
|
||||
"""Read-only connection to `volve_witsml.duckdb`. The log views stored in the file name the parquet files by
|
||||
the absolute path they had when the file was built; here they are redefined (as temporary views) over the
|
||||
files next to the database, so the tables also work after the outputs folder was moved or copied."""
|
||||
import duckdb
|
||||
|
||||
from . import paths
|
||||
out = Path(out) if out else paths.outputs_dir() / "witsml"
|
||||
con = duckdb.connect(str(out / "volve_witsml.duckdb"), read_only=True)
|
||||
for name, sql in view_sql(out.resolve()).items():
|
||||
con.execute(f"CREATE OR REPLACE TEMP VIEW {name} AS {sql}")
|
||||
return con
|
||||
Reference in New Issue
Block a user