"""Synthetic seismogram và đo lệch thời gian giữa synthetic và seismic.""" from __future__ import annotations import numpy as np def reflectivity_from_ai(ai: np.ndarray) -> np.ndarray: """r[i] = (AI[i+1] − AI[i]) / (AI[i+1] + AI[i]), đặt tại mẫu i; mẫu cuối = 0.""" ai = np.asarray(ai, dtype=float) r = np.zeros_like(ai) r[:-1] = (ai[1:] - ai[:-1]) / (ai[1:] + ai[:-1]) return np.nan_to_num(r) def shift_signal(x: np.ndarray, shift_ms: float, dt_ms: float) -> np.ndarray: """Dịch chuỗi theo thời gian (dương = muộn hơn) bằng nội suy tuyến tính; ngoài biên = 0.""" t = np.arange(len(x)) * dt_ms return np.interp(t - shift_ms, t, x, left=0.0, right=0.0) def ncc(a: np.ndarray, b: np.ndarray) -> float: a = a - a.mean() b = b - b.mean() d = np.sqrt((a * a).sum() * (b * b).sum()) return float((a * b).sum() / d) if d > 0 else float("nan") def best_shift(syn: np.ndarray, seis: np.ndarray, dt_ms: float, max_ms: float, step_ms: float = 0.5): """Dịch synthetic trong ±max_ms để cực đại tương quan với seismic. Trả về (shift_ms, r).""" shifts = np.arange(-max_ms, max_ms + step_ms / 2, step_ms) rs = np.array([ncc(shift_signal(syn, s, dt_ms), seis) for s in shifts]) k = int(np.nanargmax(rs)) return float(shifts[k]), float(rs[k]) def local_shifts( syn: np.ndarray, seis: np.ndarray, dt_ms: float, win_ms: float = 120.0, hop_ms: float = 20.0, max_ms: float = 16.0, ): """Lệch thời gian cục bộ trong cửa sổ trượt (taper Hann). Trả về (tâm cửa sổ theo chỉ số mẫu, shift_ms, r). Dương nghĩa là synthetic cần dịch muộn hơn để khớp seismic.""" n = int(round(win_ms / dt_ms)) hop = max(1, int(round(hop_ms / dt_ms))) taper = np.hanning(n) centers, shifts, rs = [], [], [] pad = int(np.ceil(max_ms / dt_ms)) + 1 for i0 in range(pad, len(syn) - n - pad + 1, hop): sl = slice(i0 - pad, i0 + n + pad) a, b = syn[sl], seis[sl] best = (0.0, -np.inf) for s in np.arange(-max_ms, max_ms + 0.25, 0.5): sa = shift_signal(a, s, dt_ms)[pad:-pad] * taper r = ncc(sa, b[pad:-pad] * taper) if r > best[1]: best = (float(s), r) centers.append(i0 + n // 2) shifts.append(best[0]) rs.append(best[1]) return np.array(centers), np.array(shifts), np.array(rs)