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
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
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
#!/usr/bin/env python3
"""Reproducible finite-dimensional checks and exact sector-capacity evaluations.

Numerical checks illustrate the mathematical statements; they do not replace
their proofs or establish scientific priority. All logarithms are base two.
Requires Python 3.10+, NumPy, SciPy; Matplotlib only for the optional figure.
Run: python3 verify.py --output-dir results
"""
from __future__ import annotations

import argparse
import csv
import itertools
import json
import math
from pathlib import Path

import numpy as np
from scipy.linalg import eigh, expm
from scipy.special import gammaln
from scipy.stats import binom

SEED = 20261101
ATOL = 3e-11
I2 = np.eye(2, dtype=complex)
X = np.array([[0, 1], [1, 0]], dtype=complex)
Y = np.array([[0, -1j], [1j, 0]], dtype=complex)
Z = np.diag([1, -1]).astype(complex)
NUMBER = np.diag([0, 1]).astype(complex)


def kron_all(ops: list[np.ndarray]) -> np.ndarray:
    out = np.ones((1, 1), dtype=complex)
    for op in ops:
        out = np.kron(out, op)
    return out


def local(op: np.ndarray, site: int, n: int) -> np.ndarray:
    return kron_all([op if j == site else I2 for j in range(n)])


def collective(op: np.ndarray, sites: list[int], n: int) -> np.ndarray:
    return sum((local(op, j, n) for j in sites), np.zeros((2**n, 2**n), complex))


def embed(op: np.ndarray, sites: list[int], n: int) -> np.ndarray:
    """Embed an arbitrary operator with the specified ordered qubit sites."""
    k = len(sites)
    assert op.shape == (2**k, 2**k)
    out = np.zeros((2**n, 2**n), complex)
    for col in range(2**n):
        bits = [(col >> (n - 1 - j)) & 1 for j in range(n)]
        subcol = sum(bits[site] << (k - 1 - r) for r, site in enumerate(sites))
        for subrow in range(2**k):
            rowbits = bits.copy()
            for r, site in enumerate(sites):
                rowbits[site] = (subrow >> (k - 1 - r)) & 1
            row = sum(bit << (n - 1 - j) for j, bit in enumerate(rowbits))
            out[row, col] += op[subrow, subcol]
    return out


def random_hermitian(d: int, rng: np.random.Generator) -> np.ndarray:
    a = rng.normal(size=(d, d)) + 1j * rng.normal(size=(d, d))
    h = (a + a.conj().T) / 2
    return h / np.linalg.norm(h, 2)


def reduced_pure(psi: np.ndarray, keep: list[int], n: int) -> np.ndarray:
    others = [j for j in range(n) if j not in keep]
    matrix = psi.reshape([2] * n).transpose(keep + others).reshape(2**len(keep), -1)
    return matrix @ matrix.conj().T


def reduced_density(rho: np.ndarray, keep: list[int], n: int) -> np.ndarray:
    others = [j for j in range(n) if j not in keep]
    order = keep + others
    tensor = rho.reshape([2] * (2 * n)).transpose(order + [j + n for j in order])
    dk, de = 2**len(keep), 2**len(others)
    return np.trace(tensor.reshape(dk, de, dk, de), axis1=1, axis2=3)


def entropy(rho: np.ndarray) -> float:
    eigenvalues = np.linalg.eigvalsh(rho)
    positive = eigenvalues[eigenvalues > 1e-13]
    return float(-np.sum(positive * np.log2(positive)))


def trace_distance(a: np.ndarray, b: np.ndarray) -> float:
    return float(np.abs(np.linalg.eigvalsh((a - b + (a - b).conj().T) / 2)).sum() / 2)


def maximally_entangled_encoding(code: np.ndarray) -> np.ndarray:
    """Physical qubits, pure |0> bath qubit, then reference qubit."""
    assert code.shape[1] == 2
    amplitudes = np.zeros((code.shape[0], 2, 2), complex)
    amplitudes[:, 0, 0] = code[:, 0] / math.sqrt(2)
    amplitudes[:, 0, 1] = code[:, 1] / math.sqrt(2)
    return amplitudes.reshape(-1)


