File size: 10,623 Bytes
e740887
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
228
"""Regenerate synthetic tables and verification results. Run from any directory."""
from __future__ import annotations
import csv
import itertools
import json
import platform
import sys
from pathlib import Path
from math import acos, degrees, factorial, log2, sqrt
import numpy as np
import scipy
import sympy as sp
from scipy.sparse import coo_matrix
from scipy.sparse.linalg import eigsh

ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(Path(__file__).resolve().parent))
from orynthra import (
    LinearEdge, observable_closure, six_wing_actions, six_wing_rank_formula,
    storage_cutoff, symmetric_cutoff, minimum_storage_mean, photon_capacity,
    photon_sector, maximum_packed_dimension, pack_items, representation_cutoff,
    permutation_matrix, helmert_matrix, simplex_code, mean_photon_lower_bound,
)


def dump_json(path, obj):
    path.write_text(json.dumps(obj, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")


def write_csv(path, rows):
    with path.open("w", newline="", encoding="utf-8") as fh:
        writer = csv.DictWriter(fh, fieldnames=list(rows[0]))
        writer.writeheader()
        writer.writerows(rows)


def cayley_gap(m=6):
    """Normalized Laplacian for {cycle, inverse cycle, (0 1)} on S_m."""
    group = list(itertools.permutations(range(m)))
    index = {g: i for i, g in enumerate(group)}
    generators = [tuple((i + 1) % m for i in range(m)),
                  tuple((i - 1) % m for i in range(m)),
                  tuple([1, 0] + list(range(2, m)))]
    rr, cc = [], []
    for i, g in enumerate(group):
        for s in generators:
            rr.append(i)
            cc.append(index[tuple(s[g[j]] for j in range(m))])
    transition = coo_matrix((np.full(len(rr), 1/3), (rr, cc)),
                            shape=(len(group), len(group))).tocsr()
    # Fixed start vector makes the numerical eigensolver run reproducible.
    values = eigsh(transition, k=4, which="LA", return_eigenvectors=False,
                   v0=np.linspace(0.1, 1.0, len(group)), tol=1e-12)
    values = sorted(values, reverse=True)
    return float(1 - values[1]), [float(v) for v in values]


def six_simplex_verification():
    m = 6
    v, number, k = simplex_code(m, 2)
    max_gram = float(np.max(np.abs(v.T @ v - np.eye(m))))
    max_gate, max_comm, max_unitary = 0.0, 0.0, 0.0
    for perm in itertools.permutations(range(m)):
        p = permutation_matrix(perm)
        u = v @ p @ v.T
        max_gate = max(max_gate, float(np.linalg.norm(u @ v - v @ p, ord=2)))
        max_comm = max(max_comm, float(np.linalg.norm(u @ number - number @ u, ord=2)))
        max_unitary = max(max_unitary, float(np.linalg.norm(u.T @ u - np.eye(m), ord=2)))
    h = sp.zeros(m, m)
    for i in range(m):
        h[0, i] = 1 / sp.sqrt(m)
    for j in range(1, m):
        for i in range(j):
            h[j, i] = 1 / sp.sqrt(j * (j + 1))
        h[j, j] = -j / sp.sqrt(j * (j + 1))
    exact_gram = sp.simplify(h.T * h) == sp.eye(m)
    exact_simplex = sp.simplify(h[1:, :].T * h[1:, :]) == sp.eye(m) - sp.ones(m, m) / m
    result = {
        "messages": m, "permutations_checked": factorial(m), "modes": 2,
        "coherent_cutoff": k, "storage_cutoff": storage_cutoff(m, 2),
        "coherent_mean_photons": k * (m - 1) / m,
        "storage_mean_photons": minimum_storage_mean(m, 2),
        "simplex_angle_degrees": degrees(acos(-1 / (m - 1))),
        "symbolic_gram_identity": bool(exact_gram),
        "symbolic_simplex_identity": bool(exact_simplex),
        "max_gram_entry_error": max_gram, "max_gate_operator_error": max_gate,
        "max_number_commutator_operator_error": max_comm,
        "max_unitarity_operator_error": max_unitary,
        "interpretation": "Exact algebraic identities plus floating-point checks; not hardware validation",
    }
    np.savetxt(ROOT / "data" / "six_label_encoding.csv", v, delimiter=",")
    return result


def multiplicity_verification():
    """Two S5 orbits, logical irreps [1,1,4,4], two modes, cutoff 3."""
    m, size = 5, 10
    h = helmert_matrix(m)
    # Logical basis order: first 5-point orbit, then second 5-point orbit.
    block_h = np.zeros((size, size))
    block_h[:m, :m] = h
    block_h[m:, m:] = h
    # Map the two trivial components to physical indices 0,1; first standard
    # to the 4-photon-degeneracy sector N=3 (indices 6...9); second standard
    # to leftover scalar physical reps (indices 2...5).
    target = [0, 6, 7, 8, 9, 1, 2, 3, 4, 5]
    rearrange = np.zeros((size, size))
    for old, new in enumerate(target):
        rearrange[new, old] = 1
    v = rearrange @ block_h
    number = np.diag([0, 1, 1, 2, 2, 2, 3, 3, 3, 3])
    total_defect = 0.0
    max_comm = 0.0
    for perm in itertools.permutations(range(m)):
        p = permutation_matrix(perm)
        logical = np.zeros((size, size))
        logical[:m, :m] = p
        logical[m:, m:] = p
        standard = h[1:] @ p @ h[1:].T
        physical = np.eye(size)
        physical[6:, 6:] = standard
        total_defect += np.linalg.norm(physical @ v - v @ logical, "fro") ** 2 / size
        max_comm = max(max_comm, float(np.linalg.norm(physical @ number - number @ physical)))
    dims, capacities = [1, 1, 4, 4], [1, 2, 3, 4]
    matched = maximum_packed_dimension(dims, capacities)
    return {
        "logical_irrep_dimensions": dims, "sector_dimensions": capacities,
        "total_dimension_test_passes": sum(capacities) >= sum(dims),
        "largest_irrep_test_passes": max(capacities) >= max(dims),
        "full_packing_exists": pack_items(dims, capacities) is not None,
        "maximum_matched_dimension": matched,
        "predicted_normalized_group_defect": 2 * (1 - matched / size),
        "measured_normalized_group_defect": float(total_defect / factorial(m)),
        "permutations_checked": factorial(m),
        "number_commutator_error": max_comm,
        "minimal_exact_cutoff": representation_cutoff(dims, 2),
    }


def main():
    for d in ["data", "verification", "figures"]:
        (ROOT / d).mkdir(exist_ok=True)
    n = 36
    actions = six_wing_actions(n)
    observation = np.eye(n, dtype=int)[0:1]
    rows = []
    for mask in range(64):
        active = [i for i in range(6) if mask & (1 << i)]
        edges = [LinearEdge(0, 0, actions[i], str(i)) for i in active]
        bases, trace = observable_closure([observation], edges)
        rank = len(bases[0])
        formula = six_wing_rank_formula(n, active)
        assert rank == formula
        rows.append({"mask": mask, "active_wings": len(active),
                     "active_names": ";".join(["Lily", "Tachy", "Raven", "Enya", "Evie", "Kaya"][i] for i in active),
                     "rank": rank, "formula": formula,
                     "source_bits": n, "retained_fraction": rank/n,
                     "closure_rounds": len(trace)-1})
    write_csv(ROOT / "data" / "six_wing_closure.csv", rows)
    max_proper_rank = max(row["rank"] for row in rows if row["mask"] < 63)

    rows = []
    for m in [1, 2, 3, 6]:
        for messages in [1, 2, 3, 4, 6, 8, 16, 64, 256, 4096, 1048576]:
            kc = symmetric_cutoff(messages, m)
            ks = storage_cutoff(messages, m)
            rows.append({"modes": m, "messages": messages, "logical_bits": log2(messages),
                         "storage_cutoff": ks,
                         "symmetric_cutoff": "impossible" if kc is None else kc,
                         "storage_mean_photons": minimum_storage_mean(messages, m),
                         "symmetric_mean_photons": "impossible" if kc is None else kc*(messages-1)/messages,
                         "cutoff_ratio": "undefined" if not ks or kc is None else kc/ks})
    write_csv(ROOT / "data" / "photon_frontiers.csv", rows)

    rows = []
    messages = 64
    for k in range(storage_cutoff(messages, 2), symmetric_cutoff(messages, 2) + 2):
        capacities = [photon_sector(2, j) for j in range(k+1)]
        matched = maximum_packed_dimension([1, messages - 1], capacities)
        rows.append({"messages": messages, "modes": 2, "cutoff": k,
                     "physical_dimension": photon_capacity(2, k), "matched_dimension": matched,
                     "minimum_normalized_group_defect": 2*(1-matched/messages)})
    write_csv(ROOT / "data" / "covariance_plateau.csv", rows)

    rows = []
    for bits in [6, 12, 20, 36]:
        for modes in [1, 2, 6]:
            for error in [0, .01, .05, .1, .2, .4]:
                rows.append({"independent_query_bits": bits, "modes": modes, "query_error": error,
                             "necessary_mean_photons": mean_photon_lower_bound(bits, modes, error)})
    write_csv(ROOT / "data" / "approximate_query_energy.csv", rows)

    six = six_simplex_verification()
    multiplicity = multiplicity_verification()
    gap, eigenvalues = cayley_gap(6)
    # Norm of the two-generator commutator for M=3,...,16.
    commutators = []
    for m in range(3, 17):
        a = permutation_matrix(tuple((i+1) % m for i in range(m)))
        b = permutation_matrix(tuple([1,0] + list(range(2,m))))
        commutators.append(float(np.linalg.norm(a @ b - b @ a, 2)))
    report = {
        "release": "ORYNTHRA-H6 v1.0.0", "seed": 20261009,
        "six_wing_subsets_checked": 64, "six_wing_source_dimension": n,
        "maximum_proper_subset_rank": max_proper_rank,
        "six_label_simplex": six, "multiplicity_trap": multiplicity,
        "one_mode_commutator": {"sizes_checked": list(range(3,17)),
                                "maximum_deviation_from_sqrt3": max(abs(x-sqrt(3)) for x in commutators),
                                "equal_generator_operator_error_lower_bound": sqrt(3)/4},
        "S6_generator_gap": {"generators": "6-cycle, inverse 6-cycle, transposition (0 1)",
                             "group_size": factorial(6), "normalized_laplacian_gap": gap,
                             "largest_transition_eigenvalues": eigenvalues,
                             "below_threshold_generator_mean_defect_lower_bound": 2*gap*(1-1/6),
                             "numeric_not_formal_certificate": True},
        "status": "All assertions in reproduce.py completed; see separate pytest report",
    }
    report["maximum_proper_subset_rank"] = int(report["maximum_proper_subset_rank"])
    dump_json(ROOT / "verification" / "results.json", report)
    dump_json(ROOT / "verification" / "environment.json", {
        "python": sys.version, "platform": platform.platform(),
        "numpy": np.__version__, "scipy": scipy.__version__, "sympy": sp.__version__,
    })
    print(json.dumps(report, indent=2))


if __name__ == "__main__":
    main()