#!/usr/bin/env python3 """T5 similar-interval retrieval and the neighbour forecast under protocol v5. scripts/20_m5_t5.py build the T5 items, score every representation, write outputs/m5/t5/ Refuses to run unless configs/protocol_v5.yaml matches its checksum. Relevance labels come from the XML-derived T3 intervals, the T1 section and the formation picks; no representation reads codes, causes, labels, section or formation. """ from __future__ import annotations import json from pathlib import Path import numpy as np import pandas as pd import yaml from volve_dia import m34, m5_t5 as t5 from volve_dia.m34_features import witsml_windows from volve_dia.m5_judge import sha256_file ROOT = Path(__file__).resolve().parents[1] PROTOCOL = ROOT / "configs/protocol_v5.yaml" RESAMPLES, SEED, HISTORY = 2000, 20261117, pd.Timedelta(hours=24) RUNS = (("b", "well", "primary"), ("a", "well", "sensitivity_definition"), ("b", "wellbore", "sensitivity_pool"), ("a", "wellbore", "sensitivity_definition_pool")) V1_T3_AP = {"majority": 0.114, "tfidf": 0.123} def pre_event_text(items, acts): """Masked comments of the same wellbore's activities that end in [start - 24 h, start), in time order.""" acts = acts.dropna(subset=["end_utc"]).sort_values(["wellbore", "end_utc", "act_id"]) by_wellbore = {w: g for w, g in acts.groupby("wellbore")} texts = [] for wellbore, start in zip(items["wellbore"], items["first_start_utc"]): g = by_wellbore.get(wellbore) if g is None: texts.append("") continue window = g[g["end_utc"].lt(start) & g["end_utc"].ge(start - HISTORY)] texts.append(t5.DELIMITER.join(window["comments"].dropna())) return texts def build_items(root, protocol, spec, definition): intervals = pd.read_parquet(root / "labels/t3_intervals.parquet") cells = pd.read_parquet(root / "labels/t3_cells.parquet") sections = pd.read_parquet(root / "labels/t1_reports.parquet", columns=["report_id", "section"]) sections = sections.set_index("report_id")["section"] picks = pd.read_parquet(root / "witsml/formation_tops.parquet", columns=["wellbore", "unit", "md"]) picks = picks.dropna(subset=["wellbore", "md"]) items = t5.eligible_intervals(intervals, cells, sections, picks, protocol["tasks"]["t3"]["wellbores"], definition) acts = pd.read_parquet(root / "labels/t2_inputs.parquet", columns=["act_id", "wellbore", "end_utc", "comments"]) comments = acts.set_index("act_id")["comments"] items["text_pre"] = pre_event_text(items, acts) items["text_event"] = items["act_ids"].map( lambda ids: t5.DELIMITER.join(str(c) for c in comments.reindex(sorted(ids)).dropna())) windows = items[["interval_id", "wellbore", "first_start_utc"]].rename( columns={"interval_id": "item", "first_start_utc": "window_end"}) windows["window_start"] = windows["window_end"] - HISTORY stats = witsml_windows(root, windows, protocol, spec).reindex(columns=list(t5.WITSML_COLUMNS)) items = items.join(stats, on="interval_id") return items def label_counts(items): return {"n": int(len(items)), "wells": int(items["well"].nunique()), "wellbores": int(items["wellbore"].nunique()), "by_well": items["well"].value_counts().sort_index().to_dict(), "by_section": items["section"].value_counts().to_dict(), "by_formation": items["formation"].value_counts().to_dict(), "witsml_missing_share": float(items[list(t5.WITSML_COLUMNS)].isna().all(axis=1).mean()), "text_pre_empty_share": float(items["text_pre"].eq("").mean())} def main(): expected = PROTOCOL.with_suffix(".yaml.sha256").read_text().split()[0] if sha256_file(PROTOCOL) != expected: raise SystemExit("configs/protocol_v5.yaml does not match its checksum") v5 = yaml.safe_load(PROTOCOL.read_text()) protocol, spec = m34.configuration() root, digests = m34.inputs(protocol) dest = root / "m5/t5" dest.mkdir(parents=True, exist_ok=True) report = {"protocol": {"file": str(PROTOCOL.relative_to(ROOT)), "sha256": expected, "version": v5["version"]}, "inputs": digests, "items": {}, "retrieval": {}, "knn_forecast": {}} frames = [] items_by_def = {d: build_items(root, protocol, spec, d) for d in ("a", "b")} for d, items in items_by_def.items(): report["items"][d] = label_counts(items) items.drop(columns=["cause_set"]).assign(act_ids=items["act_ids"].map(list)).to_parquet( dest / f"items_{d}.parquet", index=False) for definition, group, name in RUNS: per_query = t5.evaluate(items_by_def[definition], group, SEED) per_query.insert(0, "run", name) frames.append(per_query) first = per_query.drop_duplicates("interval_id") report["retrieval"][name] = { "definition": definition, "held_out": group, "n_queries": int(len(first)), "queries_without_fully_relevant": int(first["n_fully_relevant"].eq(0).sum()), "median_fully_relevant": float(first["n_fully_relevant"].median()), "median_candidates": float(first["n_candidates"].median()), "representations": t5.summarise(per_query, RESAMPLES, SEED)} print(name, {r: round(v["ndcg10"]["mean"], 3) for r, v in report["retrieval"][name]["representations"].items()}) pd.concat(frames, ignore_index=True).to_parquet(dest / "per_query.parquet", index=False) features = pd.read_parquet(root / "m34/features_t3.parquet") columns = {"depth": ["md_top"], "depth_witsml": ["md_top", "depth_from_own_top", *t5.WITSML_COLUMNS]} knn = features[["item", "well", "wellbore", "label_a", "label_b"]].copy() for label in ("label_b", "label_a"): block = {} for rep, cols in columns.items(): scores = t5.knn_scores(features, label, cols) knn[f"{rep}_{label}"] = scores block[rep] = t5.ap_ci(features[label], scores, features["well"], RESAMPLES, SEED) report["knn_forecast"][label] = block print(label, {r: round(v["ap"], 3) for r, v in block.items()}, "prevalence", round(block["depth"]["prevalence"], 3)) report["knn_forecast"]["v1_t3_reference_ap_b_masked"] = V1_T3_AP knn.to_parquet(dest / "knn_scores.parquet", index=False) m34.atomic_write(dest / "report.json", json.dumps(report, indent=1, default=_json).encode()) def _json(value): if isinstance(value, (np.integer, np.floating)): return value.item() raise TypeError(type(value)) if __name__ == "__main__": main()