Files
ML-Porosity/ml_porosity/data/synth_d2.py
lamlvh 381b5ffb06 Add P6 benchmark code, locked protocol_bench, T2 study
- ml_porosity/benchmark/ runner, scripts 32-35, scripts/run_bench.sh;
  misspec= option in synth_d2 (default path reproduces P2r bit for bit).
- configs/protocol_bench.{yaml,sha256,lock.json} locked 29/10 14:39 UTC
  (sha256 aa763f0a...), configs/d2_synth_bench.yaml.
- T2 mechanism declaration and results; operations/p6_supervisor.py.
- Docs, report and paper edits of 29/10.

outputs/ stays out of git; the repository folder is synced as a whole to
the new server. Main S1 runs are still training at this commit.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-30 01:33:18 +00:00

633 lines
32 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.
"""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.
Misspecification (phase P6, S2; docs/research/bench-generator.md). `D2Realization(..., misspec=...)` lets the
data violate the assumptions of the registration (nominal rock physics in obs["ai_log"], a stationary wavelet with
a constant phase, the F3 Matérn-3/2 warp prior) in controlled ways, on three axes:
rock_physics the earth maps φ → AI with perturbed coefficients (uniform factors; optionally a per-unit
shift of the φ–DT intercept, i.e. lithology-dependent matrix slowness) while obs["ai_log"]
keeps the nominal relation;
wavelet the true wavelet is a transformed version of the nominal one (constant phase, fractional
minimum-phase dispersion, peak-frequency factor, bulk delay) and/or a constant-Q time-variant
filter is applied in the forward model;
drift the true warp is drawn with scaled (σ_b, σ_g, ℓ), plus non-GP components: a jump of the
warp just below a horizon (a local log-slowness anomaly) and short-correlation jitter.
Common random numbers: the misspecified realization uses the same z_g, z_b, ε_a, GRF and noise draws as the
nominal one; additional draws (per-unit shifts, jitter) come from separate, rid-seeded streams, so the nominal
path consumes its random stream exactly as before. `misspec=None` (or all-nominal values) reproduces the
protocol_p2/p2r generator bit for bit (tests/test_d2_misspec.py).
"""
from __future__ import annotations
from dataclasses import dataclass, field
import numpy as np
from scipy import signal
from ml_porosity.baselines.inversion import strat_map
from ml_porosity.data.wavelet import rotate_phase
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 # φ = A + B·DT (DT in µs/m)
RHO_0, RHO_1 = 2650.0, 1600.0 # RHOB = ρ0 − ρ1·φ (kg/m³)
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 phi_to_ai_coef(phi: np.ndarray, a: np.ndarray | float, b: float, rho0: float, rho1: float) -> np.ndarray:
"""AI for the perturbed relations φ = a + b·DT, RHOB = rho0 − rho1·φ (a may vary per sample)."""
dt = (phi - a) / b
return (rho0 - rho1 * phi) * 1e6 / dt
# ------------------------------------------------------------------ misspecification parameters
MISSPEC_DEFAULTS = {
"rock_physics": {
"dt_slope_factor": 1.0, # B → B·f (φ = A + B·DT; nominal B = 0.0011 per µs/m)
"dt_intercept_factor": 1.0, # A → A·f (nominal A = −0.2018; DT_matrix = −A/B)
"rho_slope_factor": 1.0, # ρ1 → ρ1·f (nominal 1600)
"rho_intercept_factor": 1.0, # ρ0 → ρ0·f (nominal 2650)
"unit_dt_intercept_sd": 0.0, # A → A·(1 + sd·ζ_u) per stratigraphic unit, ζ_u ~ N(0, 1) per realization
"region": "all", # wells affected: all | test | pool
},
"wavelet": {
"phase_deg": 0.0, # constant phase rotation (inside the registration's family)
"minphase_frac": 0.0, # s ∈ [0, 1]: phase spectrum s·θ_min(f) of the nominal amplitude spectrum
"peak_freq_factor": 1.0, # w(t) → w(p·t): spectrum stretched by p
"delay_ms": 0.0, # bulk timing error of the wavelet (events shifted relative to the anchors)
"Q": None, # constant-Q time-variant attenuation relative to Q_t_ref_ms (None: off)
"Q_t_ref_ms": 400.0,
"Q_dispersion": True, # Kolsky–Futterman phase (reference frequency = peak of the true wavelet)
},
"drift": {
"sigma_b_factor": 1.0,
"sigma_g_factor": 1.0,
"ell_factor": 1.0,
"step_ms": 0.0, # jump J of t(τ) just below step_horizon, independent of c
"step_width_ms": 12.0, # τ extent of the log-slowness anomaly that realises the jump
"step_horizon": "Truncation",
"jitter_sd_ms": 0.0, # Matérn-3/2 jitter of t(τ) on the warp grid (own random stream per well)
"jitter_ell_ms": 8.0,
},
}
_STRENGTH_KEYS = {
"rock_physics": ("dt_slope_factor", "dt_intercept_factor", "rho_slope_factor", "rho_intercept_factor",
"unit_dt_intercept_sd"),
"wavelet": ("phase_deg", "minphase_frac", "peak_freq_factor", "delay_ms", "Q"),
"drift": ("sigma_b_factor", "sigma_g_factor", "ell_factor", "step_ms", "jitter_sd_ms"),
}
_RP_UNIFORM = ("dt_slope_factor", "dt_intercept_factor", "rho_slope_factor", "rho_intercept_factor")
_WV_STATIONARY = ("phase_deg", "minphase_frac", "peak_freq_factor", "delay_ms")
def normalize_misspec(spec: dict | None) -> dict:
"""Fill defaults. Unknown axes or keys raise, so a typo in a locked protocol cannot silently mean 'nominal'."""
spec = spec or {}
if unknown := set(spec) - set(MISSPEC_DEFAULTS):
raise ValueError(f"unknown misspec axes {sorted(unknown)}; expected {sorted(MISSPEC_DEFAULTS)}")
out = {}
for axis, defaults in MISSPEC_DEFAULTS.items():
sub = spec.get(axis) or {}
if unknown := set(sub) - set(defaults):
raise ValueError(f"unknown misspec keys {sorted(unknown)} in '{axis}'; expected {sorted(defaults)}")
out[axis] = {k: (sub[k] if k in sub else v) for k, v in defaults.items()}
rp = out["rock_physics"]
if rp["region"] not in ("all", "test", "pool"):
raise ValueError(f"rock_physics.region must be all | test | pool, got {rp['region']!r}")
wv = out["wavelet"]
if not 0.0 <= wv["minphase_frac"] <= 1.0 or wv["peak_freq_factor"] <= 0 or (wv["Q"] is not None and wv["Q"] <= 0):
raise ValueError("wavelet: minphase_frac ∈ [0, 1], peak_freq_factor > 0, Q > 0 or None")
dr = out["drift"]
if min(dr["sigma_b_factor"], dr["sigma_g_factor"], dr["ell_factor"]) <= 0 or dr["step_width_ms"] <= 0 \
or dr["jitter_sd_ms"] < 0 or dr["jitter_ell_ms"] <= 0:
raise ValueError("drift: factors, step_width_ms and jitter_ell_ms must be > 0, jitter_sd_ms ≥ 0")
return out
def active_axes(ms: dict) -> dict:
"""{axis: {key: value}} for the strength keys that differ from nominal (empty dict: nominal generator)."""
out = {}
for axis, keys in _STRENGTH_KEYS.items():
d = {k: ms[axis][k] for k in keys if ms[axis][k] != MISSPEC_DEFAULTS[axis][k]}
if d:
out[axis] = d
return out
def preset_misspec(cfg: dict, name: str | None) -> dict | None:
"""Look up cfg["misspec_presets"][name]; None or "nominal" gives the nominal generator."""
if name in (None, "nominal"):
return None
presets = cfg.get("misspec_presets") or {}
if name not in presets:
raise KeyError(f"misspec preset {name!r} not in config (have {sorted(presets)})")
return {k: v for k, v in presets[name].items() if k != "note"}
# ------------------------------------------------------------------ wavelet transforms (fine grid)
def _spectrum_buffer(w: np.ndarray, nfft: int) -> np.ndarray:
"""Centred odd-length wavelet → length-nfft buffer with time zero at index 0."""
return np.roll(np.concatenate([w, np.zeros(nfft - len(w))]), -(len(w) // 2))
def _extract_centred(buf: np.ndarray, n: int) -> np.ndarray:
m = n // 2
return np.concatenate([buf[-m:], buf[: m + 1]])
def peak_frequency_hz(w: np.ndarray, dt_ms: float, nfft: int = 4096) -> float:
f = np.fft.rfftfreq(nfft, dt_ms / 1000.0)
return float(f[np.argmax(np.abs(np.fft.rfft(w, nfft)))])
def fractional_minimum_phase(w: np.ndarray, frac: float, floor_db: float = -80.0) -> np.ndarray:
"""Same amplitude spectrum, phase spectrum frac·θ_min(f) (cepstral minimum-phase construction), re-centred at
the lag of maximum cross-correlation with the input so that the bulk delay is removed and only the
frequency-dependent part of the phase remains. frac = 0 returns the input (up to FFT round-off)."""
n = len(w)
nfft = 1 << int(np.ceil(np.log2(8 * n)))
x = _spectrum_buffer(w, nfft)
W = np.fft.rfft(x)
A = np.maximum(np.abs(W), 10 ** (floor_db / 20) * np.abs(W).max())
c = np.fft.irfft(np.log(A), nfft) # real cepstrum
fold = np.zeros(nfft)
fold[0], fold[nfft // 2] = c[0], c[nfft // 2]
fold[1: nfft // 2] = 2.0 * c[1: nfft // 2]
theta_min = np.imag(np.fft.rfft(fold)) # log W_min = ln A + i θ_min
y = np.fft.irfft(W * np.exp(1j * frac * theta_min), nfft)
xc = np.fft.irfft(np.fft.rfft(y) * np.conj(np.fft.rfft(x)), nfft)
lag = int(np.argmax(xc))
lag = lag - nfft if lag > nfft // 2 else lag
return _extract_centred(np.roll(y, -lag), n)
def true_stationary_wavelet(w_fine: np.ndarray, dt_ms: float, wv: dict) -> np.ndarray:
"""Stationary part of the true wavelet on the fine grid: peak-frequency scaling, fractional minimum phase,
constant phase rotation, bulk delay, then a Tukey taper (outer 1/8 of each side) and unit peak."""
n = len(w_fine)
tf = (np.arange(n) - n // 2) * dt_ms
w = w_fine.astype(float)
if wv["peak_freq_factor"] != 1.0:
w = np.interp(wv["peak_freq_factor"] * tf, tf, w, left=0.0, right=0.0)
if wv["minphase_frac"] != 0.0:
w = fractional_minimum_phase(w, wv["minphase_frac"])
if wv["phase_deg"] != 0.0:
w = rotate_phase(w, wv["phase_deg"])
if wv["delay_ms"] != 0.0:
k = int(round(wv["delay_ms"] / dt_ms))
w = np.roll(w, k)
if k > 0:
w[:k] = 0.0
elif k < 0:
w[k:] = 0.0
w = w * signal.windows.tukey(n, 0.25)
return w / np.max(np.abs(w))
def q_kernel(w_fine: np.ndarray, dt_ms: float, Q: float, delta_t_ms: float, dispersion: bool, f_ref_hz: float,
half_len: int = 256) -> np.ndarray:
"""Wavelet after constant-Q propagation over delta_t_ms relative to the reference time: amplitude
exp(−π f Δt/Q), Kolsky–Futterman phase (2 f Δt/Q)·ln(f/f_ref) (slower below f_ref, faster above). Returns a
centred kernel of length 2·half_len + 1 on the fine grid."""
n = len(w_fine)
nfft = 1 << int(np.ceil(np.log2(4 * max(n, 2 * half_len + 1))))
f = np.fft.rfftfreq(nfft, dt_ms / 1000.0)
W = np.fft.rfft(_spectrum_buffer(w_fine, nfft))
dts = delta_t_ms / 1000.0
H = np.exp(-np.pi * f * dts / Q)
if dispersion:
with np.errstate(divide="ignore"):
ph = np.where(f > 0, 2.0 * f * dts / Q * np.log(np.maximum(f, 1e-12) / f_ref_hz), 0.0)
H = H * np.exp(1j * ph)
return _extract_centred(np.fft.irfft(W * H, nfft), 2 * half_len + 1)
def forward_fine_q(ai: np.ndarray, t_fine: np.ndarray, t_out: np.ndarray, w_fine: np.ndarray, Q: float,
t_ref_ms: float, dispersion: bool, f_ref_hz: float, bank_dt_ms: float = 50.0) -> np.ndarray:
"""forward_fine with a constant-Q time-variant wavelet: the reflectivity at time t′ is convolved with the
kernel q_kernel(t′ − t_ref). Kernels are tabulated every bank_dt_ms and interpolated linearly in t′ (the
operator varies as exp(−π f Δt/Q), so the interpolation error is second order in bank_dt/Q)."""
ai = np.atleast_2d(ai)
r = (ai[:, 1:] - ai[:, :-1]) / (ai[:, 1:] + ai[:, :-1])
tm = 0.5 * (t_fine[1:] + t_fine[:-1])
d = t_fine[1] - t_fine[0]
half = 256
pad = half * d + bank_dt_ms
tb = np.arange(t_out[0] - pad, t_out[-1] + pad + bank_dt_ms / 2, bank_dt_ms)
idx = np.clip(np.searchsorted(tb, tm) - 1, 0, len(tb) - 2)
lam = np.clip((tm - tb[idx]) / bank_dt_ms, 0.0, 1.0)
s = np.zeros_like(r)
for k, t_k in enumerate(tb):
wk = np.where(idx == k, 1.0 - lam, 0.0) + np.where(idx == k - 1, lam, 0.0)
if np.any(wk > 0):
ker = q_kernel(w_fine, d, Q, t_k - t_ref_ms, dispersion, f_ref_hz, half)
s += signal.fftconvolve(r * wk[None, :], ker[None, :], mode="same", axes=1)
return np.stack([np.interp(t_out, tm, si) for si in s])
# ------------------------------------------------------------------ earth model primitives
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.
misspec: None (nominal) or {"rock_physics": {...}, "wavelet": {...}, "drift": {...}} with the keys of
MISSPEC_DEFAULTS. The normalised parameters are stored in `misspec`, the non-nominal ones in `misspec_active`.
`wavelet`/`w_fine` are the stationary true wavelet (the nominal objects when the wavelet axis is nominal);
`wavelet_nominal`/`w_fine_nominal` the analyst's reference; `drift_true` the hyperparameters the truth is
drawn from (`drift` when nominal)."""
def __init__(self, cfg: dict, rid: int, hg: HorizonGrid, drift: WarpHyper, wavelet: np.ndarray,
misspec: dict | None = None):
self.cfg, self.rid, self.drift = cfg, rid, drift
self.misspec = normalize_misspec(misspec)
self.misspec_active = active_axes(self.misspec)
self.misspec_info = {"monotone_repairs": 0}
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_nominal = wavelet
self.w_fine_nominal = fine_wavelet(wavelet, int(round(self.dt / f)))
self.wavelet, self.w_fine = self._true_wavelet()
self.f_ref_hz = peak_frequency_hz(self.w_fine, 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.drift_true, self.Lg_true = self._true_drift()
# Misspecification draws from separate streams (the nominal stream `rng` is consumed exactly as before)
rp = self.misspec["rock_physics"]
self.unit_dt_shift = None
if rp["unit_dt_intercept_sd"] > 0:
self.unit_dt_shift = rp["unit_dt_intercept_sd"] * np.random.default_rng([int(rid), 20261029, 1]).standard_normal(nu)
dr = self.misspec["drift"]
self.Lj = None
if dr["jitter_sd_ms"] > 0:
Kj = kernel_matrix(self.grid.tau, self.grid.tau, 1.0, dr["jitter_ell_ms"], "matern32")
self.Lj = np.linalg.cholesky(Kj + 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"]:]
if self.Lj is not None:
for k, w in enumerate(self.wells):
w.extra["z_jitter"] = np.random.default_rng([int(rid), 20261029, 2, k]).standard_normal(self.grid.n)
# ------------------------------------------------------------ misspecified truth
def _true_wavelet(self) -> tuple[np.ndarray, np.ndarray]:
wv = self.misspec["wavelet"]
if all(wv[k] == MISSPEC_DEFAULTS["wavelet"][k] for k in _WV_STATIONARY):
return self.wavelet_nominal, self.w_fine_nominal
fac = int(round(self.dt / self.cfg["fine_dt_ms"]))
w_fine = true_stationary_wavelet(self.w_fine_nominal, self.cfg["fine_dt_ms"], wv)
return w_fine[::fac].copy(), w_fine
def _true_drift(self) -> tuple[WarpHyper, np.ndarray]:
dr, d = self.misspec["drift"], self.drift
if dr["sigma_b_factor"] == 1.0 and dr["sigma_g_factor"] == 1.0 and dr["ell_factor"] == 1.0:
return d, self.Lg
h = WarpHyper(d.m_g, d.sigma_g * dr["sigma_g_factor"], d.ell_ms * dr["ell_factor"],
d.sigma_b_ms * dr["sigma_b_factor"], d.sigma_a_ms, d.kernel)
Lg = self.Lg
if dr["ell_factor"] != 1.0:
Kg = kernel_matrix(self.grid.tau, self.grid.tau, 1.0, h.ell_ms, h.kernel)
Lg = np.linalg.cholesky(Kg + 1e-8 * np.eye(self.grid.n))
return h, Lg
def rp_applies(self, name: str) -> bool:
"""Whether the rock-physics misspecification acts on the well `name` (region all | test | pool)."""
rp = self.misspec["rock_physics"]
if "rock_physics" not in self.misspec_active:
return False
return rp["region"] == "all" or (rp["region"] == "test") == name.startswith("T")
def phi_to_ai_true(self, phi: np.ndarray, unit: np.ndarray | None = None) -> np.ndarray:
"""The earth's φ → AI mapping under the rock-physics misspecification (nominal relations when the axis is
nominal). `unit`: stratigraphic unit index per sample, required when unit_dt_intercept_sd > 0."""
if "rock_physics" not in self.misspec_active:
return phi_to_ai(phi)
rp = self.misspec["rock_physics"]
a = PHI_DT_A * rp["dt_intercept_factor"]
if self.unit_dt_shift is not None:
if unit is None:
raise ValueError("unit index required for the per-unit intercept shift")
a = a * (1.0 + self.unit_dt_shift[np.asarray(unit)])
return phi_to_ai_coef(phi, a, PHI_DT_B * rp["dt_slope_factor"], RHO_0 * rp["rho_intercept_factor"],
RHO_1 * rp["rho_slope_factor"])
def ai_log_true(self, w: D2Well, obs: dict) -> np.ndarray:
"""True AI on the τ axis of the log (what a forward model with the true rock physics would use); equals
obs["ai_log"] when the rock physics is nominal for this well."""
if not self.rp_applies(w.name):
return phi_to_ai(obs["phi_log"])
unit = None
if self.unit_dt_shift is not None:
unit = np.searchsorted(self.S_ref, strat_map(obs["t_of_tau_true"], self.hg.at(w.il, w.xl), self.h_ref))
return self.phi_to_ai_true(obs["phi_log"], unit)
def true_wavelet_at(self, t_ms: float) -> np.ndarray:
"""Effective fine wavelet for a reflector at true time t_ms (the stationary wavelet unless Q is set)."""
wv = self.misspec["wavelet"]
if wv["Q"] is None:
return self.w_fine
return q_kernel(self.w_fine, self.cfg["fine_dt_ms"], wv["Q"], t_ms - wv["Q_t_ref_ms"], wv["Q_dispersion"],
self.f_ref_hz)
def _ai_true(self, phi: np.ndarray, h_bin: np.ndarray, name: str) -> np.ndarray:
if not self.rp_applies(name):
return phi_to_ai(phi)
unit = self._unit_index(h_bin)[1] if self.unit_dt_shift is not None else None
return self.phi_to_ai_true(phi, unit)
def _forward(self, ai: np.ndarray) -> np.ndarray:
wv = self.misspec["wavelet"]
if wv["Q"] is None:
return forward_fine(ai, self.t_fine, self.t_ext, self.w_fine)
return forward_fine_q(ai, self.t_fine, self.t_ext, self.w_fine, wv["Q"], wv["Q_t_ref_ms"], wv["Q_dispersion"],
self.f_ref_hz)
# ------------------------------------------------------------ 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 _unit_index(self, h_bin) -> tuple[np.ndarray, np.ndarray]:
"""Stratigraphic coordinate and unit index of t_fine at a bin with horizon times h_bin."""
s = strat_map(self.t_fine, h_bin, self.h_ref)
return s, np.searchsorted(self.S_ref, s)
def _phi_trace(self, h_bin, xy, grf_s, s_axis):
s, unit = self._unit_index(h_bin)
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(self._ai_true(phi, h, name))
seis = self._forward(np.stack(traces))
wn_len = len(self.wavelet_nominal)
white = rng.standard_normal((len(traces), len(self.t_ext) + wn_len))
noise = np.stack([np.convolve(wn, self.wavelet_nominal, "same")[wn_len // 2: wn_len // 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]:
"""(b, g) of the true warp on the warp grid: the GP part scaled by c, plus the step anomaly (drift
misspecification) folded into g. The jitter component is not representable by g; see true_warp_grid."""
d = self.drift_true
g = c * (d.m_g + d.sigma_g * (self.Lg_true @ w.z_g))
b = c * d.sigma_b_ms * w.z_b
if self.misspec["drift"]["step_ms"] != 0.0:
g = self._add_step(w, b, g)
return b, g
def _add_step(self, w: D2Well, b: float, g: np.ndarray) -> np.ndarray:
"""Jump J of t(τ) just below the step horizon: g += a on the first n_w grid nodes after τ_h = t⁻¹(t_h),
with a = ln(1 + J / (Δτ Σ e^{g_i})) so that the trapezoid integral gives exactly J below the anomaly."""
dr = self.misspec["drift"]
t_h = float(self.hg.at(w.il, w.xl)[self.cfg["horizons"].index(dr["step_horizon"])])
t_grid = self.grid.t_of_tau(b, g)[0]
tau_h = np.interp(t_h, t_grid, self.grid.tau)
n_w = max(1, int(round(dr["step_width_ms"] / self.grid.dtau)))
i0 = int(np.searchsorted(self.grid.tau, tau_h, side="right"))
nodes = np.arange(max(i0, 1), min(i0 + n_w, self.grid.n - 1))
if len(nodes) == 0:
raise ValueError(f"{w.name}: step horizon {dr['step_horizon']} at t = {t_h} ms lies outside the warp grid")
s = self.grid.dtau * np.exp(g[nodes]).sum()
if dr["step_ms"] <= -s:
raise ValueError(f"{w.name}: step_ms = {dr['step_ms']} would make the warp non-monotone (min {-s:.2f} ms)")
g = g.copy()
g[nodes] += np.log1p(dr["step_ms"] / s)
return g
def true_warp_grid(self, w: D2Well, c: float) -> np.ndarray:
"""t(τ) on the warp grid including every misspecified component (identical to grid.t_of_tau(b, g) unless
jitter is set)."""
b, g = self.true_warp(w, c)
return self._warp_grid(w, b, g)
def _warp_grid(self, w: D2Well, b: float, g: np.ndarray) -> np.ndarray:
t = self.grid.t_of_tau(b, g)[0]
if self.Lj is not None:
t = t + self.misspec["drift"]["jitter_sd_ms"] * (self.Lj @ w.extra["z_jitter"])
dmin = 0.1 * self.grid.dtau
dt = np.diff(t)
if np.any(dt < dmin): # safeguard: keep t(τ) strictly increasing (counted)
self.misspec_info["monotone_repairs"] += int(np.sum(dt < dmin))
t = t[0] + np.concatenate([[0.0], np.cumsum(np.maximum(dt, dmin))])
return t
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._warp_grid(w, b, g)
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)