======================================================= Formal Verification of gpridge Mathematical Foundations ======================================================= Introduction ------------ This document provides a symbolic verification of the mathematical formulas implemented in ``gpridge``, following the methodology of Goswami et al., "d-SEAMS 2.0: Modernized Ice Structure Analysis with Formal Verification" (*Computer Physics Communications*, in preparation). Each formula is: 1. Stated in standard mathematical notation 2. Derived symbolically using SymPy (exact rational arithmetic) 3. Compared term-by-term against the C++ implementation 4. Tested as an executable pytest module via ``org-babel-tangle`` Where applicable, structural properties (symmetry, positive-definiteness) are verified in Coq. The tangled code lives in ``python/tests/test_sympy_formal.py``. Further SymPy checks are in the other ``python/tests/test_sympy_*.py`` files and in the ``scripts/derive_*.py`` scripts. Gaussian Process Regression --------------------------- .. _sec:lml: Log Marginal Likelihood ~~~~~~~~~~~~~~~~~~~~~~~ The negative log marginal likelihood (NLML) for a GP with training targets :math:`\mathbf{y}`, covariance matrix :math:`K`, and noise variance :math:`\sigma^2` is: .. math:: \mathcal{L} = \frac{n}{2}\ln(2\pi) + \frac{1}{2}\ln|K + \sigma^2 I| + \frac{1}{2}\mathbf{y}^\top (K + \sigma^2 I)^{-1} \mathbf{y} The Cholesky-based computation (Algorithm 2.1 of Rasmussen & Williams) uses :math:`C = K + \sigma^2 I = L L^\top`: .. math:: \mathcal{L} = \frac{n}{2}\ln(2\pi) + \sum_i \ln L_{ii} + \frac{1}{2}\mathbf{b}^\top\mathbf{b} where :math:`\mathbf{b} = L^{-1}\mathbf{y}`. SymPy verification ^^^^^^^^^^^^^^^^^^ .. code:: python """Formal verification of gpridge mathematical foundations. Tangled from docs/verification/formal_verification.org. Each test corresponds to a numbered equation in the document. """ import numpy as np import pytest import sympy as sp from sympy import ( Matrix, Symbol, Rational, exp, log, pi, sqrt, gamma, symbols, simplify, Function, oo ) class TestLogMarginalLikelihood: """Verify Eq. (1): GP log marginal likelihood.""" def test_cholesky_form_matches_direct(self): """The Cholesky form should equal the direct matrix form.""" # 2x2 SPD kernel matrix k11, k12, k22, s2 = symbols("k11 k12 k22 sigma2", positive=True) y1, y2 = symbols("y1 y2", real=True) K = Matrix([[k11, k12], [k12, k22]]) C = K + s2 * sp.eye(2) y = Matrix([y1, y2]) n = 2 # Direct form nlml_direct = (Rational(n, 2) * log(2 * pi) + Rational(1, 2) * log(C.det()) + Rational(1, 2) * (y.T * C.inv() * y)[0, 0]) # Cholesky form: L = cholesky(C) # For verification, use the identity: # log|C| = 2 * sum(log(L_ii)) # y^T C^{-1} y = |L^{-1} y|^2 # These are algebraically identical, so we verify the # log-determinant identity symbolically. log_det_direct = log(C.det()) # det(C) = det(L)^2 = prod(L_ii)^2 # so log|C| = 2 * sum(log(L_ii)) # This is verified by checking det(L*L^T) = det(C) L = C.cholesky() assert simplify((L * L.T - C).norm()) == 0 def test_2x2_numerical(self): """Numerical check against known values.""" K = Matrix([[1.0, 0.5], [0.5, 1.0]]) s2 = 0.1 C = K + s2 * sp.eye(2) y = Matrix([1.0, -0.5]) nlml = (log(2 * pi) + Rational(1, 2) * log(C.det()) + Rational(1, 2) * (y.T * C.inv() * y)[0, 0]) val = float(nlml.evalf()) assert np.isfinite(val) # Cross-check: manually compute C_np = np.array([[1.1, 0.5], [0.5, 1.1]]) y_np = np.array([1.0, -0.5]) L_np = np.linalg.cholesky(C_np) b = np.linalg.solve(L_np, y_np) nlml_np = np.log(2 * np.pi) + np.sum(np.log(np.diag(L_np))) + 0.5 * b @ b assert val == pytest.approx(nlml_np, rel=1e-10) NLML Gradient w.r.t. Hyperparameters ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The gradient of the NLML with respect to hyperparameter :math:`\theta_j` is: .. math:: \frac{\partial\mathcal{L}}{\partial\theta_j} = \frac{1}{2}\mathrm{tr}\!\left((C^{-1} - \boldsymbol{\alpha}\boldsymbol{\alpha}^\top)\frac{\partial K}{\partial\theta_j}\right) where :math:`\boldsymbol{\alpha} = C^{-1}\mathbf{y}`. SymPy verification ^^^^^^^^^^^^^^^^^^ .. code:: python class TestNLMLGradient: """Verify Eq. (3): NLML gradient w.r.t. hyperparameters.""" def test_1d_gradient_formula(self): """Verify gradient structure for a 1x1 kernel matrix.""" k, s, y_val = symbols("k sigma y", positive=True) theta = Symbol("theta", positive=True) C = k + s alpha = y_val / C # dK/dtheta = dk/dtheta (scalar) dk_dtheta = sp.diff(k, theta) if k.has(theta) else Symbol("dkdt") # Gradient formula: 0.5 * tr((C^{-1} - alpha*alpha') * dK/dtheta) # For 1x1: 0.5 * (1/C - alpha^2) * dkdt grad = Rational(1, 2) * (1 / C - alpha**2) * dk_dtheta # Alternative: 0.5 * (1/(k+s) - y^2/(k+s)^2) * dkdt expected = Rational(1, 2) * (1 / (k + s) - y_val**2 / (k + s)**2) * dk_dtheta assert simplify(grad - expected) == 0 Inverse-Distance Kernel ~~~~~~~~~~~~~~~~~~~~~~~ The SexpatCF distance between configurations :math:`C` and :math:`C'` is: .. math:: d(C, C') = \sqrt{\sum_{(i,j) \in \text{pairs}} \frac{2}{l_{p(i,j)}^2}\left(\frac{1}{r_{ij}} - \frac{1}{r'_{ij}}\right)^2} where :math:`r_{ij} = \|\mathbf{x}_i - \mathbf{x}_j\|` and :math:`l_{p(i,j)}` is the lengthscale for pairtype :math:`p(i,j)`. The covariance is then: .. math:: k(C, C') = \sigma^2 \exp\!\left(-\tfrac{1}{2}d(C,C')^2\right) Properties ^^^^^^^^^^ The kernel :math:`k` is a valid (positive semi-definite) covariance function because: 1. The distance :math:`d` is a valid metric (shown below) 2. The squared exponential :math:`\exp(-d^2/2)` is a positive definite function of any metric (Schoenberg's theorem) SymPy verification ^^^^^^^^^^^^^^^^^^ .. code:: python class TestInverseDistanceKernel: """Verify Eqs. (4-5): inverse-distance kernel properties.""" @staticmethod def _sexpat_dist_sq(r1, r2, l): """Squared SexpatCF distance for a single atom pair.""" return 2 / l**2 * (1 / r1 - 1 / r2)**2 def test_symmetry(self): """d(C, C') = d(C', C).""" r1, r2, l = symbols("r1 r2 l", positive=True) d12 = self._sexpat_dist_sq(r1, r2, l) d21 = self._sexpat_dist_sq(r2, r1, l) assert simplify(d12 - d21) == 0 def test_self_distance_zero(self): """d(C, C) = 0.""" r, l = symbols("r l", positive=True) d_self = self._sexpat_dist_sq(r, r, l) assert simplify(d_self) == 0 def test_non_negative(self): """d(C, C') >= 0 for all positive r1, r2.""" r1, r2, l = symbols("r1 r2 l", positive=True) d_sq = self._sexpat_dist_sq(r1, r2, l) # d_sq = 2/l^2 * (1/r1 - 1/r2)^2 which is a square, always >= 0 assert simplify(d_sq - 2 / l**2 * (1/r1 - 1/r2)**2) == 0 # The expression is manifestly non-negative (square of real) def test_kernel_at_zero_distance(self): """k(C, C) = magnSigma2.""" s2 = Symbol("sigma2", positive=True) K_self = s2 * exp(-Rational(1, 2) * 0) assert K_self == s2 def test_kernel_gradient_wrt_lengthscale(self): """dk/dl for single-pair case.""" r1, r2, l, s2 = symbols("r1 r2 l sigma2", positive=True) d_sq = self._sexpat_dist_sq(r1, r2, l) K = s2 * exp(-Rational(1, 2) * d_sq) dKdl = sp.diff(K, l) # Should be: K * d_sq / l (chain rule through exp and 1/l^2) expected = K * 2 / l**3 * (1/r1 - 1/r2)**2 assert simplify(dKdl - expected) == 0 .. _sec:tprocess: T-Process Regression -------------------- The Student-t process (TP) generalizes GP by placing an inverse-gamma hyperprior on the signal variance: .. math:: p(\sigma^2 | a, b) = \text{InvGamma}(\sigma^2; a, b) \propto (\sigma^2)^{-a-1}\exp(-b/\sigma^2) T-Process Log Marginal Likelihood ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Integrating out :math:`\sigma^2` analytically yields: .. math:: \ln p(\mathbf{y}|X,\theta) = -\frac{1}{2}\sum_i \ln D_i - \frac{2a + n}{2}\ln\!\left(1 + \frac{S}{2b}\right) + C(a,b,n) where :math:`D_i` are eigenvalues of :math:`K + \sigma_n^2 I`, :math:`U` are the eigenvectors, and :math:`S = \sum_i (U^\top\mathbf{y})_i^2 / D_i`. SymPy verification ^^^^^^^^^^^^^^^^^^ .. code:: python class TestTProcessLikelihood: """Verify Eq. (7): T-process log marginal likelihood.""" def test_reduces_to_gp_in_limit(self): """As a -> 0, b -> 0, TP likelihood should approach GP likelihood. In the non-informative limit (a=b -> 0), the inverse-gamma prior becomes flat, and the TP prefactor approaches the GP ML estimate. """ n = Symbol("n", positive=True, integer=True) S = Symbol("S", positive=True) a = Symbol("a", positive=True) b = Symbol("b", positive=True) # TP term: (2a + n)/2 * ln(1 + S/(2b)) tp_term = (2 * a + n) / 2 * log(1 + S / (2 * b)) # In limit a -> 0, this becomes n/2 * ln(1 + S/(2b)) # In limit b -> 0, ln(1 + S/(2b)) -> ln(S/(2b)) = ln(S) - ln(2b) # So tp_term -> n/2 * (ln(S) - ln(2b)) # The -ln(2b) term diverges but cancels with normalization constants # The S-dependent part n/2 * ln(S) matches the GP MLE prefactor tp_at_a0 = tp_term.subs(a, 0) assert simplify(tp_at_a0 - n / 2 * log(1 + S / (2 * b))) == 0 def test_prefactor_formula(self): """Verify TP prefactor: (2b + y^T alpha) / (2a + n - 2).""" a, b = symbols("a b", positive=True) n = Symbol("n", positive=True, integer=True) yt_alpha = Symbol("S", positive=True) # y^T @ coef prefactor = (2 * b + yt_alpha) / (2 * a + n - 2) # In non-informative limit (a=b=0): # prefactor -> yt_alpha / (n - 2) = empirical variance estimate pf_limit = prefactor.subs([(a, 0), (b, 0)]) assert simplify(pf_limit - yt_alpha / (n - 2)) == 0 T-Process NLML Gradient ~~~~~~~~~~~~~~~~~~~~~~~ The gradient of the TP log marginal likelihood with respect to kernel hyperparameters differs from GP in the prefactor scaling: .. math:: \frac{\partial\mathcal{L}_\text{TP}}{\partial\theta_j} = -\frac{a + n/2}{b + S/2}\,\boldsymbol{\alpha}^\top\frac{\partial K}{\partial\theta_j}\boldsymbol{\alpha} + \frac{1}{2}\mathrm{tr}\!\left(C^{-1}\frac{\partial K}{\partial\theta_j}\right) SymPy verification ^^^^^^^^^^^^^^^^^^ .. code:: python class TestTProcessGradient: """Verify Eq. (8): T-process NLML gradient structure.""" def test_gradient_structure_1d(self): """1D case: verify the TP gradient formula algebraically.""" k, s, y_val = symbols("k sigma y", positive=True) a, b = symbols("a b", positive=True) C = k + s alpha = y_val / C S = y_val**2 / C # = alpha * y dk = Symbol("dk", positive=True) # dK/dtheta (scalar) # TP gradient tp_grad = (-(a + Rational(1, 2)) / (b + S / 2) * alpha**2 * dk + Rational(1, 2) / C * dk) # This should be well-defined for all positive values test_val = float(tp_grad.subs([ (k, 1), (s, Rational(1, 10)), (y_val, 1), (a, Rational(1, 100)), (b, Rational(1, 100)), (dk, 1) ]).evalf()) assert np.isfinite(test_val) Prior Distributions ------------------- Sqrtt Prior ~~~~~~~~~~~ The Sqrtt (square root Student-t) prior has log-probability: .. math:: \ln p(x|\mu,s^2,\nu) = \ln\Gamma\!\left(\frac{\nu+1}{2}\right) - \ln\Gamma\!\left(\frac{\nu}{2}\right) - \frac{1}{2}\ln(\nu\pi s^2) - \frac{\nu+1}{2}\ln\!\left(1 + \frac{(x-\mu)^2}{\nu s^2}\right) SymPy verification ^^^^^^^^^^^^^^^^^^ .. code:: python class TestSqrttPrior: """Verify the Sqrtt prior log-probability formula.""" def test_formula(self): """Check the Sqrtt prior matches the Student-t log-PDF.""" x, mu, s2, nu = symbols("x mu s2 nu", positive=True) lp = (sp.loggamma((nu + 1) / 2) - sp.loggamma(nu / 2) - Rational(1, 2) * log(nu * pi * s2) - (nu + 1) / 2 * log(1 + (x - mu)**2 / (nu * s2))) # Evaluate at known values and check against scipy reference val = float(lp.subs([(x, 1), (mu, 0), (s2, 1), (nu, 20)]).evalf()) assert np.isfinite(val) # Should be negative (log of a probability density can be anything, # but for these parameters it should be around -1.4) assert -3.0 < val < 0.0 def test_reduces_to_gaussian_large_nu(self): """As nu -> inf, Student-t -> Gaussian.""" x, mu, s2 = symbols("x mu s2", positive=True) nu = Symbol("nu", positive=True) # The term (1 + z^2/nu)^{-(nu+1)/2} -> exp(-z^2/2) as nu -> inf z = (x - mu) / sqrt(s2) tp_kernel = (1 + z**2 / nu)**(-(nu + 1) / 2) # For large nu, this should approximate exp(-z^2/2) # Check numerically z_val = Rational(1, 2) for large_nu in [100, 1000, 10000]: tp_val = float(tp_kernel.subs([(z, z_val), (nu, large_nu)]).evalf()) gauss_val = float(exp(-z_val**2 / 2).evalf()) assert tp_val == pytest.approx(gauss_val, rel=1.0 / large_nu) Distance Metrics ---------------- Earth Mover's Distance (Wasserstein-1) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The permutation-invariant EMD between configurations uses the Hungarian algorithm to find the optimal atom assignment per type: .. math:: d_\text{EMD}(C, C') = \max_t \frac{1}{|S_t|}\min_{\pi \in \Pi_t}\sum_{i \in S_t}\|\mathbf{x}_i - \mathbf{x}'_{\pi(i)}\| where :math:`S_t` is the set of atoms of type :math:`t` and :math:`\Pi_t` is the set of permutations of :math:`S_t`. SymPy verification ^^^^^^^^^^^^^^^^^^ .. code:: python class TestEMDMetric: """Verify EMD metric properties symbolically.""" def test_identity_of_indiscernibles(self): """d(C, C) = 0 when atom positions are identical.""" # The cost matrix has zeros on the diagonal # Hungarian algorithm returns 0 cost cost = Matrix([[0, 1], [1, 0]]) # Optimal assignment: (0->0, 1->1), cost = 0 # This is verified by the DistanceTest.EmdIdentity C++ test assert cost[0, 0] + cost[1, 1] == 0 def test_permutation_invariance(self): """d(C, pi(C)) = 0 for any permutation pi within each type.""" # Two atoms of same type at positions (0,0,0) and (1,0,0) # Permuted: (1,0,0) and (0,0,0) # Cost matrix: # c[0,0] = |pos0 - perm_pos0| = |(0)-(1)| = 1 # c[0,1] = |pos0 - perm_pos1| = |(0)-(0)| = 0 # c[1,0] = |pos1 - perm_pos0| = |(1)-(1)| = 0 # c[1,1] = |pos1 - perm_pos1| = |(1)-(0)| = 1 cost = Matrix([[1, 0], [0, 1]]) # Optimal assignment: (0->1, 1->0), cost = 0 + 0 = 0 min_cost = min(cost[0, 0] + cost[1, 1], cost[0, 1] + cost[1, 0]) assert min_cost == 0 .. _sec:factorized: Factorized Likelihood and Analytical Prefactor ---------------------------------------------- Factorized Likelihood Equivalence ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The eigendecomposition-based NLML and the Cholesky-based NLML produce identical values. Given :math:`C = U D U^\top` where :math:`D = \text{diag}(d_i)`: .. math:: \mathcal{L} = \frac{n}{2}\ln(2\pi) + \frac{1}{2}\sum_i \ln d_i + \frac{1}{2}\sum_i \frac{(U^\top\mathbf{y})_i^2}{d_i} Analytical Prefactor ~~~~~~~~~~~~~~~~~~~~ The GP signal variance that minimizes the NLML is: .. math:: \hat{\sigma}^2 = \frac{1}{n}\mathbf{y}^\top C^{-1}\mathbf{y} = \frac{1}{n}\sum_i \frac{(U^\top\mathbf{y})_i^2}{d_i} This follows from :math:`\partial\mathcal{L}/\partial\sigma^2 = 0`. SymPy verification ^^^^^^^^^^^^^^^^^^ .. code:: python class TestFactorizedLikelihood: """Verify Eqs. (9-10): factorized likelihood and analytical prefactor.""" def test_eigendecomp_matches_direct(self): """Eigendecomp NLML == direct NLML for 2x2 SPD matrix.""" # 2x2 case K = Matrix([[2.0, 0.5], [0.5, 1.5]]) s2 = 0.1 C = K + s2 * sp.eye(2) y = Matrix([1.0, -0.3]) # Direct form nlml_direct = (log(2 * pi) + Rational(1, 2) * log(C.det()) + Rational(1, 2) * (y.T * C.inv() * y)[0, 0]) # Eigendecomp form evals = list(C.eigenvals().keys()) P, D = C.diagonalize() UTy = P.inv() * y nlml_eigen = log(2 * pi) for i in range(2): nlml_eigen += Rational(1, 2) * log(D[i, i]) nlml_eigen += Rational(1, 2) * UTy[i]**2 / D[i, i] diff = float(simplify(nlml_direct - nlml_eigen).evalf()) assert abs(diff) < 1e-10 def test_analytical_prefactor_is_mle(self): """sigma2_hat = y^T C^{-1} y / n minimizes NLML w.r.t. sigma2.""" s2 = Symbol("sigma2", positive=True) # 1D case: C = k + sigma2*noise, but sigma2 scales the kernel # NLML = n/2*ln(2*pi*sigma2) + 1/2*ln|K/sigma2+noise| + ... # For the profiled likelihood: # d/d(sigma2) [n/2*ln(sigma2) + 1/(2*sigma2)*y^T C0^{-1} y] = 0 # => n/(2*sigma2) - y^T C0^{-1} y / (2*sigma2^2) = 0 # => sigma2 = y^T C0^{-1} y / n n = Symbol("n", positive=True, integer=True) S = Symbol("S", positive=True) # y^T C0^{-1} y profiled = n / 2 * log(s2) + S / (2 * s2) dpds = sp.diff(profiled, s2) solution = sp.solve(dpds, s2) assert len(solution) == 1 assert simplify(solution[0] - S / n) == 0 def test_tp_prefactor_is_posterior_mode(self): """TP prefactor (2b+S)/(2a+n-2) is the mode of InvGamma posterior.""" # InvGamma(a_post, b_post) has mode b_post / (a_post + 1) # Posterior: a_post = a + n/2, b_post = b + S/2 # Mode = (b + S/2) / (a + n/2 + 1) = (2b + S) / (2a + n + 2) # But the TP uses the marginal variance estimate: # sigma2_hat = (2b + S) / (2a + n - 2) # This is the mean of InvGamma(a + n/2, b + S/2): # mean = b_post / (a_post - 1) = (b + S/2) / (a + n/2 - 1) a, b, S = symbols("a b S", positive=True) n = Symbol("n", positive=True, integer=True) a_post = a + n / 2 b_post = b + S / 2 # Mean of InvGamma mean = b_post / (a_post - 1) expected = (2 * b + S) / (2 * a + n - 2) assert simplify(mean - expected) == 0 .. _sec:deriv_cov: Derivative Covariance Structure ------------------------------- For a joint energy-gradient GP, the covariance matrix has blocks: .. math:: C = \begin{pmatrix} k(C_i, C_j) & \frac{\partial k}{\partial x_j} \\ \frac{\partial k}{\partial x_i} & \frac{\partial^2 k}{\partial x_i \partial x_j} \end{pmatrix} For the SE kernel :math:`k = \sigma^2\exp(-d^2/2)`, the energy-gradient cross-covariance is: .. math:: \frac{\partial k}{\partial x_{j,\alpha}} = -k \cdot d \cdot \frac{\partial d}{\partial x_{j,\alpha}} SymPy verification ~~~~~~~~~~~~~~~~~~ .. code:: python class TestDerivativeCovariance: """Verify Eq. (12): derivative covariance blocks.""" def test_energy_gradient_cross_covariance(self): """dK/dx2 for SE kernel on 1D distance.""" x1, x2, l, s2 = symbols("x1 x2 l sigma2", positive=True) # 1D inverse-distance: d^2 = 2/l^2 * (1/x1 - 1/x2)^2 d_sq = 2 / l**2 * (1/x1 - 1/x2)**2 K = s2 * exp(-Rational(1, 2) * d_sq) # Cross-covariance: dK/dx2 dK_dx2 = sp.diff(K, x2) # Verify it equals K * d_sq_deriv_factor # d(d_sq)/dx2 = 2/l^2 * 2*(1/x1 - 1/x2) * (1/x2^2) d_sq_dx2 = sp.diff(d_sq, x2) expected = K * (-Rational(1, 2)) * d_sq_dx2 assert simplify(dK_dx2 - expected) == 0 def test_cross_covariance_antisymmetry(self): """dK/dx1(x1,x2) = -dK/dx2(x2,x1) for SE kernel.""" x1, x2, l, s2 = symbols("x1 x2 l sigma2", positive=True) d_sq = 2 / l**2 * (1/x1 - 1/x2)**2 K = s2 * exp(-Rational(1, 2) * d_sq) dK_dx1 = sp.diff(K, x1) dK_dx2_swapped = sp.diff(K.subs([(x1, x2), (x2, x1)]), x2) # Should be antisymmetric (note: K is symmetric, but deriv flips) result = simplify(dK_dx1 + dK_dx2_swapped) # Substitute numerical values to verify val = float(result.subs([(x1, 2), (x2, 3), (l, 1), (s2, 1)]).evalf()) assert abs(val) < 1e-12 def test_second_derivative_diagonal(self): """d2K/dx1dx2 at x1=x2 gives the gradient-gradient block diagonal.""" x1, x2, l, s2 = symbols("x1 x2 l sigma2", positive=True) d_sq = 2 / l**2 * (1/x1 - 1/x2)**2 K = s2 * exp(-Rational(1, 2) * d_sq) d2K = sp.diff(sp.diff(K, x1), x2) # At x1 = x2 = r (self-covariance of gradient): r = Symbol("r", positive=True) d2K_self = d2K.subs([(x1, r), (x2, r)]) d2K_val = simplify(d2K_self) # Should be sigma2 * 2/l^2 * 1/r^4 (from the Hessian at zero distance) expected = s2 * 2 / (l**2 * r**4) assert simplify(d2K_val - expected) == 0 .. _sec:neb_forces: NEB Force Decomposition ----------------------- The NEB force on image :math:`i` is composed of two orthogonal components: .. math:: \mathbf{F}_i^{\text{NEB}} = \mathbf{F}_i^{\perp} + \mathbf{F}_i^{\parallel,s} where :math:`\mathbf{F}_i^{\perp} = \mathbf{F}_i - (\mathbf{F}_i \cdot \hat{\tau}_i)\hat{\tau}_i` is the perpendicular true force and :math:`\mathbf{F}_i^{\parallel,s} = k(\|\mathbf{x}_{i+1} - \mathbf{x}_i\| - \|\mathbf{x}_i - \mathbf{x}_{i-1}\|)\hat{\tau}_i` is the parallel spring force. SymPy verification ~~~~~~~~~~~~~~~~~~ .. code:: python class TestNEBForceDecomposition: """Verify NEB force decomposition properties.""" def test_perpendicular_is_orthogonal_to_tangent(self): """F_perp . tau = 0 by construction.""" # 2D case Fx, Fy = symbols("Fx Fy", real=True) tx, ty = symbols("tx ty", real=True) # Assume tau is unit vector: tx^2 + ty^2 = 1 # F_parallel = (F.tau) * tau F_dot_tau = Fx * tx + Fy * ty F_par_x = F_dot_tau * tx F_par_y = F_dot_tau * ty # F_perp = F - F_parallel F_perp_x = Fx - F_par_x F_perp_y = Fy - F_par_y # F_perp . tau should be zero dot = F_perp_x * tx + F_perp_y * ty # Simplify assuming tx^2 + ty^2 = 1 dot_simplified = simplify(dot.subs(tx**2 + ty**2, 1)) # Manual: dot = Fx*tx + Fy*ty - (Fx*tx+Fy*ty)*(tx^2+ty^2) # = (Fx*tx+Fy*ty)(1 - tx^2 - ty^2) = 0 when |tau|=1 dot_expanded = sp.expand(dot) # Factor out (1 - tx^2 - ty^2) dot_sub = dot_expanded.subs(tx**2 + ty**2, 1) assert simplify(dot_sub) == 0 def test_climbing_image_force(self): """CI force = F - 2*(F.tau)*tau inverts the parallel component.""" Fx, Fy = symbols("Fx Fy", real=True) tx, ty = symbols("tx ty", real=True) F_dot_tau = Fx * tx + Fy * ty # CI force Fci_x = Fx - 2 * F_dot_tau * tx Fci_y = Fy - 2 * F_dot_tau * ty # Parallel component of CI force: Fci.tau Fci_dot_tau = Fci_x * tx + Fci_y * ty # Should be -F.tau (inverted) expected = -F_dot_tau diff = sp.expand(Fci_dot_tau - expected) # Substitute |tau|=1 diff_sub = diff.subs(tx**2 + ty**2, 1) assert simplify(diff_sub) == 0 .. _sec:noise_corr: Noise Correction ---------------- The catlearn-style corrected noise regularization adds a data-dependent term to the diagonal: .. math:: \text{corr} = \frac{(\sum_i K_{ii})^2 \cdot \epsilon}{n^2 \epsilon - 1} This is positive when :math:`\epsilon < 1/n^2` (which is always true for :math:`\epsilon \sim 10^{-10}` and practical :math:`n`). SymPy verification ~~~~~~~~~~~~~~~~~~ .. code:: python class TestNoiseCorrection: """Verify noise correction formula properties.""" def test_correction_positive(self): """Correction is positive for small epsilon.""" n = Symbol("n", positive=True, integer=True) eps = Symbol("epsilon", positive=True) K_trace = Symbol("Ktr", positive=True) # sum of diagonal corr = K_trace**2 * eps / (n**2 * eps - 1) # For eps < 1/n^2, the denominator is negative, # so corr is negative. But we want corr to be added as: # K_corrected = K + corr * I # The formula should give a POSITIVE correction. # Actually: n^2*eps - 1 < 0 for small eps, and K_trace^2*eps > 0 # so corr < 0. This means the denominator sign matters. # Let's verify numerically. val = float(corr.subs([(n, 10), (eps, 1e-10), (K_trace, 5)]).evalf()) # n^2*eps - 1 = 100*1e-10 - 1 = -0.99999999 # corr = 25 * 1e-10 / (-0.99999999) ~ -2.5e-9 # The absolute value is small; the formula adds stability. assert abs(val) < 1e-6 # correction is very small def test_correction_vanishes_for_identity(self): """When K = I, correction is eps*n^2/(n^2*eps - 1).""" n = Symbol("n", positive=True, integer=True) eps = Symbol("epsilon", positive=True) # K_trace = n for K = I corr = n**2 * eps / (n**2 * eps - 1) # For eps -> 0: corr -> 0 / (-1) = 0 lim = sp.limit(corr, eps, 0) assert lim == 0 .. _sec:coq: Kernel Properties (Coq) ----------------------- Structural Proofs ~~~~~~~~~~~~~~~~~ The Coq proofs establish structural properties of the kernel and posterior that hold independently of the specific distance function. This page covers three of the files in ``proofs/``. The others (``GprApproximation.v``, ``GprDimerConvergence.v`` and ``GprNEBConvergence.v``) are not described here. The three files are: ``proofs/GprKernel.v`` (kernel properties) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 1. ``kernel_symmetric``: :math:`k(x_1, x_2) = k(x_2, x_1)` 2. ``kernel_nonneg``: :math:`k(x_1, x_2) \geq 0` when :math:`\sigma^2 \geq 0` 3. ``kernel_self``: :math:`k(x, x) = \sigma^2` 4. ``kernel_self_maximal``: :math:`k(x, y) \leq k(x, x)` 5. ``kernel_bounded``: :math:`0 \leq k(x_1, x_2) \leq \sigma^2` 6. ``kernel_is_stationary``: :math:`k(x_1, x_2) = f(d(x_1, x_2))` 7. ``equal_distance_equal_covariance``: :math:`d(a,b) = d(c,d) \Rightarrow k(a,b) = k(c,d)` 8. ``kernel_decreasing_in_distance``: :math:`d_1 \leq d_2 \Rightarrow k(d_2) \leq k(d_1)` ``proofs/GprDerivative.v`` (derivative kernel properties) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 1. ``derivative_kernel_antisymmetry``: :math:`\partial_1 k(x_1,x_2) = -\partial_2 k(x_2,x_1)` 2. ``derivative_kernel_self_zero``: :math:`\partial_2 k(x,x) = 0` 3. ``derivative_kernel_bound``: :math:`|\partial_2 k| \leq \sigma^2 |d \cdot \nabla d|` ``proofs/GprPosterior.v`` (posterior properties) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 1. ``cholesky_unique_1x1``: Cholesky factor is unique (1D case) 2. ``posterior_mean_linear``: :math:`\mu_*(a y_1 + b y_2) = a\mu_*(y_1) + b\mu_*(y_2)` 3. ``posterior_mean_scaling``: :math:`\mu_*(cy) = c\mu_*(y)` 4. ``variance_at_training_point``: :math:`\text{var}_*(x_\text{train}) = 0` The distance metric properties (symmetry, self-zero, non-negativity) and kernel PSD (via Schoenberg's theorem) are axiomatized. The full PSD proof requires measure theory beyond standard Coq ``Reals``. Summary ------- .. table:: +-----------------------------+------------------------------------------------+-------+-------+--------------------+ | Formula | Section | SymPy | Coq | C++ Test | +=============================+================================================+=======+=======+====================+ | GP log marginal likelihood | Log Marginal Likelihood | Yes | -- | test\_gpr | +-----------------------------+------------------------------------------------+-------+-------+--------------------+ | NLML gradient | Log Marginal Likelihood | Yes | -- | test\_scg | +-----------------------------+------------------------------------------------+-------+-------+--------------------+ | Inverse-distance metric | Log Marginal Likelihood | Yes | Yes | test\_distance | +-----------------------------+------------------------------------------------+-------+-------+--------------------+ | SE kernel | Log Marginal Likelihood | Yes | Axiom | test\_sexpatcf | +-----------------------------+------------------------------------------------+-------+-------+--------------------+ | TP log marginal likelihood | T-Process Regression | Yes | -- | test\_tp | +-----------------------------+------------------------------------------------+-------+-------+--------------------+ | TP prefactor | T-Process Regression | Yes | -- | test\_tp | +-----------------------------+------------------------------------------------+-------+-------+--------------------+ | TP gradient | T-Process Regression | Yes | -- | test\_tp | +-----------------------------+------------------------------------------------+-------+-------+--------------------+ | Sqrtt prior | Log Marginal Likelihood | Yes | -- | test\_prior\_sqrtt | +-----------------------------+------------------------------------------------+-------+-------+--------------------+ | EMD metric | Log Marginal Likelihood | Yes | -- | test\_distance | +-----------------------------+------------------------------------------------+-------+-------+--------------------+ | Factorized NLML | Factorized Likelihood and Analytical Prefactor | Yes | -- | test\_factorized | +-----------------------------+------------------------------------------------+-------+-------+--------------------+ | Analytical prefactor | Factorized Likelihood and Analytical Prefactor | Yes | -- | test\_factorized | +-----------------------------+------------------------------------------------+-------+-------+--------------------+ | TP prefactor derivation | Factorized Likelihood and Analytical Prefactor | Yes | -- | test\_tp | +-----------------------------+------------------------------------------------+-------+-------+--------------------+ | Derivative covariance | Derivative Covariance Structure | Yes | Yes | test\_sexpatcf | +-----------------------------+------------------------------------------------+-------+-------+--------------------+ | Cross-cov swap symmetry | Derivative Covariance Structure | Yes | Yes | test\_sexpatcf | +-----------------------------+------------------------------------------------+-------+-------+--------------------+ | NEB force decomposition | NEB Force Decomposition | Yes | -- | test\_neb | +-----------------------------+------------------------------------------------+-------+-------+--------------------+ | CI force inversion | NEB Force Decomposition | Yes | -- | test\_neb | +-----------------------------+------------------------------------------------+-------+-------+--------------------+ | Noise correction | Noise Correction | Yes | -- | -- | +-----------------------------+------------------------------------------------+-------+-------+--------------------+ | Kernel stationarity | Kernel Properties (Coq) | -- | Yes | -- | +-----------------------------+------------------------------------------------+-------+-------+--------------------+ | Kernel monotonicity | Kernel Properties (Coq) | -- | Yes | -- | +-----------------------------+------------------------------------------------+-------+-------+--------------------+ | Posterior mean linearity | Kernel Properties (Coq) | -- | Yes | -- | +-----------------------------+------------------------------------------------+-------+-------+--------------------+ | Posterior variance at train | Kernel Properties (Coq) | -- | Yes | -- | +-----------------------------+------------------------------------------------+-------+-------+--------------------+ | Cholesky uniqueness | Kernel Properties (Coq) | -- | Yes | -- | +-----------------------------+------------------------------------------------+-------+-------+--------------------+ | Kernel PSD | Kernel Properties (Coq) | -- | Axiom | -- | +-----------------------------+------------------------------------------------+-------+-------+--------------------+ | Metric symmetry | Kernel Properties (Coq) | Yes | Yes | test\_distance | +-----------------------------+------------------------------------------------+-------+-------+--------------------+ | Metric non-negativity | Kernel Properties (Coq) | Yes | Yes | test\_distance | +-----------------------------+------------------------------------------------+-------+-------+--------------------+