#!/usr/bin/env python3 """Exact finite-transcript algebra and conservative certificate verification. All inputs are exact Fractions or numbers converted through their decimal string. This module checks finite algebraic certificates; it neither infers global convexity from measurements nor interprets solver status as a proof. Python standard library only. See Chapters 2, 6, and 7 of the manuscript. """ from __future__ import annotations from dataclasses import dataclass from fractions import Fraction as Q from typing import Sequence def rational(value): if isinstance(value, Q): return value if isinstance(value, bool): raise TypeError("Boolean is not a numerical certificate coefficient") return Q(str(value)) def zeros(n): return [[Q(0) for _ in range(n)] for _ in range(n)] def dot(a, b): if len(a) != len(b): raise ValueError("Vector dimensions differ") return sum((rational(x) * rational(y) for x, y in zip(a, b)), Q(0)) def outer(a, b): return [[rational(x) * rational(y) for y in b] for x in a] def symmetric_outer(a, b): if len(a) != len(b): raise ValueError("Vector dimensions differ") return [[(rational(a[i])*rational(b[j])+rational(b[i])*rational(a[j]))/2 for j in range(len(a))] for i in range(len(a))] def psd_exact(matrix): """Return an exact PSD decision and an elimination audit for rational input. A zero diagonal with a nonzero remaining row is a genuine obstruction, not a tolerance case. This is an exact Schur-complement algorithm. """ a = [[rational(x) for x in row] for row in matrix] n = len(a) if any(len(row) != n for row in a): raise ValueError("Matrix must be square") if any(a[i][j] != a[j][i] for i in range(n) for j in range(n)): raise ValueError("Matrix must be exactly symmetric") pivots = [] for k in range(n): p = a[k][k] pivots.append(str(p)) if p < 0: return False, {"reason": "negative_pivot", "index": k, "pivots": pivots} if p == 0: if any(a[k][j] != 0 for j in range(k+1, n)): return False, {"reason": "nonzero_zero_pivot_row", "index": k, "pivots": pivots} continue for i in range(k+1, n): for j in range(i, n): v = a[i][j] - a[i][k]*a[k][j]/p a[i][j] = v a[j][i] = v return True, {"reason": "exact_schur_complements", "pivots": pivots} @dataclass(frozen=True) class AffineForm: loss: tuple gram: tuple constant: Q = Q(0) @classmethod def make(cls, loss, gram=None, constant=0): f = tuple(rational(x) for x in loss) n = len(f) g = zeros(n) if gram is None else [[rational(x) for x in row] for row in gram] if len(g) != n or any(len(row) != n for row in g): raise ValueError("Loss and Gram dimensions differ") if any(g[i][j] != g[j][i] for i in range(n) for j in range(n)): raise ValueError("Gram coefficient must be symmetric") return cls(f, tuple(tuple(row) for row in g), rational(constant)) def scaled(self, coefficient): c = rational(coefficient) return self.make([c*x for x in self.loss], [[c*x for x in row] for row in self.gram], c*self.constant) def plus(self, other): if len(self.loss) != len(other.loss): raise ValueError("Affine dimensions differ") n = len(self.loss) return self.make([self.loss[i]+other.loss[i] for i in range(n)], [[self.gram[i][j]+other.gram[i][j] for j in range(n)] for i in range(n)], self.constant+other.constant) def evaluate(self, losses, gram): n = len(self.loss) if len(losses) != n or len(gram) != n or any(len(row) != n for row in gram): raise ValueError("Evaluation dimensions differ") return self.constant+dot(self.loss, losses)+sum( (self.gram[i][j]*rational(gram[i][j]) for i in range(n) for j in range(n)), Q(0)) def gd_coefficients(h, horizon): h = rational(h) if horizon < 0: raise ValueError("Horizon must be nonnegative") return [[-h if j < i else Q(0) for j in range(horizon+1)] for i in range(horizon+1)] def interpolation_form(coefficients, i, j, mu=0, smoothness=1): """Affine Gram form of the strong interpolation slack I_ij.""" mu, L = rational(mu), rational(smoothness) if not 0 <= mu < L: raise ValueError("Require 0 <= mu < L; mu=L is a separate quadratic case") n = len(coefficients) if any(len(row) != n for row in coefficients): raise ValueError("Coefficient array must be square") if not 0 <= i < n or not 0 <= j < n: raise IndexError("Interpolation index out of range") a = [rational(coefficients[i][k])-rational(coefficients[j][k]) for k in range(n)] ej = [Q(k == j) for k in range(n)] b = [Q(k == i)-Q(k == j)-mu*a[k] for k in range(n)] sa, aa, bb = symmetric_outer(ej, a), outer(a, a), outer(b, b) p = [[-sa[k][l]-mu*aa[k][l]/2-bb[k][l]/(2*(L-mu)) for l in range(n)] for k in range(n)] f = [Q(0)]*n f[i] += 1 f[j] -= 1 return AffineForm.make(f, p) def compensation_certificate(h): """Compile the universal certificate; PSD must still be checked.""" s = gd_coefficients(h, 3) target = AffineForm.make([Q(2,3), -1, 0, Q(1,3)]) weighted = AffineForm.make([0]*4) weights = {(0,1):Q(7,9), (0,2):Q(2,9), (2,0):Q(1,3), (3,1):Q(2,9), (3,2):Q(1,9)} for pair, weight in weights.items(): weighted = weighted.plus(interpolation_form(s, *pair).scaled(weight)) residual = target.plus(weighted.scaled(-1)) return target, weighted, residual, weights def residual_lower_bound(residual, trace_bound, value_bounds, psd_shift=0): """Check and return s-delta*T-sum |r_i| B_i, Chapter 6. The caller must independently justify the model's trace/value bounds and that the subtracted constraints have nonnegative multipliers. """ T, delta = rational(trace_bound), rational(psd_shift) bounds = [rational(x) for x in value_bounds] n = len(residual.loss) if T < 0 or delta < 0 or len(bounds) != n or any(x < 0 for x in bounds): raise ValueError("Bounds and PSD shift must be nonnegative and compatible") p = [[residual.gram[i][j]+(delta if i == j else 0) for j in range(n)] for i in range(n)] valid, audit = psd_exact(p) if not valid: return {"verified": False, "reason": "PSD_check_failed", "audit": audit} bound = residual.constant-delta*T-sum( (abs(c)*b for c, b in zip(residual.loss, bounds)), Q(0)) return {"verified": True, "lower_bound_exact": str(bound), "audit": audit} def trajectory_tube(eta, smoothness, initial_gradient, errors, initial_error=0, mu=0): """Exact rational displacement and value envelopes for bounded gradient error.""" eta, L, mu = map(rational, [eta, smoothness, mu]) G, E = map(rational, [initial_gradient, initial_error]) if not (0 <= mu < L and 0 < eta*L < 2 and G >= 0 and E >= 0): raise ValueError("Invalid class, step, or initial bounds") q = max(abs(1-eta*mu), abs(1-eta*L)) if mu else Q(1) rows = [{"position": E, "value": G*E+L*E*E/2, "gradient": G}] for err in errors: err = rational(err) if err < 0: raise ValueError("Gradient error bound must be nonnegative") E = q*E+eta*err G *= q rows.append({"position": E, "value": G*E+L*E*E/2, "gradient": G}) return rows def linear_error_allowance(coefficients, tube, measurement_bounds): c = [rational(x) for x in coefficients] nu = [rational(x) for x in measurement_bounds] if len(c) != len(tube) or len(c) != len(nu) or any(x < 0 for x in nu): raise ValueError("Invalid measurement envelope") return sum((abs(w)*(r["value"]+v) for w, r, v in zip(c, tube, nu)), Q(0))