Files
ML-Porosity/scripts/12_h1_blur.py
lamlvh cee2ff0859 P2 diagnosis on dev, P3 dev experiments, lock protocol_p3
- P2: SMC tie posterior (numpy + torch), RML/soft-DTW losses, bank training,
  D2 synthetic generator, scripts 09-13, protocol_p2 (locked) and its outcome
  (G-B failed; H1 not rejected, H3 rejected, H4 not rejected).
- Diagnosis on dev realizations 900/901 only (scripts 14-17, run_p3_dev.sh):
  posterior screen, SMC stability (P = 1024, K = 1), sigma_a misspecification
  stress and training, H3 with the SMC posterior, F3 placement on sigma_post.
- protocol_p3: H2 split into H2a (posterior-mean labels vs point ties) and
  H2b (RML vs posterior mean as a function of sigma_post); H3 descriptive only;
  sigma_a arm; new D2 config d2_synth_p3.yaml; main grid on realizations 8-15.
  Locked by configs/protocol_p3.sha256 and tag protocol-p3.
- runlog: per-run logs and runtime index (logs/index.csv).
- Docs: plan §12 items 10-11, theory, technical overview, report; wording
  aligned with Gunning & Glinsky (2006): the tie posterior is not claimed as new.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 06:03:33 +00:00

