File size: 8,087 Bytes
fd3c473 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 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 | #!/usr/bin/env python3
"""Reproduce the v2 circuit checks. Floating-point tests are not proofs.
Only NumPy is required. Every variable gate is simulated as fixed mixers and
two scalar phase shifts; dense Householder matrices are an independent oracle.
"""
import argparse
import json
import platform
from pathlib import Path
import numpy as np
BX = np.array([[1, 1], [1, -1]], complex) / np.sqrt(2)
BY = np.array([[1, 1], [1j, -1j]], complex) / np.sqrt(2)
def controls(u):
"""Arrays alpha[k,j], beta[k,j]; O(n^2) scalar arithmetic."""
prefix_sq = 1 + np.cumsum(np.abs(u)**2, axis=0)
before_sq = np.vstack([np.ones((1, len(u))), prefix_sq[:-1]])
alpha = 0.5 * np.arctan(u.imag / np.sqrt(before_sq))
beta = -np.arctan(u.real / np.sqrt(before_sq + u.imag**2))
return alpha, beta
def phase_rotation(axis, angle, errors=None):
"""B diag(exp(i theta),exp(-i theta)) B^dagger, with fixed B."""
b = BX if axis == 'X' else BY
phases = np.array([angle, -angle])
if errors is not None:
phases += errors
return b @ np.diag(np.exp(1j*phases)) @ b.conj().T
def swap_banks(n):
return np.block([[np.zeros((n, n)), np.eye(n)],
[np.eye(n), np.zeros((n, n))]]).astype(complex)
def compile_matrix(u, noise=None):
"""Execute a fixed circuit, starting with the fixed bank swap.
noise: optional array with one error for each of the 12*n^2 physical
tunable scalar phase occurrences. Fixed pi reflections are ideal here.
"""
n = len(u)
alpha, beta = controls(u)
out = swap_banks(n)
cursor = 0
def apply_rotation(a, k, axis, angle):
nonlocal out, cursor
errors = None if noise is None else noise[cursor:cursor+2]
gate = phase_rotation(axis, angle, errors)
out[[a, k], :] = gate @ out[[a, k], :]
cursor += 2
for j in range(n):
a = n+j
# B_j maps w_j=(-u_j,e_j)/sqrt(2) to the anchor e_{n+j}.
for k in range(n):
for axis, angle in [('X', alpha[k,j]), ('Y', beta[k,j]),
('X', alpha[k,j])]:
apply_rotation(a, k, axis, angle)
out[a, :] *= -1 # Fixed pi phase.
for k in reversed(range(n)):
for axis, angle in [('X', -alpha[k,j]), ('Y', -beta[k,j]),
('X', -alpha[k,j])]:
apply_rotation(a, k, axis, angle)
assert cursor == 12*n*n
return out
def reflection_oracle(u):
n = len(u)
out = swap_banks(n)
for j in range(n):
w = np.r_[-u[:,j], np.eye(n)[:,j]] / np.sqrt(2)
out -= 2*np.outer(w, w.conj() @ out)
return out
def expected(u):
n = len(u)
return np.block([[u, np.zeros((n,n))],
[np.zeros((n,n)), u.conj().T]])
def haar(n, rng):
z = rng.normal(size=(n,n)) + 1j*rng.normal(size=(n,n))
q, r = np.linalg.qr(z)
return q @ np.diag(np.diag(r)/np.abs(np.diag(r)))
def op(a):
return float(np.linalg.norm(a, 2))
def fro(a):
return float(np.linalg.norm(a))
def test_targets(n, rng):
eye = np.eye(n, dtype=complex)
q = np.arange(n)
yield 'identity', eye
yield 'minus_identity', -eye
yield 'imaginary_identity', 1j*eye
yield 'fourier', np.exp(2j*np.pi*np.outer(q,q)/n)/np.sqrt(n)
yield 'cyclic_permutation', np.roll(eye, 1, axis=0)
yield 'diagonal_near_minus_one', np.diag(np.exp(1j*(np.pi+1e-10*(q+1))))
for i in range(6):
yield f'haar_{i}', haar(n, rng)
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--output', default='verification.json')
args = parser.parse_args()
rng = np.random.default_rng(2709202602)
samples = []
max_gate_error = 0.0
max_lipschitz_ratio = 0.0
noise_records = []
for n in [1,2,3,4,8,16,32]:
for label, u in test_targets(n, rng):
a, b = controls(u)
actual = compile_matrix(u)
target = expected(u)
err = op(actual-target)
oracle_error = op(reflection_oracle(u)-target)
assert err < 2e-11 and oracle_error < 2e-11
assert np.max(np.abs(a)) <= np.pi/8 + 1e-14
assert np.max(np.abs(b)) <= np.pi/4 + 1e-14
prefix = 1 + np.cumsum(np.abs(u)**2, axis=0)
before = np.vstack([np.ones((1,n)), prefix[:-1]])
for j in range(n):
for k in range(n):
z = -u[k,j]/np.sqrt(prefix[k,j])
c = np.sqrt(before[k,j]/prefix[k,j])
g = np.array([[c, z.conjugate()], [-z, c]])
xyx = (phase_rotation('X', a[k,j]) @
phase_rotation('Y', b[k,j]) @
phase_rotation('X', a[k,j]))
max_gate_error = max(max_gate_error, op(g-xyx))
samples.append(dict(n=n, target=label,
full_matrix_error=err,
signal_error=op(actual[:n,:n]-u),
leakage=op(actual[n:,:n]),
reflection_oracle_error=oracle_error,
variable_phase_occurrences=12*n*n))
# Check the global derivative bound, including off-manifold directions.
u = haar(n, rng)
a,b = controls(u)
for _ in range(8):
du = rng.normal(size=u.shape)+1j*rng.normal(size=u.shape)
du *= 1e-5 / fro(du)
av,bv = controls(u+du)
ratio = np.sqrt(fro(av-a)**2+fro(bv-b)**2)/fro(du)
normalized = ratio/(np.sqrt(5*n)/2)
assert normalized <= 1+1e-8
max_lipschitz_ratio = max(max_lipschitz_ratio, float(normalized))
if n <= 8:
delta = 1e-5
noise = rng.uniform(-delta,delta,12*n*n)
error = op(compile_matrix(u,noise)-expected(u))
bound = min(2.,12*n*n*delta)
assert error <= bound+1e-12
noise_records.append(dict(n=n, phase_error_limit=delta,
operator_error=error, proved_bound=bound))
# Operational distinction: an antipodal state alone has zero channel error;
# the orthogonal witness has trace-norm distance two.
v = np.ones(2,dtype=complex)/np.sqrt(2)
rho = np.outer(v,v.conj())
anti = -v
ortho = np.diag([1j,-1j]) @ v
d_anti = float(np.linalg.norm(rho-np.outer(anti,anti.conj()), ord='nuc'))
d_ortho = float(np.linalg.norm(rho-np.outer(ortho,ortho.conj()), ord='nuc'))
assert d_anti < 1e-14 and abs(d_ortho-2)<1e-14
# Smooth closed target loop: parameter values agree at the endpoints.
ts = np.linspace(0,2*np.pi,1001)
phases = np.array([np.r_[controls(np.diag([np.exp(1j*t),np.exp(-1j*t)]))[0].ravel(),
controls(np.diag([np.exp(1j*t),np.exp(-1j*t)]))[1].ravel()]
for t in ts])
loop_closure = fro(phases[-1]-phases[0])
assert loop_closure < 1e-14
report = dict(version='2.0', seed=2709202602, python=platform.python_version(),
numpy=np.__version__, sample_count=len(samples),
all_checks_passed=True,
max_full_matrix_error=max(s['full_matrix_error'] for s in samples),
max_elementary_gate_error=max_gate_error,
max_normalized_lipschitz_ratio=max_lipschitz_ratio,
phase_loop_closure=loop_closure,
antipodal_state_trace_distance_unnormalized=d_anti,
orthogonal_state_trace_distance_unnormalized=d_ortho,
noise_checks=noise_records, samples=samples,
limits=['Floating-point checks, not interval certificates.',
'Sampling does not prove a global topological theorem.',
'No fabricated-device or experimental validation.'])
Path(args.output).write_text(json.dumps(report,indent=2)+'\n')
print(json.dumps({k:v for k,v in report.items() if k not in ['samples','noise_checks']},indent=2))
if __name__ == '__main__':
main()
|