Complete P4 Volve; pivot the manuscript to theory + benchmark

P4 (Volve field case). Add the deviated-well and Volve well builders
(ml_porosity/data/deviated.py, volve_wells.py), the ml_porosity/volve/
pipeline, scripts 23-25, the run_p4 drivers and tests. The protocol
configs/protocol_volve.yaml was locked at 2026-10-29T01:17:42Z before the
run (.sha256, .lock.json) and is committed here after the run. Gate G-D
failed: M2-Sa beats the selected B3 at 2/6 wells (lowo) and 3/6 (slot),
coverage90 is about 0.47, and no method has blind-well skill (R2 < 0).
A post hoc constant at the training-well mean beats every network, so
G-D had no power. The dropped P4x exploratory run is kept as a record
only (exploratory/, docs/research/p4-exploratory.md).

Applicability and Teapot Dome (exploratory, pre-declared). Scripts 26-29
and docs/research/applicability-*.md: F3 and Volve fail C1 and pass C2;
T3 power needs 5-18 blind wells with an exact reference; Teapot T0 and
pilot P-a failed, so Teapot is stopped. Raw Teapot data stay gitignored.

Manuscript (Pivot 1, level A). Reframe paper/ as a theory and synthetic
benchmark paper: Propositions 3-6, Corollaries 3-4, T4 coverage
(script 30) and the post hoc H2b bound check (script 31), with F3/Volve
moved to Appendix B. Correct two earlier claims: the Berkson and
classical bounds differ by 1.5-4.6x at the f^4-weighted band, and the
bank gain exceeds the registered classical bound (7/8 wide cells at
N = 16) but only 3/8 under the post hoc Berkson bound.

Docs. Sync plan, AGENTS.md, README, report.html, theory and technical
overview. The length pass for the venue is dropped by the user
(plan section 12 item 25); the length risk stays recorded as R9.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-29 12:18:22 +00:00
parent 7da6b077b6
commit 0cfe202a8b
61 changed files with 7162 additions and 881 deletions

View File

@@ -0,0 +1 @@
"""P4: blind-well Volve experiments with partial labels, separate from the frozen P3 (F3) modules."""

144
ml_porosity/volve/data.py Normal file
View File

