#!/usr/bin/env python3 """Independent exact and numerical tests of constructive spectral recovery. Exact: graph cycle matrices and recovery from a magnetic ground-state Hessian; finite-rank determinant normalization/interpolation; critical block inertia. Numerical: independently assembled magnetic, gauge-covariant linear finite elements for Kirchhoff metric graphs, using NumPy/SciPy only in that section. Run: python3 validation_v2/constructive_verification.py The exact checks are not formal machine proofs. FEM checks are floating-point consistency tests, not certified eigenvalue enclosures or evidence of novelty. """ from __future__ import annotations from collections import Counter, deque from fractions import Fraction as Q from itertools import permutations from math import isqrt from pathlib import Path import argparse import json import random SEED = 20261005 def transpose(a): return [list(row) for row in zip(*a)] def mm(a, b): bt = transpose(b) return [[sum((x * y for x, y in zip(row, col)), Q(0)) for col in bt] for row in a] def inverse(a): n = len(a) aug = [[Q(x) for x in row] + [Q(i == j) for j in range(n)] for i, row in enumerate(a)] for j in range(n): pivot = next((k for k in range(j, n) if aug[k][j]), None) if pivot is None: raise ValueError("singular exact matrix") aug[j], aug[pivot] = aug[pivot], aug[j] q = aug[j][j] aug[j] = [x / q for x in aug[j]] for i in range(n): if i != j and aug[i][j]: q = aug[i][j] aug[i] = [x - q * y for x, y in zip(aug[i], aug[j])] return [row[n:] for row in aug] def rank(a): a = [[Q(x) for x in row] for row in a] r = 0 for j in range(len(a[0]) if a else 0): pivot = next((i for i in range(r, len(a)) if a[i][j]), None) if pivot is None: continue a[r], a[pivot] = a[pivot], a[r] p = a[r][j] a[r] = [x / p for x in a[r]] for i in range(len(a)): if i != r and a[i][j]: p = a[i][j] a[i] = [x - p * y for x, y in zip(a[i], a[r])] r += 1 if r == len(a): break return r def solve_full_column_rank(a, b): rows, n = len(a), len(a[0]) aug = [[Q(x) for x in row] + [Q(value)] for row, value in zip(a, b)] r = 0 pivots = [] for j in range(n): pivot = next((i for i in range(r, rows) if aug[i][j]), None) if pivot is None: continue aug[r], aug[pivot] = aug[pivot], aug[r] p = aug[r][j] aug[r] = [x / p for x in aug[r]] for i in range(rows): if i != r and aug[i][j]: p = aug[i][j] aug[i] = [x - p * y for x, y in zip(aug[i], aug[r])] pivots.append(j) r += 1 if len(pivots) != n: raise ValueError("edge parameters not uniquely identifiable") if any(not any(row[:n]) and row[n] for row in aug): raise ValueError("inconsistent exact linear system") result = [Q(0)] * n for i, p in enumerate(pivots): result[p] = aug[i][-1] return result def determinant(a): a = [[Q(x) for x in row] for row in a] result = Q(1) for j in range(len(a)): pivot = next((i for i in range(j, len(a)) if a[i][j]), None) if pivot is None: return Q(0) if pivot != j: a[j], a[pivot] = a[pivot], a[j] result = -result p = a[j][j] result *= p for i in range(j + 1, len(a)): q = a[i][j] / p for k in range(j + 1, len(a)): a[i][k] -= q * a[j][k] return result def fundamental_cycles(nvertices, edges, *, reverse=False): """Cycle rows: positive chord u->v, followed by tree path v->u.""" adjacency = [[] for _ in range(nvertices)] for e, (u, v) in enumerate(edges): adjacency[u].append((v, e)) adjacency[v].append((u, e)) for row in adjacency: row.sort(reverse=reverse) root = nvertices - 1 if reverse else 0 seen, tree = {root}, set() queue = deque([root]) while queue: u = queue.popleft() for v, e in adjacency[u]: if v not in seen: seen.add(v) tree.add(e) queue.append(v) if len(seen) != nvertices: raise ValueError("disconnected graph") tree_adjacency = [[] for _ in range(nvertices)] for e in tree: u, v = edges[e] tree_adjacency[u].append((v, e, 1)) tree_adjacency[v].append((u, e, -1)) chords = [e for e in range(len(edges)) if e not in tree] cycles = [] for chord in chords: u, v = edges[chord] predecessor = {v: None} queue = deque([v]) while u not in predecessor: node = queue.popleft() for next_node, edge, sign in tree_adjacency[node]: if next_node not in predecessor: predecessor[next_node] = (node, edge, sign) queue.append(next_node) row = [Q(0)] * len(edges) row[chord] = 1 node = u while node != v: prev, edge, sign = predecessor[node] row[edge] += sign node = prev cycles.append(row) return cycles, chords def edge_design(cycles): return [[cycles[i][e] * cycles[j][e] for e in range(len(cycles[0]))] for i in range(len(cycles)) for j in range(i, len(cycles))] def exact_square_root(q): a, b = isqrt(q.numerator), isqrt(q.denominator) if a * a != q.numerator or b * b != q.denominator: raise ValueError("rational quantity is not an exact rational square") return Q(a, b) def polynomial_multiply(a, b): result = [Q(0)] * (len(a) + len(b) - 1) for i, x in enumerate(a): for j, y in enumerate(b): result[i + j] += x * y return result def spectral_polynomial(a): """Exact coefficients of det(a+zI), independently by permutations.""" n = len(a) result = [Q(0)] * (n + 1) for permutation in permutations(range(n)): inversions = sum(permutation[i] > permutation[j] for i in range(n) for j in range(i + 1, n)) product = [Q((-1) ** inversions)] for i, j in enumerate(permutation): product = polynomial_multiply(product, [Q(a[i][j]), Q(1)] if i == j else [Q(a[i][j])]) for i, value in enumerate(product): result[i] += value return result def poly_eval(p, z): result = Q(0) for c in reversed(p): result = result * z + c return result def inertia_without_zero_pivots(a): """Exact congruence elimination for the nondegenerate cases below.""" a = [[Q(x) for x in row] for row in a] negative = 0 for j in range(len(a)): p = a[j][j] if p == 0: raise ValueError("zero pivot requires a 2x2 inertia block") negative += int(p < 0) for i in range(j + 1, len(a)): for k in range(j + 1, len(a)): a[i][k] -= a[i][j] * a[j][k] / p return negative class Verification: def __init__(self): self.assertions = Counter() def check(self, category, condition, detail=None): if not condition: raise AssertionError(f"{category}: {detail!r}") self.assertions[category] += 1 def graphs(): return { "K4": (4, [(u, v) for u in range(4) for v in range(u + 1, 4)]), "K3_3": (6, [(u, v) for u in range(3) for v in range(3, 6)]), "triangular_prism": (6, [(0, 1), (1, 2), (0, 2), (3, 4), (4, 5), (3, 5), (0, 3), (1, 4), (2, 5)]), "wheel_W6": (6, [(0, i) for i in range(1, 6)] + [(1, 2), (2, 3), (3, 4), (4, 5), (1, 5)]), "cube": (8, [(u, v) for u in range(8) for v in range(u + 1, 8) if (u ^ v).bit_count() == 1]) } def vertex_connected_after_removal(n, edges, removed): available = set(range(n)) - set(removed) seen = {next(iter(available))} stack = list(seen) while stack: u = stack.pop() for a, b in edges: v = b if a == u else a if b == u else None if v is not None and v in available and v not in seen: seen.add(v) stack.append(v) return seen == available def exact_graph_checks(v, rng): reports, fem_cases = [], [] for name, (nv, edges) in graphs().items(): c, chords = fundamental_cycles(nv, edges) incidence = [[Q((head == node) - (tail == node)) for tail, head in edges] for node in range(nv)] v.check("cycle_boundary_zero", mm(c, transpose(incidence)) == [[Q(0)] * nv for _ in c]) v.check("cycle_rank_and_chord_coordinates", len(c) == len(edges) - nv + 1 and [[row[e] for e in chords] for row in c] == [[Q(i == j) for j in range(len(c))] for i in range(len(c))]) for a in range(nv): for b in range(a + 1, nv): v.check("graph_three_vertex_connectivity", vertex_connected_after_removal(nv, edges, (a, b))) design = edge_design(c) v.check("edge_metric_linear_identifiability", rank(design) == len(edges)) c2, _ = fundamental_cycles(nv, edges, reverse=True) u = [[row[e] for e in chords] for row in c2] v.check("cycle_basis_unimodular", abs(determinant(u)) == 1 and mm(u, c) == c2) for case in range(12): lengths = [Q(rng.randint(1, 10), rng.randint(2, 12)) for _ in edges] total = sum(lengths, Q(0)) weighted = [[value * ell for value, ell in zip(row, lengths)] for row in c] gram = mm(weighted, transpose(c)) hessian = [[2 * value / total for value in row] for row in inverse(gram)] observed = [[2 * value for value in row] for row in inverse(hessian)] rhs = [observed[i][j] for i in range(len(c)) for j in range(i, len(c))] weights = solve_full_column_rank(design, rhs) recovered_total = exact_square_root(sum(weights, Q(0))) recovered_lengths = [weight / recovered_total for weight in weights] v.check("hessian_total_length_reconstruction", recovered_total == total) v.check("hessian_all_edge_lengths_reconstruction", recovered_lengths == lengths) v.check("hessian_observation_is_LQ", observed == [[total * value for value in row] for row in gram]) gram2 = mm([[value * ell for value, ell in zip(row, lengths)] for row in c2], transpose(c2)) v.check("cycle_gram_coordinate_covariance", gram2 == mm(mm(u, gram), transpose(u))) inv_u = inverse(u) hessian2 = [[2 * value / total for value in row] for row in inverse(gram2)] v.check("hessian_coordinate_covariance", hessian2 == mm(mm(transpose(inv_u), hessian), inv_u)) if case == 0: reports.append({"graph": name, "vertices": nv, "edges": len(edges), "cycle_rank": len(c), "design_rank": rank(design), "lengths": [str(ell) for ell in lengths], "total_length": str(total), "cycle_matrix": [[int(x) for x in row] for row in c], "exact_recovered_lengths": [str(ell) for ell in recovered_lengths]}) if name in ("K4", "K3_3", "cube"): fem_cases.append((name, nv, edges, lengths, chords, gram, total)) cycle_edges = [(0, 1), (1, 2), (2, 3), (0, 3)] cc, _ = fundamental_cycles(4, cycle_edges) v.check("nonidentifiable_cycle_negative_control", rank(edge_design(cc)) == 1 < len(cycle_edges)) return reports, fem_cases def magnetic_fem_ground(nv, edges, lengths, chords, theta, subdivisions): import numpy as np from scipy.linalg import eigh nodes = nv + len(edges) * (subdivisions - 1) stiffness = np.zeros((nodes, nodes), dtype=np.complex128) mass = np.zeros_like(stiffness) chord_flux = dict(zip(chords, theta)) cursor = nv for edge, ((tail, head), ell) in enumerate(zip(edges, lengths)): interiors = list(range(cursor, cursor + subdivisions - 1)) cursor += subdivisions - 1 sequence = [tail] + interiors + [head] h = float(ell) / subdivisions phase = np.exp(-1j * chord_flux.get(edge, 0.0) / subdivisions) local_k = np.array([[1, -phase], [-phase.conjugate(), 1]], dtype=np.complex128) / h local_m = h / 6 * np.array([[2, phase], [phase.conjugate(), 2]], dtype=np.complex128) for a, b in zip(sequence, sequence[1:]): idx = np.ix_([a, b], [a, b]) stiffness[idx] += local_k mass[idx] += local_m return float(eigh(stiffness, mass, subset_by_index=[0, 0], driver="gvx", check_finite=True)[0][0]) def fem_checks(v, fem_cases): results = [] for name, nv, edges, lengths, chords, gram, total in fem_cases: beta = len(chords) inv_gram = inverse(gram) vectors = [[int(i == j) for i in range(beta)] for j in range(min(2, beta))] vectors.append([1 if i % 2 == 0 else -1 for i in range(beta)]) for subdivisions in (4, 8): baseline = magnetic_fem_ground(nv, edges, lengths, chords, [0.0] * beta, subdivisions) for vector in vectors: predicted = sum((Q(vector[i]) * inv_gram[i][j] * vector[j] for i in range(beta) for j in range(beta)), Q(0)) / total errors = [] for epsilon in (0.01, 0.005, 0.0025): positive = magnetic_fem_ground(nv, edges, lengths, chords, [epsilon * a for a in vector], subdivisions) negative = magnetic_fem_ground(nv, edges, lengths, chords, [-epsilon * a for a in vector], subdivisions) curvature_half = ((positive + negative) / 2 - baseline) / epsilon ** 2 relative = abs(curvature_half - float(predicted)) / float(predicted) v.check("fem_hessian_normalization", relative < 0.002, (name, subdivisions, vector, epsilon, relative)) v.check("fem_time_reversal_symmetry", abs(positive - negative) < 1e-9) errors.append(relative) results.append({"graph": name, "subdivisions_per_edge": subdivisions, "flux_direction": vector, "epsilon_radians": epsilon, "baseline_numerical_eigenvalue": baseline, "predicted_lambda_over_epsilon_squared": float(predicted), "observed_lambda_over_epsilon_squared": curvature_half, "relative_error": relative}) v.check("fem_small_flux_consistency", max(errors) < 0.002) return results def critical_coupling_checks(v, rng): examples = [] n = 4 t = [Q(8), Q(11), Q(15), Q(20)] base = [[t[i] if i == j else Q(0) for j in range(n)] for i in range(n)] expected_poly = spectral_polynomial(base) expected = [x / expected_poly[0] for x in expected_poly] for r in (1, 2, 3): for case in range(15): factor = [[Q(rng.randint(-4, 4), 50) for _ in range(r)] for _ in range(n)] interaction = mm(factor, transpose(factor)) v.check("coupling_rank_bound", rank(interaction) <= r) settings = [Q((i + 1) ** 2) for i in range(r + 1)] polys, dets = [], [] for setting in settings: e = [[base[i][j] - setting * interaction[i][j] for j in range(n)] for i in range(n)] v.check("coupled_matrix_positive_gershgorin", all(e[i][i] > sum(abs(e[i][j]) for j in range(n) if j != i) for i in range(n))) p = spectral_polynomial(e) v.check("permutation_determinant_independent_check", p[0] == determinant(e)) polys.append([a / p[0] for a in p]) dets.append(p[0]) alpha = [det / dets[0] for det in dets] weights = [Q(1)] * len(settings) for i, setting in enumerate(settings): for j, other in enumerate(settings): if i != j: weights[i] *= -other / (setting - other) denominator = sum((w * a for w, a in zip(weights, alpha)), Q(0)) restored = [sum((weights[i] * alpha[i] * polys[i][j] for i in range(r + 1)), Q(0)) / denominator for j in range(n + 1)] v.check("determinant_normalization_denominator_positive", denominator > 0) v.check("finite_rank_spectral_polynomial_recovery", restored == expected) naive = [sum((weights[i] * polys[i][j] for i in range(r + 1)), Q(0)) for j in range(n + 1)] if any(any(row) for row in interaction): v.check("uncalibrated_products_negative_control", naive != expected) # Positive-axis ratios independently approach the determinant # calibrations. Record exact finite-s ratios rather than assume # eigenvectors or simultaneously diagonalizable matrices. if case == 0: ratios = [[poly_eval(polys[0], s) / poly_eval(polys[i], s) for i in range(r + 1)] for s in (Q(100), Q(1000), Q(10000))] v.check("positive_axis_calibration_convergence", all( abs(ratios[-1][i] - alpha[i]) <= abs(ratios[0][i] - alpha[i]) for i in range(r + 1))) examples.append({"rank_bound": r, "settings": [str(u) for u in settings], "T_diagonal": [str(a) for a in t], "interaction_commutes_with_T": mm(base, interaction) == mm(interaction, base), "alphas": [str(a) for a in alpha], "weights": [str(w) for w in weights], "reconstructed_D_T_coefficients": [str(a) for a in restored], "positive_axis_ratios": [[str(a) for a in row] for row in ratios]}) # Exact critical-coupling cutoff counts using full block inertia, which is # independent of the determinant-polynomial interpolation test above. hard = [Q(3), Q(5)] w = [[Q(1, 5), Q(0)], [Q(1, 7), Q(1, 8)], [Q(0), Q(1, 6)], [Q(1, 9), Q(-1, 10)]] cutoff = Q(1) correction = mm([[a / (f - cutoff) for a, f in zip(row, hard)] for row in w], transpose(w)) inertia_rows = [] for setting in (Q(1), Q(4), Q(9)): effective = [[base[i][j] - setting * correction[i][j] for j in range(n)] for i in range(n)] for a in (Q(1, 4), Q(1, 9), Q(1, 16), Q(1, 25), Q(1, 100)): root = exact_square_root(a * setting) # Order hard block first so exact congruence elimination begins # with two strictly positive pivots. physical_minus_cutoff = [[Q(0)] * (n + 2) for _ in range(n + 2)] for i in range(2): physical_minus_cutoff[i][i] = hard[i] - cutoff for i in range(n): for j in range(n): physical_minus_cutoff[i + 2][j + 2] = a * base[i][j] - (cutoff if i == j else 0) for j in range(2): physical_minus_cutoff[j][i + 2] = physical_minus_cutoff[i + 2][j] = root * w[i][j] shifted_effective = [[effective[i][j] - (cutoff / a if i == j else 0) for j in range(n)] for i in range(n)] full_count = inertia_without_zero_pivots(physical_minus_cutoff) effective_count = inertia_without_zero_pivots(shifted_effective) v.check("critical_low_cutoff_exact_inertia_identity", full_count == effective_count) inertia_rows.append({"a": str(a), "u": str(setting), "physical_count_below_cutoff": full_count, "effective_count_below_cutoff_over_a": effective_count}) # The manuscript's rank-two ambiguity, and arbitrary-finite-setting # parity construction, independently tested as multisets. ta, ca, tb, cb = [Q(11), Q(12)], [Q(2), Q(2)], [Q(10), Q(13)], [Q(1), Q(3)] for setting in (Q(1), Q(2)): v.check("rank_two_two_scan_nonuniqueness", sorted(t - setting * c for t, c in zip(ta, ca)) == sorted(t - setting * c for t, c in zip(tb, cb))) v.check("rank_two_unperturbed_spectra_differ", sorted(ta) != sorted(tb)) for k in range(1, 6): settings = list(range(1, k + 1)) displacements = [10 ** i for i in range(k)] t0 = 10 + k * (1 + sum(displacements)) even, odd = [], [] for mask in range(2 ** k): point = (Q(t0 + sum(settings[i] * displacements[i] for i in range(k) if mask >> i & 1)), Q(1 + sum(displacements[i] for i in range(k) if mask >> i & 1))) (even if mask.bit_count() % 2 == 0 else odd).append(point) for setting in settings: observed_a = sorted(t - setting * c for t, c in even) observed_b = sorted(t - setting * c for t, c in odd) v.check("arbitrary_setting_parity_nonuniqueness", observed_a == observed_b and min(observed_a) > 0) v.check("parity_unperturbed_spectra_differ", sorted(t for t, c in even) != sorted(t for t, c in odd)) return {"determinant_examples": examples, "critical_cutoff_inertia_examples": inertia_rows} def run(skip_fem=False): rng, v = random.Random(SEED), Verification() graph_reports, fem_cases = exact_graph_checks(v, rng) coupling = critical_coupling_checks(v, rng) exact_assertions = sum(v.assertions.values()) fem_reports = [] if skip_fem else fem_checks(v, fem_cases) return {"status": "PASS", "seed": SEED, "exact_assertions": exact_assertions, "numerical_assertions": sum(v.assertions.values()) - exact_assertions, "assertions_total": sum(v.assertions.values()), "assertions_by_category": dict(sorted(v.assertions.items())), "flux_convention": "Cycle holonomies in radians; positive chord entry 1; tree-edge flux 0", "hessian_formula": "lambda0(theta)=theta^T Q^-1 theta/L+O(|theta|^4), H=2Q^-1/L", "inverse_metric_algorithm": "S=2H^-1=LQ; solve S=sum_e w_e c_e c_e^T; L=sqrt(sum_e w_e); ell_e=w_e/L", "graphs": graph_reports, "finite_element_normalization": fem_reports, "critical_coupling": coupling, "limitations": ["Exact rational finite tests are not formal proofs for all graphs or infinite operators.", "The graph reconstruction assumes the labeled graph and a known fundamental cycle-coordinate basis.", "Graph topology recovery from an unmarked period lattice requires separate theory and is not validated here.", "FEM checks use floating-point eigenvalues and are not rigorous spectral enclosures.", "No originality, priority or 10/10 importance certification is provided."]} def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--output", type=Path, default=Path(__file__).resolve().parent / "constructive_verification_results.json") parser.add_argument("--skip-fem", action="store_true") args = parser.parse_args() result = run(args.skip_fem) args.output.parent.mkdir(parents=True, exist_ok=True) args.output.write_text(json.dumps(result, indent=2) + "\n", encoding="utf-8") print(json.dumps({"status": result["status"], "exact_assertions": result["exact_assertions"], "numerical_assertions": result["numerical_assertions"], "assertions_total": result["assertions_total"], "worst_fem_relative_error": max((r["relative_error"] for r in result["finite_element_normalization"]), default=None), "assertions_by_category": result["assertions_by_category"], "output": str(args.output.resolve())}, indent=2)) if __name__ == "__main__": main()