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
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
#!/usr/bin/env python3
"""Checks for spatial moment sectors, smooth longitudinal fields, and decoupling.

This script is separate from verify.py and leaves the earlier verification
unchanged. Numerical checks illustrate claims; they do not certify novelty or
replace proofs. Run: python3 verify_spatial.py --output-dir spatial_results
Requires Python 3.10+, NumPy, SciPy, Matplotlib.
"""
from __future__ import annotations

import argparse
import csv
from functools import lru_cache
import json
import math
from pathlib import Path
import random

import numpy as np
from scipy.linalg import expm

from verify import I2, X, Y, Z, reduced_density, reduced_pure, trace_distance

SEED = 20261102
ATOL = 4e-11


def joint_sector_counts(n: int) -> dict[tuple[int, int], int]:
    """Exact DP for Hamming weight and dipole sum using positions 0,...,n-1."""
    counts = {(0, 0): 1}
    for position in range(n):
        updated = dict(counts)
        for (weight, dipole), multiplicity in counts.items():
            key = weight + 1, dipole + position
            updated[key] = updated.get(key, 0) + multiplicity
        counts = updated
    assert sum(counts.values()) == 2**n
    return counts


class MomentSectorEncoder:
    """Exact lexicographic rank/unrank encoder for a joint (Q0,Q1) sector.

    Rank is an integer label, not a claim of an efficient coherent gate circuit.
    Completion counts use arbitrary precision Python integers.
    """

    def __init__(self, n: int, weight: int, dipole: int):
        self.n, self.weight, self.dipole = n, weight, dipole

        @lru_cache(maxsize=None)
        def completions(position: int, weight_left: int, dipole_left: int) -> int:
            available = n - position
            if weight_left < 0 or weight_left > available:
                return 0
            minimum = weight_left * (2 * position + weight_left - 1) // 2
            maximum = weight_left * (2 * n - weight_left - 1) // 2
            if dipole_left < minimum or dipole_left > maximum:
                return 0
            if position == n:
                return int(weight_left == 0 and dipole_left == 0)
            return (completions(position + 1, weight_left, dipole_left)
                    + completions(position + 1, weight_left - 1, dipole_left - position))

        self._completions = completions
        self.dimension = completions(0, weight, dipole)
        if not self.dimension:
            raise ValueError("The requested moment sector is empty")

    def unrank(self, rank: int) -> str:
        if not 0 <= rank < self.dimension:
            raise ValueError("Rank lies outside the sector")
        weight_left, dipole_left = self.weight, self.dipole
        bits = []
        for position in range(self.n):
            zeros = self._completions(position + 1, weight_left, dipole_left)
            if rank < zeros:
                bits.append("0")
            else:
                bits.append("1")
                rank -= zeros
                weight_left -= 1
                dipole_left -= position
        assert rank == 0 and weight_left == 0 and dipole_left == 0
        return "".join(bits)

    def rank(self, bitstring: str) -> int:
        if len(bitstring) != self.n or any(bit not in "01" for bit in bitstring):
            raise ValueError("Expected an n-character binary string")
        if sum(map(int, bitstring)) != self.weight:
            raise ValueError("Incorrect Q0 moment")
        if sum(j * int(bit) for j, bit in enumerate(bitstring)) != self.dipole:
            raise ValueError("Incorrect Q1 moment")
        result = 0
        weight_left, dipole_left = self.weight, self.dipole
        for position, bit in enumerate(bitstring):
            if bit == "1":
                result += self._completions(position + 1, weight_left, dipole_left)
                weight_left -= 1
                dipole_left -= position
        return result


