Files
ML-Porosity/ml_porosity/data/synth_d2.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

268 lines
12 KiB
Python
Raw 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.
"""D2: F3-calibrated synthetic dataset with known ground-truth registration (plan §5.1, §5.5).
Earth model in true time t: a stratigraphic framework from 5 laterally extensive F3 horizons (Shallow, FS8,
FS7, Truncation, MFS4), subdivided into sub-units of thickness ≈ `sub_unit_ms` (proportional sub-surfaces
between horizons, parallel above Shallow and below MFS4). Porosity
φ(t) = φ0 + slope·(t − 850) + o_u(x, y) + GRF(s(t)),
where s is the stratigraphic coordinate (strat_map onto the median horizon times), o_u is a per-unit offset
(with a linear lateral gradient), and GRF is a sum of OU processes in s, independent across pseudo-wells
(spaced ≥ 500 m apart). Exact F3 rock physics: DT = (φ + 0.2018)/0.0011, RHOB = 2650 − 1600φ,
AI = RHOB·10⁶/DT. Seismic: 3×3 patch (using the horizons of neighbouring bins), forward model
tie_likelihood.forward_fine with the F3 wavelet, and band-limited noise scaled to the target SNR.
Registration: logs lie on the τ axis (sonic time). True warp t(τ) = τ + b + ∫(e^g − 1) with
g = c·(m_g + L z), b = c·σ_b·z_b, where (m_g, σ_g, ℓ, σ_b) come from the GP fit to the F3 anchors (scripts/09);
z is shared across all drift factors c. Anchors: unit boundaries within the extended window, τ_k = t⁻¹(t_b),
t_k = t_b + ε_k, with ε_k ~ N(0, σ_a²) shared across all c.
"""
from __future__ import annotations
from dataclasses import dataclass, field
import numpy as np
from ml_porosity.baselines.inversion import strat_map
from ml_porosity.registration.labels import antialias, invert_warps
from ml_porosity.registration.tie_likelihood import fine_wavelet, forward_fine
from ml_porosity.registration.warp_prior import WarpGrid, WarpHyper, kernel_matrix
PHI_DT_A, PHI_DT_B = -0.2018, 0.0011
def phi_to_ai(phi: np.ndarray) -> np.ndarray:
dt = (phi - PHI_DT_A) / PHI_DT_B # µs/m
return (2650.0 - 1600.0 * phi) * 1e6 / dt
def ou_process(n: int, d: float, sd: float, ell: float, rng) -> np.ndarray:
rho = np.exp(-d / ell)
e = rng.standard_normal(n) * sd * np.sqrt(1 - rho**2)
x = np.empty(n)
x[0] = sd * rng.standard_normal()
for i in range(1, n):
x[i] = rho * x[i - 1] + e[i]
return x
@dataclass
class HorizonGrid:
h: np.ndarray # (H, nIL, nXL) TWT ms, NaN if missing
il0: int
xl0: int
geom: object
def at(self, il: int, xl: int) -> np.ndarray:
return self.h[:, il - self.il0, xl - self.xl0]
def valid_mask(self, min_gap_ms: float = 8.0, radius: int = 1) -> np.ndarray:
ok = np.all(np.isfinite(self.h), 0)
ok[ok] &= np.all(np.diff(self.h[:, ok], axis=0) >= min_gap_ms, 0)
out = ok.copy()
for di in range(-radius, radius + 1):
for dj in range(-radius, radius + 1):
out &= np.roll(np.roll(ok, di, 0), dj, 1)
out[:radius], out[-radius:], out[:, :radius], out[:, -radius:] = False, False, False, False
return out
@dataclass
class D2Well:
name: str
il: int
xl: int
x: float
y: float
seis_clean: np.ndarray # (9, L_ext) noise-free
noise_unit: np.ndarray # (9, L_ext) band-limited noise, unit variance on the centre trace
phi_t: np.ndarray # φ of the centre trace on t_fine
z_g: np.ndarray # (n_grid,) standard normal draws for g
z_b: float
boundaries_t: np.ndarray # unit boundaries (true time) within the extended window
eps_a: np.ndarray # standard normal pick noise, same length as boundaries_t
extra: dict = field(default_factory=dict)
class D2Realization:
"""A single realization: earth model, pseudo-well locations, noise, and standard normal draws for drift/picks."""
def __init__(self, cfg: dict, rid: int, hg: HorizonGrid, drift: WarpHyper, wavelet: np.ndarray):
self.cfg, self.rid, self.drift = cfg, rid, drift
rng = np.random.default_rng([int(rid), 20261026])
f = cfg["fine_dt_ms"]
self.dt = cfg["dt_ms"]
self.t_fine = np.arange(cfg["model_t_ms"][0], cfg["model_t_ms"][1] + f / 2, f)
self.tau_fine = np.arange(cfg["log_tau_ms"][0], cfg["log_tau_ms"][1] + f / 2, f)
self.grid = WarpGrid(cfg["log_tau_ms"][0], cfg["log_tau_ms"][1], cfg["warp_dtau_ms"])
e0, e1 = cfg["ext_window_ms"]
m0, m1 = cfg["main_window_ms"]
self.t_ext = np.arange(e0, e1 + self.dt / 2, self.dt)
self.main = (self.t_ext >= m0) & (self.t_ext <= m1)
self.t_main = self.t_ext[self.main]
self.wavelet = wavelet
self.w_fine = fine_wavelet(wavelet, int(round(self.dt / f)))
# Stratigraphic framework
valid = hg.valid_mask(cfg["min_gap_ms"], cfg["patch_radius"])
H = hg.h[:, valid]
self.h_ref = np.median(H, axis=1)
self.S_ref = self._unit_surfaces(self.h_ref, cfg["sub_unit_ms"], *cfg["model_t_ms"])
self.hg = hg
# Well locations: test wells first, then the training pool (nested by order)
ii, jj = np.nonzero(valid)
il_all, xl_all = ii + hg.il0, jj + hg.xl0
xy = np.column_stack(hg.geom.bin_to_xy(il_all, xl_all))
order = rng.permutation(len(il_all))
W = cfg["wells"]
test, train = [], []
for k in order:
p = xy[k]
if len(test) < W["n_test"]:
if all(np.hypot(*(p - xy[q])) >= W["min_dist_test_m"] for q in test):
test.append(k)
elif len(train) < W["n_train_pool"]:
if all(np.hypot(*(p - xy[q])) >= W["min_dist_test_m"] for q in test) and \
all(np.hypot(*(p - xy[q])) >= W["min_dist_train_m"] for q in train):
train.append(k)
else:
break
if len(train) < W["n_train_pool"]:
raise RuntimeError("not enough pseudo-well locations satisfying the spacing constraints")
# Realization-level properties
P = cfg["property"]
self.phi0 = P["phi0"] + P["phi0_sd"] * rng.standard_normal()
nu = len(self.S_ref) + 1
self.unit_off = P["unit_offset_sd"] * rng.standard_normal(nu)
self.unit_grad = P["unit_lateral_sd"] * rng.standard_normal((nu, 2))
xy_all = xy
self.xy_c, self.xy_s = xy_all.mean(0), np.ptp(xy_all, 0) / 2
Kg = kernel_matrix(self.grid.tau, self.grid.tau, 1.0, drift.ell_ms, drift.kernel)
self.Lg = np.linalg.cholesky(Kg + 1e-8 * np.eye(self.grid.n))
self.wells: list[D2Well] = []
for tag, idx in [("T", test), ("P", train)]:
for n, k in enumerate(idx):
self.wells.append(self._make_well(f"{tag}{n:02d}", int(il_all[k]), int(xl_all[k]), rng))
self.test = self.wells[: W["n_test"]]
self.pool = self.wells[W["n_test"]:]
# ------------------------------------------------------------ earth model
@staticmethod
def _unit_surfaces(h_ref, sub_ms, t0, t1) -> np.ndarray:
s = [h_ref[0] - k * sub_ms for k in range(int((h_ref[0] - t0) // sub_ms), 0, -1)]
for a, b in zip(h_ref[:-1], h_ref[1:]):
n = max(1, int(round((b - a) / sub_ms)))
s += list(a + (b - a) * np.arange(n) / n)
s += [h_ref[-1] + k * sub_ms for k in range(0, int((t1 - h_ref[-1]) // sub_ms) + 1)]
return np.array(s)
def _phi_trace(self, h_bin, xy, grf_s, s_axis):
s = strat_map(self.t_fine, h_bin, self.h_ref)
unit = np.searchsorted(self.S_ref, s)
u = (np.asarray(xy) - self.xy_c) / self.xy_s
off = self.unit_off[unit] + self.unit_grad[unit] @ u
phi = self.phi0 + self.cfg["property"]["slope_per_100ms"] * (self.t_fine - 850.0) / 100.0 + off
phi = phi + np.interp(s, s_axis, grf_s)
return np.clip(phi, *self.cfg["property"]["clip"])
def _make_well(self, name, il, xl, rng) -> D2Well:
P, r = self.cfg["property"], self.cfg["patch_radius"]
f = self.cfg["fine_dt_ms"]
s_axis = np.arange(self.t_fine[0] - 200, self.t_fine[-1] + 200 + f / 2, f)
grf = sum(ou_process(len(s_axis), f, c["sd"], c["ell_ms"], rng) for c in P["grf"])
traces, phi_c = [], None
for di in range(-r, r + 1):
for dj in range(-r, r + 1):
h = self.hg.at(il + di, xl + dj)
xy = np.array(self.hg.geom.bin_to_xy(il + di, xl + dj), dtype=float).ravel()
phi = self._phi_trace(h, xy, grf, s_axis)
if di == 0 and dj == 0:
phi_c = phi
traces.append(phi_to_ai(phi))
seis = forward_fine(np.stack(traces), self.t_fine, self.t_ext, self.w_fine)
white = rng.standard_normal((len(traces), len(self.t_ext) + len(self.wavelet)))
noise = np.stack([np.convolve(wn, self.wavelet, "same")[len(self.wavelet) // 2: len(self.wavelet) // 2 + len(self.t_ext)]
for wn in white])
noise /= noise[len(traces) // 2].std()
h0 = self.hg.at(il, xl)
bt = strat_map(self.S_ref, self.h_ref, h0)
bt = bt[(bt >= self.t_ext[0]) & (bt <= self.t_ext[-1])]
x, y = (float(v) for v in np.ravel(self.hg.geom.bin_to_xy(il, xl)))
return D2Well(name, il, xl, x, y, seis, noise, phi_c, rng.standard_normal(self.grid.n),
float(rng.standard_normal()), bt, rng.standard_normal(len(bt)))
# ------------------------------------------------------------ observations per cell configuration
def true_warp(self, w: D2Well, c: float) -> tuple[float, np.ndarray]:
d = self.drift
g = c * (d.m_g + d.sigma_g * (self.Lg @ w.z_g))
return c * d.sigma_b_ms * w.z_b, g
def observe(self, w: D2Well, c: float, snr_db: float | None, sigma_a_ms: float,
anchor_density: str = "full") -> dict:
"""Data for one well at drift factor c: noisy seismic, logs on τ, anchors and the true warp."""
b, g = self.true_warp(w, c)
t_tau_grid = self.grid.t_of_tau(b, g)[0]
t_tau = np.interp(self.tau_fine, self.grid.tau, t_tau_grid)
if t_tau[0] < self.t_fine[0] or t_tau[-1] > self.t_fine[-1]:
raise ValueError(f"{w.name}: warp extends outside the earth-model domain (c = {c})")
phi_log = np.interp(t_tau, self.t_fine, w.phi_t)
seis = w.seis_clean.copy()
if snr_db is not None and np.isfinite(snr_db):
ps = np.mean(w.seis_clean[len(seis) // 2] ** 2)
seis = seis + np.sqrt(ps / 10 ** (snr_db / 10)) * w.noise_unit
tau_k = np.interp(w.boundaries_t, t_tau, self.tau_fine)
t_k = w.boundaries_t + sigma_a_ms * w.eps_a
keep = self._anchor_subset(len(tau_k), anchor_density)
f = self.cfg["fine_dt_ms"]
y_true = np.interp(self.t_main, self.t_fine, antialias(w.phi_t, f, self.dt))
return {"name": w.name, "seis": seis.astype(np.float32), "tau_fine": self.tau_fine, "phi_log": phi_log,
"ai_log": phi_to_ai(phi_log), "tau_k": tau_k[keep], "t_k": t_k[keep], "b": b, "g": g,
"t_of_tau_true": t_tau, "y_true": y_true, "xy": (w.x, w.y)}
@staticmethod
def _anchor_subset(n: int, density: str) -> np.ndarray:
if density == "full":
return np.arange(n)
if density == "half":
return np.arange(0, n, 2)
if density == "topbottom":
return np.array([0, n - 1]) if n > 1 else np.arange(n)
if density == "none":
return np.arange(0)
raise ValueError(density)
def true_tau_at(self, obs: dict, t: np.ndarray) -> np.ndarray:
return invert_warps(obs["t_of_tau_true"], self.tau_fine, t)[0]
def load_horizon_grid(names, cache) -> HorizonGrid:
"""IL×XL grid of the F3 horizons (cached as npz because the ASCII files are large)."""
from ml_porosity.data.geometry import SurveyGeometry
from ml_porosity.data.horizons import horizon_path
from ml_porosity.paths import f3_root
geom = SurveyGeometry.from_survey(f3_root())
il0, il1, _ = geom.il_range
xl0, xl1, _ = geom.xl_range
if cache is not None and cache.exists():
z = np.load(cache)
if list(z["names"]) == list(names):
return HorizonGrid(z["h"], il0, xl0, geom)
h = np.full((len(names), il1 - il0 + 1, xl1 - xl0 + 1), np.nan)
for k, nm in enumerate(names):
a = np.loadtxt(horizon_path(nm))
il, xl = geom.xy_to_bin(a[:, 0], a[:, 1])
il, xl = np.rint(il).astype(int), np.rint(xl).astype(int)
ok = (il >= il0) & (il <= il1) & (xl >= xl0) & (xl <= xl1)
h[k, il[ok] - il0, xl[ok] - xl0] = a[ok, 2]
if cache is not None:
cache.parent.mkdir(parents=True, exist_ok=True)
np.savez_compressed(cache, h=h, names=np.array(names))
return HorizonGrid(h, il0, xl0, geom)