"""GP log-slowness warp prior conditioned on anchors (plan §4.1). The reference axis τ is sonic time (integrated DT, ms) and t is seismic time (ms): t(τ) = τ + b + ∫_{τ0}^{τ} (e^{g(τ')} − 1) dτ', g ~ GP(m_g, k_{σ_g, ℓ}), b ~ N(0, σ_b²) Anchors (markers with TWT): t_k = t(τ_k) + ε_k, ε_k ~ N(0, σ_a²). Writing dt/dτ = e^g is equivalent to the depth form in the plan (dt/dz = 2·DT·e^g) since dτ/dz = 2·DT. g is defined on a uniform τ grid; the integral is the trapezoid rule on that grid (the same quadrature for the linearised version e^g − 1 ≈ g and the exact one), so the difference between the two comes only from the nonlinearity of e^g. Latent vector u = [b, g_1..g_n]. The linearised Gaussian posterior serves as the proposal for elliptical slice sampling (sampler.py). Hyperparameters (m_g, σ_g, ℓ, σ_b, σ_a) are fitted by type-II maximum likelihood on the anchors of the training wells (empirical Bayes). """ from __future__ import annotations from dataclasses import asdict, dataclass import numpy as np from scipy import optimize from scipy.linalg import cho_factor, cho_solve @dataclass class WarpHyper: m_g: float = 0.0 sigma_g: float = 0.03 ell_ms: float = 200.0 sigma_b_ms: float = 30.0 sigma_a_ms: float = 4.0 kernel: str = "matern32" def scaled(self, c: float) -> WarpHyper: """Drift scaled by a factor c (used for the ×c drift grid of D2): g → c·g, b → c·b.""" return WarpHyper(c * self.m_g, c * self.sigma_g, self.ell_ms, c * self.sigma_b_ms, self.sigma_a_ms, self.kernel) def as_dict(self) -> dict: return asdict(self) def kernel_matrix(x: np.ndarray, y: np.ndarray, sigma: float, ell: float, kind: str = "matern32") -> np.ndarray: r = np.abs(np.asarray(x)[:, None] - np.asarray(y)[None, :]) / ell if kind == "matern32": a = np.sqrt(3.0) * r return sigma**2 * (1.0 + a) * np.exp(-a) if kind == "se": return sigma**2 * np.exp(-0.5 * r**2) raise ValueError(kind) def cumtrapz_matrix(n: int, dx: float) -> np.ndarray: """Q with (Q f)_i = ∫_{x_0}^{x_i} f by the trapezoid rule on a uniform grid.""" Q = np.zeros((n, n)) for i in range(1, n): Q[i, :i + 1] = dx Q[i, 0] = Q[i, i] = dx / 2 return Q def interp_matrix(x: np.ndarray, grid: np.ndarray) -> np.ndarray: """P with P f = linear interpolation of f (on grid) at x. x must lie within grid.""" x = np.asarray(x, dtype=float) P = np.zeros((len(x), len(grid))) j = np.clip(np.searchsorted(grid, x) - 1, 0, len(grid) - 2) w = (x - grid[j]) / (grid[j + 1] - grid[j]) P[np.arange(len(x)), j] = 1 - w P[np.arange(len(x)), j + 1] = w return P class WarpGrid: """τ grid of one well and the associated linear operators.""" def __init__(self, tau0: float, tau1: float, dtau: float = 4.0): n = int(np.ceil((tau1 - tau0) / dtau)) + 1 self.tau = tau0 + dtau * np.arange(n) self.dtau = dtau self.Q = cumtrapz_matrix(n, dtau) @property def n(self) -> int: return len(self.tau) def t_of_tau(self, b, g, tau=None) -> np.ndarray: """t(τ) for samples (b, g); b scalar or (S,), g (n,) or (S, n). Returns (S, ·) on the grid or at tau (linear interpolation; tau must lie within the grid).""" g = np.atleast_2d(g) t = self.tau[None, :] + np.reshape(b, (-1, 1)) + np.expm1(g) @ self.Q.T if tau is not None: t = t @ interp_matrix(tau, self.tau).T return t def anchor_operator(self, tau_k: np.ndarray) -> np.ndarray: """A with t(τ_k) − τ_k ≈ A u (linearised), u = [b, g].""" C = interp_matrix(tau_k, self.tau) @ self.Q return np.hstack([np.ones((len(tau_k), 1)), C]) def prior_moments(grid: WarpGrid, h: WarpHyper) -> tuple[np.ndarray, np.ndarray]: mu = np.concatenate([[0.0], np.full(grid.n, h.m_g)]) S = np.zeros((grid.n + 1, grid.n + 1)) S[0, 0] = h.sigma_b_ms**2 S[1:, 1:] = kernel_matrix(grid.tau, grid.tau, h.sigma_g, h.ell_ms, h.kernel) S[1:, 1:] += 1e-10 * np.eye(grid.n) return mu, S def linearize(grid: WarpGrid, tau_k: np.ndarray, g0: np.ndarray) -> tuple[np.ndarray, np.ndarray]: """t(τ_k) − τ_k ≈ A u + off, linearising e^g − 1 at g0. g0 = 0 gives A = anchor_operator, off = 0.""" C = interp_matrix(tau_k, grid.tau) @ grid.Q e = np.exp(g0) return np.hstack([np.ones((len(tau_k), 1)), C * e[None, :]]), C @ (e - 1.0 - e * g0) def linear_posterior(grid: WarpGrid, h: WarpHyper, tau_k, d_k, g0=None) -> tuple[np.ndarray, np.ndarray]: """Gaussian posterior of u = [b, g] given d_k = t_k − τ_k ≈ A u + off + ε (linearised at g0, default 0). Without anchors: returns the prior.""" mu, S = prior_moments(grid, h) tau_k = np.asarray(tau_k, dtype=float) if tau_k.size == 0: return mu, S A, off = linearize(grid, tau_k, np.zeros(grid.n) if g0 is None else g0) SA = S @ A.T G = A @ SA + h.sigma_a_ms**2 * np.eye(len(tau_k)) cf = cho_factor(G) mu_p = mu + SA @ cho_solve(cf, np.asarray(d_k) - off - A @ mu) S_p = S - SA @ cho_solve(cf, SA.T) return mu_p, 0.5 * (S_p + S_p.T) def laplace_posterior(grid: WarpGrid, h: WarpHyper, tau_k, d_k, n_iter: int = 8, tol: float = 1e-7): """Gauss–Newton: iterated linearisation at the posterior mean; converges to the MAP of the exact posterior (ignoring the g_max constraint). Returns (mu, S, A, off) with A, off the linearisation at mu.""" g0 = np.full(grid.n, h.m_g) mu, S = linear_posterior(grid, h, tau_k, d_k, g0) for _ in range(n_iter): if np.max(np.abs(mu[1:] - g0)) < tol: break g0 = mu[1:].copy() mu, S = linear_posterior(grid, h, tau_k, d_k, g0) A, off = linearize(grid, np.asarray(tau_k, dtype=float), g0) return mu, S, A, off # ---------------------------------------------------------------- type-II maximum likelihood def _marginal_cov(C: np.ndarray, Kgg: np.ndarray, h: WarpHyper) -> np.ndarray: n = C.shape[0] return h.sigma_b_ms**2 * np.ones((n, n)) + C @ Kgg @ C.T + h.sigma_a_ms**2 * np.eye(n) def log_marginal(wells: list[dict], h: WarpHyper) -> float: """Σ_w log N(d_w; C_w m_g 1, σ_b² 11ᵀ + C_w K C_wᵀ + σ_a² I). wells[i] = {"grid", "tau_k", "d_k"}.""" total = 0.0 for w in wells: grid: WarpGrid = w["grid"] C = interp_matrix(w["tau_k"], grid.tau) @ grid.Q K = kernel_matrix(grid.tau, grid.tau, h.sigma_g, h.ell_ms, h.kernel) V = _marginal_cov(C, K, h) r = np.asarray(w["d_k"]) - h.m_g * C.sum(1) try: cf = cho_factor(V) except np.linalg.LinAlgError: return -np.inf total += -0.5 * r @ cho_solve(cf, r) - np.log(np.diag(cf[0])).sum() - 0.5 * len(r) * np.log(2 * np.pi) return float(total) _FREE = ("m_g", "sigma_g", "ell_ms", "sigma_b_ms", "sigma_a_ms") _LOG = {"sigma_g", "ell_ms", "sigma_b_ms", "sigma_a_ms"} def fit_hyper( wells: list[dict], init: WarpHyper | None = None, fixed: dict | None = None, bounds: dict | None = None, hyperprior: dict | None = None, n_starts: int = 8, seed: int = 0, ) -> tuple[WarpHyper, dict]: """Type-II ML (or MAP-II if a hyperprior is given) for the hyperparameters that are not fixed. hyperprior[name] = (mean, sd) of the parameter on the log scale (σ, ℓ) or the original scale (m_g). Returns (best hyperparameters, info containing the log-marginal and the starting points).""" init = init or WarpHyper() fixed = fixed or {} hyperprior = hyperprior or {} bnd = {"m_g": (-0.2, 0.2), "sigma_g": (1e-4, 0.3), "ell_ms": (10.0, 3000.0), "sigma_b_ms": (0.5, 200.0), "sigma_a_ms": (0.2, 50.0)} | (bounds or {}) free = [k for k in _FREE if k not in fixed] to_x = lambda k, v: np.log(v) if k in _LOG else v from_x = lambda k, x: float(np.exp(x)) if k in _LOG else float(x) lo = np.array([to_x(k, bnd[k][0]) for k in free]) hi = np.array([to_x(k, bnd[k][1]) for k in free]) def make(x): vals = asdict(init) | fixed | {k: from_x(k, xi) for k, xi in zip(free, x)} return WarpHyper(**vals) def obj(x): h = make(x) lp = log_marginal(wells, h) for k, xi in zip(free, x): if k in hyperprior: m, s = hyperprior[k] lp += -0.5 * ((xi - m) / s) ** 2 return -lp if np.isfinite(lp) else 1e12 rng = np.random.default_rng(seed) x0s = [np.clip([to_x(k, getattr(init, k)) for k in free], lo, hi)] x0s += [lo + (hi - lo) * rng.uniform(0.15, 0.85, len(free)) for _ in range(n_starts - 1)] best, starts = None, [] for x0 in x0s: res = optimize.minimize(obj, x0, method="L-BFGS-B", bounds=list(zip(lo, hi))) starts.append(float(-res.fun)) if best is None or res.fun < best.fun: best = res h = make(best.x) return h, {"log_marginal": log_marginal(wells, h), "objective": float(-best.fun), "starts": starts, "free": free, "at_bound": [k for k, xi, a, b in zip(free, best.x, lo, hi) if min(xi - a, b - xi) < 1e-3]} def loao_zscores(wells: list[dict], h: WarpHyper) -> list[np.ndarray]: """Leave-one-anchor-out: z-score of d_k under the (linearised) posterior prediction from the remaining anchors of the same well (plan §5.4). Returns a list of z arrays, one per well.""" out = [] for w in wells: grid: WarpGrid = w["grid"] tk, dk = np.asarray(w["tau_k"]), np.asarray(w["d_k"]) A = grid.anchor_operator(tk) z = np.empty(len(tk)) for k in range(len(tk)): keep = np.arange(len(tk)) != k mu, S = linear_posterior(grid, h, tk[keep], dk[keep]) m = A[k] @ mu v = A[k] @ S @ A[k] + h.sigma_a_ms**2 z[k] = (dk[k] - m) / np.sqrt(v) out.append(z) return out