diff --git a/configs/protocol_v5.yaml b/configs/protocol_v5.yaml new file mode 100644 index 0000000..601e4c3 --- /dev/null +++ b/configs/protocol_v5.yaml @@ -0,0 +1,98 @@ +# Protocol v5: T5 similar-interval retrieval (optional task of plan section 4). Extends locked v4. +protocol: volve-dia +version: 5 +status: locked +drafted: 2026-11-20 +locked_before: >- + any retrieval or forecasting score was computed; only relevance-label counts (eligible intervals per definition, + well, section and formation, and the number of fully relevant candidates per query) were inspected +extends: + file: configs/protocol_v4.yaml + sha256: 6a9ad0fb64e319b914427e4ec58c4cfafdca91b393da9309f9b30391a12568d0 +deviation: + date: 2026-11-20 + what: >- + Plan section 4 lists T5 as optional (embedding of WITSML, DDR and formation windows; nDCG@k, MRR; PR-AUC when + trouble is forecast from neighbours; leave-one-wellbore-out; relevance by rule: same hole section, same formation, + same NPT group). Protocols v1 to v4 do not define it. v5 fixes items, relevance, representations, metrics and + statistics before any score. The primary candidate pool excludes the query's whole well, matching the primary + grouping of v1; the plan's leave-one-wellbore-out pool is a sensitivity analysis. + consequence: >- + T5 is a diagnostic task outside G2. The relevance labels come from the XML-derived T3 intervals, the T1 section + and the formation picks, all by code. No rater is involved and no gate depends on T5. +unchanged: + - protocols v1 to v4 in full, including masking, T3 labels and the T1-T4 headline metrics +items: + unit: T3 interval (outputs/labels/t3_intervals.parquet) + primary_definition: b + sensitivity_definition: a + eligible: >- + an interval of a T3 wellbore of protocol v1 (tasks.t3.wellbores) whose md_top lies in the own hole + (md_top >= own_hole_top_md of that wellbore), whose section is known and whose formation is known + section: >- + t1_reports.section (published or forward-filled) of the report of the interval's first activity (the act_id + that sorts first); intervals whose report has no section are not eligible + formation: >- + the unit of the deepest formation pick with md <= interval md_top among the picks of the DDR wellbore + (outputs/witsml/formation_tops.parquet, column wellbore); the unit is case-folded and the words "volve" and + "sand" and the suffixes "fm." and "gp." are removed, so "Hugin Fm. VOLVE" becomes "hugin" and "Heather Fm. Sand + VOLVE" becomes "heather"; intervals above the first pick are not eligible + cause_set: the pipe-separated causes of the interval (derived from codes by the T3 rule; never a model input) +relevance: + gain: g = [same section] + [same formation] + [cause sets intersect], so g takes the values 0 to 3 + fully_relevant: g = 3 +candidates: + primary: every eligible interval of the same definition from the other wells (leave-one-well-out) + sensitivity: every eligible interval of the same definition from the other wellbores (leave-one-wellbore-out) +representations: + rule: >- + No representation reads activity codes, causes, labels, section or formation fields. Text is the masked + activity comments of table t2_inputs. Hole sizes or depths named in the text are observable context, not code + leakage (as in v1 t1_hole_size). Transformations (TF-IDF vocabulary and weights, imputation medians, z-scores) + are fitted on the candidate pool of each held-out group, never on the query group. + random: mean of each metric over 100 random orderings of the candidates (numpy default_rng, seed 20261117) + depth: absolute difference of md_top (smaller is closer) + witsml_pre: >- + mean and population standard deviation of HKLD, ROP, RPM and SPPA in the 24 hours before the interval's + first_start_utc (end excluded; suspect values missing as in v1), the same aggregation as the T3 features; + missing values replaced by the candidate-pool median, z-scored on the pool, Euclidean distance + text_pre: >- + TF-IDF (word 1-2 grams, min_df 1, sublinear tf) of the masked comments of the same wellbore's activities that end + in [first_start_utc - 24 h, first_start_utc), joined in time order; cosine similarity + text_event: >- + TF-IDF as above of the masked comments of the interval's own activities. This is a description view (query by + example after the event), not a forecast, and is reported separately from the pre-event representations + rrf_pre: reciprocal rank fusion, sum of 1 / (60 + rank), over depth, witsml_pre and text_pre + rrf_all: reciprocal rank fusion over depth, witsml_pre, text_pre and text_event + ties: equal scores are ordered by one fixed random order of the candidates (numpy default_rng, seed 20261117) +metrics: + primary: nDCG@10 with linear gain g; the ideal ranking sorts all candidates of the query by g + secondary: + - MRR of the first fully relevant candidate; queries without a fully relevant candidate are left out of MRR and + their number is reported + - P@10, the share of fully relevant candidates among the first 10 + - per-attribute share among the first 10 (same section, same formation, cause overlap), descriptive + aggregation: mean over queries +statistics: + ci: whole-well cluster bootstrap over query wells, 2,000 resamples, seed 20261117, percentile 95% interval + paired: per-query differences against random and against depth, with the same bootstrap + reading: >- + Descriptive, no gate. A representation is said to retrieve better than another only if the 95% interval of the + paired difference excludes 0. Section and formation are both functions of depth within one field, so depth is + the reference baseline. +knn_forecast: + purpose: the plan's PR-AUC when trouble is forecast from neighbours; secondary + items: the 4,894 cells of outputs/m34/features_t3.parquet (the T3 universe of v1), label_b primary, label_a + sensitivity + neighbours: the k = 10 nearest cells from the other wells (leave-one-well-out); ties by row order + representations: + depth: md_top + depth_witsml: >- + md_top, depth_from_own_top and the eight witsml mean and sd columns of the T3 feature table; missing values + replaced by the training-pool median, z-scored on the training pool, Euclidean distance + score: mean label of the k neighbours + metric: >- + pooled out-of-fold average precision with a whole-well bootstrap 95% interval (2,000 resamples, seed 20261117), + reported beside the prevalence and the v1 T3 baselines (majority 0.114, TF-IDF 0.123, definition b, masked) +code: scripts/20_m5_t5.py, volve_dia/m5_t5.py +outputs: outputs/m5/t5/ diff --git a/configs/protocol_v5.yaml.sha256 b/configs/protocol_v5.yaml.sha256 new file mode 100644 index 0000000..e201103 --- /dev/null +++ b/configs/protocol_v5.yaml.sha256 @@ -0,0 +1 @@ +c99bb91bdca9a4ab00ef065847ec095121944ddccbffde32c34dc6f8fc125047 configs/protocol_v5.yaml diff --git a/scripts/20_m5_t5.py b/scripts/20_m5_t5.py new file mode 100644 index 0000000..3588cb1 --- /dev/null +++ b/scripts/20_m5_t5.py @@ -0,0 +1,133 @@ +#!/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() diff --git a/tests/test_m5_t5.py b/tests/test_m5_t5.py new file mode 100644 index 0000000..08bc0e2 --- /dev/null +++ b/tests/test_m5_t5.py @@ -0,0 +1,107 @@ +from __future__ import annotations + +import numpy as np +import pandas as pd +import pytest + +from volve_dia import m5_t5 as t5 + + +@pytest.mark.parametrize("unit,expected", [ + ("Hugin Fm. VOLVE", "hugin"), ("Heather Fm. Sand VOLVE", "heather"), ("NORDLAND GP.", "nordland"), + ("Smith Bank Fm.", "smith bank"), ("Seabed", "seabed"), ("Heather Fm.", "heather")]) +def test_normalise_unit(unit, expected): + assert t5.normalise_unit(unit) == expected + + +def test_formation_and_eligibility(): + picks = pd.DataFrame({"wellbore": ["W1", "W1", "W1"], "unit": ["NORDLAND GP.", "Utsira Fm.", "Hugin Fm. VOLVE"], + "md": [100.0, 500.0, 3000.0]}) + assert t5.formation_at(picks, "W1", 50) is None + assert t5.formation_at(picks, "W1", 500) == "utsira" + assert t5.formation_at(picks, "W1", 3500) == "hugin" + intervals = pd.DataFrame({ + "interval_id": ["W1:b:I1", "W1:b:I2", "W1:b:I3", "W1:a:I1", "W2:b:I1"], "definition": ["b", "b", "b", "a", "b"], + "wellbore": ["W1", "W1", "W1", "W1", "W2"], "well": ["A"] * 5, "md_top": [80.0, 600.0, 3100.0, 600.0, 700.0], + "causes": ["equipment", "equipment|weather", None, "other", "other"], + "act_ids": [["W1_2008_01_02:001"], ["W1_2008_01_03:004", "W1_2008_01_03:002"], ["W1_2008_01_09:001"], + ["W1_2008_01_03:002"], ["W2_2008_02_01:001"]]}) + cells = pd.DataFrame({"wellbore": ["W1", "W2"], "own_hole_top_md": [50.0, 0.0]}) + sections = pd.Series({"W1_2008_01_02": "26", "W1_2008_01_03": "12.25"}) + items = t5.eligible_intervals(intervals, cells, sections, picks, ["W1"], "b") + # I1 lies above the first pick, I3 has no section, W2 is not a T3 wellbore. + assert list(items["interval_id"]) == ["W1:b:I2"] + row = items.iloc[0] + assert row["report_id"] == "W1_2008_01_03" and row["formation"] == "utsira" + assert row["cause_set"] == frozenset({"equipment", "weather"}) + + +def test_gains_and_metrics(): + query = pd.Series({"section": "8.5", "formation": "hugin", "cause_set": frozenset({"equipment"})}) + pool = pd.DataFrame({"section": ["8.5", "8.5", "12.25", "8.5"], "formation": ["hugin", "ty", "hugin", "hugin"], + "cause_set": [frozenset({"equipment", "weather"}), frozenset(), frozenset({"equipment"}), + frozenset({"weather"})]}) + gain, parts = t5.gains(query, pool) + assert list(gain) == [3, 1, 2, 2] + best = t5.ranking_metrics(np.array([0, 2, 3, 1]), gain, parts, k=2) + assert best["ndcg10"] == pytest.approx(1.0) and best["mrr"] == 1.0 and best["p10"] == 0.5 + worst = t5.ranking_metrics(np.array([1, 2, 3, 0]), gain, parts, k=2) + idcg = 3 + 2 / np.log2(3) + assert worst["ndcg10"] == pytest.approx((1 + 2 / np.log2(3)) / idcg) and worst["mrr"] == 0.25 + assert worst["section10"] == 0.5 and worst["formation10"] == 0.5 + none = t5.ranking_metrics(np.array([1, 0]), np.array([0, 2]), {a: np.zeros(2, bool) for a in t5.ATTRIBUTES}, k=2) + assert np.isnan(none["mrr"]) + + +def test_order_ties_and_rrf(): + assert list(t5.order([1.0, 2.0, 1.0], np.array([2, 0, 1]))) == [1, 2, 0] + fused = t5.rrf([np.array([3.0, 2.0, 1.0]), np.array([1.0, 2.0, 3.0])], np.arange(3)) + assert fused[1] == pytest.approx(2 / 62) and fused[0] == pytest.approx(fused[2]) + + +def synthetic_items(n_wells=4, per_well=12, seed=0): + rng = np.random.default_rng(seed) + rows = [] + for w in range(n_wells): + for i in range(per_well): + deep = i % 2 == 0 + rows.append({"interval_id": f"W{w}:b:I{i:02d}", "well": f"W{w}", "wellbore": f"W{w}", + "md_top": (3000.0 if deep else 500.0) + rng.normal(0, 50), + "section": "8.5" if deep else "17.5", "formation": "hugin" if deep else "utsira", + "cause_set": frozenset({"equipment" if deep else "weather"}), + "text_pre": "reaming tight hole" if deep else "waiting on weather", + "text_event": "packed off" if deep else "crane stopped wind", + **{c: rng.normal(5 if deep else 0, 1) for c in t5.WITSML_COLUMNS}}) + return pd.DataFrame(rows) + + +def test_evaluate_and_summarise(): + items = synthetic_items() + per_query = t5.evaluate(items, "well", seed=1, orders=20) + assert set(per_query["representation"]) == set(t5.REPRESENTATIONS) + assert per_query.groupby("representation").size().eq(len(items)).all() + assert (per_query["n_candidates"] == 36).all() and (per_query["n_fully_relevant"] == 18).all() + mean = per_query.groupby("representation")["ndcg10"].mean() + for rep in ("depth", "witsml_pre", "text_pre", "text_event", "rrf_pre", "rrf_all"): + assert mean[rep] == pytest.approx(1.0) + assert mean["random"] < 0.9 + summary = t5.summarise(per_query, resamples=200, seed=1) + depth = summary["depth"] + assert depth["ndcg10"]["mean"] == pytest.approx(1.0) + assert depth["ndcg10_minus_random"]["ci95"][0] > 0 + assert "ndcg10_minus_depth" not in depth and "ndcg10_minus_random" not in summary["random"] + + +def test_cluster_ci_weights_queries(): + out = t5.cluster_ci([1.0, 1.0, 1.0, 0.0, np.nan], ["A", "A", "A", "B", "B"], 500, 0) + assert out["n"] == 4 and out["mean"] == pytest.approx(0.75) + assert out["ci95"][0] <= 0.75 <= out["ci95"][1] + + +def test_knn_scores_leave_group_out(): + features = pd.DataFrame({"well": ["A"] * 4 + ["B"] * 4, "md_top": [10.0, 20, 30, 40] * 2, + "label_b": [1, 0, 0, 0, 1, 0, 0, 0]}) + scores = t5.knn_scores(features, "label_b", ["md_top"], k=1) + assert list(scores) == [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0] + result = t5.ap_ci(features["label_b"], scores, features["well"], 100, 0) + assert result["ap"] == pytest.approx(1.0) and result["prevalence"] == 0.25 diff --git a/volve_dia/m5_t5.py b/volve_dia/m5_t5.py new file mode 100644 index 0000000..d183b8c --- /dev/null +++ b/volve_dia/m5_t5.py @@ -0,0 +1,209 @@ +"""T5 similar-interval retrieval and the neighbour forecast of protocol v5. + +Relevance labels come from the XML-derived T3 intervals, the T1 section and the formation picks, all by code. +No representation reads activity codes, causes, labels, section or formation fields.""" + +from __future__ import annotations + +import re + +import numpy as np +import pandas as pd +from sklearn.feature_extraction.text import TfidfVectorizer +from sklearn.metrics import average_precision_score + +WITSML_COLUMNS = tuple(f"witsml_{stat}_{channel}" for stat in ("mean", "sd") + for channel in ("hkld", "rop", "rpm", "sppa")) +PRE_EVENT = ("depth", "witsml_pre", "text_pre") +REPRESENTATIONS = ("random",) + PRE_EVENT + ("text_event", "rrf_pre", "rrf_all") +METRICS = ("ndcg10", "mrr", "p10", "section10", "formation10", "cause10") +ATTRIBUTES = ("section", "formation", "cause") +RRF_K, CUTOFF, RANDOM_ORDERS = 60, 10, 100 +DELIMITER = " [SEP] " + + +def normalise_unit(unit): + """'Hugin Fm. VOLVE' -> 'hugin', 'Heather Fm. Sand VOLVE' -> 'heather', 'NORDLAND GP.' -> 'nordland'.""" + text = re.sub(r"\b(volve|sand)\b", " ", str(unit).casefold()) + text = re.sub(r"\b(fm|gp)\.", " ", text) + return " ".join(text.split()) + + +def formation_at(picks, wellbore, md): + """Normalised unit of the deepest pick with md <= `md` for the DDR wellbore, or None above the first pick.""" + own = picks[picks["wellbore"].eq(wellbore) & picks["md"].le(md)] + if own.empty: + return None + return normalise_unit(own.sort_values(["md", "unit"]).iloc[-1]["unit"]) + + +def eligible_intervals(intervals, cells, sections, picks, wellbores, definition): + """Eligible T3 intervals of one definition with section, formation and cause set (protocol v5 items).""" + frame = intervals[intervals["definition"].eq(definition) & intervals["wellbore"].isin(wellbores)].copy() + own_top = cells.groupby("wellbore")["own_hole_top_md"].first() + frame = frame[frame["md_top"].ge(frame["wellbore"].map(own_top))] + frame["first_act"] = frame["act_ids"].map(lambda ids: sorted(ids)[0]) + frame["report_id"] = frame["first_act"].str.rsplit(":", n=1).str[0] + frame["section"] = frame["report_id"].map(sections) + frame["formation"] = [formation_at(picks, w, md) for w, md in zip(frame["wellbore"], frame["md_top"])] + frame["cause_set"] = frame["causes"].fillna("").map(lambda c: frozenset(x for x in c.split("|") if x)) + frame = frame[frame["section"].notna() & frame["formation"].notna()] + return frame.sort_values("interval_id").reset_index(drop=True) + + +def gains(query, candidates): + """g = [same section] + [same formation] + [cause sets intersect], per candidate, with the three parts.""" + section = candidates["section"].to_numpy() == query["section"] + formation = candidates["formation"].to_numpy() == query["formation"] + cause = np.array([bool(query["cause_set"] & c) for c in candidates["cause_set"]], dtype=bool) + return section.astype(int) + formation.astype(int) + cause.astype(int), { + "section": section, "formation": formation, "cause": cause} + + +def order(scores, tiebreak): + """Candidate indices by descending score; equal scores follow the fixed random tie order.""" + return np.lexsort((tiebreak, -np.asarray(scores, dtype=float))) + + +def ranking_metrics(ranked, gain, parts, k=CUTOFF): + """nDCG@k (linear gain, ideal over all candidates), reciprocal rank of the first g = 3, P@k and attribute shares.""" + discount = 1 / np.log2(np.arange(2, k + 2)) + top = ranked[:k] + ideal = np.sort(gain)[::-1][:k] + idcg = float((ideal * discount[:len(ideal)]).sum()) + ndcg = float((gain[top] * discount[:len(top)]).sum()) / idcg if idcg > 0 else np.nan + full = np.flatnonzero(gain[ranked] == 3) + out = {"ndcg10": ndcg, "mrr": 1 / (full[0] + 1) if len(full) else np.nan, + "p10": float((gain[top] == 3).sum()) / k} + for name in ATTRIBUTES: + out[f"{name}10"] = float(parts[name][top].sum()) / k + return out + + +def rrf(score_lists, tiebreak): + """Reciprocal rank fusion: sum of 1 / (RRF_K + rank) with ranks starting at 1.""" + fused = np.zeros(len(tiebreak)) + for scores in score_lists: + ranks = np.empty(len(tiebreak)) + ranks[order(scores, tiebreak)] = np.arange(1, len(tiebreak) + 1) + fused += 1 / (RRF_K + ranks) + return fused + + +def standardise(train, test): + """Median imputation and z-scores fitted on `train`; constant columns are set to 0.""" + train, test = train.astype(float), test.astype(float) + median = train.median().fillna(0.0) + train, test = train.fillna(median), test.fillna(median) + mean, sd = train.mean(), train.std(ddof=0).replace(0, 1.0) + return ((train - mean) / sd).to_numpy(), ((test - mean) / sd).to_numpy() + + +def text_similarity(train_text, test_text): + """Cosine similarity of TF-IDF vectors fitted on the candidate pool; empty pools give zeros.""" + vectorizer = TfidfVectorizer(ngram_range=(1, 2), min_df=1, sublinear_tf=True) + try: + pool = vectorizer.fit_transform(train_text) + except ValueError: + return np.zeros((len(test_text), len(train_text))) + return (vectorizer.transform(test_text) @ pool.T).toarray() + + +def fold_scores(queries, pool): + """Similarity of every query to every candidate (higher is closer) for the non-random representations.""" + depth = -np.abs(queries["md_top"].to_numpy()[:, None] - pool["md_top"].to_numpy()[None, :]) + z_pool, z_query = standardise(pool[list(WITSML_COLUMNS)], queries[list(WITSML_COLUMNS)]) + witsml = -np.sqrt(((z_query[:, None, :] - z_pool[None, :, :]) ** 2).sum(axis=2)) + return {"depth": depth, "witsml_pre": witsml, + "text_pre": text_similarity(pool["text_pre"].tolist(), queries["text_pre"].tolist()), + "text_event": text_similarity(pool["text_event"].tolist(), queries["text_event"].tolist())} + + +def evaluate(items, group, seed, orders=RANDOM_ORDERS): + """Per-query metrics for every representation; candidates are the items of the other groups.""" + tie_rank = np.random.default_rng(seed).permutation(len(items)) + rng = np.random.default_rng(seed) + rows = [] + for name in sorted(items[group].unique()): + held = items[group].eq(name).to_numpy() + queries, pool = items[held].reset_index(drop=True), items[~held].reset_index(drop=True) + if pool.empty: + continue + tiebreak = tie_rank[~held] + scores = fold_scores(queries, pool) + for i, query in queries.iterrows(): + gain, parts = gains(query, pool) + base = {"interval_id": query["interval_id"], "well": query["well"], "wellbore": query["wellbore"], + "n_candidates": len(pool), "n_fully_relevant": int((gain == 3).sum())} + per = {r: scores[r][i] for r in scores} + per["rrf_pre"] = rrf([per[r] for r in PRE_EVENT], tiebreak) + per["rrf_all"] = rrf([per[r] for r in PRE_EVENT + ("text_event",)], tiebreak) + for rep, s in per.items(): + rows.append(base | {"representation": rep} | ranking_metrics(order(s, tiebreak), gain, parts)) + draws = pd.DataFrame([ranking_metrics(rng.permutation(len(pool)), gain, parts) for _ in range(orders)]) + rows.append(base | {"representation": "random"} | draws.mean(skipna=False).to_dict()) + return pd.DataFrame(rows) + + +def cluster_ci(values, clusters, resamples, seed): + """Mean over non-missing values with a whole-cluster percentile bootstrap 95% interval.""" + values, clusters = np.asarray(values, dtype=float), np.asarray(clusters) + keep = ~np.isnan(values) + values, clusters = values[keep], clusters[keep] + if not len(values): + return {"n": 0, "mean": None, "ci95": None} + names = np.unique(clusters) + sums = np.array([values[clusters == c].sum() for c in names]) + counts = np.array([(clusters == c).sum() for c in names]) + rng = np.random.default_rng(seed) + draws = rng.integers(0, len(names), size=(resamples, len(names))) + means = sums[draws].sum(axis=1) / counts[draws].sum(axis=1) + return {"n": int(len(values)), "mean": float(values.mean()), + "ci95": [float(np.percentile(means, 2.5)), float(np.percentile(means, 97.5))]} + + +def summarise(per_query, resamples, seed, metrics=METRICS): + """Mean and well-bootstrap interval per representation, plus paired differences against random and depth.""" + out = {} + wide = {m: per_query.pivot(index="interval_id", columns="representation", values=m) for m in metrics} + wells = per_query.drop_duplicates("interval_id").set_index("interval_id")["well"] + for rep in [r for r in REPRESENTATIONS if r in set(per_query["representation"])]: + block = {} + for m in metrics: + table = wide[m] + block[m] = cluster_ci(table[rep], wells.loc[table.index], resamples, seed) + for ref in ("random", "depth"): + if ref != rep and m in ("ndcg10", "mrr", "p10"): + block[f"{m}_minus_{ref}"] = cluster_ci(table[rep] - table[ref], wells.loc[table.index], + resamples, seed) + out[rep] = block + return out + + +def knn_scores(features, label, columns, group="well", k=CUTOFF): + """Leave-one-group-out k-nearest-neighbour score: the mean label of the k closest cells of the other groups.""" + scores = pd.Series(np.nan, index=features.index) + y = features[label].astype(float).to_numpy() + for name in sorted(features[group].unique()): + held = features[group].eq(name).to_numpy() + train, test = standardise(features.loc[~held, list(columns)], features.loc[held, list(columns)]) + distance = np.sqrt(((test[:, None, :] - train[None, :, :]) ** 2).sum(axis=2)) + nearest = np.argsort(distance, axis=1, kind="stable")[:, :k] + scores[held] = y[~held][nearest].mean(axis=1) + return scores + + +def ap_ci(y, scores, clusters, resamples, seed): + """Pooled average precision with a whole-cluster percentile bootstrap 95% interval.""" + y, scores, clusters = np.asarray(y, dtype=int), np.asarray(scores, dtype=float), np.asarray(clusters) + names = np.unique(clusters) + index = {c: np.flatnonzero(clusters == c) for c in names} + rng = np.random.default_rng(seed) + values = [] + for _ in range(resamples): + rows = np.concatenate([index[c] for c in rng.choice(names, size=len(names), replace=True)]) + if 0 < y[rows].sum() < len(rows): + values.append(average_precision_score(y[rows], scores[rows])) + return {"n": int(len(y)), "positives": int(y.sum()), "prevalence": float(y.mean()), + "ap": float(average_precision_score(y, scores)), + "ci95": [float(np.percentile(values, 2.5)), float(np.percentile(values, 97.5))] if values else None}