"""P4 nested selection, scoring and the descriptive G-D report. Selection (the budget of each trajectory, the point competitor of each outer fold) reads validation labels through the data view of the outer training wells, VolveData(training_wells=T_out), which holds no label, log or pick of the outer test well. Outer-test labels are read only by `score`, after every prediction is fixed. """ from __future__ import annotations import json from pathlib import Path import numpy as np import pandas as pd from ml_porosity.data.volve_wells import blind_key from ml_porosity.eval.metrics import gaussian_metrics, point_metrics from ml_porosity.f3.evaluation import choose_budget from ml_porosity.f3.progress import write_json from ml_porosity.f3.training import ensemble from ml_porosity.volve.data import VolveData, load_arrays from ml_porosity.volve.folds import inner_folds, outer_folds, target_name from ml_porosity.volve.losses import finite_runs, highpass_segment from ml_porosity.volve.protocol import source_config from ml_porosity.volve.runner import arm_methods, fold_sets, job_path, load_bundle, reg_path Z90 = 1.6448536269514722 COLUMNS = ["rmse", "mae", "pcc", "r2", "std_ratio", "coverage_80", "coverage_90", "nll", "crps", "mean_sigma", "band_rmse", "band_pcc"] def neural_predictions(p: dict, root: Path, arrays: dict, sigmas: list[float]) -> tuple[list[dict], list[dict]]: """Per scheme, outer fold, σ_a arm, method and seed: the budget with the lowest mean validation MSE over the inner wells (original scale, labelled samples; earliest tie), the inner models ensembled at that budget on the outer test input (key T_out), then the seeds ensembled.""" p4 = source_config(p)["p4"] label, ref, budgets = p["data"]["label"], p["data"]["primary_reference"], p["training"]["budgets"] cache, predictions, selections = {}, [], [] for scheme in p["split"]["schemes"]: for test, outer_train in outer_folds(p["data"]["wells"], scheme, p4): view = VolveData(p, training_wells=outer_train, arrays=arrays) folds = inner_folds(outer_train) labels = {v: view.y(v, ref) for v, _ in folds} test_key = blind_key(outer_train) for sa in sigmas: for method in arm_methods(p, sa): fold = dict(scheme=scheme, test_well=test, method=method, label=label, sigma_a_ms=sa) per_seed = [] for seed in p["split"]["seeds"]: curves, members = [], [] for v, t_in in folds: path = job_path(root, t_in, method, label, seed, sa) if path not in cache: cache[path] = load_bundle(path) z = cache[path] if tuple(z["wells"]) != tuple(sorted(t_in)): raise RuntimeError(f"Trajectory trained on other wells: {path}") names = list(z["targets"]) y = labels[v] ok = np.isfinite(y) i = names.index(target_name(v, blind_key(t_in))) curves.append([np.mean((z[f"{b}/mu"][i][ok] - y[ok]) ** 2) for b in budgets]) members.append((z, names.index(target_name(test, test_key)))) budget = choose_budget(np.array(curves), budgets) mu, sigma = ensemble(np.stack([z[f"{budget}/mu"][i] for z, i in members]), np.stack([z[f"{budget}/sigma"][i] for z, i in members])) entry = fold | dict(seed=seed, members=len(folds), test_key=test_key, mu=mu, sigma=sigma) predictions.append(entry) per_seed.append(entry) selections.append(fold | dict( seed=seed, budget=budget, validation_mse=float(np.mean(np.asarray(curves)[:, budgets.index(budget)])), validation_wells=";".join(v for v, _ in folds), validation_keys=";".join(blind_key(t) for _, t in folds), training_sets=";".join(",".join(t) for _, t in folds))) mu, sigma = ensemble(np.stack([e["mu"] for e in per_seed]), np.stack([e["sigma"] for e in per_seed])) predictions.append(fold | dict(seed="ensemble", members=sum(e["members"] for e in per_seed), test_key=test_key, mu=mu, sigma=sigma)) return predictions, selections def references(full: VolveData, well: str, p: dict) -> list[str]: """The scoring references that exist for a well (NIVSP and OPTIMIZED only at F-11 T2).""" return [r for r in p["data"]["references"] if f"{well}/{r}/{full.label}" in full.arrays] def desc_band(y: np.ndarray, mu: np.ndarray, f_c: float, dt: float, min_samples: int) -> dict: """High-passed (< f_c removed) reference and prediction on each finite reference run of ≥ min_samples, pooled. Runs are shorter than one period at f_c: descriptive only.""" runs = [(a, b) for a, b in finite_runs(y) if b - a >= min_samples] if not runs: return {"band_samples": 0, "band_rmse": np.nan, "band_pcc": np.nan, "band_std_ratio": np.nan} t = np.concatenate([highpass_segment(y[a:b], f_c, dt) for a, b in runs]) q = np.concatenate([highpass_segment(mu[a:b], f_c, dt) for a, b in runs]) m = point_metrics(t, q) return {"band_samples": int(t.size)} | {f"band_{k}": m[k] for k in ("rmse", "pcc", "std_ratio")} def score(full: VolveData, pred: dict, reference: str, p: dict) -> dict: """Metrics in porosity units on the samples where the reference exists; references with fewer than min_label_samples samples are listed but not scored.""" y = 100 * full.y(pred["test_well"], reference) mu, sigma = 100 * pred["mu"], np.maximum(100 * pred["sigma"], 1e-6) ok = np.isfinite(y) row = {k: v for k, v in pred.items() if k not in ("mu", "sigma")} | dict(reference=reference, n_reference=int(ok.sum())) if ok.sum() < p["data"]["min_label_samples"]: return row | dict(scored=False) m = p["metrics"] return (row | dict(scored=True) | point_metrics(y, mu) | gaussian_metrics(y[ok], mu[ok], sigma[ok]) | desc_band(y, mu, m["f_c_hz"], full.dt, m["desc_band_min_samples"])) def best_shift(full: VolveData, pred: dict, reference: str, max_shift: int) -> dict: """Lag (samples, positive = prediction later) maximising PCC with the reference; diagnostic only, smallest |lag| on ties. Never alters a score.""" y = full.y(pred["test_well"], reference) idx = np.flatnonzero(np.isfinite(y)) best = (-np.inf, 0) for s in sorted(range(-max_shift, max_shift + 1), key=abs): j = idx + s if j[0] < 0 or j[-1] >= pred["mu"].size: continue r = point_metrics(y[idx], pred["mu"][j])["pcc"] if np.isfinite(r) and r > best[0]: best = (r, s) return {"best_shift_samples": best[1], "best_shift_ms": best[1] * full.dt, "best_shift_pcc": best[0]} def gate_gd(metrics: pd.DataFrame, selection: pd.DataFrame, p: dict) -> dict: """G-D: report every well in either direction; claim wording follows protocol_volve gate.claim_rules.""" g, sa = p["gate"], p["registration"]["sigma_a_ms"] rules = g["claim_rules"] primary = metrics[(metrics.reference == p["data"]["primary_reference"]) & (metrics.seed.astype(str) == "ensemble") & (metrics.sigma_a_ms == sa)] within = lambda c, band: band[0] - 1e-12 <= c <= band[1] + 1e-12 schemes = {} for scheme in p["split"]["schemes"]: rows = [] for well in p["data"]["wells"]: sel = selection[(selection.scheme == scheme) & (selection.test_well == well) & (selection.sigma_a_ms == sa) & selection.method.isin(g["point_competitors"])] scores = sel.groupby("method").validation_mse.mean() if len(scores) != len(g["point_competitors"]): return {"evaluated": False, "reason": "Incomplete point competitors"} competitor = str(scores.idxmin()) pick = {} for role, method in (("candidate", g["candidate"]), ("competitor", competitor), ("same_posterior", g["same_posterior_method"])): hit = primary[(primary.scheme == scheme) & (primary.test_well == well) & (primary.method == method)] if len(hit) != 1 or not bool(hit.iloc[0].scored): raise ValueError(f"Incomplete G-D predictions: {scheme}/{well}/{method}") pick[role] = hit.iloc[0] a, b, d = pick["candidate"], pick["competitor"], pick["same_posterior"] rows.append(dict(well=well, competitor=competitor, competitor_validation_mse=float(scores[competitor]), n=int(a.n), rmse=float(a.rmse), competitor_rmse=float(b.rmse), ratio=float(a.rmse / b.rmse), improved=bool(a.rmse < b.rmse), same_posterior_rmse=float(d.rmse), improved_vs_same_posterior=bool(a.rmse < d.rmse), coverage_80=float(a.coverage_80), coverage_90=float(a.coverage_90))) frame = pd.DataFrame(rows) c80, c90 = float(frame.coverage_80.mean()), float(frame.coverage_90.mean()) wins = int(frame.improved.sum()) schemes[scheme] = dict( improved_wells=wins, n_wells=len(rows), macro_rmse=float(frame.rmse.mean()), macro_competitor_rmse=float(frame.competitor_rmse.mean()), macro_same_posterior_rmse=float(frame.same_posterior_rmse.mean()), improved_vs_same_posterior_wells=int(frame.improved_vs_same_posterior.sum()), coverage_80=c80, coverage_90=c90, consistent_improvement=wins >= rules["min_improved_wells"], coverage_in_band=within(c80, rules["coverage_80"]) and within(c90, rules["coverage_90"]), per_well=rows) claims = {"consistent_improvement": all(s["consistent_improvement"] for s in schemes.values()), "calibrated": all(s["coverage_in_band"] for s in schemes.values())} return dict(evaluated=True, descriptive=True, schemes=schemes, claims=claims, note=g["note"]) def registration_table(p: dict, root: Path, sigmas: list[float]) -> pd.DataFrame: """Per training set and well: γ, particles, posterior spread and label support per method (fewest and most samples over the members; training wells only).""" rows = [] for names in fold_sets(p): for sa in sigmas: meta = json.loads(reg_path(root, names, sa).with_suffix(".json").read_text(encoding="utf-8")) for d in meta["diagnostics"]: rows.append(dict(training_wells=";".join(names), sigma_a_ms=sa, phase0=meta["phase0"], phase_R=meta["phase_R"], lam=meta["lambda"], tau_c=meta["tau_c"], wall_seconds=meta["wall_seconds"], lik_start_ms=d["lik_ms"][0], lik_stop_ms=d["lik_ms"][1], **{k: v for k, v in d.items() if not isinstance(v, (list, dict))}, **{f"label_samples_{m}": n for m, n in d["label_samples"].items()}, **{f"label_samples_max_{m}": n for m, n in d["label_samples_max"].items()})) return pd.DataFrame(rows) def summarize(p: dict, root: Path, sigmas: list[float], arrays: dict | None = None) -> dict: arrays = load_arrays() if arrays is None else arrays pred, sel = neural_predictions(p, root, arrays, sigmas) full = VolveData(p, arrays=arrays) frame = pd.DataFrame([score(full, a, ref, p) for a in pred for ref in references(full, a["test_well"], p)]) selections = pd.DataFrame(sel) gate = gate_gd(frame, selections, p) smoke = root.name == "smoke" if smoke: gate = {"evaluated": False, "reason": "Smoke run; not the registered P4 experiment", "pipeline_check": gate} dest = root / "summary" dest.mkdir(parents=True, exist_ok=True) frame.to_csv(dest / "metrics.csv", index=False) selections.to_csv(dest / "selection.csv", index=False) registration_table(p, root, sigmas).to_csv(dest / "registration.csv", index=False) ens = frame[(frame.seed.astype(str) == "ensemble") & frame.scored.astype(bool)] groups = ens.groupby(["scheme", "sigma_a_ms", "reference", "method"]) macro = groups[COLUMNS].mean().join(groups.size().rename("n_wells")).reset_index() macro.to_csv(dest / "macro.csv", index=False) shifts = [{k: v for k, v in a.items() if k not in ("mu", "sigma")} | best_shift(full, a, p["data"]["primary_reference"], p["metrics"]["best_shift_max_samples"]) for a in pred if a["seed"] == "ensemble"] pd.DataFrame(shifts).to_csv(dest / "best_shift_DIAGNOSTIC_ONLY.csv", index=False) saved = {} for i, a in enumerate(pred): saved[f"{i}/mu"], saved[f"{i}/sigma"] = a["mu"], a["sigma"] np.savez_compressed(dest / "predictions.npz", times_ms=full.t_main, **saved) write_json(dest / "prediction_index.json", [{k: v for k, v in a.items() if k not in ("mu", "sigma")} for a in pred]) write_json(dest / "gate_gd.json", gate) main = macro[(macro.reference == p["data"]["primary_reference"]) & (macro.sigma_a_ms == p["registration"]["sigma_a_ms"])] text = ["# P4 Volve — nested blind folds (" + ", ".join(p["split"]["schemes"]) + ")", "", "Smoke only; no scientific result." if smoke else "Registered protocol_volve; outer-test labels are scoring-only.", "", "G-D (descriptive): " + json.dumps(gate, ensure_ascii=False, default=str), "", f"## Macro over wells, {p['data']['primary_reference']} reference, " f"σ_a = {p['registration']['sigma_a_ms']:g} ms (p.u.)", "", main.to_markdown(index=False, floatfmt=".4f"), "", "Per-well, per-seed and reference-sensitivity results: metrics.csv and macro.csv. Budgets: selection.csv. " "Registration diagnostics (training wells only): registration.csv.", f"band_* is a high-pass of reference runs of at least {p['metrics']['desc_band_min_samples']} samples, " "shorter than one period at f_c: descriptive only. Best-shift is diagnostic only and never alters a score.", "Six wells in three slots: per-well results are the replication unit; no p-values."] (dest / "summary.md").write_text("\n".join(text) + "\n", encoding="utf-8") plot_results(full, p, pred, gate.get("pipeline_check", gate), dest) return gate def plot_results(full: VolveData, p: dict, pred: list[dict], gate: dict, dest: Path) -> None: import matplotlib matplotlib.use("Agg") import matplotlib.pyplot as plt sa, ref, wells = p["registration"]["sigma_a_ms"], p["data"]["primary_reference"], p["data"]["wells"] files = [] for scheme in p["split"]["schemes"]: chosen = {r["well"]: r["competitor"] for r in gate.get("schemes", {}).get(scheme, {}).get("per_well", [])} fig, axes = plt.subplots(1, len(wells), figsize=(2.5 * len(wells), 6), sharey=True, sharex=True, layout="constrained") for ax, w in zip(axes, wells): ax.plot(100 * full.y(w, ref), full.t_main, "k", label="Reference") competitor = chosen.get(w, "B3b") for method, color, style, name in ((competitor, "#0072B2", "--", "Selected B3"), ("B3d-Sa", "#8F5800", ":", "B3d-Sa"), ("M2-Sa", "#CC3311", "-", "M2-Sa")): rows = [a for a in pred if a["scheme"] == scheme and a["test_well"] == w and a["method"] == method and a["seed"] == "ensemble" and a["sigma_a_ms"] == sa] if not rows: continue a = rows[0] ax.plot(100 * a["mu"], full.t_main, color=color, linestyle=style, label=name) if method == "M2-Sa": ax.fill_betweenx(full.t_main, 100 * (a["mu"] - Z90 * a["sigma"]), 100 * (a["mu"] + Z90 * a["sigma"]), color=color, alpha=0.18) ax.set(title=f"{w}\n(B3: {competitor})", xlabel="PHIF (p.u.)") ax.grid(alpha=0.2) axes[0].set_ylabel("TWT (ms)") axes[0].invert_yaxis() axes[0].legend(fontsize=8) for ext in ("png", "pdf"): fig.savefig(dest / f"wells_{scheme}.{ext}", dpi=160) files.append(f"wells_{scheme}.{ext}") plt.close(fig) write_json(dest / "figure_manifest.json", { "files": files, "source": "predictions.npz and prediction_index.json", "reference": "marker-calibrated vertical sonic (TVD-integrated DT) of the held-out well", "uncertainty": "nominal 90% moment-matched Gaussian predictive interval of M2-Sa; calibration is evaluated " "separately", "replication_unit": "well (n=6, three slots); network seeds are computational repeats", "transform": "porosity fraction multiplied by 100", "filters": "none for plotting", "publisher_requirements": "not yet verified", "description": "One panel per held-out well and blind scheme: reference over its support and blind " "predictions over the main window against downward-increasing two-way time; the B3 line is the " "point competitor selected by inner validation."})