"""Leakage-controlled feature tables for classification and paired OCR diagnostics.""" from __future__ import annotations import numpy as np import pandas as pd from . import labels, witsml from .ddr.qc import OPERATIONS, TEXT_COLUMNS TEXT = ("comments", "previous", "next", "sum24Hr", "forecast24Hr") DELIMITER = " [SEP] " def render_status(root): docs = pd.read_csv(root / "ocr/hub_docs.csv") pages = pd.read_csv(root / "ocr/hub/match.csv", usecols=["file", "ddr", "matched", "dates_agree"]) flagged = pages[pages["ddr"] & pages["matched"] & pages["dates_agree"].eq(False)] flags = flagged["file"].str.rsplit("/", n=1).str[-1].str.removesuffix(".pdf") return set(docs.loc[docs["n_pages"].eq(docs["ok"]), "report_id"]), set(flags), len(flagged) def ocr_text(root, activities): # QC row alignment transfers printed row identities. Empty recognitions stay empty. qc = pd.read_parquet(root / "ocr_qc_hub/items.parquet", columns=["doc", "part", "table", "key", "row", "hyp"]) summary = (qc[qc["part"].eq("text") & qc["key"].isin(TEXT_COLUMNS)] .pivot(index="doc", columns="key", values="hyp").rename(columns=TEXT_COLUMNS)) comments = (qc[qc["part"].eq("cell") & qc["table"].eq(OPERATIONS[0]) & qc["key"].eq("Remark")] .set_index(["doc", "row"])["hyp"]) ordered = activities.sort_values(["report_id", "seq"]) loc = pd.MultiIndex.from_arrays([ordered["report_id"], ordered.groupby("report_id").cumcount()]) return summary, pd.Series(comments.reindex(loc).to_numpy(), index=ordered["act_id"]) def activity_text(view): view = view.sort_values(["report_id", "seq"]).copy() view["previous"] = view.groupby("report_id")["comments"].shift(1) view["next"] = view.groupby("report_id")["comments"].shift(-1) return view def strings(frame, cols): return frame[list(cols)].fillna("").replace("None", "").astype(str).agg(DELIMITER.join, axis=1) def witsml_windows(root, windows, protocol, spec): """Aggregate by explicit UTC bounds. The end of every window is excluded.""" windows = windows.dropna(subset=["window_start", "window_end"]) mnemonics = spec["classification"]["witsml_mnemonics"] missing = protocol["witsml_features"]["treat_as_missing"] with witsml.connect(root / "witsml") as con: con.execute("SET threads=4") con.register("windows", windows) values = con.execute(""" SELECT w.item, upper(d.mnemonic) AS channel, avg(d.value) AS mean, stddev_pop(d.value) AS sd, max(d.time) AS last_channel FROM time_log d JOIN windows w ON d.wellbore = w.wellbore AND d.time >= w.window_start AND d.time < w.window_end WHERE d.dup_rank = 0 AND upper(d.mnemonic) IN (SELECT unnest(?)) AND isfinite(d.value) AND abs(d.value) <= ? AND d.value NOT IN (SELECT unnest(?)) GROUP BY 1, 2 """, [mnemonics, float(missing["abs_greater_than"]), missing["values"]]).df() depth = con.execute(""" SELECT w.item, count(*) AS depth_samples, max(d.md) AS max_hole_md, max(d.time) AS last_depth FROM drill_depth d JOIN windows w ON d.wellbore = w.wellbore AND d.time >= w.window_start AND d.time < w.window_end WHERE d.depth = 'hole' AND isfinite(d.md) AND abs(d.md) <= ? AND d.md NOT IN (SELECT unnest(?)) GROUP BY 1 """, [float(missing["abs_greater_than"]), missing["values"]]).df() wide = values.pivot(index="item", columns="channel", values=["mean", "sd"]) wide.columns = ["witsml_" + "_".join(c).lower() for c in wide.columns] return depth.set_index("item").join(wide, how="outer").join(values.groupby("item")["last_channel"].max()) def t1_frame(root, view, summary, complete, flagged): days = pd.read_parquet(root / "labels/t1_reports.parquet").query("scope == 'drilling_day'").copy() days["subset"] = np.where(days["filled_by"].eq("diaHole"), "published", "filled") frame = days.rename(columns={"report_id": "item", "section": "target"}) for mode, acts in view.items(): daily = acts.groupby("report_id", sort=False).agg( comments=("comments", lambda s: " ".join(s.dropna().astype(str))), sum24Hr=("sum24Hr", "first"), forecast24Hr=("forecast24Hr", "first")) if mode == "ocr": daily = daily[["comments"]].join(summary) frame[f"text_{mode}"] = frame["item"].map(strings(daily, ("sum24Hr", "forecast24Hr", "comments"))).fillna("") frame["c4"] = frame["item"].isin(complete) frame["date_flag"] = frame["item"].isin(flagged) return frame[["item", "wellbore", "well", "target", "subset", "c4", "date_flag", "text_xml", "text_ocr", "start_utc", "end_utc"]] def t2_frame(root, view, codes, complete, flagged): target = pd.read_parquet(root / "labels/t2_labels.parquet", columns=["act_id", "npt_a", "npt_b", "cause_b"]) frame = (view["xml"][["act_id", "report_id", "well", "wellbore", "comments"]] .merge(target, on="act_id", validate="one_to_one").rename(columns={"act_id": "item"})) frame["comment_length"] = frame["comments"].fillna("").str.len() frame["c4"] = frame["report_id"].isin(complete) frame["date_flag"] = frame["report_id"].isin(flagged) for mode, acts in view.items(): frame[f"text_{mode}"] = frame["item"].map(strings(acts.set_index("act_id"), TEXT)) frame["codes"] = frame["item"].map(strings(codes, labels.MASKED)) return frame.drop(columns="comments") def t3_frame(root, view, codes, protocol, spec): acts = pd.read_parquet(root / "labels/t3_activities.parquet") cells = pd.read_parquet(root / "labels/t3_cells.parquet") cells = cells[cells["in_own_hole"] & cells["wellbore"].isin(protocol["tasks"]["t3"]["wellbores"])].copy() intervals = pd.read_parquet(root / "labels/t3_intervals.parquet") # Forecast all cells at the first in-hole DDR activity. This landmark is defined without NPT labels. cutoff = acts[acts["depth_class"].eq("in_hole")].groupby("wellbore")["start_utc"].min() cutoff = cutoff.reindex(sorted(cells["wellbore"].unique())) cells["cutoff"] = cells["wellbore"].map(cutoff) for suffix in ("a", "b"): starts = cells[f"interval_id_{suffix}"].map(intervals.set_index("interval_id")["first_start_utc"]) if cells["cutoff"].isna().any() or (starts.notna() & (cells["cutoff"] > starts)).any(): raise ValueError("A T3 forecast cutoff falls after the start of its reference interval.") if len(cells) != protocol["validation"]["m2_evidence"]["t3_split"]["cells"]: raise ValueError("T3 cell universe differs from G1.") history = pd.Timedelta(hours=spec["classification"]["t3_history_hours"]) ends = view["xml"]["wellbore"].map(cutoff) # Current-day summaries and neighbouring rows can cross the landmark, so use only completed activity comments. before = view["xml"]["end_utc"].lt(ends) & view["xml"]["end_utc"].ge(ends - history) past = view["xml"].loc[before, ["act_id", "wellbore", "comments", "end_utc"]] past["codes"] = past["act_id"].map(strings(codes, labels.MASKED)) past = past.sort_values(["wellbore", "end_utc", "act_id"]) grouped = past.groupby("wellbore").agg( text_xml=("comments", lambda s: DELIMITER.join(s.dropna())), codes=("codes", DELIMITER.join), last_activity=("end_utc", "max")) reps = pd.read_parquet(root / "ddr/reports.parquet", columns=["wellbore", "end_utc", "sum24Hr", "forecast24Hr"]) end = reps["wellbore"].map(cutoff) reps = reps[reps["end_utc"].lt(end) & reps["end_utc"].ge(end - history)].sort_values("end_utc") completed = strings(reps, ("sum24Hr", "forecast24Hr")).groupby(reps["wellbore"]).agg(DELIMITER.join) windows = cutoff.rename("window_end").reset_index().assign(item=lambda d: d["wellbore"], window_start=lambda d: d["window_end"] - history) cells = cells.join(grouped, on="wellbore").join(witsml_windows(root, windows, protocol, spec), on="wellbore") cells["last_report"] = cells["wellbore"].map(reps.groupby("wellbore")["end_utc"].max()) cells["text_xml"] = cells["text_xml"].fillna("") + DELIMITER + cells["wellbore"].map(completed).fillna("") cells["item"] = cells["wellbore"] + ":" + cells["cell"].astype(str) cells["depth_from_own_top"] = cells["md_top"] - cells["own_hole_top_md"] # Keep source start/last-used timestamps in the feature audit, outside the model column allowlists. keep = ["item", "well", "wellbore", "cutoff", "cell", "md_top", "depth_from_own_top", "text_xml", "codes", "label_a", "label_b", "last_activity", "last_report", "last_channel", "last_depth", "depth_samples", "max_hole_md"] return cells[keep + [c for c in cells if c.startswith("witsml_")]] def feature_tables(root, protocol, spec): acts = pd.read_parquet(root / "ddr/activities.parquet") codes = acts.set_index("act_id") t2 = pd.read_parquet(root / "labels/t2_inputs.parquet") forbidden = set(protocol["masking"]["masked_fields"] + protocol["masking"]["withheld_for_t2_t3"]) if forbidden & set(t2): raise ValueError("A withheld field appears in the masked input view.") complete, flagged, pages = render_status(root) c4 = protocol["reporting"]["c4"] reports = pd.read_parquet(root / "ddr/reports.parquet", columns=["report_id"]) if len(set(reports["report_id"]) - complete) != c4["incomplete_ocr_reports_excluded"]: raise ValueError("Incomplete OCR count differs from G1.") if pages != c4["date_disagreement_pages"]: raise ValueError("OCR date disagreement count differs from G1.") summary, comments = ocr_text(root, acts) ocr = t2.assign(comments=t2["act_id"].map(comments)) for c in TEXT_COLUMNS.values(): ocr[c] = ocr["report_id"].map(summary[c]) view = {"xml": activity_text(t2), "ocr": activity_text(ocr)} section = t1_frame(root, view, summary, complete, flagged) windows = section[["item", "wellbore", "start_utc", "end_utc"]].rename( columns={"start_utc": "window_start", "end_utc": "window_end"}) section = section.join(witsml_windows(root, windows, protocol, spec), on="item") return {"t1": section, "t2": t2_frame(root, view, codes, complete, flagged), "t3": t3_frame(root, view, codes, protocol, spec)}