def evolve(psi: np.ndarray, h_phys_bath: np.ndarray, duration: float) -> np.ndarray:
    return (expm(-1j * duration * h_phys_bath) @ psi.reshape(h_phys_bath.shape[0], 2)).reshape(-1)


def twirl_two_spins_with_reference(rho: np.ndarray) -> np.ndarray:
    """Exact SU(2) Haar twirl for two surviving spins and a reference qubit."""
    singlet = np.array([0, 1, -1, 0], complex) / math.sqrt(2)
    p0 = np.outer(singlet, singlet.conj())
    p1 = np.eye(4) - p0
    out = np.zeros_like(rho)
    for projector, dimension in [(p0, 1), (p1, 3)]:
        projected = np.kron(projector, I2) @ rho @ np.kron(projector, I2)
        reference_state = np.trace(projected.reshape(4, 2, 4, 2), axis1=0, axis2=2)
        out += np.kron(projector / dimension, reference_state)
    return out


def check_su2_moving_boundary(rng: np.random.Generator) -> dict:
    n = 4
    js = [collective(a / 2, list(range(n)), n) for a in (X, Y, Z)]
    casimir = sum(j @ j for j in js)
    eigenvalues, vectors = eigh(casimir)
    code = vectors[:, np.abs(eigenvalues) < 1e-10]
    assert code.shape == (16, 2)
    for j in js:
        assert np.linalg.norm(j @ code) < ATOL
    initial = maximally_entangled_encoding(code)
    psi = initial.copy()
    stages = [(list(range(4)), [], 0.83), ([1, 2, 3], [0], 1.27), ([2, 3], [0, 1], 1.91)]
    stage_details = []
    for active, lost, duration in stages:
        jx, jy, jz = [collective(a / 2, active, n) for a in (X, Y, Z)]
        h = 0.73 * np.kron(jx, X) + 0.51 * np.kron(jy, Z) + 0.27 * np.kron(jz, Y)
        h += 0.19 * np.kron(jx @ jx, Y)
        h += np.kron(np.eye(16), 0.23 * X + 0.37 * Z)
        if lost:
            h += 1.1 * embed(random_hermitian(2 ** (len(lost) + 1), rng), lost + [4], 5)
        assert np.linalg.norm(h - h.conj().T) < ATOL
        psi = evolve(psi, h, duration)
        stage_details.append({"active": active, "lost": lost, "duration_hbar_units": duration})
    # Physical positions 2 and 3 survive; position 5 is the reference.
    target = reduced_pure(initial, [2, 3, 5], 6)
    noisy = reduced_pure(psi, [2, 3, 5], 6)
    after_twirl = twirl_two_spins_with_reference(noisy)
    residual = trace_distance(after_twirl, target)
    assert residual < ATOL
    before = trace_distance(noisy, target)
    assert before > 1e-4, "Bath should visibly change the irrep gauge before twirling"
    return {
        "physical_qubits": 4,
        "bath_dimension": 2,
        "reference_dimension": 2,
        "joint_dimension": 64,
        "stages": stage_details,
        "trace_distance_before_final_twirl": before,
        "trace_distance_after_final_twirl": residual,
        "state_norm_error": float(abs(np.vdot(psi, psi) - 1)),
    }


def check_u1_moving_boundary(rng: np.random.Generator) -> dict:
    n, weight = 6, 3
    indices = [x for x in range(2**n) if x.bit_count() == weight]
    a = rng.normal(size=(len(indices), 2)) + 1j * rng.normal(size=(len(indices), 2))
    q, _ = np.linalg.qr(a)
    code = np.zeros((2**n, 2), complex)
    code[indices] = q
    initial = maximally_entangled_encoding(code)
    psi = initial.copy()
    stages = [(list(range(n)), 0.7), ([1, 2, 3, 4, 5], 1.3), ([1, 3, 4, 5], 2.1)]
    for active, duration in stages:
        charge = collective(NUMBER, active, n)
        h = np.kron(charge, 0.71 * X + 0.19 * Z)
        h += np.kron(charge @ charge, 0.13 * Y - 0.17 * Z)
        h += np.kron(np.eye(2**n), 0.31 * X + 0.23 * Y)
        psi = evolve(psi, h, duration)
    keep = [1, 3, 4, 5, 7]
    target = reduced_pure(initial, keep, 8)
    noisy = reduced_pure(psi, keep, 8)
    residual = trace_distance(noisy, target)
    assert residual < ATOL
    return {
        "physical_qubits": n,
        "weight": weight,
        "erased_positions": [0, 2],
        "joint_dimension": 256,
        "trace_distance_to_bare_erasure_without_twirl": residual,
    }


