- 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>
729 lines
31 KiB
Python
729 lines
31 KiB
Python
"""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}
|