"""Wavelet, synthetic seismogram 4 giếng và misregistration còn lại sau tie (P1, cổng G-A). python scripts/04_wavelet_tie.py Với mỗi giếng và mỗi TDR: synthetic = wavelet ∗ r(AI theo TDR), so với trace seismic tại giếng. Báo cáo tương quan với pha chung ở shift 0, tie tốt nhất theo từng giếng (pha hằng + bulk shift) và lệch cục bộ còn lại sau tie tốt nhất (cửa sổ trượt 120 ms, chỉ tính cửa sổ có r > 0.5). Phép đo dùng log của cả 4 giếng nên chỉ là QC/audit, không dùng cho huấn luyện. Đầu ra: 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 # tần số trội trung bình đo ở plan mục 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"]))) # Wavelet thống kê (chỉ seismic) và wavelet LS từ 4 giếng với tie calibrated. 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) # Pha hằng chung cho wavelet thống kê: cực đại tương quan trung bình (calibrated, shift 0). 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"Pha hằng tốt nhất của wavelet thống kê: {phase:+.0f}°, r trung bình {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]) # Tie tốt nhất theo từng giếng: pha hằng và bulk shift tìm đồng thời (lưới 10° × 0.5 ms). 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) # Lệch còn lại sau tie tốt nhất: lệch cục bộ của synthetic đã dịch bulk và xoay pha. 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}) # Ngưỡng nhiễu của phép đo: synthetic + nhiễu băng hạn chế (nhiễu trắng ∗ wavelet) sao cho # tương quan toàn cục bằng r_best_tie; lệch thật = 0 nên RMS đo được là sai số của phép đo. 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("lệch cục bộ (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 (tie tốt nhất từng giếng) vs seismic; " "cột hẹp: lệch cục bộ còn lại, dải vàng ±T/8 ở 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"thống kê, pha {phase:+.0f}°") ax.plot(tw, w_ls / np.abs(w_ls).max(), label="LS từ 4 giếng (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 ở {F_DOM_HZ:.0f} Hz = {1000 / F_DOM_HZ / 8:.1f} ms") # Đối chiếu thời gian marker với horizon tại giếng (mốc thời gian SEG-Y, 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: trung vị {hd.diff_ms.median():+.1f} ms, |Δ| trung vị {hd.diff_ms.abs().median():.1f} ms") if __name__ == "__main__": main()