Datasets:
Formats:
csv
Languages:
English
Size:
< 1K
Tags:
quantum-information
quantum-error-correction
quantum-memory
quantum-capacity
quantum-erasure-channel
non-markovian-noise
Download research/code/verify.py from PureOne/Soryun-IV-Quantum-Memory-Noncommuting-Spatial-Fields: direct link, hf CLI and curl.
- Browser
- Download file 18.4 kB
-
https://huggingface.co/datasets/PureOne/Soryun-IV-Quantum-Memory-Noncommuting-Spatial-Fields/resolve/main/research/code/verify.py
- Command line
-
hf download hf://datasets/PureOne/Soryun-IV-Quantum-Memory-Noncommuting-Spatial-Fields/research/code/verify.py
-
curl -L -o verify.py https://huggingface.co/datasets/PureOne/Soryun-IV-Quantum-Memory-Noncommuting-Spatial-Fields/resolve/main/research/code/verify.py
18.4 kB
| #!/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() | |