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>
This commit is contained in:
2026-10-30 01:06:59 +00:00
parent 0cfe202a8b
commit 381b5ffb06
47 changed files with 6263 additions and 58 deletions

View File

@@ -16,6 +16,24 @@ Registration: logs lie on the τ axis (sonic time). True warp t(τ) = τ + b +
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
@@ -23,13 +41,16 @@ 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
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:
@@ -37,6 +58,203 @@ def phi_to_ai(phi: np.ndarray) -> np.ndarray:
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)
@@ -86,10 +304,20 @@ class D2Well:
class D2Realization:
"""A single realization: earth model, pseudo-well locations, noise, and standard normal draws for drift/picks."""
"""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):
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"]
@@ -101,8 +329,10 @@ class D2Realization:
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)))
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"])
@@ -142,6 +372,18 @@ class D2Realization:
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)]:
@@ -149,6 +391,83 @@ class D2Realization:
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
@@ -161,9 +480,13 @@ class D2Realization:
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):
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)
unit = np.searchsorted(self.S_ref, s)
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
@@ -183,10 +506,11 @@ class D2Realization:
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)]
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)
@@ -199,15 +523,56 @@ class D2Realization:
# ------------------------------------------------------------ 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
"""(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.grid.t_of_tau(b, g)[0]
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})")