def ten_seal_supports() -> list[list[str]]:
    x, y = "1111100000", "1100011100"
    complement = lambda s: "".join("1" if c == "0" else "0" for c in s)
    return [[x, complement(x)], [y, complement(y)]]


def reduced_code_operator(mu: int, nu: int, erased: tuple[int, ...]) -> dict:
    """Sparse exact reduced |mu_L><nu_L| on the erased region.

    Values are doubled, hence integer, to keep the KL test exact.
    """
    supports = ten_seal_supports()
    kept = [j for j in range(10) if j not in erased]
    result: dict[tuple[str, str], int] = {}
    for a in supports[mu]:
        for b in supports[nu]:
            if all(a[j] == b[j] for j in kept):
                key = ("".join(a[j] for j in erased), "".join(b[j] for j in erased))
                result[key] = result.get(key, 0) + 1
    return result


def check_ten_seal_code() -> dict:
    counts, correctable = {}, {}
    for size in range(6):
        good = []
        for erased in itertools.combinations(range(10), size):
            if (reduced_code_operator(0, 0, erased) == reduced_code_operator(1, 1, erased)
                    and not reduced_code_operator(0, 1, erased)
                    and not reduced_code_operator(1, 0, erased)):
                good.append(list(erased))
        counts[str(size)] = {"correctable": len(good), "total": math.comb(10, size)}
        correctable[str(size)] = good
    assert counts["1"]["correctable"] == 10
    assert [0, 2] not in correctable["2"]
    # Inhomogeneous single-site fields: at time pi/2,
    # exp[-i*pi/2*(Z_0-Z_2)] = Z_0 Z_2 = logical Z on this code.
    signs = []
    for support in ten_seal_supports():
        signs.append([(-1) ** (int(s[0]) + int(s[2])) for s in support])
    assert signs == [[1, 1], [-1, -1]]
    return {
        "zero_based_positions": True,
        "correctability_counts": counts,
        "correctable_erased_subsets": correctable,
        "inhomogeneous_counterexample": {
            "Hamiltonian_in_hbar_units": "Z_0 - Z_2",
            "duration": math.pi / 2,
            "logical_action": "Z",
            "Bell_reference_trace_distance_from_identity": 1.0,
            "exact_basis_signs": signs,
        },
    }


def logchoose(n: int, k: int) -> float:
    if k < 0 or k > n:
        return -math.inf
    return float((gammaln(n + 1) - gammaln(k + 1) - gammaln(n - k + 1)) / math.log(2))


def charge_marginal_entropy(b: int, w: int, size: int) -> float:
    """Entropy of any `size` sites of uniform fixed-weight b-qubit state."""
    logd = logchoose(b, w)
    answer = logd
    for k in range(max(0, w - (b - size)), min(size, w) + 1):
        log_rest = logchoose(b - size, w - k)
        probability = 2 ** (logchoose(size, k) + log_rest - logd)
        answer -= probability * log_rest
    return max(0.0, answer)


def spin_multiplicity(n: int, twice_j: int) -> int:
    if twice_j < 0 or twice_j > n or (n - twice_j) % 2:
        return 0
    k = (n - twice_j) // 2
    return math.comb(n, k) - (math.comb(n, k - 1) if k else 0)