@@ -0,0 +1,144 @@
"""P4 data views (plan §5.2): private arrays of the training wells, seismic-only blind inputs of every other well.
A restricted view (training_wells given) keeps, for a well outside the training set, only
times_ms, main_mask, kb_msl, survey/* the well path, known without its logs or picks
blind/<K>/{seismic_patch, md, il, xl, beyond} only for K ⊇ training_wells, well ∉ K
so its logs, picks, TDRs, reference path and the label-centred bin (il, xl, x, y: placed at the middle of the
label interval) are never loaded. Labels, the reference input and registration observations of such a well
raise RuntimeError. The full view (training_wells None) is for scoring only.
"""
from __future__ import annotations
import numpy as np
from ml_porosity.data.resample import log_to_time
from ml_porosity.data.tdr import TDR
from ml_porosity.models.bank_train import zscore_patch
from ml_porosity.paths import outputs_dir
from ml_porosity.registration.warp_prior import WarpGrid
PUBLIC = frozenset({"times_ms", "main_mask", "kb_msl"})
PUBLIC_PREFIXES = ("survey/",)
def npz_path():
return outputs_dir() / "volve" / "volve_wells.npz"
def load_arrays(path=None) -> dict[str, np.ndarray]:
with np.load(npz_path() if path is None else path) as z:
return {k: z[k] for k in z.files}
def blind_members(key: str) -> frozenset[str]:
return frozenset(key.split("+"))
def visible(key: str, training_wells: frozenset[str] | None) -> bool:
"""Whether the flat npz key "<well>/<item>" belongs to a view on `training_wells`."""
well, item = key.split("/", 1)
if training_wells is None or well in training_wells:
return True
if item in PUBLIC or item.startswith(PUBLIC_PREFIXES):
return True
if item.startswith("blind/"):
members = blind_members(item.split("/")[1])
return well not in members and training_wells <= members
return False
class VolveData:
def __init__(self, protocol: dict, training_wells: tuple[str, ...] | None = None,
arrays: dict[str, np.ndarray] | None = None):
self.protocol = protocol
self.wells = list(protocol["data"]["wells"])
self.label = protocol["data"]["label"]
self.training_wells = None if training_wells is None else frozenset(training_wells)
if self.training_wells is not None and not self.training_wells <= set(self.wells):
raise ValueError("Unknown training well")
source = load_arrays() if arrays is None else arrays
self.arrays = {k: v for k, v in source.items()
if k.split("/", 1)[0] in self.wells and visible(k, self.training_wells)}
self.t = self.ext(self.wells[0], "times_ms")
self.main = self.ext(self.wells[0], "main_mask").astype(bool)
self.t_main = self.t[self.main]
self.dt = float(np.diff(self.t)[0])
for w in self.wells:
if not (np.array_equal(self.ext(w, "times_ms"), self.t)
and np.array_equal(self.ext(w, "main_mask").astype(bool), self.main)):
raise ValueError(f"Volve time axes differ: {w}")
r = protocol["registration"]
f = r["fine_dt_ms"]
self.grid = WarpGrid(*r["tau_range_ms"], r["warp_dtau_ms"])
self.tau = np.arange(r["tau_range_ms"][0], r["tau_range_ms"][1] + f / 2, f)
self.t_fine = np.arange(self.t[0] - 300, self.t[-1] + 300 + f / 2, f)
def is_training(self, well: str) -> bool:
return self.training_wells is None or well in self.training_wells
def ext(self, well: str, key: str) -> np.ndarray:
try:
return self.arrays[f"{well}/{key}"]
except KeyError:
raise KeyError(f"{well}/{key} is not in this data view") from None
def blind_keys(self, well: str) -> list[str]:
head = f"{well}/blind/"
return sorted({k[len(head):].split("/")[0] for k in self.arrays if k.startswith(head)})
def patch(self, well: str, key: str) -> np.ndarray:
"""(C, n_ext) seismic patch: key 'reference' (calibrated path, training wells only) or a blind key."""
if key == "reference":
if not self.is_training(well):
raise RuntimeError("The reference path of a held-out well uses its own picks and DT")
return self.ext(well, "reference/seismic_patch")
if well in blind_members(key):
raise RuntimeError(f"Blind key {key!r} contains its own well {well!r}")
return self.ext(well, f"blind/{key}/seismic_patch")
def X(self, well: str, key: str) -> np.ndarray:
"""Network input (C, L) on the main window."""
return zscore_patch(self.patch(well, key), self.main)
def y(self, well: str, reference: str, label: str | None = None) -> np.ndarray:
"""Label on the main window under TDR `reference`; NaN outside its support."""
if not self.is_training(well):
raise RuntimeError("Held-out labels are unavailable in a training data view")
return self.ext(well, f"{reference}/{label or self.label}")[self.main]
def training_observations(self, names: tuple[str, ...]) -> list[dict]:
"""Registration inputs of training wells on the sonic time axis τ (vertical sonic through the first anchor
in the DT range). Anchors: in the DT range and inside the ext window. `lik`: ext samples from the first to
the last finite calibrated AI sample (the tie likelihood is evaluated there only)."""
if self.training_wells is not None and not set(names) <= self.training_wells:
raise RuntimeError("Held-out logs and anchors are unavailable in a training data view")
r = self.protocol["registration"]
obs = []
for name in names:
sonic = TDR(self.ext(name, "tdr/sonic/md"), self.ext(name, "tdr/sonic/twt_ms"), "sonic")
md = self.ext(name, "log/md")
amd, att = self.ext(name, "anchors_md"), self.ext(name, "anchors_twt_ms")
keep = self.ext(name, "anchors_in_dt").astype(bool) & (att >= self.t[0]) & (att <= self.t[-1])
if keep.sum() < 1:
raise ValueError(f"No anchor in the DT range: {name}")
resampled, valid = {}, {}
for curve in ("AI", self.label):
v = log_to_time(md, self.ext(name, f"log/{curve}"), sonic, self.tau,
fine_dt_ms=r["log_fine_dt_ms"], cutoff_frac=r["log_cutoff_frac"])
good = np.isfinite(v)
if good.sum() < 2:
raise ValueError(f"No sonic-domain log: {name}/{curve}")
resampled[curve] = np.interp(self.tau, self.tau[good], v[good])
valid[curve] = good
ok = np.flatnonzero(np.isfinite(self.ext(name, "calibrated/AI")))
lik = np.zeros(self.t.size, bool)
lik[ok[0]: ok[-1] + 1] = True
seis = self.ext(name, "reference/seismic_patch")
obs.append({"name": name, "tau_k": sonic.time_at(amd[keep]), "t_k": att[keep].astype(float),
"ai_log": resampled["AI"], "labels": {self.label: resampled[self.label]},
"label_valid": {self.label: valid[self.label]}, "lik": lik,
"seis": seis[len(seis) // 2].astype(float)})
return obs

View File

@@ -0,0 +1,287 @@
"""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."})

View File

@@ -0,0 +1,74 @@
"""Nested blind folds for P4 (plan §5.2).
Outer fold: test well u, training wells T_out = blind_training_wells(u, scheme) (`lowo`: every other well; `slot`:
every well outside the slot group of u). Inner folds: leave one well of T_out out, under both schemes — under
`slot` an inner validation well may share a slot with inner training wells, so inner validation can be optimistic
there (recorded deviation in protocol_volve).
Every model sees seismic only through blind keys: the input of a non-training well u under key K is placed in time
by the TD model of the wells K, with T_in ⊆ K ⊆ W∖{u} (never u's own picks or DT). Validation of v in T_out uses
K = T_in; the outer test of u uses K = T_out. Training wells use their calibrated reference path.
"""
from __future__ import annotations
import itertools
from ml_porosity.data.volve_wells import blind_key, blind_training_wells
def outer_folds(wells: list[str], scheme: str, p4: dict) -> list[tuple[str, tuple[str, ...]]]:
"""[(test well u, T_out)] in `wells` order; T_out sorted."""
out = []
for u in wells:
train = tuple(sorted(blind_training_wells(u, scheme, p4)))
if u in train or not train:
raise RuntimeError(f"invalid outer fold for {u}: {train}")
out.append((u, train))
return out
def inner_folds(outer_train: tuple[str, ...]) -> list[tuple[str, tuple[str, ...]]]:
"""[(validation well v, T_in = T_out ∖ {v})], leave-one-well-out within the outer training set."""
train = tuple(sorted(outer_train))
if len(train) < 2:
raise ValueError("inner LOWO needs at least two outer training wells")
return [(v, tuple(w for w in train if w != v)) for v in train]
def nested_folds(wells: list[str], schemes: list[str], p4: dict) -> list[dict]:
"""Every (scheme, test well, validation well, T_out, T_in), with the blind key of each role."""
rows = []
for scheme in schemes:
for u, t_out in outer_folds(wells, scheme, p4):
for v, t_in in inner_folds(t_out):
if u in t_in or v in t_in:
raise RuntimeError("held-out well entered an inner training set")
rows.append(dict(scheme=scheme, test=u, validation=v, outer_train=t_out, inner_train=t_in,
validation_key=blind_key(t_in), test_key=blind_key(t_out)))
return rows
def training_sets(wells: list[str], schemes: list[str], p4: dict) -> list[tuple[str, ...]]:
"""Distinct inner training sets over all schemes (one trajectory per set, method, seed and σ_a arm)."""
return sorted({f["inner_train"] for f in nested_folds(wells, schemes, p4)}, key=lambda s: (-len(s), s))
def prediction_targets(wells: list[str], train: tuple[str, ...]) -> list[tuple[str, str]]:
"""(well, key) inputs predicted by a model trained on `train`: training wells on their reference path
(key 'reference'), every other well u on every blind key K with train ⊆ K ⊆ W∖{u}. Covers the validation
(K = T_in) and outer-test (K = T_out ⊋ T_in) inputs of every fold that trains on `train`."""
train = tuple(sorted(train))
out = [(w, "reference") for w in train]
for u in wells:
if u in train:
continue
rest = [w for w in wells if w != u and w not in train]
for k in range(len(rest) + 1):
for extra in itertools.combinations(rest, k):
out.append((u, blind_key(train + extra)))
return out
def target_name(well: str, key: str) -> str:
return f"{well}|{key}"

View File

@@ -0,0 +1,93 @@
"""Bank losses with label masks (P4: Volve labels cover 16–37 of the 126 main-window samples).
Member s of the bank of training well b places the same label run at its own times, so it has its own support
mask M_bs (L); a (B, L) mask is shared by all members. For window j, n_bjs = Σ_{i ∈ j} M_bsi and n̄_bj = mean_s n_bjs:
ℓ_bjs = (n̄_bj / n_bjs) Σ_{i ∈ j} M_bsi log N(y_bs,i; μ_i, σ_i²) (members compared at a common count)
RML: L_b = −Σ_j (1/λ) log Σ_s π_bs exp(λ ℓ_bjs) / Σ_j n̄_bj
hard-min: L_b = −Σ_j max_s ℓ_bjs / Σ_j n̄_bj
and the loss is the mean of L_b over wells. A window where some member has no valid sample contributes nothing.
With a shared mask the count factor is 1; with every sample valid the loss equals losses.rml.bank_loss.
"""
from __future__ import annotations
import numpy as np
import torch
from scipy import signal
from ml_porosity.losses.rml import LOG_2PI, gather_windows
def masked_window_loglik(mu, sigma, Y, mask, starts, win: int) -> tuple[torch.Tensor, torch.Tensor]:
"""mu, sigma (B, L); Y (B, S, L), any value where the mask is False; mask (B, L) or (B, S, L)
→ summed ℓ (B, J, S) and valid counts n (B, J, S)."""
if mask.dim() == 2:
mask = mask[:, None, :].expand(Y.shape)
if mask.shape != Y.shape:
raise ValueError("mask must be (B, L) or match the bank (B, S, L)")
y = torch.where(mask, Y, torch.zeros((), dtype=Y.dtype, device=Y.device))
m = gather_windows(mu, starts, win)[:, :, None, :]
s = gather_windows(sigma, starts, win)[:, :, None, :]
w = gather_windows(mask.to(mu.dtype), starts, win)
term = -torch.log(s) - 0.5 * ((gather_windows(y, starts, win) - m) / s) ** 2 - 0.5 * LOG_2PI
return (term * w).sum(-1), w.sum(-1)
def masked_bank_loss(mu, sigma, Y, logpi, mask, starts, win: int, lam: float | None) -> torch.Tensor:
"""lam = None → hard-min (max ℓ); otherwise RML with power λ. Every well needs a window in which every member
has a valid sample."""
ll, n = masked_window_loglik(mu, sigma, Y, mask, starts, win)
use = (n > 0).all(-1)
nbar = n.mean(-1)
ll = torch.where(use[..., None], ll * nbar[..., None] / n.clamp(min=1), torch.zeros((), dtype=ll.dtype,
device=ll.device))
total = (nbar * use).sum(1)
if not bool((total > 0).all()):
raise ValueError("a training well has no labelled sample in any window")
v = ll.max(-1).values if lam is None else torch.logsumexp(logpi[:, None, :] + lam * ll, dim=-1) / lam
v = torch.where(use, v, torch.zeros((), dtype=v.dtype, device=v.device))
return -(v.sum(1) / total).mean()
def highpass_segment(y: np.ndarray, f_c_hz: float, dt_ms: float = 4.0, order: int = 4) -> np.ndarray:
"""y minus its zero-phase Butterworth low band below f_c, as eval.metrics.split_bands (identical for ≥ 16
samples at order 4); shorter segments use the longest even padding scipy accepts."""
y = np.asarray(y, dtype=float)
sos = signal.butter(order, f_c_hz, fs=1000.0 / dt_ms, output="sos")
pad = min(3 * (2 * len(sos) + 1), y.size - 1)
return y - signal.sosfiltfilt(sos, y, padtype="even", padlen=pad)
def segment_lambda(segments: list[np.ndarray], f_c_hz: float = 6.0, dt_ms: float = 4.0,
max_lag: int = 32) -> tuple[float, float]:
"""losses.rml.effective_lambda for label segments of any length ≥ 2: λ = 1/τ_c, τ_c = 1 + 2 Σ_k ρ(k)², with ρ
the ACF of the high-passed segments pooled as lagged products (a lag longer than a segment adds nothing). Σ runs
up to the first lag with ρ ≤ 0. Equals effective_lambda when every segment has more than max_lag samples."""
acc = np.zeros(max_lag + 1)
for y in segments:
y = np.asarray(y, dtype=float)
if y.size < 2 or not np.isfinite(y).all():
raise ValueError("segments must be finite with at least two samples")
hi = highpass_segment(y, f_c_hz, dt_ms)
hi = hi - hi.mean()
a = np.correlate(hi, hi, "full")[hi.size - 1: hi.size + max_lag]
acc[: a.size] += a
rho = acc / acc[0]
k = np.argmax(rho[1:] <= 0) + 1 if np.any(rho[1:] <= 0) else max_lag + 1
tau_c = 1.0 + 2.0 * float(np.sum(rho[1:k] ** 2))
return 1.0 / tau_c, tau_c
def finite_runs(y: np.ndarray) -> list[tuple[int, int]]:
"""[start, stop) of the maximal runs of finite samples of a series (NaN separates runs)."""
ok = np.isfinite(np.asarray(y, dtype=float))
edges = np.flatnonzero(np.diff(np.r_[0, ok.astype(int), 0]))
return [(int(a), int(b)) for a, b in zip(edges[::2], edges[1::2])]
def label_segments(y: np.ndarray) -> list[np.ndarray]:
"""Maximal runs of finite samples of a series."""
y = np.asarray(y, dtype=float)
return [y[a:b] for a, b in finite_runs(y)]

View File

@@ -0,0 +1,123 @@
"""Protocol locking and resume fingerprints for P4 (Volve), separate from the frozen P3 lock.
Paths in the stamp are relative to their root (repo, outputs or Volve data directory), so a lock is portable between
checkouts; it is still bound to one environment, as in P3. Before the lock exists, `current_stamp` gives the same
stamp without writing it (smoke runs only).
"""
from __future__ import annotations
import json
from datetime import datetime, timezone
from pathlib import Path
import yaml
from ml_porosity.f3.protocol import digest, environment, fingerprint
from ml_porosity.paths import REPO_ROOT, outputs_dir, volve_root
__all__ = ["CONFIG", "LOCK", "current_stamp", "fingerprint", "freeze", "load_protocol", "source_config"]
CONFIG = REPO_ROOT / "configs/protocol_volve.yaml"
LOCK = REPO_ROOT / "configs/protocol_volve.lock.json"
SCRIPTS = ("scripts/23_build_volve_wells.py", "scripts/24_run_volve.py", "scripts/run_p4.ps1", "scripts/run_p4.sh")
PROTECTED = ("wavelets.npz", "p2/warp_prior_f3.json")
RESULTS = ("registration", "train", "summary")
def load_protocol() -> dict:
return yaml.safe_load(CONFIG.read_text(encoding="utf-8"))
def source_config(p: dict) -> dict:
"""configs/d3_volve.yaml, which built the dataset; its p4 section holds the slot groups of the blind folds."""
cfg = yaml.safe_load((REPO_ROOT / p["data"]["source_config"]).read_text(encoding="utf-8"))
if list(cfg["p4"]["wells"]) != list(p["data"]["wells"]) or cfg["p4"]["label"] != p["data"]["label"]:
raise RuntimeError("protocol_volve and its source configuration disagree on wells or label")
if not set(p["split"]["schemes"]) <= set(cfg["p4"]["blind_schemes"]):
raise RuntimeError("Unknown blind scheme in protocol_volve")
return cfg
def code_files() -> list[Path]:
paths = sorted((REPO_ROOT / "ml_porosity").rglob("*.py"))
paths += [REPO_ROOT / s for s in SCRIPTS if (REPO_ROOT / s).exists()]
return paths + [REPO_ROOT / "pyproject.toml"]
def source_hash() -> str:
import hashlib
h = hashlib.sha256()
for f in code_files():
h.update(f.relative_to(REPO_ROOT).as_posix().encode() + b"\0")
h.update(f.read_bytes().replace(b"\r\n", b"\n") + b"\0")
return h.hexdigest()
def input_files(p: dict) -> list[Path]:
"""Derived dataset, its configuration and every raw file the build reads, except the cube (checked against the
data manifest at the first lock)."""
cfg = source_config(p)
root, p4 = volve_root(), cfg["p4"]
files = [outputs_dir() / "volve/volve_wells.npz", outputs_dir() / "volve/volve_wells_summary.json",
root / cfg["picks"], root / cfg["horizons_twt"] / cfg["grid_horizon"]]
for spec in p4["wells"].values():
files.append(root / p4["survey_dir"] / spec["survey"])
logs = root / cfg["well_logs_dir"] / spec["logs"] / p4["log_subdir"]
files += [logs / p4["las_input"], logs / p4["las_output"]]
files += [root / cfg["well_logs_dir"] / cfg["checkshots"][spec["picks"]][kind]
for kind in spec.get("checkshots", [])]
return files
def portable_name(path: Path) -> str:
"""Portable name: 'repo:', 'outputs:' or 'volve:' plus the POSIX path relative to that root."""
path = path.resolve()
for prefix, base in (("volve", volve_root()), ("outputs", outputs_dir()), ("repo", REPO_ROOT)):
try:
return f"{prefix}:{path.relative_to(base.resolve()).as_posix()}"
except ValueError:
continue
raise ValueError(f"Input outside the repository, outputs and Volve roots: {path}")
def current_stamp(p: dict | None = None) -> dict:
p = load_protocol() if p is None else p
missing = [f for f in input_files(p) + [outputs_dir() / a for a in PROTECTED] if not f.exists()]
if missing:
raise FileNotFoundError(f"P4 inputs missing (sync data/ and outputs/ first): {[str(f) for f in missing]}")
config = REPO_ROOT / p["data"]["source_config"]
return {"protocol_sha256": digest(CONFIG, True), "code_sha256": source_hash(), "environment": environment(),
"protected_artifacts": {portable_name(outputs_dir() / a): digest(outputs_dir() / a) for a in PROTECTED},
"inputs": {portable_name(f): digest(f, f == config) for f in [config] + input_files(p)}}
def freeze(check: bool = False) -> dict:
"""Return the lock; create it if absent and check is False. Any difference from an existing lock is an error."""
p = load_protocol()
stamp = current_stamp(p)
if LOCK.exists():
old = json.loads(LOCK.read_text(encoding="utf-8"))
for k, v in stamp.items():
if old[k] != v:
raise RuntimeError(f"P4 lock mismatch: {k}. Preserve results and create a new protocol version.")
return old
if check:
raise RuntimeError("P4 is not locked. Run the lock stage before registration/training.")
if any((outputs_dir() / "p4" / d).exists() for d in RESULTS):
raise RuntimeError("Refusing a first lock after P4 results already exist.")
cfg = source_config(p)
manifest = json.loads((REPO_ROOT / "data_manifest/volve.json").read_text(encoding="utf-8"))
expected = manifest["files"][cfg["cube"]]["sha256"]
cube = volve_root() / cfg["cube"]
if not cube.exists() or digest(cube) != expected:
raise RuntimeError(f"Volve cube missing or different from the audited source: {cube}")
stamp |= {"locked_utc": datetime.now(timezone.utc).isoformat(), "segy_sha256": expected,
"canonical_text": "UTF-8, CRLF normalized to LF for code, protocol and source configuration; "
"binary inputs exact",
"wells": p["data"]["wells"]}
LOCK.write_text(json.dumps(stamp, indent=2), encoding="utf-8")
CONFIG.with_suffix(".sha256").write_text(stamp["protocol_sha256"] + " configs/protocol_volve.yaml\n",
encoding="utf-8")
return stamp

View File

@@ -0,0 +1,171 @@
"""Training-set-only P4 registration and label banks. No held-out well is passed to this module.
Follows ml_porosity.f3.registration.register_set with three recorded deviations (protocol_volve):
- Likelihood window: AI exists only over the logged interval (45–151 of the 301 ext samples), so the tie
likelihood of a well (phase grid, SMC, γ) is evaluated on `lik`, the ext samples from the first to the last
finite calibrated AI sample of that well; outside it the constant AI extension gives a zero synthetic that would
only fit noise. B3c/B3c-R keep the F3 full-window local shifts: windows without synthetic energy have r = NaN and
are dropped by r_min.
- Particle validity: labels cover 16–37 of the 126 main samples, so a particle only has to invert over the main
window (F3 also required full label support there).
- Member support: every member keeps the samples where its own warp places the label run (NaN elsewhere), so
no label is extrapolated and the run is not trimmed to the intersection of all members (which loses both ends
of a 16-sample run under the posterior spread). A member with fewer than `min_label_samples` is an error. The
intersection over members and methods is recorded as a diagnostic only.
"""
from __future__ import annotations
import gc
import time
from types import SimpleNamespace
import numpy as np
from ml_porosity.data.wavelet import rotate_phase, statistical_wavelet
from ml_porosity.registration.labels import antialias, invert_warps, labels_for_warps
from ml_porosity.registration.pipeline import PHASES, fit_cell_hyper
from ml_porosity.registration.sampler import sample_warps
from ml_porosity.registration.smc import TiePosterior, gamma_acf, phase_basis, phase_wavelet
from ml_porosity.registration.tie_likelihood import fine_wavelet, fit_phase, profile_loglik, synth_for_warps
from ml_porosity.registration.ties import tie_b3b, tie_b3c
from ml_porosity.volve.data import VolveData
from ml_porosity.volve.losses import label_segments, segment_lambda
METHODS = ("B3b", "B3c", "B3c-R", "B3d-Sa", "M2-Sa")
def valid_warps(data: VolveData, warps: np.ndarray) -> np.ndarray:
"""Warps whose inverse τ(t) exists over the whole main window."""
return np.isfinite(invert_warps(warps, data.tau, data.t_main)).all(axis=1)
def window_phase_loglik(syn0: np.ndarray, seis: np.ndarray, lik: np.ndarray, phases=PHASES) -> np.ndarray:
"""(P, S) as tie_likelihood.phase_loglik, with the phase rotated on the full ext synthetic and the profile
likelihood taken over the samples `lik` only."""
syn0 = np.atleast_2d(syn0)
return np.stack([profile_loglik(rotate_phase(syn0, p)[:, lik], seis[lik]) for p in phases])
def label_fn(data: VolveData, obs: dict, y_filtered: np.ndarray):
"""t(τ) warps (S, n_tau) → labels (S, L) on the main window, NaN where the label is not supported."""
valid = obs["label_valid"][data.label].astype(float)
def lab(warps):
warps = np.atleast_2d(warps)
tau_at = invert_warps(warps, data.tau, data.t_main)
support = np.interp(np.nan_to_num(tau_at, nan=data.tau[0] - 1.0), data.tau, valid, left=0, right=0)
out = labels_for_warps(data.tau, y_filtered, warps, data.t_main)
return np.where(np.isfinite(tau_at) & (support >= 1 - 1e-9), out, np.nan)
return lab
def register_set(data: VolveData, names: tuple[str, ...], p: dict, device: str,
sigma_a: float = 7.0) -> tuple[dict, dict]:
import torch
from ml_porosity.registration.smc_torch import TiePosteriorTorch, smc_fit_phase, smc_tie_posterior
started = time.perf_counter()
names = tuple(sorted(names))
r = p["registration"] | {"sigma_a_ms": sigma_a}
label = data.label
obs = data.training_observations(names)
if tuple(o["name"] for o in obs) != names:
raise RuntimeError("Unexpected training-well payload")
h, hinfo = fit_cell_hyper(SimpleNamespace(grid=data.grid), obs, r, r["smc_seed"])
f = r["fine_dt_ms"]
fac = int(round(data.dt / f))
w0 = statistical_wavelet(np.stack([o["seis"] for o in obs]), data.dt, r["wavelet_ms"])
B = phase_basis(w0, fac)
cover = (data.t_main[0], data.t_main[-1])
samples, Ts, Zs, LL, anchor_valid = [], [], [], [], []
for i, o in enumerate(obs):
smp = sample_warps(data.grid, h, o["tau_k"], o["t_k"], r["particles"], r["g_max"],
np.random.default_rng([r["smc_seed"], i, 13]))
samples.append(smp)
tg = data.grid.t_of_tau(smp["b"][:r["S"]], smp["g"][:r["S"]], data.tau)
valid = valid_warps(data, tg)
if not valid.any():
raise ValueError(f"No anchor sample covers the main window: {o['name']}")
anchor_valid.append(valid)
syn = synth_for_warps(data.tau, o["ai_log"], tg, data.t_fine, data.t, fine_wavelet(w0, fac))
LL.append(window_phase_loglik(syn, o["seis"], o["lik"]))
phase0 = float(PHASES[fit_phase(LL, anchor_valid, PHASES)])
for o, smp in zip(obs, samples):
T = TiePosteriorTorch(TiePosterior(data.grid, h, o["tau_k"], o["t_k"], r["g_max"], data.tau, o["ai_log"],
data.t_fine, data.t[o["lik"]], phase_wavelet(B, phase0),
o["seis"][o["lik"]], cover), device)
Zs.append(T.z(smp["u"]))
Ts.append(T)
phase_r, ph = smc_fit_phase(Ts, Zs, B, phase0, [r["smc_seed"], 19], step=r["phase_step"],
half_width=r["phase_half_width"], max_extra=r["phase_max_extra"],
n_moves=r["smc_moves"])
wf = phase_wavelet(B, phase_r)
post, diag = [], []
for i, (o, T0, z0) in enumerate(zip(obs, Ts, Zs)):
T = T0.with_wavelet(wf)
gamma = gamma_acf(T, z0, T.parts(z0)[1])
res = smc_tie_posterior(T, z0, [gamma], np.random.default_rng([r["smc_seed"], i, 17]),
n_moves=r["smc_moves"])
u = T.u(res["Z"][gamma])
tg = data.grid.t_of_tau(u[:, 0], u[:, 1:], data.tau)
valid = valid_warps(data, tg)
if valid.sum() < min(256, r["particles"]):
raise ValueError(f"Insufficient posterior particles covering the main window: {o['name']}, "
f"{valid.sum()} valid")
post.append(tg[valid])
diag.append({"well": o["name"], "gamma": gamma, "n_stages": len(res["stages"]),
"valid_particles": int(valid.sum()), "particles": len(valid),
"n_anchors": len(o["tau_k"]), "lik_samples": int(o["lik"].sum()),
"lik_ms": [float(data.t[o["lik"]][0]), float(data.t[o["lik"]][-1])]})
bundle = {"wells": np.asarray(names), "phase0": np.asarray(phase0), "phase_R": np.asarray(phase_r)}
banks = {m: [] for m in METHODS}
logpi = []
filtered = [antialias(o["labels"][label], f, data.dt) for o in obs]
normsel = (data.tau >= data.t_main[0]) & (data.tau <= data.t_main[-1])
vals = np.concatenate([y[normsel & o["label_valid"][label]] for o, y in zip(obs, filtered)])
bundle[f"{label}/norm"] = np.array([vals.mean(), max(vals.std(), 1e-8)])
for i, (o, tg, y) in enumerate(zip(obs, post, filtered)):
lab = label_fn(data, o, y)
b3b = tie_b3b(o["tau_k"], o["t_k"], data.tau)
ties = {"B3b": b3b, "B3d-Sa": tg.mean(axis=0)}
for name, phase in (("B3c", phase0), ("B3c-R", phase_r)):
syn = synth_for_warps(data.tau, o["ai_log"], b3b, data.t_fine, data.t,
fine_wavelet(rotate_phase(w0, phase), fac))[0]
ties[name] = tie_b3c(b3b, data.tau, syn, o["seis"], data.t, data.dt)
per = {m: lab(t) for m, t in ties.items()}
sub = np.random.default_rng([r["smc_seed"], i, 29]).choice(len(tg), r["S"], replace=False)
per["M2-Sa"] = lab(tg[sub])
counts = {m: np.isfinite(a).sum(axis=1) for m, a in per.items()}
short = {m: int(c.min()) for m, c in counts.items() if c.min() < p["data"]["min_label_samples"]}
if short:
raise ValueError(f"Label support too short: {o['name']}, fewest samples per member {short}")
for m in METHODS:
banks[m].append(per[m])
common = np.logical_and.reduce([np.isfinite(a).all(axis=0) for a in per.values()])
union = np.isfinite(per["M2-Sa"]).any(axis=0)
logpi.append(np.full(r["S"], -np.log(r["S"])))
tau_at = invert_warps(tg, data.tau, data.t_main)
q = np.diff(np.quantile(tau_at, [0.05, 0.95], axis=0), axis=0)[0] / 3.29
diag[i] |= {"sigma_post_ms": float(np.mean(q)), "sigma_post_label_ms": float(np.mean(q[union])),
"common_samples": int(common.sum()),
"label_samples": {m: int(c.min()) for m, c in counts.items()},
"label_samples_max": {m: int(c.max()) for m, c in counts.items()}}
for m in METHODS:
bundle[f"{label}/{m}"] = np.stack(banks[m]).astype(np.float32)
bundle[f"{label}/M2-Sa/logpi"] = np.stack(logpi).astype(np.float32)
segments = [s for y in bundle[f"{label}/B3b"][:, 0] for s in label_segments(y) if s.size >= 2]
lam, tau_c = segment_lambda(segments, p["metrics"]["f_c_hz"], data.dt)
bundle[f"{label}/lambda"], bundle[f"{label}/tau_c"] = np.asarray(lam), np.asarray(tau_c)
for o, tg in zip(obs, post):
bundle[f"posterior/{o['name']}/tau_at_main"] = invert_warps(tg, data.tau, data.t_main)
meta = {"training_wells": list(names), "sigma_a_ms": sigma_a, "phase0": phase0, "phase_R": phase_r,
"phase_info": ph, "hyper": h.as_dict(), "hyper_info": hinfo, "diagnostics": diag,
"lambda": lam, "tau_c": tau_c, "wall_seconds": time.perf_counter() - started}
del Ts, Zs, T, T0
gc.collect()
if torch.cuda.is_available():
torch.cuda.empty_cache()
return bundle, meta

283
ml_porosity/volve/runner.py Normal file
View File

@@ -0,0 +1,283 @@
"""Resumable P4 stages. A worker only ever loads the data view of its own training wells and selects nothing.
Progress goes to outputs/p4/<root>/progress.json (retried when Windows locks the file, and never fatal), not to the
P3 dashboard.
"""
from __future__ import annotations
import copy
import itertools
import json
import time
from concurrent.futures import FIRST_COMPLETED, ProcessPoolExecutor, wait
from datetime import datetime
from multiprocessing import get_context
from pathlib import Path
import numpy as np
from ml_porosity.f3.progress import write_json
from ml_porosity.paths import outputs_dir
from ml_porosity.volve.data import VolveData
from ml_porosity.volve.folds import prediction_targets, target_name, training_sets
from ml_porosity.volve.protocol import current_stamp, digest, fingerprint, freeze, source_config
from ml_porosity.volve.registration import METHODS
def set_name(names) -> str:
"""'F-1A__F-1B__F-11A__F-12': sorted well names without spaces."""
return "__".join(sorted(n.replace(" ", "") for n in names))
def reg_path(root: Path, names, sigma_a: float = 7) -> Path:
return root / "registration" / f"{set_name(names)}_sa{sigma_a:g}.npz"
def job_path(root: Path, names, method: str, label: str, seed: int, sigma_a: float = 7) -> Path:
return root / "train" / f"{set_name(names)}__{method}__{label}__s{seed}__sa{sigma_a:g}.npz"
def load_bundle(path: Path) -> dict:
with np.load(path) as z:
return {k: z[k] for k in z.files}
def nan_allowed(key: str) -> bool:
"""Label banks are NaN outside each member's label support; every other numeric array must be finite."""
parts = key.split("/")
return len(parts) == 2 and parts[1] in METHODS
def check_arrays(path: Path, arrays: dict) -> None:
if not arrays:
raise RuntimeError(f"Empty completed artifact: {path}")
for k, a in arrays.items():
if not np.issubdtype(a.dtype, np.number):
continue
if np.isinf(a).any() or (np.isnan(a).any() and not nan_allowed(k)) or np.isnan(a).all():
raise RuntimeError(f"Corrupt/non-finite artifact: {path}/{k}")
def reusable(path: Path, key: str) -> bool:
meta = path.with_suffix(".json")
if not path.exists() or not meta.exists():
return False
stored = json.loads(meta.read_text(encoding="utf-8"))
if stored.get("fingerprint") != key:
raise RuntimeError(f"Resume fingerprint mismatch: {path}. Use a new output directory.")
if stored.get("artifact_sha256") is None or digest(path) != stored["artifact_sha256"]:
raise RuntimeError(f"Missing or mismatched completed-artifact checksum: {path}")
if path.parent.name == "train":
ckpt = path.with_suffix(".pt")
if not ckpt.exists() or digest(ckpt) != stored.get("checkpoint_sha256"):
raise RuntimeError(f"Missing or mismatched model checkpoint: {ckpt}")
check_arrays(path, load_bundle(path))
return True
def save_npz(path: Path, arrays: dict) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
tmp = path.with_suffix(".tmp.npz")
np.savez_compressed(tmp, **arrays)
tmp.replace(path)
def registration_worker(job: dict) -> dict:
import torch
from ml_porosity.volve.registration import register_set
torch.set_num_threads(job["p"]["runtime"]["cpu_threads_per_worker"])
path = reg_path(Path(job["root"]), job["names"], job["sa"])
if reusable(path, job["key"]):
return {"cached": True, "path": str(path)}
data = VolveData(job["p"], training_wells=tuple(job["names"]))
bundle, meta = register_set(data, tuple(job["names"]), job["p"], job["device"], job["sa"])
check_arrays(path, bundle)
save_npz(path, bundle)
write_json(path.with_suffix(".json"), meta | {"fingerprint": job["key"], "artifact_sha256": digest(path)})
return {"cached": False, "path": str(path), **meta}
def training_worker(job: dict) -> dict:
from ml_porosity.volve.training import method_spec, train_trajectory
root, p = Path(job["root"]), job["p"]
label, names = p["data"]["label"], tuple(sorted(job["names"]))
path = job_path(root, names, job["method"], label, job["seed"], job["sa"])
if reusable(path, job["key"]):
return {"cached": True, "path": str(path)}
data = VolveData(p, training_wells=names)
bundle = load_bundle(reg_path(root, names, job["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 = method_spec(bundle, label, job["method"])
ckpt = path.with_suffix(".pt")
ckpt.parent.mkdir(parents=True, exist_ok=True)
pred, meta = train_trajectory(X, X_targets, spec, job["method"], p["training"], job["seed"],
p["training"]["budgets"], job["device"], ckpt,
p["runtime"]["cpu_threads_per_worker"])
mean, sd = bundle[f"{label}/norm"]
pred = {k: v * sd + (mean if k.endswith("/mu") else 0) for k, v 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"]}
check_arrays(path, pred)
save_npz(path, pred)
write_json(path.with_suffix(".json"), meta | {
"fingerprint": job["key"], "artifact_sha256": digest(path), "checkpoint_sha256": digest(ckpt),
"training_wells": list(names), "label": label, "method": job["method"], "seed": job["seed"],
"sigma_a_ms": job["sa"], "n_targets": len(targets)})
return {"cached": False, "path": str(path), **meta}
def progress(root: Path, **values) -> None:
path = root / "progress.json"
for attempt in range(20):
try:
old = json.loads(path.read_text(encoding="utf-8")) if path.exists() else {}
write_json(path, old | values | {"updated": datetime.now().astimezone().isoformat(timespec="seconds")})
return
except (PermissionError, json.JSONDecodeError):
time.sleep(0.25 * (attempt + 1))
print(f"warning: progress file not updated: {path}", flush=True)
def run_jobs(jobs: list[dict], fn, workers: int, stage: str) -> list[dict]:
if not jobs:
return []
root = Path(jobs[0]["root"])
started, results = time.perf_counter(), []
progress(root, stage=stage, status="running", completed=0, total=len(jobs), error=None)
with ProcessPoolExecutor(max_workers=workers, mp_context=get_context("spawn")) as pool:
futures = {pool.submit(fn, job): job for job in jobs}
pending = set(futures)
while pending:
done, pending = wait(pending, timeout=30, return_when=FIRST_COMPLETED)
for fut in done:
try:
result = fut.result()
except Exception as exc:
for other in pending:
other.cancel()
progress(root, status="failed; pending jobs cancelled", error=f"{futures[fut]['key'][:12]}: {exc}")
raise
results.append(result)
fresh = sum(not r.get("cached") for r in results)
elapsed = time.perf_counter() - started
eta = elapsed / fresh * (len(jobs) - len(results)) if fresh else None
progress(root, completed=len(results), cached=len(results) - fresh, elapsed_seconds=elapsed,
eta_seconds=eta)
print(f"{stage} {len(results)}/{len(jobs)} {'cached ' if result.get('cached') else ''}"
f"{result['path']}", flush=True)
progress(root, status="done", eta_seconds=0)
return results
def sigma_arms(p: dict, arms: str) -> list[float]:
"""'primary' → [σ_a], 'sensitivity' → the misspecification arms, 'all' → both."""
primary, extra = [p["registration"]["sigma_a_ms"]], list(p["registration"]["sigma_a_sensitivity_ms"])
return {"primary": primary, "sensitivity": extra, "all": primary + extra}[arms]
def fold_sets(p: dict) -> list[tuple[str, ...]]:
return training_sets(p["data"]["wells"], p["split"]["schemes"], source_config(p)["p4"])
def registration_jobs(p: dict, stamp: dict, root: Path, device: str, arms: str = "primary") -> list[dict]:
jobs = []
for names, sa in itertools.product(fold_sets(p), sigma_arms(p, arms)):
settings = dict(names=list(names), sa=sa)
jobs.append(dict(p=p, root=str(root), device=device, **settings,
key=fingerprint(stamp, stage="registration", **settings)))
return jobs
def arm_methods(p: dict, sa: float) -> list[str]:
main = sa == p["registration"]["sigma_a_ms"]
return list(p["methods"]["main"] if main else p["registration"]["sensitivity_methods"])
def training_jobs(p: dict, stamp: dict, root: Path, device: str, arms: str = "primary") -> list[dict]:
jobs = []
for names, sa in itertools.product(fold_sets(p), sigma_arms(p, arms)):
for method, seed in itertools.product(arm_methods(p, sa), p["split"]["seeds"]):
settings = dict(names=list(names), method=method, label=p["data"]["label"], seed=seed, sa=sa)
jobs.append(dict(p=p, root=str(root), device=device, **settings,
key=fingerprint(stamp, stage="train", **settings)))
return jobs
def smoke_protocol(p: dict) -> dict:
"""Reduced settings for a pipeline check; outputs go to outputs/p4/smoke and are never results."""
p = copy.deepcopy(p)
p["split"]["seeds"] = [0]
p["registration"].update(particles=16, S=8, hyper_starts=1, smc_moves=1, phase_half_width=0,
phase_max_extra=0, sigma_a_sensitivity_ms=[])
p["training"]["budgets"] = [2, 4]
return p
def benchmark(p: dict, device: str, steps: int = 100) -> dict:
"""Runtime pilot outside the result tree: one registration of the first (largest) training set and `steps`
training steps of B3b and M2-Sa on it. Training wells only; no held-out label, nothing selected."""
from ml_porosity.volve.training import method_spec, train_trajectory
root, sa, label = outputs_dir() / "p4" / "benchmark", p["registration"]["sigma_a_ms"], p["data"]["label"]
sets = fold_sets(p)
names = sets[0]
stamp = current_stamp(p) | {"benchmark_only": True}
registration_worker(dict(p=p, root=str(root), device=device, names=list(names), sa=sa,
key=fingerprint(stamp, stage="registration", names=list(names), sa=sa)))
seconds = json.loads(reg_path(root, names, sa).with_suffix(".json").read_text(encoding="utf-8"))["wall_seconds"]
data = VolveData(p, training_wells=names)
bundle = load_bundle(reg_path(root, names, sa))
X = np.stack([data.X(w, "reference") for w in names])
X_targets = np.stack([data.X(w, k) for w, k in prediction_targets(data.wells, names)])
per_step = {m: train_trajectory(X, X_targets, method_spec(bundle, label, m), m, p["training"], 0, [steps], device,
None, p["runtime"]["cpu_threads_per_worker"])[1]["seconds_per_step"]
for m in ("B3b", "M2-Sa")}
# Registration cost grows with the number of wells; the largest set gives the training-step upper bound.
reg_primary = seconds * sum(len(s) for s in sets) / len(names)
n_sens = len(p["registration"]["sigma_a_sensitivity_ms"])
steps_per_job = max(p["training"]["budgets"]) * max(per_step.values())
jobs = {"primary": len(sets) * len(p["methods"]["main"]) * len(p["split"]["seeds"]),
"sensitivity": len(sets) * len(p["registration"]["sensitivity_methods"]) * len(p["split"]["seeds"]) * n_sens}
out = {"device": device, "training_wells": list(names), "registration_seconds_largest_set": seconds,
"seconds_per_step": per_step, "registration_jobs": {"primary": len(sets), "sensitivity": len(sets) * n_sens},
"training_jobs": jobs,
"sequential_seconds": {"registration_primary": reg_primary, "registration_sensitivity": reg_primary * n_sens,
"training_primary": jobs["primary"] * steps_per_job,
"training_sensitivity": jobs["sensitivity"] * steps_per_job},
"note": "One-worker extrapolation from one real training set; parallel workers on one GPU speed this up "
"sublinearly. Not a confidence interval."}
write_json(outputs_dir() / "p4" / "benchmark.json", out)
return out
def run(stage: str, p: dict, device: str, workers: int, smoke: bool = False, arms: str = "primary") -> None:
root = outputs_dir() / "p4"
if smoke:
if arms != "primary":
raise ValueError("Smoke runs use the primary σ_a arm only")
p = smoke_protocol(p)
root = root / "smoke"
if stage == "summarize":
# Scores held-out PHIF: only once the design is frozen.
stamp = freeze(check=True) | {"smoke": p}
else:
stamp = current_stamp() | {"smoke": p, "unlocked_draft": True}
else:
stamp = freeze(check=True)
if stage == "register":
run_jobs(registration_jobs(p, stamp, root, device, arms), registration_worker, workers, stage)
elif stage == "train":
run_jobs(training_jobs(p, stamp, root, device, arms), training_worker, workers, stage)
elif stage == "summarize":
from ml_porosity.volve.evaluation import summarize
# The G-D report always needs the primary arm.
summarize(p, root, sigma_arms(p, "primary" if arms == "primary" else "all"))
else:
raise ValueError(stage)

View File

@@ -0,0 +1,87 @@
"""P4 trajectories: masked bank losses, a checkpoint at every registered budget, no held-out label.
Mirrors ml_porosity.f3.training.train_trajectory for the bank methods (same model, optimiser, seeding and
checkpoints); the loss is volve.losses.masked_bank_loss on the label support of each bank member (finite samples).
"""
from __future__ import annotations
import time
from pathlib import Path
import numpy as np
import torch
from torch import nn
from ml_porosity.f3.training import ensemble, make_model
from ml_porosity.models.bank_train import window_starts_fixed
from ml_porosity.models.train import predict
from ml_porosity.volve.losses import masked_bank_loss
__all__ = ["ensemble", "method_spec", "train_trajectory"]
def method_spec(bundle: dict, label: str, method: str) -> dict:
"""Normalised bank (NaN outside each member's label support), log prior weights, the member support masks
(B, S, L) and λ. Single-member banks reduce to the masked Gaussian NLL for any λ."""
m0, s0 = bundle[f"{label}/norm"]
Y = bundle[f"{label}/{method}"]
lp = bundle.get(f"{label}/{method}/logpi", np.full(Y.shape[:2], -np.log(Y.shape[1])))
if lp.shape != Y.shape[:2]:
raise ValueError(f"Bank weights do not match the bank: {label}/{method}")
if np.isinf(Y).any():
raise ValueError(f"Label bank is not finite on its support: {label}/{method}")
mask = np.isfinite(Y)
if not mask.any(axis=2).all():
raise ValueError(f"A bank member has no label support: {label}/{method}")
return dict(Y=(Y - m0) / s0, logpi=lp, mask=mask, lam=float(bundle[f"{label}/lambda"]))
def train_trajectory(X, X_targets, spec: dict, method: str, cfg: dict, seed: int, budgets: list[int],
device: str, checkpoint: Path | None = None, threads: int = 2) -> tuple[dict, dict]:
torch.set_num_threads(threads)
torch.backends.cudnn.benchmark = False
torch.backends.cudnn.deterministic = True
torch.default_generator.manual_seed(seed)
if torch.device(device).type == "cuda":
torch.cuda.set_device(device)
torch.cuda.manual_seed(seed)
np.random.seed(seed)
tensor = lambda a: torch.as_tensor(np.asarray(a), dtype=torch.float32, device=device)
x, y, logpi = tensor(X), tensor(spec["Y"]), tensor(spec["logpi"])
mask = torch.as_tensor(np.asarray(spec["mask"], bool), device=device)
N, _, L = X.shape
win = cfg["window_samples"]
starts = torch.as_tensor(np.tile(window_starts_fixed(L, win, cfg["window_step"]), (N, 1)), device=device)
model = make_model(method, X.shape[1], cfg).to(device)
opt = torch.optim.Adam(model.parameters(), lr=cfg["lr"])
outputs, states = {}, {}
if torch.device(device).type == "cuda":
torch.cuda.synchronize()
torch.cuda.reset_peak_memory_stats()
begin = time.perf_counter()
for step in range(1, max(budgets) + 1):
model.train()
opt.zero_grad(set_to_none=True)
mu, sigma = model(x)
loss = masked_bank_loss(mu[:, 0], sigma[:, 0], y, logpi, mask, starts, win, spec["lam"])
if not torch.isfinite(loss):
raise FloatingPointError(f"Non-finite loss in {method}, step {step}")
loss.backward()
nn.utils.clip_grad_norm_(model.parameters(), cfg["grad_clip"])
opt.step()
if step in budgets:
m, s = predict(model, X_targets, device)
outputs[f"{step}/mu"], outputs[f"{step}/sigma"] = m, s
if checkpoint is not None:
states[step] = {k: v.detach().cpu().clone() for k, v in model.state_dict().items()}
if torch.device(device).type == "cuda":
torch.cuda.synchronize()
elapsed = time.perf_counter() - begin
if checkpoint is not None:
tmp = checkpoint.with_suffix(".pt.tmp")
torch.save({"states": states, "method": method, "channels": X.shape[1], "config": cfg}, tmp)
tmp.replace(checkpoint)
return outputs, {"wall_seconds": elapsed, "steps": max(budgets), "seconds_per_step": elapsed / max(budgets),
"parameters": sum(v.numel() for v in model.parameters()),
"peak_vram_bytes": torch.cuda.max_memory_allocated() if torch.device(device).type == "cuda" else 0}