"""P4x: exploratory, post hoc model variants on Volve (docs/research/p4-exploratory.md). Not part of any locked protocol. Imports the locked P4 code read-only (data views, folds, banks, trajectory trainer, nested selection and scoring) and changes only what a variant declares: a low-frequency trend subtracted from the targets (V1a velocity, V1b TWT), the network width (V2a) or a linear-Gaussian model (V2b, V3). python exploratory/p4x_volve.py paths # velocity/TVDSS along every path (no label) python exploratory/p4x_volve.py train --variants V0 V1a ... --methods B3b M2-Sa --workers 8 --device cuda:0 python exploratory/p4x_volve.py summarize # V0a check, every variant, reference predictors """ from __future__ import annotations import argparse import copy import itertools import json import sys import time from concurrent.futures import FIRST_COMPLETED, ProcessPoolExecutor, wait from datetime import datetime, timezone from multiprocessing import get_context from pathlib import Path import numpy as np REPO = Path(__file__).resolve().parents[1] sys.path.insert(0, str(REPO)) from ml_porosity.volve.folds import prediction_targets, target_name # noqa: E402 from ml_porosity.volve.runner import fold_sets, job_path, load_bundle, reg_path, save_npz # noqa: E402 P4 = REPO / "outputs" / "p4" OUT = REPO / "outputs" / "p4x" VEL = (REPO / "data/Volve/Seismic/ST10010/Velocities" / "ST10010ZC11-MIG-VEL.MIG_VEL.VELOCITY.3D.JS-017527.segy") SA = 7.0 LABEL = "PHIF" VARIANTS = { "V0": dict(trend=None, model="cnn", d=64), # retraining check (seed 0 only) "V1a": dict(trend="velocity", model="cnn", d=64), "V1b": dict(trend="twt", model="cnn", d=64), "V2a": dict(trend=None, model="cnn", d=8), "V2b": dict(trend=None, model="linear"), "V3": dict(trend="velocity", model="linear"), } def stamp() -> str: return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ") def protocol() -> dict: from ml_porosity.volve.protocol import load_protocol return load_protocol() # ---------------------------------------------------------------- velocity and depth along every path (no label) def velocity_cube(): import segyio with segyio.open(VEL, iline=189, xline=193) as f: cube = segyio.tools.cube(f).astype(np.float64) il, xl, z = np.asarray(f.ilines, float), np.asarray(f.xlines, float), np.asarray(f.samples, float) h = np.array([[t[segyio.su.iline], t[segyio.su.xline], t[segyio.su.cdpx], t[segyio.su.cdpy], t[segyio.su.scalco]] for t in f.header], float) scale = np.where(h[:, 4] < 0, -1.0 / h[:, 4], np.where(h[:, 4] > 0, h[:, 4], 1.0)) xy = h[:, 2:4] * scale[:, None] A = np.c_[xy, np.ones(len(xy))] coef, *_ = np.linalg.lstsq(A, h[:, :2], rcond=None) # (x, y, 1) -> (il, xl) resid = np.abs(A @ coef - h[:, :2]).max() return cube, (il, xl, z), coef, float(resid) def build_paths() -> None: """V(t) and TVDSS(t) on the main window for every (well, key) path in the dataset: key 'reference' and every blind key. Uses the well path (public survey) and the seismic-derived velocity only; no log, pick or label.""" from scipy.interpolate import RegularGridInterpolator from ml_porosity.volve.data import load_arrays p = protocol() arrays = load_arrays() cube, (il, xl, z), coef, resid = velocity_cube() interp = RegularGridInterpolator((il, xl, z), cube, method="linear", bounds_error=True) main = arrays[f"{p['data']['wells'][0]}/main_mask"].astype(bool) t_main = arrays[f"{p['data']['wells'][0]}/times_ms"][main] out, qc = {"times_ms": t_main}, {"affine_max_residual_bins": resid, "paths": {}} for w in p["data"]["wells"]: smd, stvd = arrays[f"{w}/survey/md"], arrays[f"{w}/survey/tvd"] sx, sy, kb = arrays[f"{w}/survey/x"], arrays[f"{w}/survey/y"], float(arrays[f"{w}/kb_msl"]) keys = ["reference"] + sorted({k.split("/")[2] for k in arrays if k.startswith(f"{w}/blind/")}) for key in keys: base = f"{w}/{'reference' if key == 'reference' else 'blind/' + key}" md = arrays[f"{base}/md"][main] x, y = np.interp(md, smd, sx), np.interp(md, smd, sy) tvdss = np.interp(md, smd, stvd) - kb ij = np.c_[x, y, np.ones_like(x)] @ coef v = interp(np.c_[ij, tvdss]) out[f"{w}|{key}/velocity"], out[f"{w}|{key}/tvdss"] = v, tvdss q = {"dil_vs_dataset": float(np.abs(ij[:, 0] - arrays[f"{base}/il"][main]).max()), "dxl_vs_dataset": float(np.abs(ij[:, 1] - arrays[f"{base}/xl"][main]).max()), "v_range": [float(v.min()), float(v.max())]} if key == "reference": q["dtvd_vs_dataset_m"] = float(np.abs(tvdss + kb - arrays[f"{base}/tvd"][main]).max()) qc["paths"][f"{w}|{key}"] = q OUT.mkdir(parents=True, exist_ok=True) np.savez_compressed(OUT / "paths.npz", **out) worst = {k: max(q[k] for q in qc["paths"].values() if k in q) for k in ("dil_vs_dataset", "dxl_vs_dataset", "dtvd_vs_dataset_m")} qc["worst"] = worst (OUT / "paths_qc.json").write_text(json.dumps(qc, indent=1), encoding="utf-8") print(json.dumps({"affine_max_residual_bins": resid, **worst})) # ---------------------------------------------------------------- trends (training wells of each set only) def covariate(paths: dict, kind: str, well: str, key: str) -> np.ndarray: if kind == "velocity": return paths[f"{well}|{key}/velocity"] return paths["times_ms"].astype(float) def fit_trend(kind: str, paths: dict, labels: dict[str, np.ndarray]) -> tuple[float, float, float]: """OLS of the label on the covariate over all labelled samples of the given wells (path: reference). Returns (a, b, residual SD).""" c = np.concatenate([covariate(paths, kind, w, "reference")[np.isfinite(y)] for w, y in labels.items()]) y = np.concatenate([y[np.isfinite(y)] for y in labels.values()]) if kind is None or kind == "constant": return float(y.mean()), 0.0, float(y.std()) A = np.c_[np.ones_like(c), c] (a, b), *_ = np.linalg.lstsq(A, y, rcond=None) return float(a), float(b), float(np.std(y - A @ np.array([a, b]))) def b3b_labels(names) -> dict[str, np.ndarray]: """B3b-tie labels (fraction, main window, NaN off support) of the wells of a registration set.""" z = load_bundle(reg_path(P4, names, SA)) Y = z[f"{LABEL}/B3b"] return {w: Y[i, 0] for i, w in enumerate(z["wells"])} # ---------------------------------------------------------------- linear-Gaussian model (V2b, V3) def linear_factory(method, channels, cfg): import torch from torch import nn import torch.nn.functional as F class LinearGaussian(nn.Module): """μ = Conv1d(patch channels → 1, kernel k) + bias; a single scalar σ = softplus(s) + σ_min.""" def __init__(self, in_ch: int, k: int = 9, sigma_min: float = 1e-3): super().__init__() self.conv = nn.Conv1d(in_ch, 1, k, padding=k // 2) self.s = nn.Parameter(torch.zeros(1)) self.sigma_min = sigma_min def forward(self, x): mu = self.conv(x) return mu, (F.softplus(self.s) + self.sigma_min).expand_as(mu) torch.backends.cudnn.benchmark = False torch.backends.cudnn.deterministic = True return LinearGaussian(channels, cfg.get("kernel", 9)) # ---------------------------------------------------------------- one trajectory def train_job(job: dict) -> dict: import torch import ml_porosity.volve.training as T from ml_porosity.f3.training import make_model as cnn_factory from ml_porosity.volve.data import VolveData p, v = job["p"], VARIANTS[job["variant"]] root = OUT / job["variant"] names = tuple(sorted(job["names"])) path = job_path(root, names, job["method"], LABEL, job["seed"], SA) if path.exists(): return {"cached": True, "path": str(path)} T.make_model = linear_factory if v["model"] == "linear" else cnn_factory cfg = dict(p["training"]) if v["model"] == "cnn": cfg["d_channels"] = v["d"] data = VolveData(p, training_wells=names) bundle = load_bundle(reg_path(P4, names, SA)) if tuple(bundle["wells"]) != names: raise RuntimeError("Registration cache contains different wells") targets = prediction_targets(data.wells, names) X = np.stack([data.X(w, "reference") for w in names]) X_targets = np.stack([data.X(w, k) for w, k in targets]) spec = T.method_spec(bundle, LABEL, job["method"]) m0, s0 = bundle[f"{LABEL}/norm"] trend_meta = {} if v["trend"]: with np.load(OUT / "paths.npz") as z: paths = {k: z[k] for k in z.files} Yb = bundle[f"{LABEL}/B3b"] a, b, rsd = fit_trend(v["trend"], paths, {w: Yb[i, 0] for i, w in enumerate(names)}) tr_train = np.stack([a + b * covariate(paths, v["trend"], w, "reference") for w in names]) tr_targets = np.stack([a + b * covariate(paths, v["trend"], w, k) for w, k in targets]) spec["Y"] = spec["Y"] - ((tr_train - m0) / s0)[:, None, :] trend_meta = {"trend": v["trend"], "a": a, "b": b, "residual_sd": rsd} else: tr_targets = np.full((len(targets), X.shape[2]), m0) pred, meta = T.train_trajectory(X, X_targets, spec, job["method"], cfg, job["seed"], p["training"]["budgets"], job["device"], None, p["runtime"]["cpu_threads_per_worker"]) pred = {k: (val * s0 + tr_targets if k.endswith("/mu") else val * s0) for k, val in pred.items()} pred |= {"targets": np.asarray([target_name(w, k) for w, k in targets]), "wells": np.asarray(names), "norm": bundle[f"{LABEL}/norm"]} if v["trend"]: pred["trend_targets"] = tr_targets save_npz(path, pred) path.with_suffix(".json").write_text(json.dumps(meta | trend_meta | { "variant": job["variant"], "training_wells": list(names), "method": job["method"], "seed": job["seed"], "device": job["device"], "finished": stamp(), "torch": torch.__version__}, indent=1), encoding="utf-8") return {"cached": False, "path": str(path), "wall_seconds": meta["wall_seconds"]} def run_train(variants, methods, seeds, workers, device) -> None: p = protocol() jobs = [dict(p=p, variant=var, names=list(n), method=m, seed=s, device=device) for var in variants for m in methods for s in ([0] if var == "V0" else seeds) for n in fold_sets(p)] todo = [j for j in jobs if not job_path(OUT / j["variant"], j["names"], j["method"], LABEL, j["seed"], SA).exists()] print(f"{stamp()} train: {len(jobs)} jobs, {len(todo)} to run, workers={workers}, device={device}", flush=True) begin, done = time.time(), 0 with ProcessPoolExecutor(workers, mp_context=get_context("spawn")) as ex: pending = {ex.submit(train_job, j): j for j in todo} while pending: finished, _ = wait(pending, return_when=FIRST_COMPLETED) for f in finished: j = pending.pop(f) f.result() done += 1 if done % 10 == 0 or not pending: el = time.time() - begin print(f"{stamp()} {done}/{len(todo)} {j['variant']} {j['method']} s{j['seed']} " f"elapsed {el / 60:.1f} min, eta {el / done * (len(todo) - done) / 60:.1f} min", flush=True) # ---------------------------------------------------------------- evaluation def extra(y: np.ndarray, mu: np.ndarray, sigma: np.ndarray) -> dict: """Porosity units; labelled samples only.""" from scipy.stats import norm ok = np.isfinite(y) y, mu, sigma = 100 * y[ok], 100 * mu[ok], np.maximum(100 * sigma[ok], 1e-6) e = mu - y bias = e.mean() out = dict(n=int(ok.sum()), rmse=float(np.sqrt(np.mean(e ** 2))), bias=float(bias), abs_bias=float(abs(bias)), rmse_debiased=float(np.sqrt(np.mean((e - bias) ** 2))), label_sd=float(y.std()), pcc=float(np.corrcoef(y, mu)[0, 1]) if mu.std() > 0 else np.nan, r2=float(1 - np.mean(e ** 2) / y.var())) for lev in (80, 90): zq = norm.ppf(0.5 + lev / 200) out[f"coverage_{lev}"] = float(np.mean(np.abs(e) <= zq * sigma)) out["debiased_over_sd"] = out["rmse_debiased"] / out["label_sd"] return out def variant_predictions(variant: str, p: dict, arrays: dict) -> tuple[list[dict], list[str]]: from ml_porosity.volve.evaluation import neural_predictions root = OUT / variant methods = [m for m in ("B3b", "B3d-Sa", "M2-Sa") if all(job_path(root, n, m, LABEL, s, SA).exists() for n in fold_sets(p) for s in p["split"]["seeds"])] if not methods: return [], [] q = copy.deepcopy(p) q["methods"]["main"] = methods pred, _ = neural_predictions(q, root, arrays, [SA]) return [a for a in pred if a["seed"] == "ensemble"], methods def reference_predictors(p: dict, arrays: dict, paths: dict) -> list[dict]: """T0 constant, T1a velocity trend, T1b TWT trend: fitted on the outer training wells (B3b labels), applied along the outer test well's blind path T_out.""" from ml_porosity.data.volve_wells import blind_key from ml_porosity.volve.folds import outer_folds from ml_porosity.volve.protocol import source_config p4 = source_config(p)["p4"] labels = {} for names in fold_sets(p): for w, y in b3b_labels(names).items(): if w in labels and not np.allclose(labels[w], y, equal_nan=True): raise RuntimeError(f"B3b labels of {w} differ between sets") labels[w] = y out = [] for scheme in p["split"]["schemes"]: for test, train in outer_folds(p["data"]["wells"], scheme, p4): key = blind_key(train) for name, kind in (("T0", "constant"), ("T1a", "velocity"), ("T1b", "twt")): a, b, rsd = fit_trend(kind, paths, {w: labels[w] for w in train}) mu = a + b * (covariate(paths, kind, test, key) if kind != "constant" else 0.0) mu = np.broadcast_to(mu, paths["times_ms"].shape).astype(float) out.append(dict(variant=name, scheme=scheme, test_well=test, method="trend-only", mu=mu, sigma=np.full_like(mu, rsd), a=a, b=b)) return out def summarize() -> None: import pandas as pd from ml_porosity.volve.data import VolveData, load_arrays from ml_porosity.volve.evaluation import neural_predictions p = protocol() arrays = load_arrays() full = VolveData(p, arrays=arrays) ref = p["data"]["primary_reference"] report = {"created": stamp()} # V0a: locked trajectories through this harness locked = pd.read_csv(P4 / "summary" / "metrics.csv") locked = locked[(locked.seed.astype(str) == "ensemble") & (locked.reference == ref) & (locked.sigma_a_ms == SA)] pred, _ = neural_predictions(p, P4, arrays, [SA]) diffs = [] for a in pred: if a["seed"] != "ensemble": continue row = locked[(locked.scheme == a["scheme"]) & (locked.test_well == a["test_well"]) & (locked.method == a["method"])] diffs.append(abs(extra(full.y(a["test_well"], ref), a["mu"], a["sigma"])["rmse"] - float(row.rmse.iloc[0]))) report["V0a_max_abs_rmse_diff"] = float(max(diffs)) report["V0a_rows"] = len(diffs) rows = [] for a in pred: if a["seed"] == "ensemble" and a["method"] in ("B3b", "B3d-Sa", "M2-Sa"): rows.append(dict(variant="P4", scheme=a["scheme"], test_well=a["test_well"], method=a["method"]) | extra(full.y(a["test_well"], ref), a["mu"], a["sigma"])) # V0b: retrained seed-0 trajectories versus the stored P4 ones v0 = [] for names in fold_sets(p): for m in ("B3b", "M2-Sa"): mine, theirs = job_path(OUT / "V0", names, m, LABEL, 0, SA), job_path(P4, names, m, LABEL, 0, SA) if not mine.exists(): continue a, b = load_bundle(mine), load_bundle(theirs) assert list(a["targets"]) == list(b["targets"]) v0.append(max(float(np.max(np.abs(a[k] - b[k]))) for k in a if k.endswith("/mu") or k.endswith("/sigma"))) report["V0b_trajectories"] = len(v0) report["V0b_max_abs_diff_fraction"] = float(max(v0)) if v0 else None report["V0b_median_max_abs_diff_fraction"] = float(np.median(v0)) if v0 else None for variant in ("V1a", "V1b", "V2a", "V2b", "V3"): preds, methods = variant_predictions(variant, p, arrays) report[f"{variant}_methods"] = methods for a in preds: rows.append(dict(variant=variant, scheme=a["scheme"], test_well=a["test_well"], method=a["method"]) | extra(full.y(a["test_well"], ref), a["mu"], a["sigma"])) with np.load(OUT / "paths.npz") as z: paths = {k: z[k] for k in z.files} for a in reference_predictors(p, arrays, paths): rows.append({k: a[k] for k in ("variant", "scheme", "test_well", "method")} | extra(full.y(a["test_well"], ref), a["mu"], a["sigma"]) | dict(trend_a=a["a"], trend_b=a["b"])) per = pd.DataFrame(rows) dest = OUT / "summary" dest.mkdir(parents=True, exist_ok=True) per.to_csv(dest / "per_well.csv", index=False) cols = ["rmse", "abs_bias", "rmse_debiased", "label_sd", "debiased_over_sd", "pcc", "r2", "coverage_80", "coverage_90"] g = per.groupby(["variant", "scheme", "method"], sort=False) macro = g[cols].mean().join(g.size().rename("n_wells")) macro["wells_r2_pos"] = g.r2.apply(lambda s: int((s > 0).sum())) macro["wells_debiased_le_0.9sd"] = g.debiased_over_sd.apply(lambda s: int((s <= 0.9).sum())) macro = macro.reset_index() macro["skill"] = (macro.r2 > 0) | (macro.rmse_debiased <= 0.9 * macro.label_sd) macro.to_csv(dest / "macro.csv", index=False) gaps = [] for (variant, scheme), d in per[per.method.isin(["B3b", "M2-Sa"])].groupby(["variant", "scheme"], sort=False): w = d.pivot(index="test_well", columns="method", values=["rmse", "rmse_debiased"]) if ("rmse", "M2-Sa") not in w or ("rmse", "B3b") not in w: continue dr = w[("rmse", "M2-Sa")] - w[("rmse", "B3b")] dd = w[("rmse_debiased", "M2-Sa")] - w[("rmse_debiased", "B3b")] gaps.append(dict(variant=variant, scheme=scheme, macro_gap_rmse=float(dr.mean()), macro_gap_rmse_debiased=float(dd.mean()), wells_m2_better=int((dr < 0).sum()), n_wells=int(dr.size), **{f"gap_{k}": float(x) for k, x in dr.items()})) gaps = pd.DataFrame(gaps) gaps.to_csv(dest / "gap_m2_minus_b3b.csv", index=False) (dest / "checks.json").write_text(json.dumps(report, indent=1), encoding="utf-8") text = ["# P4x — exploratory Volve variants (post hoc; see docs/research/p4-exploratory.md)", "", f"Generated {report['created']}. σ_a = 7 ms, primary reference `{ref}`, combined ensembles, " "porosity units. Exploratory: cannot support plan §10 claims or alter G-D.", "", "## Checks", "", "```", json.dumps(report, indent=1), "```", "", "## Macro over wells", "", macro.to_markdown(index=False, floatfmt=".3f"), "", "## M2-Sa − B3b (RMSE, p.u.; negative = M2-Sa better)", "", gaps.to_markdown(index=False, floatfmt=".3f") if len(gaps) else "(none)", "", "Per-well rows: per_well.csv. Skill: macro R² > 0 or macro bias-removed RMSE ≤ 0.9 × macro label SD."] (dest / "summary.md").write_text("\n".join(text) + "\n", encoding="utf-8") print(json.dumps(report, indent=1)) def main() -> None: ap = argparse.ArgumentParser() ap.add_argument("stage", choices=["paths", "train", "summarize"]) ap.add_argument("--variants", nargs="+", default=["V0", "V1a", "V1b", "V2a", "V2b"]) ap.add_argument("--methods", nargs="+", default=["B3b", "M2-Sa"]) ap.add_argument("--seeds", nargs="+", type=int, default=[0, 1, 2, 3, 4]) ap.add_argument("--workers", type=int, default=8) ap.add_argument("--device", default="cuda:0") a = ap.parse_args() if a.stage == "paths": build_paths() elif a.stage == "train": run_train(a.variants, a.methods, a.seeds, a.workers, a.device) else: summarize() if __name__ == "__main__": main()