"""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"(? list[float]: """Hole sizes named in `text` as '" 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()}