def singlet_marginal_entropy(b: int, size: int) -> float:
    """Schur-Weyl entropy of a marginal of the uniform total-singlet state."""
    assert b % 2 == 0
    d = spin_multiplicity(b, 0)
    answer = 0.0
    normalization = 0.0
    for twice_j in range(size % 2, min(size, b - size) + 1, 2):
        m_left = spin_multiplicity(size, twice_j)
        m_right = spin_multiplicity(b - size, twice_j)
        if not m_left or not m_right:
            continue
        probability = (m_left * m_right) / d
        eigenvalue = m_right / (d * (twice_j + 1))
        normalization += probability
        answer -= probability * math.log2(eigenvalue)
    assert abs(normalization - 1) < 1e-10
    return answer


def sector_capacity(b: int, p: float, family: str, w: int | None = None) -> float:
    if p >= 0.5:
        return 0.0
    if family == "charge":
        w = b // 2 if w is None else w
        entropies = [charge_marginal_entropy(b, w, size) for size in range(b + 1)]
    elif family == "singlet":
        entropies = [singlet_marginal_entropy(b, size) for size in range(b + 1)]
    else:
        raise ValueError(f"Unknown family: {family}")
    return float(sum(binom.pmf(t, b, p) * (entropies[b - t] - entropies[t]) for t in range(b + 1)))


def check_marginal_entropy_formulas() -> dict:
    """Compare combinatorial formulas with independently diagonalized matrices."""
    residuals = {}
    for b in (4, 6):
        w = b // 2
        weight_projector = np.diag([float(x.bit_count() == w) for x in range(2**b)])
        rho_charge = weight_projector / np.trace(weight_projector)
        js = [collective(a / 2, list(range(b)), b) for a in (X, Y, Z)]
        _, vectors = eigh(sum(j @ j for j in js))
        d = spin_multiplicity(b, 0)
        rho_singlet = vectors[:, :d] @ vectors[:, :d].conj().T / d
        for family, rho, formula in [
            ("charge", rho_charge, lambda size: charge_marginal_entropy(b, w, size)),
            ("singlet", rho_singlet, lambda size: singlet_marginal_entropy(b, size)),
        ]:
            errors = [abs(entropy(reduced_density(rho, list(range(size)), b)) - formula(size))
                      for size in range(b + 1)]
            residuals[f"{family}_b{b}_maximum_entropy_error_bits"] = max(errors)
            assert max(errors) < ATOL
    return residuals


