"""Time–depth relationship (TDR): MD (m, from KB) ↔ TWT (ms, from the seismic datum). Three ways of constructing a TDR: * `legacy_sonic_tdr` – reproduces the thesis approach (prepare_data.py:110): integrates DT with t = 0 at the first LAS sample, without drift correction. For auditing only. * `sonic_tdr` – integrates DT starting from an anchor point (md0, t0). * `calibrate_to_anchors` – drift correction: stretches/squeezes the sonic time within each interval between consecutive anchors so that every anchor is honoured exactly. Since each interval's stretch factor is positive, the resulting TDR is always monotonically increasing. """ from __future__ import annotations from dataclasses import dataclass import numpy as np from scipy import integrate US_PER_M_TO_S_PER_M = 1e-6 @dataclass(frozen=True) class TDR: md: np.ndarray # (N,) strictly increasing twt_ms: np.ndarray # (N,) strictly increasing name: str = "" def __post_init__(self): md = np.asarray(self.md, dtype=float) t = np.asarray(self.twt_ms, dtype=float) if md.shape != t.shape or md.ndim != 1 or md.size < 2: raise ValueError("md and twt_ms must be 1-D arrays of equal length ≥ 2") if np.any(np.diff(md) <= 0): raise ValueError(f"TDR {self.name!r}: MD is not strictly increasing") if np.any(np.diff(t) <= 0): raise ValueError(f"TDR {self.name!r}: TWT is not strictly increasing") object.__setattr__(self, "md", md) object.__setattr__(self, "twt_ms", t) @classmethod def from_pairs(cls, pairs: np.ndarray, name: str = "", drop_flat: bool = False) -> TDR: """`drop_flat=True` drops points whose time does not increase relative to the previously kept point (e.g. F02-1.wlt contains two pairs with different MD but the same TWT of 700 and 800 ms).""" pairs = np.asarray(pairs, dtype=float) pairs = pairs[np.argsort(pairs[:, 0], kind="stable")] if drop_flat: keep = [0] for i in range(1, len(pairs)): if pairs[i, 0] > pairs[keep[-1], 0] and pairs[i, 1] > pairs[keep[-1], 1]: keep.append(i) pairs = pairs[keep] return cls(pairs[:, 0], pairs[:, 1], name) def time_at(self, md) -> np.ndarray: """TWT (ms) at MD; outside the range, linearly extrapolated from the first/last interval.""" return _interp_extrap(md, self.md, self.twt_ms) def depth_at(self, twt_ms) -> np.ndarray: return _interp_extrap(twt_ms, self.twt_ms, self.md) def interval_velocity(self) -> np.ndarray: """Interval velocity (m/s) between consecutive nodes.""" return 2000.0 * np.diff(self.md) / np.diff(self.twt_ms) def _interp_extrap(x, xp, fp) -> np.ndarray: x = np.asarray(x, dtype=float) y = np.interp(x, xp, fp) lo, hi = x < xp[0], x > xp[-1] if np.any(lo): y[lo] = fp[0] + (x[lo] - xp[0]) * (fp[1] - fp[0]) / (xp[1] - xp[0]) if np.any(hi): y[hi] = fp[-1] + (x[hi] - xp[-1]) * (fp[-1] - fp[-2]) / (xp[-1] - xp[-2]) return y def fill_nan(a: np.ndarray) -> np.ndarray: """Linearly interpolate NaNs by index, holding the edge values at both ends (as in the thesis).""" a = np.asarray(a, dtype=float).copy() ok = np.isfinite(a) if not ok.any(): raise ValueError("all values are NaN") a[~ok] = np.interp(np.flatnonzero(~ok), np.flatnonzero(ok), a[ok]) return a def legacy_sonic_tdr(md: np.ndarray, dt_us_per_m: np.ndarray) -> TDR: """TWT = 2·∫DT dz with t = 0 at the first LAS sample (prepare_data.py:110).""" dt = fill_nan(np.where(np.asarray(dt_us_per_m) < 0, np.nan, dt_us_per_m)) owt_s = integrate.cumulative_trapezoid(dt * US_PER_M_TO_S_PER_M, md, initial=0.0) return TDR(md, 2000.0 * owt_s, "legacy_sonic") def sonic_tdr(md: np.ndarray, dt_us_per_m: np.ndarray, md0: float, t0_ms: float) -> TDR: """Integrated DT passing through the anchor point (md0, t0_ms). Only valid DT samples are used, so gaps are integrated as DT varying linearly between their ends; if md0 lies above the first DT sample, the segment from md0 to the first sample uses the DT of the first sample.""" md = np.asarray(md, dtype=float) dt = np.asarray(dt_us_per_m, dtype=float) ok = np.isfinite(dt) & (dt > 0) md_v, dt_v = md[ok], dt[ok] t = 2000.0 * integrate.cumulative_trapezoid(dt_v * US_PER_M_TO_S_PER_M, md_v, initial=0.0) if md0 < md_v[0]: t_md0 = -2000.0 * (md_v[0] - md0) * dt_v[0] * US_PER_M_TO_S_PER_M else: t_md0 = float(_interp_extrap(md0, md_v, t)) return TDR(md_v, t - t_md0 + t0_ms, "sonic") def calibrate_to_anchors(base: TDR, anchor_md, anchor_twt_ms, name: str = "calibrated") -> TDR: """Interval-wise drift correction: between consecutive anchors (z_i, t_i), (z_{i+1}, t_{i+1}) t(z) = t_i + (t_b(z) − t_b(z_i)) · (t_{i+1} − t_i) / (t_b(z_{i+1}) − t_b(z_i)) where t_b is the base (sonic) TDR. Outside the anchor range: bulk shift to the nearest anchor. The result honours every anchor exactly and is monotonic if the anchors are strictly increasing in both z and t. """ za = np.asarray(anchor_md, dtype=float) ta = np.asarray(anchor_twt_ms, dtype=float) order = np.argsort(za) za, ta = za[order], ta[order] if np.any(np.diff(za) <= 0) or np.any(np.diff(ta) <= 0): raise ValueError("anchors must be strictly increasing in MD and TWT") z = np.union1d(base.md, za) tb = base.time_at(z) tba = base.time_at(za) t = np.empty_like(z) k = np.clip(np.searchsorted(za, z, side="right") - 1, 0, len(za) - 2) inside = (z >= za[0]) & (z <= za[-1]) scale = (ta[k + 1] - ta[k]) / (tba[k + 1] - tba[k]) t[inside] = ta[k[inside]] + (tb[inside] - tba[k[inside]]) * scale[inside] above, below = z < za[0], z > za[-1] t[above] = tb[above] + (ta[0] - tba[0]) t[below] = tb[below] + (ta[-1] - tba[-1]) return TDR(z, t, name) def misfit_at_anchors(tdr: TDR, anchor_md, anchor_twt_ms) -> np.ndarray: """TDR-predicted TWT minus anchor TWT (ms). Negative means the TDR is earlier than the anchor.""" return tdr.time_at(anchor_md) - np.asarray(anchor_twt_ms, dtype=float)