def sector_dp_checks() -> list[dict]:
    rng = random.Random(SEED)
    rows = []
    for n in (4, 8, 12, 16, 24, 32, 64):
        counts = joint_sector_counts(n)
        sector, dimension = min(counts.items(), key=lambda item: (-item[1], item[0]))
        weight, dipole = sector
        encoder = MomentSectorEncoder(n, weight, dipole)
        assert encoder.dimension == dimension
        test_ranks = set([0, dimension - 1, dimension // 2])
        test_ranks.update(rng.randrange(dimension) for _ in range(min(30, dimension)))
        if dimension <= 1000:
            test_ranks.update(range(dimension))
        for rank in test_ranks:
            assert encoder.rank(encoder.unrank(rank)) == rank
        pigeonhole_lower = 2**n / ((n + 1) * (n * (n - 1) // 2 + 1))
        requested_safe_lower = 2**n / ((n + 1) * (n * (n + 1) // 2 + 1))
        assert dimension >= pigeonhole_lower
        rows.append({
            "cell_qubits": n, "Q0": weight, "Q1_zero_based": dipole,
            "Q1_one_based": dipole + weight,
            "largest_sector_dimension_exact": dimension,
            "sector_count": len(counts), "total_strings_exact": sum(counts.values()),
            "log2_largest_sector_dimension": math.log2(dimension),
            "largest_sector_fraction_log2": math.log2(dimension) - n,
            "pigeonhole_dimension_lower_bound": pigeonhole_lower,
            "stated_safe_dimension_lower_bound": requested_safe_lower,
            "rank_unrank_roundtrips": len(test_ranks),
            "first_bitstring": encoder.unrank(0),
            "last_bitstring": encoder.unrank(dimension - 1),
        })
    return rows


def random_reference_state(n: int, indices: list[int], rng: np.random.Generator) -> np.ndarray:
    raw = rng.normal(size=(len(indices), 2)) + 1j * rng.normal(size=(len(indices), 2))
    code, _ = np.linalg.qr(raw)
    state = np.zeros((2**n, 2, 2), complex)
    state[indices, 0, 0] = code[:, 0] / math.sqrt(2)
    state[indices, 0, 1] = code[:, 1] / math.sqrt(2)
    return state


def conditional_evolve(state: np.ndarray, active: list[int], coordinates: np.ndarray,
                       b0: np.ndarray, b1: np.ndarray, b2: np.ndarray,
                       curvature: float, bath_h: np.ndarray, duration: float) -> np.ndarray:
    """Exact longitudinal evolution using one 2x2 bath unitary per bitstring."""
    n = len(coordinates)
    result = np.empty_like(state)
    for integer in range(2**n):
        occupied = [j for j in active if (integer >> (n - 1 - j)) & 1]
        h = bath_h.copy()
        for j in occupied:
            x = coordinates[j]
            h += b0 + x * b1 + curvature * (x * x / 2) * b2
        result[integer] = expm(-1j * duration * h) @ state[integer]
    return result


def spatial_field_checks(rng: np.random.Generator) -> dict:
    n, span = 8, 1.0
    counts = joint_sector_counts(n)
    (weight, dipole), dimension = min(counts.items(), key=lambda item: (-item[1], item[0]))
    encoder = MomentSectorEncoder(n, weight, dipole)
    indices = [int(encoder.unrank(rank), 2) for rank in range(dimension)]
    coordinates = (np.arange(n) - (n - 1) / 2) * span / n
    initial = random_reference_state(n, indices, rng)
    charge_indices = [integer for integer in range(2**n) if integer.bit_count() == weight]
    charge_only_initial = random_reference_state(n, charge_indices, rng)
    # Erased registers are kept as inert environmental registers in this dilation.
    stages = [
        {"active": list(range(n)), "duration": 0.41,
         "b0": 0.67 * X + 0.21 * Z, "b1": 1.19 * Z + 0.31 * Y,
         "b2": X, "bath_h": 0.37 * Y},
        {"active": [1, 2, 3, 4, 5, 6, 7], "duration": 0.63,
         "b0": -0.43 * Y + 0.39 * Z, "b1": 0.89 * X - 0.61 * Z,
         "b2": Y, "bath_h": 0.23 * X + 0.31 * Z},
        {"active": [1, 3, 4, 6, 7], "duration": 0.79,
         "b0": 0.57 * X - 0.47 * Z, "b1": -0.99 * Y + 0.73 * Z,
         "b2": Z, "bath_h": -0.29 * X + 0.41 * Y},
    ]
    final_survivors = stages[-1]["active"]
    keep = final_survivors + [n + 1]
    target = reduced_pure(initial.reshape(-1), keep, n + 2)
    charge_target = reduced_pure(charge_only_initial.reshape(-1), keep, n + 2)

    def run(state: np.ndarray, curvature: float) -> np.ndarray:
        for stage in stages:
            state = conditional_evolve(state, stage["active"], coordinates,
                                       stage["b0"], stage["b1"], stage["b2"],
                                       curvature, stage["bath_h"], stage["duration"])
        return state

    affine = run(initial, 0.0)
    affine_output = reduced_pure(affine.reshape(-1), keep, n + 2)
    affine_error = trace_distance(affine_output, target)
    assert affine_error < ATOL
    charge_output = reduced_pure(run(charge_only_initial, 0.0).reshape(-1), keep, n + 2)
    charge_only_error = trace_distance(charge_output, charge_target)
    assert charge_only_error > 1e-3
    curvature_rows = []
    for curvature in (0.03, 0.1, 0.3):
        actual_output = reduced_pure(run(initial, curvature).reshape(-1), keep, n + 2)
        actual_error = trace_distance(actual_output, target)
        # Each quadratic residual has positive scalar coefficients multiplying
        # one norm-one bath Pauli in this piecewise-constant example.
        integrated_residual_norm = sum(stage["duration"] * curvature *
                                       sum(coordinates[j]**2 / 2 for j in stage["active"])
                                       for stage in stages)
        a2 = curvature * sum(stage["duration"] for stage in stages)
        theorem_bound = span**2 * a2 * (n*n - 1) / (24 * n)
        assert actual_error <= min(1.0, integrated_residual_norm) + ATOL
        assert integrated_residual_norm <= theorem_bound + ATOL
        curvature_rows.append({
            "curvature_norm": curvature, "integrated_curvature_A2": a2,
            "reference_state_trace_distance": actual_error,
            "exact_integrated_residual_norm": integrated_residual_norm,
            "theorem_half_diamond_upper_bound": min(1.0, theorem_bound),
            "unclipped_theorem_bound": theorem_bound,
        })
    return {
        "physical_qubits": n, "span_a": span, "coordinates": coordinates.tolist(),
        "coordinate_convention": "spacing a/N, centered cell; occupied extent a*(N-1)/N",
        "Q0": weight, "Q1_zero_based": dipole, "sector_dimension": dimension,
        "bath_dimension": 2, "reference_dimension": 2,
        "final_survivors_zero_based": final_survivors,
        "known_erased_positions": [0, 2, 5],
        "affine_field_reference_state_trace_distance": affine_error,
        "charge_only_gradient_counterexample_trace_distance": charge_only_error,
        "noncommuting_field_operator_commutator_norm_example": float(np.linalg.norm(
            stages[0]["b0"] @ stages[0]["b1"] - stages[0]["b1"] @ stages[0]["b0"], 2)),
        "curvature_checks": curvature_rows,
    }


def haar_isometry(rows: int, columns: int, rng: np.random.Generator) -> np.ndarray:
    a = rng.normal(size=(rows, columns)) + 1j * rng.normal(size=(rows, columns))
    q, r = np.linalg.qr(a)
    phase = np.diag(r) / np.abs(np.diag(r))
    return q * phase.conj()[None, :]


def decoupling_monte_carlo(rng: np.random.Generator, samples: int) -> list[dict]:
    n, k = 4, 2
    rows = []
    families = {
        "weight_two_sector": [integer for integer in range(16) if integer.bit_count() == 2],
        "full_four_qubit_space": list(range(16)),
    }
    for family, basis in families.items():
        d = len(basis)
        omega = np.zeros((16, 16), complex)
        omega[basis, basis] = 1 / d
        for erased in ([0], [0, 1]):
            kept = [j for j in range(n) if j not in erased]
            de = 2**len(erased)
            omega_e = reduced_density(omega, erased, n)
            omega_r = reduced_density(omega, kept, n)
            purity_e = float(np.trace(omega_e @ omega_e).real)
            purity_r = float(np.trace(omega_r @ omega_r).real)
            predicted_hs = ((d * k - 1) / (k * (d*d - 1))) * (d * purity_r - purity_e)
            hs_values, trace_norms = [], []
            for _ in range(samples):
                isometry = haar_isometry(d, k, rng)
                state = np.zeros((16, k), complex)
                state[basis] = isometry / math.sqrt(k)
                # Reorder qubits to (reference, erased sites, retained sites).
                rho_le = reduced_pure(state.reshape(-1), [n] + erased, n + 1)
                delta = rho_le - np.kron(I2 / k, omega_e)
                hs_values.append(float(np.trace(delta @ delta).real))
                trace_norms.append(float(np.abs(np.linalg.eigvalsh(delta)).sum()))
            hs_mean = float(np.mean(hs_values))
            hs_se = float(np.std(hs_values, ddof=1) / math.sqrt(samples))
            mean_trace = float(np.mean(trace_norms))
            zscore = abs(hs_mean - predicted_hs) / hs_se if hs_se else 0.0
            # Statistical reporting, not a brittle assertion on a sample mean.
            assert abs(predicted_hs) > 0
            rows.append({
                "subspace": family, "physical_qubits": n, "D": d, "K": k,
                "erased_qubits": len(erased), "d_E": de, "samples": samples,
                "Omega_E_purity": purity_e, "Omega_R_purity": purity_r,
                "predicted_mean_HS_squared": predicted_hs,
                "empirical_mean_HS_squared": hs_mean,
                "empirical_HS_standard_error": hs_se,
                "standard_errors_from_prediction": zscore,
                "empirical_mean_trace_norm": mean_trace,
                "HS_Cauchy_bound_for_mean_trace_norm": math.sqrt(k * de * predicted_hs),
                "simple_mean_trace_norm_upper_bound": math.sqrt(k * de**2 / d),
                "delta_definition": "rho_reference,E - I_reference/K tensor Omega_E",
            })
    return rows


def dimension_cost(n: int, cell_size: int) -> float:
    """Log2 product-sector dimension lower bound, exact for cell partition sizes."""
    full, remainder = divmod(n, cell_size)
    def penalty(length: int) -> float:
        return math.log2((length + 1) * (length * (length - 1) / 2 + 1))
    cost = full * penalty(cell_size) + (penalty(remainder) if remainder else 0)
    return n - cost


def tradeoff_rows() -> list[dict]:
    n, p, span, a2 = 1_000_000, 0.1, 1.0, 1.0
    rows = []
    for b in sorted(set([4, 8, 12, 16, 24, 32, 48, 64, 96, 128, 192, 256,
                         384, 512, 768, 1024])):
        logd = dimension_cost(n, b)
        rows.append({
            "physical_qubits_N": n, "cell_max_qubits_b": b,
            "erasure_probability_p": p, "span_a": span, "integrated_curvature_A2": a2,
            "log2_product_sector_dimension_lower_bound": logd,
            "sector_dimension_lower_bound_per_qubit": logd / n,
            "sufficient_asymptotic_rate_threshold_from_dimension_bound": max(0.0, logd / n - 2*p),
            "unclipped_dimension_rate_expression": logd / n - 2*p,
            "curvature_half_diamond_upper_bound": min(1.0, span**2 * a2 * b*b / (24*n)),
            "unclipped_curvature_bound": span**2 * a2 * b*b / (24*n),
            "interpretation": "Analytic dimension/rate bounds, not finite-block achieved coding rates",
        })
    return rows


def write_csv(path: Path, rows: list[dict]) -> None:
    with path.open("w", newline="") as f:
        writer = csv.DictWriter(f, fieldnames=list(rows[0]))
        writer.writeheader()
        writer.writerows(rows)


def analytic_horizon_checks() -> list[dict]:
    """Check finite degree selection in log space; no huge time is exponentiated."""
    rows = []
    ratio = 0.25
    for n in (10_000, 1_000_000, 100_000_000, 1_000_000_000_000):
        for gamma in (0.2, 0.4):
            log_lambda = n ** gamma
            log_target = -2 * math.log(n)
            degree_plus_one = max(1, math.ceil(
                (math.log(n) + log_lambda - log_target - math.log1p(-ratio)) / abs(math.log(ratio))))
            log_bound = math.log(n) + log_lambda + degree_plus_one * math.log(ratio) - math.log1p(-ratio)
            assert log_bound <= log_target + 1e-9
            redundancy = degree_plus_one + degree_plus_one * (degree_plus_one + 1) * math.log2(n) / 2
            rows.append({
                "physical_qubits_N": n, "gamma": gamma,
                "log_integrated_amplitude_Lambda": log_lambda,
                "geometric_ratio": ratio, "degree": degree_plus_one - 1,
                "log_target_field_error": log_target,
                "log_proved_field_error_bound": log_bound,
                "sector_redundancy_upper_bound_qubits": redundancy,
                "redundancy_bound_per_physical_qubit": redundancy / n,
                "interpretation": "Analytic model bounds; growing horizon assumes zero losses or fixed endpoint p<1/2",
            })
    return rows


def plot_tradeoff(path: Path, rows: list[dict]) -> 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})
    fig, axes = plt.subplots(1, 2, figsize=(9.1, 3.9), layout="constrained")
    bs = [row["cell_max_qubits_b"] for row in rows]
    rates = [row["sufficient_asymptotic_rate_threshold_from_dimension_bound"] for row in rows]
    errors = [row["unclipped_curvature_bound"] for row in rows]
    axes[0].semilogx(bs, rates, base=2, color="#276d83", marker="o", markersize=3)
    axes[0].axhline(0.8, color="#46505f", linestyle="--", linewidth=1,
                    label="Unrestricted asymptotic limit: 0.8")
    axes[0].set(xlabel="Maximum qubits per cell b", ylabel="Sufficient asymptotic rate threshold",
                title="Counting bound improves with cell size", ylim=(-0.05, 0.85))
    axes[0].legend(frameon=False, fontsize=8, loc="lower right")
    axes[1].loglog(bs, errors, base=2, color="#9356a0", marker="o", markersize=3)
    axes[1].set(xlabel="Maximum qubits per cell b", ylabel="Curvature error upper bound",
                title="Smooth-field error grows with cell size")
    for ax in axes:
        ax.grid(alpha=0.18)
    fig.suptitle("Analytic bounds: N=10^6, p=0.1, a=1, integrated curvature A2=1", fontsize=11)
    fig.savefig(path / "spatial_tradeoff.png", dpi=220)
    fig.savefig(path / "spatial_tradeoff.pdf")
    plt.close(fig)


def main() -> None:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--output-dir", type=Path,
                        default=Path(__file__).resolve().parent / "spatial_results")
    parser.add_argument("--samples", type=int, default=2000)
    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)
    dp = sector_dp_checks()
    field = spatial_field_checks(rng)
    decoupling = decoupling_monte_carlo(rng, args.samples)
    tradeoff = tradeoff_rows()
    horizons = analytic_horizon_checks()
    summary = {
        "seed": SEED, "numerical_tolerance": ATOL,
        "status": "Numerical illustrations and exact integer enumeration; not novelty certification",
        "joint_moment_sector_DP": dp,
        "spatial_field_trajectory_checks": field,
        "random_subspace_decoupling_checks": decoupling,
        "analytic_tradeoff_bounds": tradeoff,
        "analytic_horizon_degree_checks": horizons,
    }
    with (args.output_dir / "spatial_verification.json").open("w") as f:
        json.dump(summary, f, indent=2)
        f.write("\n")
    write_csv(args.output_dir / "moment_sector_counts.csv", dp)
    write_csv(args.output_dir / "decoupling_monte_carlo.csv", decoupling)
    write_csv(args.output_dir / "analytic_tradeoff.csv", tradeoff)
    write_csv(args.output_dir / "analytic_horizon.csv", horizons)
    if not args.no_plot:
        plot_tradeoff(args.output_dir, tradeoff)
    print(json.dumps({
        "all_deterministic_assertions_passed": True,
        "largest_sector_n64": dp[-1],
        "affine_field_error": field["affine_field_reference_state_trace_distance"],
        "charge_only_gradient_counterexample_error": field["charge_only_gradient_counterexample_trace_distance"],
        "curvature_checks": field["curvature_checks"],
        "MC_max_standard_errors_from_prediction": max(
            row["standard_errors_from_prediction"] for row in decoupling),
    }, indent=2))


if __name__ == "__main__":
    main()