#!/usr/bin/env python3 """Finite checks for the central-sector repair and noncompletion extensions. Finite calculations are supplementary checks, not proofs or certificates of novelty. The large tail examples are checked through exact counts and Fourier coefficients; no 2**m by 2**m matrix is allocated for them. """ from __future__ import annotations import argparse import json from math import comb from pathlib import Path import numpy as np from verify_rigidity import nearest_phase_projection, phase_code, support_data SEED = 20261103 TOLERANCE = 3.0e-9 def operator_norm(matrix: np.ndarray) -> float: return float(np.linalg.norm(matrix, ord=2)) def check_tail_construction(m: int) -> dict: assert m % 4 == 3 tail_parameter = (m - 3) // 4 low = {word for word in range(1 << m) if word.bit_count() % 2 == 0 and word.bit_count() <= 2 * tail_parameter} high = {word for word in range(1 << m) if word.bit_count() % 2 == 1 and word.bit_count() >= 2 * tail_parameter + 3} chosen = low | high half_dimension = 1 << (m - 1) expected_deficit = comb(m - 1, (m - 1) // 2) assert len(low) == len(high) assert len(chosen) == half_dimension - expected_deficit mask = (1 << m) - 1 assert {word ^ mask for word in low} == high forbidden_edges = sum( ((word ^ (1 << position)) in chosen) for word in chosen for position in range(m) ) assert forbidden_edges == 0 # Fourier matrix elements of logical Z_j are exactly adjacency indicators: # _X = 1 if t = u xor 2**j, and zero otherwise. # The preceding exhaustive edge check therefore checks every KL entry. parity_sum = sum((-1) ** word.bit_count() for word in chosen) complement_coefficient = parity_sum / (1 << m) assert parity_sum == 0 # Physical dual rails preserve every basis vector's weight m. physical_words = [] for logical_word in range(1 << m): physical_word = 0 for position in range(m): bit = (logical_word >> position) & 1 physical_word |= bit << (2 * position) physical_word |= (1 - bit) << (2 * position + 1) assert physical_word.bit_count() == m physical_words.append(physical_word) physical_mask = (1 << (2 * m)) - 1 physical_set = set(physical_words) assert all((word ^ physical_mask) in physical_set for word in physical_words) signs = np.array([[2 * ((word >> j) & 1) - 1 for j in range(2 * m)] for word in physical_words], dtype=float) covariance = signs.T @ signs / (1 << m) expected_covariance = np.kron(np.eye(m), np.array([[1, -1], [-1, 1]])) covariance_error = float(np.max(np.abs(covariance - expected_covariance))) assert covariance_error == 0 # Every complementary matrix entry is zero, so the general-rank nearest # phase formula is K - 2 sum_pairs |P[x, complement(x)]| = K. nearest_squared_distance = half_dimension return { "kind": "exact_tail_noncompletion", "logical_coordinates": m, "physical_coordinates": 2 * m, "ambient_dimension": 1 << m, "maximum_code_rank_K": half_dimension, "tail_code_rank_k": len(chosen), "rank_deficit": expected_deficit, "rank_fraction": len(chosen) / half_dimension, "even_count": len(low), "odd_count": len(high), "forbidden_cube_edges": forbidden_edges, "complement_fourier_coefficient": complement_coefficient, "covariance_error": covariance_error, "largest_covariance_eigenvalue": float(np.linalg.eigvalsh(covariance)[-1]), "nearest_maximal_code_squared_distance": nearest_squared_distance, "normalized_squared_distance": nearest_squared_distance / half_dimension, "check_method": "Exact tail counts, exhaustive cube-edge check, exact parity sum, and small covariance matrix; no global code projector allocated.", } def check_operator_repair(n: int, projection: np.ndarray, label: str) -> dict: data = support_data(n, [word for word in range(1 << n) if word.bit_count() == n // 2]) dimension, rank = data["dimension"], data["rank"] identity = np.eye(dimension) reflection = 2 * projection - identity eigenvalues, eigenvectors = np.linalg.eigh(projection) positive_space = eigenvectors[:, -rank:] negative_space = eigenvectors[:, :rank] assert np.max(np.abs(eigenvalues[:rank])) < TOLERANCE assert np.max(np.abs(eigenvalues[-rank:] - 1)) < TOLERANCE alphas, defects = [], [] maximum_cs_spectral_error = 0.0 maximum_operator_identity_error = 0.0 observables = [] for position in range(n): observable = np.diag(data["signs"][:, position]) observables.append(observable) compression = positive_space.conj().T @ observable @ positive_space other_compression = negative_space.conj().T @ observable @ negative_space alpha = float(np.trace(compression).real / rank) defect = operator_norm(compression - alpha * np.eye(rank)) residual = reflection @ observable + observable @ reflection - 2 * alpha * identity maximum_operator_identity_error = max( maximum_operator_identity_error, abs(operator_norm(residual) - 2 * defect) ) maximum_cs_spectral_error = max( maximum_cs_spectral_error, float(np.max(np.abs(np.linalg.eigvalsh(other_compression) + np.linalg.eigvalsh(compression)[::-1]))), ) alphas.append(alpha) defects.append(defect) epsilon = max(defects) alpha_bound = (n - 1) * epsilon / n assert max(abs(alpha) for alpha in alphas) <= alpha_bound + TOLERANCE assert abs(sum(alphas)) < TOLERANCE assert maximum_operator_identity_error < TOLERANCE assert maximum_cs_spectral_error < TOLERANCE filtered = reflection.copy() maximum_step_excess = 0.0 for position in range(n - 1): next_filtered = (filtered - observables[position] @ filtered @ observables[position]) / 2 step_norm = operator_norm(filtered - next_filtered) step_bound = defects[position] + (abs(alphas[position]) if position == 0 else 0) maximum_step_excess = max(maximum_step_excess, step_norm - step_bound) assert step_norm <= step_bound + TOLERANCE filtered = next_filtered complementary_only = np.zeros_like(reflection) complementary_only[np.arange(dimension), data["complements"]] = reflection[np.arange(dimension), data["complements"]] filter_selection_error = operator_norm(filtered - complementary_only) assert filter_selection_error < TOLERANCE eta = (n - 1 / n) * epsilon filter_distance = operator_norm(reflection - filtered) assert filter_distance <= eta + TOLERANCE rounded = nearest_phase_projection(data, projection) rounded_reflection = 2 * rounded - identity phase_rounding_distance = operator_norm(filtered - rounded_reflection) if eta < 1: assert phase_rounding_distance <= eta + TOLERANCE repair_distance = operator_norm(projection - rounded) repair_bound = min(1.0, eta) assert repair_distance <= repair_bound + TOLERANCE return { "kind": "central_operator_repair", "label": label, "n": n, "ambient_dimension": dimension, "rank": rank, "epsilon": epsilon, "largest_absolute_alpha": max(abs(alpha) for alpha in alphas), "alpha_bound": alpha_bound, "maximum_cs_spectral_error": maximum_cs_spectral_error, "maximum_operator_identity_error": maximum_operator_identity_error, "maximum_filter_step_excess": max(0.0, maximum_step_excess), "filter_selection_error": filter_selection_error, "filter_distance": filter_distance, "eta": eta, "phase_rounding_distance": phase_rounding_distance, "repair_distance": repair_distance, "repair_bound": repair_bound, "repair_bound_is_nontrivial": eta < 1, } def run_checks() -> dict: rng = np.random.default_rng(SEED) checks = [check_tail_construction(m) for m in (3, 7, 11)] for n in (4, 6): data = support_data(n, [word for word in range(1 << n) if word.bit_count() == n // 2]) for repetition in range(4): gaussian = rng.normal(size=(data["dimension"], data["rank"])) gaussian = gaussian + 1j * rng.normal(size=gaussian.shape) encoding, _ = np.linalg.qr(gaussian, mode="reduced") checks.append(check_operator_repair(n, encoding @ encoding.conj().T, f"random_{repetition}")) exact_encoding = phase_code(data, rng.uniform(-np.pi, np.pi, data["rank"])) gaussian = rng.normal(size=(data["dimension"], data["dimension"])) gaussian = gaussian + 1j * rng.normal(size=gaussian.shape) generator = (gaussian + gaussian.conj().T) / 2 generator /= operator_norm(generator) values, vectors = np.linalg.eigh(generator) for angle in (0.001, 0.01, 0.05): unitary = (vectors * np.exp(1j * angle * values)) @ vectors.conj().T encoding = unitary @ exact_encoding checks.append(check_operator_repair(n, encoding @ encoding.conj().T, f"near_optimal_angle_{angle}")) operator_checks = [check for check in checks if check["kind"] == "central_operator_repair"] return { "label": "Finite supplementary checks; not a proof or novelty certificate.", "seed": SEED, "numpy_version": np.__version__, "tolerance": TOLERANCE, "all_checks_passed": True, "check_count": len(checks), "maximum_cs_spectral_error": max(check["maximum_cs_spectral_error"] for check in operator_checks), "maximum_operator_identity_error": max(check["maximum_operator_identity_error"] for check in operator_checks), "maximum_filter_step_excess": max(check["maximum_filter_step_excess"] for check in operator_checks), "nontrivial_operator_bounds_checked": sum(check["repair_bound_is_nontrivial"] for check in operator_checks), "checks": checks, } def main() -> None: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--output", type=Path, default=Path(__file__).with_name("extensions_results.json")) arguments = parser.parse_args() result = run_checks() arguments.output.write_text(json.dumps(result, indent=2) + "\n", encoding="utf-8") print(json.dumps({key: value for key, value in result.items() if key != "checks"}, indent=2)) if __name__ == "__main__": main()