155 lines
7.4 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""H1 (Prop 1): MSE training on labels with a random time shift δ ~ N(0, σ²) yields blurred predictions with
transfer function exp(−2π²σ²f²).
c = 0, N = 16, Oracle labels. Each (well, sub-window) receives one shift δ = σ·z held fixed throughout training
(z shared across all σ: common random numbers); MSE loss on μ. The transfer function is estimated on the test wells:
Ĥ(f) = Σ Re[Y* P_σ] / Σ Re[Y* P_0] (pooled over test wells, realizations, seeds; Hann taper)
and r(σ) = geometric mean of Ĥ/theory over the frequencies used (protocol_p2, hypotheses.H1).
python scripts/12_h1_blur.py [--workers 6] [--device cuda:1]
"""
from __future__ import annotations
import argparse
import importlib.util
import json
import os
import time
from concurrent.futures import ProcessPoolExecutor, as_completed
from multiprocessing import get_context
import numpy as np
import pandas as pd
import yaml
from ml_porosity.paths import REPO_ROOT, outputs_dir
_spec = importlib.util.spec_from_file_location("run_d2", REPO_ROOT / "scripts" / "11_run_d2.py")
run_d2 = importlib.util.module_from_spec(_spec)
_spec.loader.exec_module(run_d2)
NFFT = 256
def run_job(job) -> dict:
rid, seed, sigmas, budget, P, device = job
import torch
torch.set_num_threads(2)
from ml_porosity.data.synth_d2 import D2Realization, load_horizon_grid
from ml_porosity.models.bank_train import WIN, train_predict, window_starts_fixed, zscore_patch
from ml_porosity.registration.labels import antialias, labels_for_warps
from ml_porosity.registration.pipeline import label_norm
from ml_porosity.registration.warp_prior import WarpHyper
cfg = yaml.safe_load((REPO_ROOT / P["inputs"]["d2_config"]["path"]).read_text())
hg = load_horizon_grid(cfg["horizons"], REPO_ROOT / cfg["horizon_cache"])
prior = json.loads((REPO_ROOT / P["inputs"]["warp_prior"]["path"]).read_text())["fits"][P["inputs"]["warp_prior"]["fit"]]
wav = np.load(REPO_ROOT / P["inputs"]["wavelet"]["path"])[P["inputs"]["wavelet"]["key"]]
R = D2Realization(cfg, rid, hg, WarpHyper(**prior["hyper"]), wav)
G, H = P["grid"], P["hypotheses"]["H1"]
sa = cfg["anchors"]["sigma_a_ms"]
obs = [R.observe(w, 0.0, G["snr_db"], sa) for w in R.pool[:16]]
test = [R.observe(w, 0.0, G["snr_db"], sa) for w in R.test]
X = np.stack([zscore_patch(o["seis"], R.main) for o in obs])
Xte = np.stack([zscore_patch(o["seis"], R.main) for o in test])
m0, s0 = label_norm(R, obs)
starts = window_starts_fixed(len(R.t_main))
tw = R.t_main[starts[:, None] + np.arange(WIN)] # (J, WIN)
z = np.random.default_rng([rid, seed, 7]).standard_normal((len(obs), len(starts)))
f = cfg["fine_dt_ms"]
tcfg = P["training"]["model"] | P["training"]["optimizer"]
preds = {}
for sg in sigmas:
Yw = np.stack([labels_for_warps(R.tau_fine, antialias(o["phi_log"], f, R.dt), o["t_of_tau_true"],
(tw + sg * z[i][:, None]).ravel()).reshape(tw.shape)
for i, o in enumerate(obs)])
mu = train_predict(X, Xte, {"kind": "mse_win", "Ywin": (Yw - m0) / s0}, tcfg, seed, [budget], device)[budget][0]
preds[sg] = 100 * (mu * s0 + m0)
return {"rid": rid, "seed": seed, "y_true": 100 * np.stack([o["y_true"] for o in test]),
"wells": [w.name for w in R.test], "preds": preds}
def cross_spectrum(Y: np.ndarray, Pr: np.ndarray) -> np.ndarray:
w = np.hanning(Y.shape[1])
Fy = np.fft.rfft((Y - Y.mean(1, keepdims=True)) * w, NFFT)
Fp = np.fft.rfft((Pr - Pr.mean(1, keepdims=True)) * w, NFFT)
return np.real(np.conj(Fy) * Fp).sum(0)
def transfer(S: dict, f: np.ndarray, f_c: float) -> dict:
"""S[σ]: accumulated cross-spectrum Re[Y* P_σ]. Returns Ĥ, the theoretical curve, r(σ) and the number of frequencies used."""
band = f >= f_c
out = {"H_hat": {}, "theory": {}, "r": {}, "n_freq": {}}
for sg, Ss in S.items():
th = np.exp(-2 * np.pi**2 * (sg / 1000.0) ** 2 * f**2)
use = band & (th >= 0.1) & (S[0.0] >= 0.1 * S[0.0][band].max())
Hh = Ss / S[0.0]
out["H_hat"][sg], out["theory"][sg] = Hh.tolist(), th.tolist()
out["r"][sg] = float(np.exp(np.mean(np.log(np.clip(Hh[use] / th[use], 1e-3, None))))) if use.any() else float("nan")
out["n_freq"][sg] = int(use.sum())
return out
def main() -> None:
ap = argparse.ArgumentParser()
ap.add_argument("--workers", type=int, default=6)
ap.add_argument("--device", default="cuda:1")
ap.add_argument("--n-boot", type=int, default=2000)
args = ap.parse_args()
for k, v in {"OMP_NUM_THREADS": "2", "MKL_NUM_THREADS": "2", "OPENBLAS_NUM_THREADS": "2"}.items():
os.environ.setdefault(k, v)
P = run_d2.load_protocol(check=True)
H = P["hypotheses"]["H1"]
sigmas = [float(s) for s in H["sigma_ms"]]
budget = int(P["training"]["budgets"]["MSE0"])
rids, seeds = P["grid"]["realizations"], P["grid"]["seeds"]
out_dir = outputs_dir() / "p2" / "h1"
out_dir.mkdir(parents=True, exist_ok=True)
jobs = [(rid, s, sigmas, budget, P, args.device) for rid in rids for s in seeds]
t0 = time.time()
results = []
with ProcessPoolExecutor(args.workers, mp_context=get_context("spawn")) as ex:
for i, fut in enumerate(as_completed([ex.submit(run_job, j) for j in jobs]), 1):
results.append(fut.result())
print(f"[{i}/{len(jobs)}] {time.time() - t0:.0f} s", flush=True)
results.sort(key=lambda r: (r["rid"], r["seed"]))
from ml_porosity.eval.metrics import band_metrics, point_metrics
f_c = P["metrics"]["bands"]["f_c_hz"]
rows = [{"rid": r["rid"], "seed": r["seed"], "sigma_ms": sg, "test_well": w} | point_metrics(y, p) | band_metrics(y, p, f_c)
for r in results for sg in sigmas for w, y, p in zip(r["wells"], r["y_true"], r["preds"][sg])]
pd.DataFrame(rows).assign(protocol_sha256=P["sha256"][:12]).to_csv(out_dir / "results.csv", index=False)
np.savez_compressed(out_dir / "preds.npz", **{f"r{r['rid']}/s{r['seed']}/sigma{sg:g}": r["preds"][sg] for r in results for sg in sigmas},
**{f"r{r['rid']}/y_true": r["y_true"] for r in results})
f = np.fft.rfftfreq(NFFT, 4.0 / 1000.0)
cs = {r["rid"]: {sg: 0.0 for sg in sigmas} for r in results} # cross-spectrum accumulated per realization
for r in results:
for sg in sigmas:
cs[r["rid"]][sg] = cs[r["rid"]][sg] + cross_spectrum(r["y_true"], r["preds"][sg])
tf = {"f_hz": f.tolist()} | transfer({sg: sum(cs[i][sg] for i in cs) for sg in sigmas}, f, f_c)
rng = np.random.default_rng(0)
boot = {sg: [] for sg in sigmas}
for _ in range(args.n_boot): # bootstrap over realizations
pick = rng.choice(list(cs), len(cs))
for sg, v in transfer({sg: sum(cs[i][sg] for i in pick) for sg in sigmas}, f, f_c)["r"].items():
boot[sg].append(v)
tf["r_ci95"] = {sg: [float(np.nanpercentile(boot[sg], 2.5)), float(np.nanpercentile(boot[sg], 97.5))] for sg in sigmas}
lo, hi = 0.5, 2.0
tf["reject_H1"] = bool(any(not (lo <= tf["r"][sg] <= hi) for sg in sigmas if sg > 0))
tf["budget"] = budget
tf["protocol_sha256"] = P["sha256"][:12]
(out_dir / "h1.json").write_text(json.dumps(tf, indent=1))
print("r(σ):", {sg: round(v, 3) for sg, v in tf["r"].items()}, "CI:", tf["r_ci95"], "reject H1:", tf["reject_H1"])
print(f"-> {out_dir} ({time.time() - t0:.0f} s)")
if __name__ == "__main__":
os.environ.setdefault("PYTHONHASHSEED", "0")
main()