PureOne's picture
Upload research package with Eve Uploader
942193c verified
Raw History Blame Contribute Delete
22.9 kB
#!/usr/bin/env python3
"""Reproducible finite checks for spectral shells and diagonal Dyson truncation.
The calculations illustrate stated theorems. They do not certify scientific
priority or replace the proofs. Requires Python 3.10+, numpy, scipy, matplotlib.
Run from any directory: python3 verify_broad.py --output-dir ../results/broad
"""
from __future__ import annotations
import argparse
import csv
import json
import math
from pathlib import Path
import numpy as np
from scipy.linalg import expm
from scipy.special import gammaln
SEED = 20261103
TOL = 2e-11
I2 = np.eye(2, dtype=complex)
X = np.array([[0, 1], [1, 0]], complex)
Y = np.array([[0, -1j], [1j, 0]], complex)
Z = np.diag([1, -1]).astype(complex)
def bits_table(n: int) -> np.ndarray:
return np.array([[(a >> (n - 1 - j)) & 1 for j in range(n)]
for a in range(2**n)], dtype=int)
def reduced_pure(psi: np.ndarray, keep: list[int], n: int) -> np.ndarray:
discard = [j for j in range(n) if j not in keep]
matrix = psi.reshape([2] * n).transpose(keep + discard).reshape(2**len(keep), -1)
return matrix @ matrix.conj().T
def trace_distance(a: np.ndarray, b: np.ndarray) -> float:
d = (a - b + (a - b).conj().T) / 2
return float(np.abs(np.linalg.eigvalsh(d)).sum() / 2)
def shell_partition(features: np.ndarray, widths: np.ndarray) -> dict:
"""Partition every basis string into product charge bins; exact floating inputs."""
n = features.shape[1]
charges = bits_table(n) @ features.T
lower = np.minimum(features, 0).sum(axis=1)
upper = np.maximum(features, 0).sum(axis=1)
labels = np.floor((charges - lower) / widths).astype(int)
# An exact endpoint at a range boundary belongs to the final half-open bin.
count = np.maximum(1, np.ceil((upper - lower) / widths).astype(int))
labels = np.maximum(0, np.minimum(labels, count - 1))
groups: dict[tuple[int, ...], list[int]] = {}
for integer, label in enumerate(labels):
groups.setdefault(tuple(int(v) for v in label), []).append(integer)
best_label, indices = min(groups.items(), key=lambda item: (-len(item[1]), item[0]))
left = lower + np.array(best_label) * widths
right = np.minimum(left + widths, upper)
center = (left + right) / 2
halfwidth = (right - left) / 2
assert np.all(np.abs(charges[indices] - center) <= halfwidth + 1e-12)
return {"indices": indices, "center": center, "halfwidth": halfwidth,
"largest_dimension": len(indices), "occupied_bins": len(groups),
"safe_bin_count": int(np.prod(count, dtype=object)),
"charge_range_lengths": upper - lower, "chosen_label": best_label,
"charges": charges}
def shell_trajectory(rng: np.random.Generator) -> tuple[dict, list[dict]]:
n = 8
features = np.vstack([np.sqrt(np.arange(1, n + 1)) / math.sqrt(n),
np.sin(np.arange(n) + 0.37)])
widths = np.array([0.32, 0.37])
shell = shell_partition(features, widths)
d = shell["largest_dimension"]
assert d >= 2
raw = rng.normal(size=(d, 2)) + 1j * rng.normal(size=(d, 2))
code, _ = np.linalg.qr(raw)
initial = np.zeros((2**n, 2, 2), complex)
initial[shell["indices"], 0, :] = code / math.sqrt(2)
stages = [
(list(range(n)), 0.37, [0.53*X+0.19*Z, 0.47*Y-0.11*Z], 0.23*X),
([1,2,3,4,5,6,7], 0.51, [0.31*Y-0.29*Z, 0.39*X+0.21*Z], -0.17*Y),
([1,3,4,6,7], 0.68, [-0.43*X+0.13*Y, 0.37*Z+0.23*Y], 0.19*X+0.07*Z),
]
states = bits_table(n)
actual = initial.copy()
comparison = initial.copy()
exposure = np.zeros(2)
for active, duration, couplings, hb in stages:
exposure += duration * np.array([np.linalg.norm(c, 2) for c in couplings])
erased = [j for j in range(n) if j not in active]
for integer in range(2**n):
qa = features[:, active] @ states[integer, active]
qe = features[:, erased] @ states[integer, erased] if erased else np.zeros(2)
h = hb + sum(qa[l] * couplings[l] for l in range(2))
hc = hb + sum((shell["center"][l] - qe[l]) * couplings[l] for l in range(2))
actual[integer] = expm(-1j * duration * h) @ actual[integer]
comparison[integer] = expm(-1j * duration * hc) @ comparison[integer]
keep = stages[-1][0] + [n + 1]
target = reduced_pure(initial.reshape(-1), keep, n + 2)
noisy = reduced_pure(actual.reshape(-1), keep, n + 2)
compared = reduced_pure(comparison.reshape(-1), keep, n + 2)
error = trace_distance(noisy, target)
comparison_error = trace_distance(compared, target)
bound = float(np.dot(shell["halfwidth"], exposure))
assert comparison_error < TOL
assert error <= min(1, bound) + TOL
assert abs(np.vdot(actual, actual) - 1) < TOL
tradeoff = []
for scale in (0.5, 1, 2, 4, 8, 16, 32):
eta = 0.25
h = 2 * eta / (2 * scale * exposure)
chosen = shell_partition(features, h)
tradeoff.append({"exposure_multiplier": scale,
"target_shell_channel_error": eta,
"width_feature_1": float(h[0]), "width_feature_2": float(h[1]),
"largest_shell_dimension": chosen["largest_dimension"],
"occupied_bins": chosen["occupied_bins"],
"safe_product_bin_count": chosen["safe_bin_count"],
"log2_largest_shell_dimension": math.log2(chosen["largest_dimension"]),
"pigeonhole_log2_dimension_lower_bound": n-math.log2(chosen["safe_bin_count"]),
"interpretation": "Finite exact enumeration; inverse-exposure bin widths"})
result = {"physical_qubits": n, "feature_values": features.tolist(),
"requested_bin_widths": widths.tolist(), "chosen_bin": list(shell["chosen_label"]),
"chosen_centers": shell["center"].tolist(),
"actual_halfwidths": shell["halfwidth"].tolist(),
"largest_shell_dimension": d, "chosen_basis_indices": shell["indices"],
"integrated_feature_exposures": exposure.tolist(),
"known_erased_sites": [0,2,5],
"reference_trace_distance_to_bare_erasure": error,
"reference_comparison_evolution_trace_distance": comparison_error,
"proved_half_diamond_upper_bound": min(1, bound),
"noncommuting_bath_commutator_norm": float(np.linalg.norm(
stages[0][2][0]@stages[0][2][1]-stages[0][2][1]@stages[0][2][0], 2))}
return result, tradeoff
def choi(kraus: list[np.ndarray]) -> np.ndarray:
vectors = [k.reshape(-1, order="F") for k in kraus]
return sum((np.outer(v, v.conj()) for v in vectors),
np.zeros((len(vectors[0]), len(vectors[0])), complex))
def cp_dyson_checks() -> list[dict]:
"""Full Choi PSD test for approximate CP maps; maps need not be TP."""
n, r_sites, t_erased, bath = 3, 2, 1, 2
d_a, d_r = 2**n, 2**r_sites
couplings = [0.41*X+0.13*Z, 0.29*Y-0.17*Z, 0.23*Z+0.11*X]
duration = 0.19
h = np.zeros((d_a*bath, d_a*bath), complex)
for a, bits in enumerate(bits_table(n)):
h[a*bath:(a+1)*bath, a*bath:(a+1)*bath] = sum(bits[j]*couplings[j] for j in range(n))
exact = expm(-1j*duration*h)
a_budget = duration * sum(np.linalg.norm(c, 2) for c in couplings)
bare = []
for e in range(2**t_erased):
k = np.zeros((d_r, d_a), complex)
for r in range(d_r): k[r, r*2+e] = 1
bare.append(k)
sector_indices = [a for a in range(d_a) if a.bit_count() == 1]
sector_embedding = np.eye(d_a)[:, sector_indices]
rows = []
for s in (0, 1, 2):
truncated = np.eye(d_a*bath, dtype=complex)
term = np.eye(d_a*bath, dtype=complex)
for degree in range(1, s+1):
term = term @ (-1j*duration*h) / degree
truncated += term
tau = math.exp(a_budget + (s+1)*math.log(a_budget) - gammaln(s+2))
actual_tail = float(np.linalg.norm(exact-truncated, 2))
assert actual_tail <= tau + TOL
# Pure |0> bath preparation gives one column per physical input string.
vs = truncated[:, np.arange(d_a)*bath]
norm_vs_sq = float(np.linalg.norm(vs, 2)**2)
assert norm_vs_sq <= (1+tau)**2 + TOL
masks = [mask for mask in range(d_r) if mask.bit_count() <= s]
m = len(masks)
coefficients = np.zeros((2, bath, d_r), complex)
for e in range(2):
for b in range(bath):
amplitudes = np.array([vs[(r*2+e)*bath+b, r*2+e] for r in range(d_r)])
for mask in range(d_r):
coefficients[e,b,mask] = sum(amplitudes[r] * (-1)**((r&mask).bit_count())
for r in range(d_r)) / d_r
forbidden = [mask for mask in range(d_r) if mask not in masks]
forbidden_norm = float(np.max(np.abs(coefficients[:,:,forbidden]))) if forbidden else 0.0
assert forbidden_norm < TOL
gram_traces, gram_max_eigenvalues = [], []
for e in range(2):
c = coefficients[e][:,masks]
gram = c.T @ c.conj()
gram_traces.append(float(np.trace(gram).real))
gram_max_eigenvalues.append(float(np.linalg.eigvalsh(gram)[-1]))
assert gram_traces[-1] <= norm_vs_sq + TOL
approx_kraus = []
canonical = []
for e in range(2):
for b in range(bath):
k = np.zeros((d_r,d_a), complex)
for r in range(d_r): k[r,r*2+e] = vs[(r*2+e)*bath+b,r*2+e]
approx_kraus.append(k)
for mask in masks:
phase = np.diag([(-1)**((r&mask).bit_count()) for r in range(d_r)])
canonical.append(phase @ bare[e] / math.sqrt(m))
domination = m*(1+tau)**2
values = {}
for name, embedding in [("full_input",np.eye(d_a)), ("weight_one_input",sector_embedding)]:
jpsi = choi([k@embedding for k in approx_kraus])
jphi = choi([k@embedding for k in canonical])
diff = domination*jphi-jpsi
smallest = float(np.linalg.eigvalsh((diff+diff.conj().T)/2)[0])
assert smallest >= -TOL
values[name+"_minimum_Choi_domination_eigenvalue"] = smallest
rows.append({"physical_qubits":n,"surviving_qubits":r_sites,"erased_qubits":t_erased,
"truncation_order":s,"a_integrated_norm_budget":float(a_budget),
"tail_bound_tau":tau,"actual_joint_unitary_tail_norm":actual_tail,
"phase_support_count_M":m,"CP_domination_factor":domination,
"approximate_amplitude_operator_norm_squared":norm_vs_sq,
"Gram_traces_by_erasure_basis":gram_traces,
"Gram_maximum_eigenvalues_by_erasure_basis":gram_max_eigenvalues,
"forbidden_phase_coefficient_maximum":forbidden_norm,
"canonical_channel": "bare erasure followed by uniform Z masks of weight <=s",
"Choi_normalization": "unnormalized column-stacked Kraus Choi",
**values})
return rows
def h2(x: float) -> float:
if x <= 0 or x >= 1: return 0.0
return -x*math.log2(x)-(1-x)*math.log2(1-x)
def support_tail_rows() -> list[dict]:
rows = []
for nu in (1,2,3):
for beta in (0.25,0.5,1.0):
for exponent in (3,4,5,6,8,10,12):
n = 10**exponent
cell = max(2, int(math.ceil(math.log(n)**2)))
epsilon = min(1.0, (cell/n)**(beta/nu))
a = n*epsilon
s = int(math.ceil(math.e**2*a + 4*math.log(n)))
fraction = min(1.0, s/n)
logtau = a+(s+1)*math.log(a)-gammaln(s+2)
log_m_bound = n*h2(fraction) if fraction <= .5 else n
# Exact finite support count is checked only at small n; its
# entropy upper envelope is evaluated at the large n above.
rows.append({"N":n,"spatial_dimension_nu":nu,"Holder_beta":beta,
"cell_qubits_b":cell,"per_site_integrated_residual_epsilon":epsilon,
"a_integrated_total_budget":a,"support_cutoff_s":s,
"support_fraction_s_over_N":s/n,
"log_safe_Dyson_tail_bound":float(logtau),
"log2_phase_support_count_upper_bound":log_m_bound,
"normalized_log2_support_count_upper_bound":log_m_bound/n,
"interpretation":"Dyson-tail and support-entropy envelope, not achieved finite code rate"})
assert logtau < 0
for n in (8,16,32,64):
for s in range(0,n//2+1):
exact = sum(math.comb(n,w) for w in range(s+1))
assert math.log2(exact) <= n*h2(s/n)+1e-10
return rows
def shell_rate_rows() -> list[dict]:
rows = []
for n in [2**k for k in range(4,27)]:
for rank in (1,2,4,8):
for exposure_exponent in (0,1,2):
exposure = n**exposure_exponent
target = 1/n
width = 2*target/(rank*exposure)
bins_per_feature = max(1, math.ceil(n/width))
deficit = rank*math.log2(bins_per_feature)
rows.append({"N":n,"feature_count_r":rank,"exposure_exponent":exposure_exponent,
"per_feature_exposure":exposure,"target_shell_error":target,
"bin_width":width,"safe_label_deficit_qubits":deficit,
"normalized_label_deficit":deficit/n,"erasure_probability_p":.1,
"dimension_based_rate_threshold":max(0.0,.8-deficit/n),
"interpretation":"Dimension threshold before finite erasure coding slack; feature ranges <=N"})
return rows
def continuous_rate_certificates() -> list[dict]:
"""Evaluate the manuscript's sufficient C0 finite-error certificate.
The geometry-dependent input is an asserted per-site residual budget
epsilon=0.01*(b/N)^(beta/nu); the numerical curves do not establish that
budget for a particular device. All entropy/sector estimates are upper or
lower envelopes in the safe direction specified by the theorem.
"""
rows=[]
p,target,amplitude=.1,.01,.01
for nu in (1,2,3):
for beta in (.25,.5,1.0):
for exponent in range(4,13):
n=10**exponent
b=max(2,int(math.ceil(math.log(n)**2)))
cells=math.ceil(n/b)
logd_lower=n-cells*math.log2(1+n/cells)
epsilon=amplitude*(b/n)**(beta/nu)
a=n*epsilon
s=int(math.ceil(math.e**2*a+4*math.log(n)))
logtau=a+(s+1)*math.log(a)-gammaln(s+2)
tau=math.exp(logtau) if logtau>-745 else 0.0
log_tail_error=logtau+math.log(2+tau)
tail_ok=log_tail_error<=math.log(target/4)
eta=math.sqrt(math.log(4/target)/(2*n))
cutoff_ok=s<=n/2
logm=n*h2(s/n) if cutoff_ok else float(n)
# The root theorem uses 3 log M, not a guessed asymptotic
# proxy: (1+tau)^2 2^[(ell+2N(p+eta)+3logM-logD)/2]<=target/2.
correction=2*math.log2(target/(2*(1+tau)**2))
ell_bound=logd_lower-2*n*(p+eta)-3*logm+correction
logical=max(0,int(math.floor(ell_bound))-16) if tail_ok and cutoff_ok else 0
if logical:
log_middle=2*math.log1p(tau)+math.log(2)*(logical+2*n*(p+eta)+3*logm-logd_lower)/2
assert log_middle<=math.log(target/2)+1e-9
rows.append({"N":n,"nu":nu,"Holder_beta":beta,"p":p,
"target_entanglement_infidelity":target,"residual_amplitude":amplitude,
"cell_qubits_b":b,"cell_count_C":cells,
"log2_sector_dimension_lower_bound":logd_lower,
"per_site_residual_epsilon":epsilon,"support_cutoff_s":s,
"support_fraction":s/n,"log_Dyson_tail_bound":float(logtau),
"log_tail_infidelity_bound":float(log_tail_error),
"tail_budget_certified":bool(tail_ok),"entropy_bound_applicable":bool(cutoff_ok),
"erasure_slack_eta":eta,"log2_support_count_upper_bound":logm,
"logical_qubits_certified":logical,"certified_rate":logical/n,
"interpretation":"Sufficient finite-error certificate from proved envelopes; no implemented decoder"})
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 make_plots(output: Path, shells: list[dict], rates: list[dict], tails: list[dict], certificates: 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,ax=plt.subplots(figsize=(7,4.3),layout="constrained")
for rank,color in [(1,"#267882"),(2,"#517fa7"),(4,"#9174b3"),(8,"#ad6b59")]:
chosen=[r for r in rates if r["feature_count_r"]==rank and r["exposure_exponent"]==1]
ax.plot([r["N"] for r in chosen],[r["dimension_based_rate_threshold"] for r in chosen],
label=f"{rank} real-valued feature"+("s" if rank != 1 else ""),color=color)
ax.axhline(.8,color="#354052",linestyle="--",label="Erasure limit, p=0.1")
ax.set(xscale="log",xlabel="Physical qubits N",ylabel="Dimension-based rate threshold",
title="Real-charge shells: exposure N, target field error 1/N",ylim=(-.02,.83))
ax.text(.03,.06,"Excludes finite erasure-code slack; profile charge ranges ≤ N",transform=ax.transAxes,fontsize=8)
ax.legend(frameon=False,fontsize=8);ax.grid(alpha=.16)
for ext in ("png","pdf"):fig.savefig(output/f"real_shell_rate_bounds.{ext}",dpi=220)
plt.close(fig)
fig,axes=plt.subplots(1,2,figsize=(9,3.8),layout="constrained")
axes[0].plot([r["exposure_multiplier"] for r in shells],
[r["largest_shell_dimension"] for r in shells],marker="o",color="#267882")
axes[0].set_xscale("log",base=2)
axes[0].set(xlabel="Exposure multiplier",ylabel="Largest shell dimension",
title="Eight-site exact enumeration")
for nu,color in [(1,"#267882"),(2,"#9174b3"),(3,"#ad6b59")]:
chosen=[r for r in tails if r["spatial_dimension_nu"]==nu and r["Holder_beta"]==.5]
axes[1].plot([r["N"] for r in chosen],
[r["normalized_log2_support_count_upper_bound"] for r in chosen],
marker="o",color=color,label=f"Spatial dimension {nu}")
axes[1].set(xscale="log",xlabel="Physical qubits N",ylabel="Upper bound on log₂ M / N",
title="Dyson support envelope, Hölder β=1/2",ylim=(-.02,1.03))
axes[1].legend(frameon=False,fontsize=8)
for ax in axes:ax.grid(alpha=.16)
fig.suptitle("Bound and enumeration diagnostics; no measured hardware rates",fontsize=10)
for ext in ("png","pdf"):fig.savefig(output/f"shell_and_Dyson_diagnostics.{ext}",dpi=220)
plt.close(fig)
fig,axes=plt.subplots(1,2,figsize=(9,3.8),layout="constrained")
for nu,color in [(1,"#267882"),(2,"#9174b3"),(3,"#ad6b59")]:
chosen=[r for r in certificates if r["nu"]==nu and r["Holder_beta"]==.5]
axes[0].plot([r["N"] for r in chosen],[r["certified_rate"] for r in chosen],
marker="o",color=color,label=f"Dimension {nu}")
for beta,color in [(.25,"#ad6b59"),(.5,"#9174b3"),(1.0,"#267882")]:
chosen=[r for r in certificates if r["nu"]==2 and r["Holder_beta"]==beta]
axes[1].plot([r["N"] for r in chosen],[r["certified_rate"] for r in chosen],
marker="o",color=color,label=f"Hölder β={beta:g}")
for ax in axes:
ax.axhline(.8,color="#354052",linestyle="--",linewidth=1)
ax.set(xscale="log",xlabel="Physical qubits N",ylabel="Sufficient certified rate",ylim=(-.02,.83))
ax.legend(frameon=False,fontsize=8);ax.grid(alpha=.16)
axes[0].set_title("Hölder β=1/2")
axes[1].set_title("Spatial dimension 2")
fig.suptitle("Finite-error bound: p=0.1, target error=0.01, residual amplitude=0.01",fontsize=10)
for ext in ("png","pdf"):fig.savefig(output/f"continuous_field_certificates.{ext}",dpi=220)
plt.close(fig)
def main() -> None:
parser=argparse.ArgumentParser(description=__doc__)
parser.add_argument("--output-dir",type=Path,default=Path(__file__).resolve().parents[1]/"results"/"broad")
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)
trajectory,shells=shell_trajectory(rng)
cp=cp_dyson_checks();tails=support_tail_rows();rates=shell_rate_rows();certificates=continuous_rate_certificates()
summary={"seed":SEED,"numerical_tolerance":TOL,
"status":"Deterministic numerical checks and analytic envelopes, not novelty certification",
"real_charge_shell_trajectory":trajectory,"finite_shell_exposure_tradeoff":shells,
"Dyson_CP_domination_checks":cp,"Dyson_support_tail_envelopes":tails,
"real_charge_shell_rate_envelopes":rates,"continuous_field_rate_certificates":certificates}
(args.output_dir/"broad_verification.json").write_text(json.dumps(summary,indent=2)+"\n")
write_csv(args.output_dir/"finite_shell_tradeoff.csv",shells)
write_csv(args.output_dir/"Dyson_CP_checks.csv",cp)
write_csv(args.output_dir/"Dyson_support_envelopes.csv",tails)
write_csv(args.output_dir/"real_shell_rate_envelopes.csv",rates)
write_csv(args.output_dir/"continuous_field_certificates.csv",certificates)
if not args.no_plot:make_plots(args.output_dir,shells,rates,tails,certificates)
print(json.dumps({"all_assertions_passed":True,
"shell_reference_error":trajectory["reference_trace_distance_to_bare_erasure"],
"shell_proved_bound":trajectory["proved_half_diamond_upper_bound"],
"comparison_evolution_error":trajectory["reference_comparison_evolution_trace_distance"],
"smallest_CP_domination_eigenvalue":min(r["full_input_minimum_Choi_domination_eigenvalue"] for r in cp),
"rows":{"CP":len(cp),"tails":len(tails),"rates":len(rates),"finite_certificates":len(certificates)}},indent=2))
if __name__=="__main__":main()