- 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>
163 lines
8.6 KiB
Python
163 lines
8.6 KiB
Python
"""Wavelets, synthetic seismograms for the 4 wells, and residual misregistration after the tie (P1, gate G-A).
|
||
|
||
python scripts/04_wavelet_tie.py
|
||
|
||
For each well and each TDR: synthetic = wavelet ∗ r(AI under the TDR), compared with the seismic trace at the well.
|
||
Reports the correlation with a common phase at zero shift, the best per-well tie (constant phase + bulk shift),
|
||
and the residual local shift after the best tie (120 ms sliding window, only windows with r > 0.5 counted).
|
||
The measurement uses the logs of all 4 wells, so it is QC/audit only and is not used for training.
|
||
|
||
Outputs: outputs/tie_qc.csv, outputs/tie_local_shifts.csv, outputs/figures/ties.png,
|
||
outputs/figures/wavelets.png, outputs/wavelets.npz
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
import matplotlib
|
||
|
||
matplotlib.use("Agg")
|
||
import matplotlib.pyplot as plt
|
||
import numpy as np
|
||
import pandas as pd
|
||
|
||
from ml_porosity.data.las_io import F3_WELLS
|
||
from ml_porosity.data.synthetic import best_shift, local_shifts, ncc, reflectivity_from_ai, shift_signal
|
||
from ml_porosity.data.wavelet import convolve_same, estimate_wavelet_ls, rotate_phase, statistical_wavelet
|
||
from ml_porosity.paths import outputs_dir
|
||
|
||
DT = 4.0
|
||
TDRS = ["calibrated", "wlt", "anchors", "legacy"]
|
||
F_DOM_HZ = 50.0 # mean dominant frequency measured in plan §2.3 (49–60 Hz)
|
||
|
||
|
||
def main() -> None:
|
||
D = np.load(outputs_dir() / "f3_wells.npz")
|
||
seis = {w: D[f"{w}/seismic_patch"][4].astype(float) for w in F3_WELLS}
|
||
t = D[f"{F3_WELLS[0]}/times_ms"]
|
||
main_m = D[f"{F3_WELLS[0]}/main_mask"]
|
||
|
||
def refl(w, tdr):
|
||
return reflectivity_from_ai(np.nan_to_num(D[f"{w}/{tdr}/AI"], nan=np.nanmean(D[f"{w}/{tdr}/AI"])))
|
||
|
||
# Statistical wavelet (seismic only) and LS wavelet from the 4 wells with the calibrated tie.
|
||
w_stat = statistical_wavelet(np.stack([seis[w][main_m] for w in F3_WELLS]), DT)
|
||
w_ls = estimate_wavelet_ls([refl(w, "calibrated")[main_m] for w in F3_WELLS],
|
||
[seis[w][main_m] for w in F3_WELLS], DT)
|
||
|
||
# Common constant phase for the statistical wavelet: maximizes the mean correlation (calibrated, zero shift).
|
||
phases = np.arange(-180, 180, 5)
|
||
score = [np.mean([ncc(convolve_same(refl(w, "calibrated"), rotate_phase(w_stat, p))[main_m], seis[w][main_m])
|
||
for w in F3_WELLS]) for p in phases]
|
||
phase = float(phases[int(np.argmax(score))])
|
||
w_use = rotate_phase(w_stat, phase)
|
||
print(f"Best constant phase of the statistical wavelet: {phase:+.0f}°, mean r {max(score):.3f}")
|
||
|
||
rows, lrows = [], []
|
||
fig, axes = plt.subplots(1, 2 * len(F3_WELLS), figsize=(16, 8), sharey=True,
|
||
gridspec_kw={"width_ratios": [2, 1] * len(F3_WELLS)}, constrained_layout=True)
|
||
colors = {"calibrated": "#1f5fbf", "wlt": "#2a9d8f", "anchors": "#8a5cc2", "legacy": "#c0392b"}
|
||
for k, w in enumerate(F3_WELLS):
|
||
s = seis[w]
|
||
ax_tr, ax_sh = axes[2 * k], axes[2 * k + 1]
|
||
ax_tr.plot(s / np.std(s[main_m]), t, "k", lw=1.0, label="seismic")
|
||
for tdr in TDRS:
|
||
r_w = refl(w, tdr)
|
||
r0 = ncc(convolve_same(r_w, w_use)[main_m], s[main_m])
|
||
# Best per-well tie: constant phase and bulk shift searched jointly (10° × 0.5 ms grid).
|
||
best = (-np.inf, 0.0, 0.0)
|
||
for p in range(-180, 180, 10):
|
||
syn_p = convolve_same(r_w, rotate_phase(w_stat, p))
|
||
for sh in np.arange(-40, 40.25, 0.5):
|
||
rr = ncc(shift_signal(syn_p, sh, DT)[main_m], s[main_m])
|
||
if rr > best[0]:
|
||
best = (rr, float(p), float(sh))
|
||
r_best, p_best, sh_best = best
|
||
syn = shift_signal(convolve_same(r_w, rotate_phase(w_stat, p_best)), sh_best, DT)
|
||
# Residual shift after the best tie: local shift of the bulk-shifted, phase-rotated synthetic.
|
||
c, ls, lr = local_shifts(syn, s, DT, win_ms=120, hop_ms=20, max_ms=24)
|
||
tc = t[c]
|
||
inwin = (tc >= t[main_m][0] + 60) & (tc <= t[main_m][-1] - 60)
|
||
good = inwin & (lr > 0.5)
|
||
rows.append({"well": w, "tdr": tdr, "r_common_phase_shift0": round(r0, 3),
|
||
"best_phase_deg": p_best, "best_bulk_shift_ms": sh_best, "r_best_tie": round(r_best, 3),
|
||
"local_n": int(good.sum()), "local_n_total": int(inwin.sum()),
|
||
"local_rms_ms": round(float(np.sqrt(np.mean(ls[good] ** 2))), 1) if good.any() else np.nan,
|
||
"local_range_ms": round(float(np.ptp(ls[good])), 1) if good.any() else np.nan})
|
||
# Noise floor of the measurement: synthetic + band-limited noise (white noise ∗ wavelet) such that
|
||
# the global correlation equals r_best_tie; the true shift is 0, so the measured RMS is the measurement error.
|
||
rng = np.random.default_rng(0)
|
||
floor = []
|
||
for _ in range(20):
|
||
nz = convolve_same(rng.standard_normal(len(syn)), w_stat)
|
||
nz *= np.std(syn[main_m]) / np.std(nz[main_m]) * np.sqrt(1 / max(r_best, 0.05) ** 2 - 1)
|
||
_, ls0, lr0 = local_shifts(syn, syn + nz, DT, win_ms=120, hop_ms=20, max_ms=24)
|
||
g0 = inwin & (lr0 > 0.5)
|
||
if g0.any():
|
||
floor.append(np.sqrt(np.mean(ls0[g0] ** 2)))
|
||
rows[-1]["noise_floor_rms_ms"] = round(float(np.median(floor)), 1) if floor else np.nan
|
||
for tci, lsi, lri in zip(tc[inwin], ls[inwin], lr[inwin]):
|
||
lrows.append({"well": w, "tdr": tdr, "t_ms": tci, "shift_ms": lsi, "r": round(lri, 3)})
|
||
if tdr in ("calibrated", "legacy"):
|
||
ax_tr.plot(syn / np.std(syn[main_m]) + (3 if tdr == "calibrated" else 6), t,
|
||
color=colors[tdr], lw=1.0, label=f"synthetic ({tdr})")
|
||
ax_sh.plot(ls[inwin], tc[inwin], "o-", ms=3, color=colors[tdr], label=tdr,
|
||
alpha=1.0 if tdr in ("calibrated", "legacy") else 0.6)
|
||
ax_tr.set_title(f"{w}", fontsize=10)
|
||
ax_tr.set_xticks([])
|
||
ax_sh.axvline(0, color="k", lw=0.7)
|
||
ax_sh.axvspan(-1000 / F_DOM_HZ / 8, 1000 / F_DOM_HZ / 8, color="#f0c040", alpha=0.3, lw=0)
|
||
ax_sh.set_xlim(-26, 26)
|
||
ax_sh.set_xlabel("local shift (ms)", fontsize=8)
|
||
for a in (ax_tr, ax_sh):
|
||
a.axhspan(t[main_m][0], t[main_m][-1], color="#eee", zorder=-1, lw=0)
|
||
axes[0].set_ylim(t[-1], t[0])
|
||
axes[0].set_ylabel("TWT (ms)")
|
||
h1, l1 = axes[0].get_legend_handles_labels()
|
||
h2, l2 = axes[1].get_legend_handles_labels()
|
||
fig.legend(h1 + h2, l1 + l2, loc="outside lower center", ncol=7, fontsize=9)
|
||
fig.suptitle("Synthetic (best per-well tie) vs seismic; "
|
||
"narrow column: residual local shift, yellow band ±T/8 at 50 Hz", fontsize=11)
|
||
out = outputs_dir()
|
||
(out / "figures").mkdir(exist_ok=True)
|
||
fig.savefig(out / "figures" / "ties.png", dpi=130)
|
||
|
||
fw, ax = plt.subplots(figsize=(6, 3.5), constrained_layout=True)
|
||
tw = (np.arange(len(w_stat)) - len(w_stat) // 2) * DT
|
||
ax.plot(tw, w_use / np.abs(w_use).max(), label=f"statistical, phase {phase:+.0f}°")
|
||
ax.plot(tw, w_ls / np.abs(w_ls).max(), label="LS from 4 wells (calibrated)")
|
||
ax.set_xlabel("ms")
|
||
ax.legend()
|
||
ax.grid(alpha=0.3)
|
||
fw.savefig(out / "figures" / "wavelets.png", dpi=130)
|
||
np.savez(out / "wavelets.npz", statistical=w_stat, statistical_rotated=w_use, phase_deg=phase, ls_all_wells=w_ls)
|
||
|
||
df = pd.DataFrame(rows)
|
||
df.to_csv(out / "tie_qc.csv", index=False)
|
||
pd.DataFrame(lrows).to_csv(out / "tie_local_shifts.csv", index=False)
|
||
print(df.to_string(index=False))
|
||
print(f"T/8 at {F_DOM_HZ:.0f} Hz = {1000 / F_DOM_HZ / 8:.1f} ms")
|
||
|
||
# Compare marker times with horizons at the wells (SEG-Y time datum, XM delay 4 ms).
|
||
names = {"FS8": "FS8", "FS7": "FS7", "Truncation": "Truncation 1", "FS6": "FS6", "MFS4": "MFS4"}
|
||
from ml_porosity.data.las_io import load_well
|
||
hrows = []
|
||
for w in F3_WELLS:
|
||
mk = load_well(w).markers
|
||
cs = load_well(w).checkshot
|
||
for h, mname in names.items():
|
||
th = float(D[f"{w}/horizon/{h}"])
|
||
md = mk.loc[mk.name == mname, "md"]
|
||
if md.empty or not np.isfinite(th):
|
||
continue
|
||
tm = float(np.interp(md.iloc[0], cs.md, cs.twt_ms))
|
||
hrows.append({"well": w, "horizon": h, "horizon_ms": round(th, 1), "marker_ms": round(tm, 1),
|
||
"diff_ms": round(th - tm, 1)})
|
||
hd = pd.DataFrame(hrows)
|
||
hd.to_csv(out / "marker_vs_horizon.csv", index=False)
|
||
print(hd.to_string(index=False))
|
||
print(f"horizon − marker: median {hd.diff_ms.median():+.1f} ms, median |Δ| {hd.diff_ms.abs().median():.1f} ms")
|
||
|
||
|
||
if __name__ == "__main__":
|
||
main()
|