OQAIVAEI / research /experiments /quantum_experiments.py
PureOne's picture
Publish OQAIVAEI research release
9552b49 verified
Raw History Blame Contribute Delete
13.8 kB
#!/usr/bin/env python3
"""Finite consistency checks for the quantum-continuation chapter.
Run from the release directory:
python experiments/quantum_experiments.py --output results/quantum_results.json
Requires NumPy. Checks are explicit exceptions, not assert statements, so
python -O does not remove them. These are floating-point checks, not formal
proofs or interval certificates. No network or external data are required.
"""
from __future__ import annotations
import argparse
import itertools
import json
import math
import platform
from pathlib import Path
import numpy as np
TOL = 2e-9
SEED = 20261020
class Audit:
def __init__(self):
self.count = 0
self.max_abs_residual = 0.0
self.named_checks = []
def close(self, label, observed, expected=0.0, tol=TOL):
err = float(np.max(np.abs(np.asarray(observed) - np.asarray(expected))))
self.count += 1
self.max_abs_residual = max(self.max_abs_residual, err)
if not math.isfinite(err) or err > tol:
raise RuntimeError(f"{label}: residual {err} exceeds {tol}")
def truth(self, label, condition):
self.count += 1
if not bool(condition):
raise RuntimeError(label)
def opnorm(x):
return float(np.linalg.norm(x, 2))
def proj(v):
return np.outer(v, v.conj())
def two_bases(d):
z = np.eye(d, dtype=complex)
j = np.arange(d)
x = np.exp(2j * np.pi * np.outer(j, j) / d) / np.sqrt(d)
return z, x
def basis_projectors(u):
return [proj(u[:, j]) for j in range(u.shape[0])]
def apply_channel(ks, x):
return sum((k @ x @ k.conj().T for k in ks), np.zeros_like(x, dtype=complex))
def apply_adjoint(ks, x):
return sum((k.conj().T @ x @ k for k in ks), np.zeros_like(x, dtype=complex))
def subset_kraus(u, k):
d = u.shape[0]
norm = math.sqrt(math.comb(d - 1, k - 1))
return [u[:, s] @ u[:, s].conj().T / norm
for s in itertools.combinations(range(d), k)]
def laplacian(projectors, weights=None):
d = projectors[0].shape[0]
if weights is None:
weights = np.ones(len(projectors))
out = np.zeros((d * d, d * d), dtype=complex)
for p, w in zip(projectors, weights):
# vec(PX+XP-2PXP), column-major convention.
out += w * (np.kron(np.eye(d), p) + np.kron(p.T, np.eye(d))
- 2 * np.kron(p.T, p))
return (out + out.conj().T) / 2
def full_algebra_defect(ks, d):
return float(d - sum(abs(np.trace(k)) ** 2 for k in ks) / d)
def check_mub_frontiers(audit):
rows = []
for d in range(2, 8):
z, x = two_bases(d)
ps, qs = basis_projectors(z), basis_projectors(x)
audit.close(f"MUB overlaps d={d}", np.abs(z.conj().T @ x) ** 2, 1 / d)
eig = np.linalg.eigvalsh(laplacian(ps + qs))
audit.close(f"Laplacian kernel d={d}", eig[0], 0)
audit.close(f"Laplacian gap d={d}", eig[1], 2)
for k in range(1, d + 1):
kz, kx = subset_kraus(z, k), subset_kraus(x, k)
for mixing in (0.0, 0.2, 0.5, 0.8, 1.0):
ks = [np.sqrt(mixing) * a for a in kz]
ks += [np.sqrt(1 - mixing) * a for a in kx]
audit.close("trace preservation", sum(a.conj().T @ a for a in ks), np.eye(d))
audit.close("unitality", sum(a @ a.conj().T for a in ks), np.eye(d))
audit.truth("Kraus rank exceeds memory dimension",
max(np.linalg.matrix_rank(a, tol=1e-8) for a in ks) <= k)
ez = max(opnorm(apply_adjoint(ks, p) - p) for p in ps)
ex = max(opnorm(apply_adjoint(ks, q) - q) for q in qs)
audit.close("Z error formula", ez, (1 - mixing) * (1 - k / d))
audit.close("X error formula", ex, mixing * (1 - k / d))
defect = full_algebra_defect(ks, d)
audit.close("sharp defect profile", defect, d - k)
energy = sum(np.linalg.norm(a @ p - p @ a, "fro") ** 2
for a in ks for p in ps + qs)
audit.close("MUB gap saturation", energy, 2 * (d - k))
if mixing == 0.5:
rows.append(dict(dimension=d, quantum_dimension=k,
observed_error=max(ez, ex),
predicted_error=(d-k)/(2*d),
classical_branches=len(ks), defect=defect))
return rows
def check_response_only(audit):
rows = []
for d in range(2, 11):
z, x = two_bases(d)
ps, qs = basis_projectors(z), basis_projectors(x)
joint = [[None for _ in range(d)] for _ in range(d)]
for j in range(d):
for ell in range(d):
overlap = np.vdot(z[:, j], x[:, ell])
phase = np.sqrt(d) * overlap.conjugate()
chi = z[:, j] + phase * x[:, ell]
joint[j][ell] = proj(chi) / (2 * (d + np.sqrt(d)))
audit.truth("joint POVM positivity", np.linalg.eigvalsh(joint[j][ell])[0] > -TOL)
audit.close("joint POVM normalization", sum(sum(row) for row in joint), np.eye(d))
ptilde = [sum(row) for row in joint]
qtilde = [sum(joint[j][ell] for j in range(d)) for ell in range(d)]
ez = max(opnorm(a-b) for a,b in zip(ptilde,ps))
ex = max(opnorm(a-b) for a,b in zip(qtilde,qs))
expected = (1 - 1/np.sqrt(d))/2
audit.close("response-only Z optimum", ez, expected)
audit.close("response-only X optimum", ex, expected)
restoration = (1 - 1/d)/2
audit.truth("contract separation", max(ez,ex) < restoration)
rows.append(dict(dimension=d, response_only_error=max(ez,ex),
common_restoration_error=restoration,
joint_classical_labels=d*d))
return rows
def check_anchor_and_noisy_compiler(audit):
e = np.eye(3, dtype=complex)
ks = [np.outer(e[:,0],e[:,0]), np.outer(e[:,1],e[:,1]),
np.outer(e[:,0],e[:,2])/np.sqrt(2),
np.outer(e[:,1],e[:,2])/np.sqrt(2)]
test = np.diag([0.,1.,.5]).astype(complex)
tau = np.eye(3)/3
audit.close("unanchored test preserved", apply_adjoint(ks,test), test)
square_error = opnorm(apply_adjoint(ks,test@test) - test@test)
audit.close("unanchored square not preserved", square_error, .25)
anchor = np.trace((apply_channel(ks,tau)-tau) @ test @ test).real
audit.close("quadratic anchor detects missing product", anchor, 1/12)
def damping(gamma):
return [np.diag([1.,np.sqrt(1-gamma)]).astype(complex),
np.array([[0.,np.sqrt(gamma)],[0.,0.]],dtype=complex)]
phi = damping(.3)
psi = damping(.4)
q = np.diag([1.,-1.]).astype(complex)
ee = apply_adjoint(phi,q)
rr = apply_adjoint(phi,q@q)
cc = rr-ee@ee
tau2 = np.eye(2)/2
drift = apply_channel(psi,tau2)-tau2
accessible = abs(np.trace(drift@rr))
intrinsic = abs(np.trace(drift@ee@ee))
osc = float(np.ptp(np.linalg.eigvalsh(cc)))
delta = float(np.sum(np.abs(np.linalg.eigvalsh(drift))))
audit.close("accessible quadratic drift is zero",accessible,0)
audit.close("intrinsic drift is nonzero",intrinsic,.168)
audit.close("noisy compiler bound saturation", intrinsic, accessible+delta*osc/2)
audit.truth("Schwarz defect PSD",np.linalg.eigvalsh(cc)[0]>=-TOL)
return dict(unanchored_square_error=square_error, anchor_drift=float(anchor),
accessible_drift=float(accessible), intrinsic_drift=float(intrinsic),
schwarz_defect_oscillation=osc, reference_trace_distance=delta)
def hermitian_orthobasis(candidates, tolerance=1e-9):
out=[]
for x in candidates:
v=(x+x.conj().T)/2
for q in out:
v=v-np.vdot(q,v).real*q
norm=np.linalg.norm(v,"fro")
if norm>tolerance:
out.append(v/norm)
return out
def check_continuation_closure(audit):
h=np.array([[1,1],[1,-1]],dtype=complex)/np.sqrt(2)
s=np.diag([1,1j])
p=np.diag([1.,0.]).astype(complex)
current=hermitian_orthobasis([np.eye(2),p])
dims=[len(current)]
for _ in range(4):
newer=hermitian_orthobasis(current+[u.conj().T@a@u for u in (h,s) for a in current])
dims.append(len(newer))
if len(newer)==len(current):
break
current=newer
audit.truth("finite closure dimension chain",dims==[2,3,4,4])
single=hermitian_orthobasis([np.eye(2),p,h.conj().T@p@h])
audit.truth("operator system can be smaller than algebra",len(single)==3)
return dict(two_control_dimensions=dims, one_control_operator_system_dimension=3,
generated_algebra_dimension=4)
def check_graph_gap(audit):
rng=np.random.default_rng(SEED)
rows=[]
for d in range(2,7):
for trial in range(5):
m=2*d
v=rng.normal(size=(d,m))+1j*rng.normal(size=(d,m))
v=v/np.linalg.norm(v,axis=0)
weights=rng.uniform(.5,1.5,m)
weights=weights/weights.sum()
ps=[proj(v[:,j]) for j in range(m)]
frame=sum(w*p for w,p in zip(weights,ps))
amin=float(np.linalg.eigvalsh(frame)[0])
c=weights[:,None]*weights[None,:]*abs(v.conj().T@v)**2
np.fill_diagonal(c,0)
graph=np.diag(c.sum(axis=1))-c
scaled=graph/np.sqrt(weights[:,None]*weights[None,:])
gamma=float(np.linalg.eigvalsh(scaled)[1])
bound=2*amin*gamma/(gamma+2*weights.sum())
gap=float(np.linalg.eigvalsh(laplacian(ps,weights))[1])
audit.truth("graph gap bound violated",gap+TOL>=bound>0)
rows.append(dict(dimension=d,trial=trial,frame_min=amin,
graph_gap=gamma,bound=bound,actual_gap=gap))
return rows
def check_direct_sum_profile(audit):
blocks=[(3,2),(2,1)]
d=sum(n*m for n,m in blocks)
rows=[]
for k in (1,2,3):
ks=[]
offset=0
for n,m in blocks:
r=min(k,n)
c=math.comb(n-1,r-1)
for subset in itertools.combinations(range(n),r):
p=np.diag([1. if i in subset else 0. for i in range(n)])
for a in range(m):
for b in range(m):
unit=np.zeros((m,m));unit[a,b]=1
local=np.kron(p,unit)/np.sqrt(c*m)
full=np.zeros((d,d),dtype=complex)
full[offset:offset+n*m,offset:offset+n*m]=local
ks.append(full)
offset+=n*m
audit.close("direct sum TP",sum(a.conj().T@a for a in ks),np.eye(d))
defect=0.
for a in ks:
projection=np.zeros_like(a)
offset=0
for n,m in blocks:
local=a[offset:offset+n*m,offset:offset+n*m].reshape(n,m,n,m)
partial=sum(local[i,:,i,:] for i in range(n))
projection[offset:offset+n*m,offset:offset+n*m]=np.kron(np.eye(n)/n,partial)
offset+=n*m
defect+=np.linalg.norm(a-projection,"fro")**2
predicted=sum(m*max(n-k,0) for n,m in blocks)
audit.close("direct sum sharp profile",defect,predicted)
audit.truth("direct sum Kraus ranks",max(np.linalg.matrix_rank(a,tol=1e-8) for a in ks)<=k)
rows.append(dict(blocks=blocks,quantum_dimension=k,defect=float(defect),predicted=predicted))
return rows
def check_mean_storage(audit):
rows=[]
for d in (2,3,4,6):
z,x=two_bases(d)
ps=basis_projectors(z)+basis_projectors(x)
base=[a/np.sqrt(2) for a in subset_kraus(z,1)+subset_kraus(x,1)]
for p in (0,.25,.5,.75,1):
ks=[np.sqrt(p)*np.eye(d)]+[np.sqrt(1-p)*a for a in base]
eps=max(opnorm(apply_adjoint(ks,a)-a) for a in ps)
b=p*np.log2(d)
predicted=(d-1)/(2*d)*(1-b/np.log2(d))
audit.close("mean storage frontier",eps,predicted)
rows.append(dict(dimension=d,mean_qubits=float(b),observed_error=eps,
predicted_error=float(predicted),peak_quantum_dimension=d))
return rows
def main():
parser=argparse.ArgumentParser(description=__doc__)
parser.add_argument("--output",type=Path,default=Path("results/quantum_results.json"))
args=parser.parse_args()
audit=Audit()
results=dict(
common_restoration=check_mub_frontiers(audit),
response_only=check_response_only(audit),
calibration=check_anchor_and_noisy_compiler(audit),
finite_closure=check_continuation_closure(audit),
overlap_graph_gap=check_graph_gap(audit),
direct_sum_profile=check_direct_sum_profile(audit),
mean_storage=check_mean_storage(audit))
# Deliberate corruption is expected to fail normalization; this confirms
# that a plausible-looking but non-channel Kraus list is rejected.
corrupted=[1.01*a for a in subset_kraus(np.eye(3),2)]
audit.truth("corrupted channel was not detected",
opnorm(sum(a.conj().T@a for a in corrupted)-np.eye(3))>1e-3)
payload=dict(status="PASS",method="floating-point finite consistency checks",
theorem_proof_status="analytical proofs in manuscript; no proof assistant",
seed=SEED,python=platform.python_version(),numpy=np.__version__,
checks=audit.count,max_abs_equality_residual=audit.max_abs_residual,
tolerance=TOL,results=results)
args.output.parent.mkdir(parents=True,exist_ok=True)
args.output.write_text(json.dumps(payload,indent=2)+"\n",encoding="utf-8")
print(json.dumps({k:payload[k] for k in ("status","checks","max_abs_equality_residual","tolerance")},indent=2))
if __name__=="__main__":
main()