Files
Volve-DIA/volve_dia/m5_t5.py
lamlvh 4a1011f5e1 Add protocol v5: T5 similar-interval retrieval and neighbour forecast
Protocol v5 extends v4 and was locked before any retrieval score. It fixes
the T5 items (own-hole T3 intervals with a known section and formation),
the rule-based graded relevance, leakage-free representations, nDCG@10,
MRR, P@10, the whole-well bootstrap and the k-nearest-neighbour forecast.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 08:25:29 +00:00

210 lines
10 KiB
Python

"""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}