def capacity_data() -> tuple[list[dict], dict]:
    rows = []
    for b in (4, 10, 20, 100):
        for p in (0.1, 0.25, 0.4):
            charge = sector_capacity(b, p, "charge")
            singlet = sector_capacity(b, p, "singlet")
            unrestricted = b * (1 - 2 * p)
            lower_bound = unrestricted - 0.5 * math.log2(2 / p)
            spin_lower_bound = unrestricted - (0.5 + 1.5 * math.log2((b + 2) / ((b + 1) * p)))
            assert charge <= unrestricted + 1e-9
            assert singlet <= charge + 1e-9
            assert charge >= lower_bound - 1e-9
            assert singlet >= spin_lower_bound - 1e-9
            rows.append({
                "block_qubits": b,
                "erasure_probability": p,
                "unrestricted_qubits_per_block": unrestricted,
                "fixed_half_charge_qubits_per_block": charge,
                "singlet_qubits_per_block": singlet,
                "fixed_half_charge_per_physical_qubit": charge / b,
                "singlet_per_physical_qubit": singlet / b,
                "charge_constant_penalty_lower_bound_per_block": lower_bound,
                "singlet_constant_penalty_lower_bound_per_block": spin_lower_bound,
            })
    checks = {}
    for b in (2, 4, 10):
        assert abs(sector_capacity(b, 0, "charge") - logchoose(b, b // 2)) < ATOL
        assert abs(sector_capacity(b, 0, "singlet") - math.log2(spin_multiplicity(b, 0))) < ATOL
        assert sector_capacity(b, 0.5, "charge") == 0
        assert sector_capacity(b, 0.75, "singlet") == 0
    # For half filling the fixed-interior-p penalty tends to this constant.
    for p in (0.1, 0.25, 0.4):
        b = 400
        actual_penalty = b * (1 - 2 * p) - sector_capacity(b, p, "charge")
        predicted = (math.log((1 - p) / p) - (1 - 2 * p)) / (2 * math.log(2))
        checks[str(p)] = {
            "block_qubits": b,
            "numerical_charge_penalty": actual_penalty,
            "predicted_large_block_constant": predicted,
            "absolute_difference": abs(actual_penalty - predicted),
        }
        assert abs(actual_penalty - predicted) < 0.04
        spin_penalty = b * (1 - 2 * p) - sector_capacity(b, p, "singlet")
        checks[str(p)]["numerical_singlet_penalty"] = spin_penalty
        checks[str(p)]["predicted_singlet_constant"] = 3 * predicted
        checks[str(p)]["singlet_absolute_difference"] = abs(spin_penalty - 3 * predicted)
        assert abs(spin_penalty - 3 * predicted) < 0.04
    return rows, checks


def plot_capacities(output: Path) -> None:
    import matplotlib
    matplotlib.use("Agg")
    import matplotlib.pyplot as plt
    plt.rcParams.update({"font.size": 10, "axes.spines.top": False, "axes.spines.right": False})
    ps = np.linspace(0, 0.5, 101)
    fig, ax = plt.subplots(figsize=(7, 4.4), layout="constrained")
    ax.plot(ps, 1 - 2 * ps, color="#151f33", linewidth=2, label="Unrestricted erasure capacity")
    for b, color in [(10, "#9071c9"), (100, "#257a81")]:
        ax.plot(ps, [sector_capacity(b, float(p), "charge") / b for p in ps], color=color,
                label=f"Fixed half charge, b={b}")
        ax.plot(ps, [sector_capacity(b, float(p), "singlet") / b for p in ps], color=color,
                linestyle="--", label=f"SU(2) singlet, b={b}")
    ax.set(xlabel="Independent flagged erasure probability p", ylabel="Qubits per physical qubit",
           xlim=(0, 0.5), ylim=(0, 1.02), title="Exact sector-restricted erasure capacities")
    ax.grid(alpha=0.17)
    ax.legend(frameon=False, fontsize=8)
    fig.savefig(output / "sector_capacity.png", dpi=220)
    fig.savefig(output / "sector_capacity.pdf")
    plt.close(fig)


def main() -> None:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--output-dir", type=Path, default=Path(__file__).resolve().parent / "results")
    parser.add_argument("--no-plot", action="store_true")
    args = parser.parse_args()
    args.output_dir.mkdir(parents=True, exist_ok=True)
    rng = np.random.default_rng(SEED)
    summary = {"seed": SEED, "numerical_tolerance": ATOL,
               "status": "Numerical illustrations, not mathematical proofs or novelty certification"}
    summary["su2_moving_boundary"] = check_su2_moving_boundary(rng)
    summary["u1_moving_boundary"] = check_u1_moving_boundary(rng)
    summary["ten_seal_code"] = check_ten_seal_code()
    summary["direct_matrix_marginal_entropy_checks"] = check_marginal_entropy_formulas()
    rows, asymptotics = capacity_data()
    summary["finite_block_capacity_table"] = rows
    summary["charge_penalty_asymptotics_check"] = asymptotics
    with (args.output_dir / "verification.json").open("w") as f:
        json.dump(summary, f, indent=2)
        f.write("\n")
    with (args.output_dir / "capacity_table.csv").open("w", newline="") as f:
        writer = csv.DictWriter(f, fieldnames=list(rows[0]))
        writer.writeheader()
        writer.writerows(rows)
    if not args.no_plot:
        plot_capacities(args.output_dir)
    print(json.dumps({"all_assertions_passed": True,
                      "su2_trace_distance_before_twirl": summary["su2_moving_boundary"]["trace_distance_before_final_twirl"],
                      "su2_trace_distance_after_twirl": summary["su2_moving_boundary"]["trace_distance_after_final_twirl"],
                      "u1_trace_distance": summary["u1_moving_boundary"]["trace_distance_to_bare_erasure_without_twirl"],
                      "ten_seal_correctability": summary["ten_seal_code"]["correctability_counts"],
                      "capacity_rows": len(rows)}, indent=2))


if __name__ == "__main__":
    main()