File size: 10,588 Bytes
1f85192
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
#!/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:
    # <t|_X Z_j |u>_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()