"""Misspecification parameters of the D2 generator (phase P6, item p6-gen; plan §12 item 22, decision 2). The nominal path of ml_porosity/data/synth_d2.py must stay bit-identical to the generator used by protocol_p2 and protocol_p2r: tests/data/d2_fingerprints.json records SHA-256 fingerprints of the realization fields and of the observe() outputs, taken before the misspecification parameters were added. The other tests check that each axis changes only what it claims to change (common random numbers) and that the anchors stay consistent with the true warp. """ import hashlib import json import numpy as np import pytest import scipy import yaml from ml_porosity.data.synth_d2 import D2Realization, load_horizon_grid from ml_porosity.paths import REPO_ROOT, f3_root from ml_porosity.registration.warp_prior import WarpHyper P = yaml.safe_load(open(REPO_ROOT / "configs" / "protocol_p2r.yaml")) INP = P["inputs"] CFG = yaml.safe_load(open(REPO_ROOT / INP["d2_config"]["path"])) FP_PATH = REPO_ROOT / "tests" / "data" / "d2_fingerprints.json" NEEDED = [f3_root() / ".survey", REPO_ROOT / CFG["horizon_cache"], REPO_ROOT / INP["warp_prior"]["path"], REPO_ROOT / INP["wavelet"]["path"]] pytestmark = pytest.mark.skipif(not all(p.exists() for p in NEEDED), reason="missing D2 inputs (run scripts/09, 10)") WELL_FIELDS = ("seis_clean", "noise_unit", "phi_t", "z_g", "z_b", "boundaries_t", "eps_a") OBS_KEYS = ("seis", "phi_log", "ai_log", "tau_k", "t_k", "b", "g", "t_of_tau_true", "y_true") FP_RIDS = (900, 8, 902) # P2/P2r dev, first P2r main realization, first bench dev realization FP_DRIFT = (0.0, 1.0, 2.0) FP_SNR_DB, FP_SIGMA_A, FP_DENSITY = 10, 7.0, "full" def _sha(chunks) -> str: h = hashlib.sha256() for a in chunks: h.update(np.ascontiguousarray(np.asarray(a)).tobytes()) return h.hexdigest() def fingerprint_wells(R) -> dict: return {k: _sha(getattr(w, k) for w in R.wells) for k in WELL_FIELDS} def fingerprint_obs(R, **kw) -> dict: wells = R.test + R.pool[:4] obs = [R.observe(w, c, FP_SNR_DB, FP_SIGMA_A, FP_DENSITY, **kw) for c in FP_DRIFT for w in wells] return {k: _sha(o[k] for o in obs) for k in OBS_KEYS} def fingerprint(R, **kw) -> dict: return {"wells": fingerprint_wells(R), "obs": fingerprint_obs(R, **kw)} @pytest.fixture(scope="module") def make(): hg = load_horizon_grid(CFG["horizons"], REPO_ROOT / CFG["horizon_cache"]) prior = json.loads((REPO_ROOT / INP["warp_prior"]["path"]).read_text())["fits"][INP["warp_prior"]["fit"]] wav = np.load(REPO_ROOT / INP["wavelet"]["path"])[INP["wavelet"]["key"]] return lambda rid, **kw: D2Realization(CFG, rid, hg, WarpHyper(**prior["hyper"]), wav, **kw) @pytest.fixture(scope="module") def recorded() -> dict: fp = json.loads(FP_PATH.read_text()) env = fp["meta"]["env"] if (env["numpy"], env["scipy"]) != (np.__version__, scipy.__version__): pytest.skip(f"fingerprints recorded with numpy {env['numpy']} / scipy {env['scipy']}; " f"this environment has {np.__version__} / {scipy.__version__}") return fp def test_inputs_match_fingerprint_record(recorded): for key in ("d2_config", "warp_prior", "wavelet"): f = REPO_ROOT / INP[key]["path"] assert hashlib.sha256(f.read_bytes()).hexdigest() == recorded["meta"]["inputs"][key], key @pytest.mark.parametrize("rid", FP_RIDS) def test_default_path_matches_fingerprints(make, recorded, rid): """Realizations and observations are bit-identical to the record taken before the misspec parameters existed.""" fp = fingerprint(make(rid)) for part in ("wells", "obs"): for k, v in recorded["realizations"][str(rid)][part].items(): assert fp[part][k] == v, f"rid {rid}: {part}.{k} changed" # ---------------------------------------------------------------- bench config and preset validation BENCH = yaml.safe_load((REPO_ROOT / "configs" / "d2_synth_bench.yaml").read_text()) def test_d2_bench_generator_matches_p2r(): """configs/d2_synth_bench.yaml uses the protocol_p2r generator and regimes: only misspec_presets may be added.""" from ml_porosity.data.synth_d2 import normalize_misspec, preset_misspec p2r = yaml.safe_load((REPO_ROOT / "configs" / "d2_synth_p2r.yaml").read_text()) bench = dict(BENCH) presets = bench.pop("misspec_presets") assert bench == p2r assert preset_misspec(BENCH, None) is None and preset_misspec(BENCH, "nominal") is None for name in presets: ms = normalize_misspec(preset_misspec(BENCH, name)) assert ms["rock_physics"]["region"] == "all" with pytest.raises(KeyError): preset_misspec(BENCH, "no_such_preset") def test_normalize_misspec_rejects_unknown_keys(): from ml_porosity.data.synth_d2 import MISSPEC_DEFAULTS, active_axes, normalize_misspec assert normalize_misspec(None) == normalize_misspec({}) == MISSPEC_DEFAULTS assert active_axes(normalize_misspec({"wavelet": {"Q": None, "Q_t_ref_ms": 500.0}})) == {} assert active_axes(normalize_misspec({"drift": {"step_ms": 4.0}})) == {"drift": {"step_ms": 4.0}} for bad in ({"rockphysics": {}}, {"wavelet": {"Q_factor": 2.0}}, {"drift": {"ell_factor": 0.0}}, {"rock_physics": {"region": "train"}}, {"wavelet": {"minphase_frac": 1.5}}): with pytest.raises(ValueError): normalize_misspec(bad) # ---------------------------------------------------------------- common random numbers and axis semantics RID = 902 C, SNR, SIGMA_A = 1.0, 10, 7.0 CRN_FIELDS = ("phi_t", "noise_unit", "z_g", "z_b", "boundaries_t", "eps_a") @pytest.fixture(scope="module") def R0(make): return make(RID) def _assert_crn(R, R0): """Earth model, noise and standard-normal draws identical to the nominal realization.""" for a, b in zip(R.wells, R0.wells): assert (a.name, a.il, a.xl) == (b.name, b.il, b.xl) for k in CRN_FIELDS: np.testing.assert_array_equal(getattr(a, k), getattr(b, k)) def test_all_nominal_misspec_is_bit_identical(make, R0): explicit = {"rock_physics": {"dt_slope_factor": 1.0, "region": "all"}, "wavelet": {"Q": None}, "drift": {"sigma_b_factor": 1.0, "step_ms": 0.0, "jitter_sd_ms": 0.0}} R = make(RID, misspec=explicit) assert R.misspec_active == {} and R.w_fine is R.w_fine_nominal and R.drift_true is R.drift assert fingerprint(R) == fingerprint(R0) def test_rock_physics_changes_seismic_only(make, R0): R = make(RID, misspec={"rock_physics": {"dt_slope_factor": 1.15, "unit_dt_intercept_sd": 0.05}}) _assert_crn(R, R0) for w, w0 in zip(R.wells, R0.wells): assert not np.allclose(w.seis_clean, w0.seis_clean) o, o0 = (r.observe(x, C, SNR, SIGMA_A) for r, x in ((R, w), (R0, w0))) for k in ("phi_log", "ai_log", "tau_k", "t_k", "b", "g", "t_of_tau_true", "y_true"): np.testing.assert_array_equal(o[k], o0[k]) # labels, anchors, warp: unchanged ai_true = R.ai_log_true(w, o) assert ai_true.shape == o["ai_log"].shape and not np.allclose(ai_true, o["ai_log"]) np.testing.assert_array_equal(R0.ai_log_true(w0, o0), o0["ai_log"]) # region: the perturbation acts on the named wells only Rt = make(RID, misspec={"rock_physics": {"unit_dt_intercept_sd": 0.05, "region": "test"}}) for w, w0 in zip(Rt.pool, R0.pool): np.testing.assert_array_equal(w.seis_clean, w0.seis_clean) assert not np.allclose(Rt.test[0].seis_clean, R0.test[0].seis_clean) assert Rt.rp_applies("T00") and not Rt.rp_applies("P00") def test_rock_physics_uniform_error_is_near_affine(make): """Uniform coefficient errors change ln AI almost affinely in φ over the D2 porosity range (15–20 % coefficient errors: 4 % of ln AI, of which < 1 % of the ln AI range is non-affine), so the profiled amplitude of the tie likelihood absorbs them; this is why the rp_* presets add per-unit scatter.""" from ml_porosity.data.synth_d2 import phi_to_ai phi = np.linspace(0.2, 0.43, 200) R = make(RID, misspec={"rock_physics": {"dt_slope_factor": 1.15, "dt_intercept_factor": 1.15, "rho_slope_factor": 1.2}}) d = np.log(R.phi_to_ai_true(phi)) - np.log(phi_to_ai(phi)) resid = d - np.polyval(np.polyfit(phi, d, 1), phi) assert np.abs(d).max() > 0.02 and np.abs(resid).max() < 0.01 * np.ptp(np.log(phi_to_ai(phi))) def test_wavelet_axis_changes_seismic_only(make, R0): from ml_porosity.data.wavelet import rotate_phase cases = {"phase": {"phase_deg": 45.0}, "minphase": {"minphase_frac": 1.0}, "peak": {"peak_freq_factor": 1.2}, "delay": {"delay_ms": 4.0}, "Q": {"Q": 80.0}} phases = np.arange(-180.0, 180.0, 1.0) for name, wv in cases.items(): R = make(RID, misspec={"wavelet": wv}) _assert_crn(R, R0) w, w0 = R.pool[0], R0.pool[0] assert not np.allclose(w.seis_clean, w0.seis_clean), name o, o0 = R.observe(w, C, SNR, SIGMA_A), R0.observe(w0, C, SNR, SIGMA_A) for k in ("phi_log", "ai_log", "tau_k", "t_k", "t_of_tau_true", "y_true"): np.testing.assert_array_equal(o[k], o0[k]) if name == "Q": assert R.w_fine is R.w_fine_nominal # stationary part nominal; Q acts in the forward k600, k1100 = R.true_wavelet_at(600.0), R.true_wavelet_at(1100.0) spec = lambda k: np.abs(np.fft.rfft(k, 4096)) f = np.fft.rfftfreq(4096, 0.0005) hi = f > 50 assert (spec(k1100)[hi] / spec(k1100).max()).sum() < (spec(k600)[hi] / spec(k600).max()).sum() else: cc = [np.corrcoef(rotate_phase(R.w_fine_nominal, p), R.w_fine)[0, 1] for p in phases] best = phases[int(np.argmax(cc))] if name == "phase": assert abs(best - 45.0) <= 1.0 and max(cc) > 0.999 # inside the constant-phase family if name == "minphase": assert max(cc) < 0.9 # not representable by a constant phase assert len(R.wavelet) == len(R0.wavelet) and len(R.w_fine) == len(R0.w_fine) def test_minimum_phase_keeps_amplitude_spectrum(R0): from ml_porosity.data.synth_d2 import fractional_minimum_phase w = R0.w_fine_nominal for frac in (0.0, 0.5, 1.0): y = fractional_minimum_phase(w, frac) a, b = np.abs(np.fft.rfft(w, 4096)), np.abs(np.fft.rfft(y, 4096)) band = a > 0.1 * a.max() # truncation to 128 ms only touches the band edges assert np.abs(b[band] / a[band] - 1.0).max() < 0.05, frac assert abs(np.sum(y**2) / np.sum(w**2) - 1.0) < 0.01, frac np.testing.assert_allclose(fractional_minimum_phase(w, 0.0), w, atol=1e-9) def test_drift_hyper_factors_use_common_random_numbers(make, R0): R = make(RID, misspec={"drift": {"sigma_b_factor": 3.0, "sigma_g_factor": 1.5}}) _assert_crn(R, R0) for w, w0 in zip(R.pool[:3], R0.pool[:3]): np.testing.assert_array_equal(w.seis_clean, w0.seis_clean) # the seismic is untouched o, o0 = R.observe(w, C, SNR, SIGMA_A), R0.observe(w0, C, SNR, SIGMA_A) assert o["b"] == pytest.approx(3.0 * o0["b"]) m = C * R.drift.m_g np.testing.assert_allclose(o["g"] - m, 1.5 * (o0["g"] - m), atol=1e-12) np.testing.assert_array_equal(o["t_k"], o0["t_k"]) # picks keep their noise draws np.testing.assert_allclose(np.interp(o["tau_k"], R.tau_fine, o["t_of_tau_true"]), w.boundaries_t, atol=1e-9) Rl = make(RID, misspec={"drift": {"ell_factor": 0.5}}) assert Rl.drift_true.ell_ms == pytest.approx(0.5 * R0.drift.ell_ms) and Rl.Lg_true is not Rl.Lg def test_drift_step_is_exact_jump_below_horizon(make, R0): J, width = 8.0, 12.0 R = make(RID, misspec={"drift": {"step_ms": J, "step_width_ms": width}}) _assert_crn(R, R0) k = CFG["horizons"].index("Truncation") for w, w0 in zip(R.wells, R0.wells): o, o0 = R.observe(w, C, SNR, SIGMA_A), R0.observe(w0, C, SNR, SIGMA_A) d = o["t_of_tau_true"] - o0["t_of_tau_true"] t_h = R.hg.at(w.il, w.xl)[k] tau_h = np.interp(t_h, o0["t_of_tau_true"], R.tau_fine) assert np.all(np.diff(o["t_of_tau_true"]) > 0) np.testing.assert_allclose(d[R.tau_fine < tau_h - R.grid.dtau], 0.0, atol=1e-9) np.testing.assert_allclose(d[R.tau_fine > tau_h + width + 2 * R.grid.dtau], J, atol=1e-9) np.testing.assert_allclose(R.grid.t_of_tau(o["b"], o["g"])[0], R.true_warp_grid(w, C), atol=1e-9) np.testing.assert_allclose(np.interp(o["tau_k"], R.tau_fine, o["t_of_tau_true"]), w.boundaries_t, atol=1e-9) assert o["b"] == o0["b"] and np.count_nonzero(o["g"] != o0["g"]) == int(round(width / R.grid.dtau)) Rn = make(RID, misspec={"drift": {"step_ms": -6.0}}) o = Rn.observe(Rn.pool[0], C, SNR, SIGMA_A) assert np.all(np.diff(o["t_of_tau_true"]) > 0) def test_drift_jitter_is_high_frequency_and_monotone(make, R0): sd, ell = 1.0, 8.0 R = make(RID, misspec={"drift": {"jitter_sd_ms": sd, "jitter_ell_ms": ell}}) _assert_crn(R, R0) rms = [] for w, w0 in zip(R.wells, R0.wells): o, o0 = R.observe(w, C, SNR, SIGMA_A), R0.observe(w0, C, SNR, SIGMA_A) d = o["t_of_tau_true"] - o0["t_of_tau_true"] assert np.all(np.diff(o["t_of_tau_true"]) > 0) np.testing.assert_array_equal(o["g"], o0["g"]) # jitter is not folded into g np.testing.assert_allclose(np.interp(o["tau_k"], R.tau_fine, o["t_of_tau_true"]), w.boundaries_t, atol=1e-9) rms.append(np.sqrt(np.mean(d**2))) # decorrelates within a few ℓ: lag-40 ms autocorrelation small, lag-4 ms large g = np.interp(R.grid.tau, R.tau_fine, d) acf = lambda lag: np.corrcoef(g[:-lag], g[lag:])[0, 1] assert acf(1) > 0.5 and abs(acf(10)) < 0.4 assert 0.5 * sd < np.mean(rms) < 1.5 * sd assert R.misspec_info["monotone_repairs"] == 0 assert "z_jitter" in R.wells[0].extra and "z_jitter" not in R0.wells[0].extra def test_presets_build_and_report_active_axes(make, R0): from ml_porosity.data.synth_d2 import preset_misspec for name in BENCH["misspec_presets"]: R = make(RID, misspec=preset_misspec(BENCH, name)) _assert_crn(R, R0) axis = next(p for p in name.split("_") if p in ("rp", "wv", "dr")) # names: rp_L1, wv_Q, cand_dr_s, ... assert list(R.misspec_active) == [{"rp": "rock_physics", "wv": "wavelet", "dr": "drift"}[axis]] o = R.observe(R.pool[0], C, SNR, SIGMA_A) assert np.isfinite(o["seis"]).all() and np.all(np.diff(o["t_of_tau_true"]) > 0)