PureOne's picture
Publish NIRAEL quantum instant language research release
e3bdcca verified
Raw History Blame Contribute Delete
9.72 kB
"""NIRAEL quantum-language checks and manuscript figures.
All data are finite synthetic calculations. The analytic proofs are in the PDF.
Requires Python 3.10+, NumPy, Matplotlib. No network access is used.
"""
from pathlib import Path
from itertools import combinations
from math import comb
import json
import numpy as np
ROOT = Path(__file__).resolve().parent
OUT = ROOT.parent / 'output' / 'pdf' / 'figures'
OUT.mkdir(parents=True, exist_ok=True)
def zeta_upper(a, n):
a = np.array(a, float, copy=True)
for i in range(n):
bit = 1 << i
for mask in range(1 << n):
if not (mask & bit):
a[mask] += a[mask | bit]
return a
def walsh(a):
v = np.array(a, float, copy=True)
h = 1
while h < len(v):
for i in range(0, len(v), 2*h):
left, right = v[i:i+h].copy(), v[i+h:i+2*h].copy()
v[i:i+h], v[i+h:i+2*h] = left + right, left - right
h *= 2
return v
def periods(f):
N = len(f)
return [h for h in range(N) if all(f[x] == f[x ^ h] for x in range(N))]
def check_periods():
n = 3; N = 1 << n
checked = 0
rng = np.random.default_rng(260624)
for fm in range(1 << N):
f = np.array([(fm >> x) & 1 for x in range(N)])
H = periods(f)
annihilator = [a for a in range(N) if all((a & h).bit_count() % 2 == 0 for h in H)]
p = np.zeros(N)
p[annihilator] = 1/len(annihilator)
w = walsh(p)
assert max((abs(w[x ^ y]) for x in range(N) for y in range(N) if f[x] != f[y]), default=0) < 1e-12
# A translation-invariant randomized mixture of annihilator cosets.
base = rng.random(N); base /= base.sum()
q = sum(base[np.arange(N) ^ a] for a in annihilator)/len(annihilator)
wq = walsh(q)
assert all(abs(wq[h]) < 1e-12 for h in range(N) if h not in H)
checked += 1
hamming = []
for n in range(1, 9):
for k in range(n):
f = np.array([int(x.bit_count() <= k) for x in range(1 << n)])
assert periods(f) == [0]
hamming.append((n,k))
return {'boolean_functions_checked': checked, 'hamming_ball_predicates_checked':len(hamming)}
def rank_f2(a):
a=np.array(a,dtype=np.uint8,copy=True)
if not a.size: return 0
r=0
for c in range(a.shape[1]):
piv=np.flatnonzero(a[r:,c])
if not len(piv): continue
j=r+int(piv[0]); a[[r,j]]=a[[j,r]]
for i in range(a.shape[0]):
if i!=r and a[i,c]: a[i]^=a[r]
r+=1
if r==a.shape[0]: break
return r
def reduced_betti(faces):
# Augmented simplicial complex, over F_2. Empty face included.
levels={d:[f for f in faces if f.bit_count()==d+1] for d in range(-1,6)}
ranks={}
for d in range(0,6):
rows=levels[d-1]; cols=levels[d]
mat=np.zeros((len(rows),len(cols)),dtype=np.uint8)
lookup={r:i for i,r in enumerate(rows)}
for j,f in enumerate(cols):
for i in range(5):
if f & (1<<i): mat[lookup[f^(1<<i)],j]=1
ranks[d]=rank_f2(mat)
return {d:len(levels[d])-ranks.get(d,0)-ranks.get(d+1,0) for d in range(-1,5)}
def check_homology():
n=5; forbidden=[0b00111,0b11100,0b01001]
faces=[f for f in range(1<<n) if not any(f&c==c for c in forbidden)]
coeff=np.zeros(1<<n,dtype=int)
betti=[]
for S in range(1<<n):
induced=[f for f in faces if f&S==f]
bs=reduced_betti(induced)
for i in range(n+1):
val=bs.get(S.bit_count()-i-1,0)
if val:
betti.append({'homological_degree':i,'support':S,'value':val})
coeff[S]+=(-1)**i*val
expected=np.zeros(1<<n,dtype=int)
expected[0]=1
for mask in forbidden: expected[mask]-=1
expected[0b01111]+=1
expected[0b11101]+=1
assert np.array_equal(coeff,expected)
rng=np.random.default_rng(413)
error=0
for _ in range(100):
q=rng.random(n)
accept=sum(np.prod([q[i] if f&(1<<i) else 1-q[i] for i in range(n)]) for f in faces)
algebra=sum(coeff[S]*np.prod([q[i] for i in range(n) if S&(1<<i)]) for S in range(1<<n))
error=max(error,abs(accept-algebra))
assert error<1e-12
return {'faces':len(faces),'minimal_nonfaces':forbidden,'nonzero_betti':betti,
'hilbert_numerator_coefficients':{str(i):int(c) for i,c in enumerate(coeff) if c},
'max_probability_error':float(error),'all_active_q_0_64_refusal':float(.64**2+2*.64**3-2*.64**4)}
def check_compiler():
n=8; N=1<<n
candidates=np.array([sum(1<<i for i in C) for C in combinations(range(n),3)])
rng=np.random.default_rng(20261024)
# A frozen nonuniform prior with two clusters of frequent deviations.
x=np.arange(N)
prior=rng.random(N)**2
prior*=1+4*((x&7)==7)+3*((x&224)==224)
prior/=prior.sum()
local_q=np.array([.88,.82,.73,.92,.62,.79,.84,.68])
gamma=np.array([np.prod([local_q[i] for i in range(n) if c&(1<<i)]) for c in candidates])
r=np.array([g*((x&c)==c) for c,g in zip(candidates,gamma)])
v=prior.copy(); chosen=[]; scores=[0.0]; maxerr=0
for _ in range(4):
z=zeta_upper(v,n)
gain=gamma*z[candidates]
direct=r@v
maxerr=max(maxerr,float(np.max(abs(gain-direct))))
gain[chosen]=-1
j=int(np.argmax(gain)); chosen.append(j)
v*=1-r[j]
scores.append(float(1-v.sum()))
exact_value=-1; exact=None
# Three packets allow a meaningful complete finite optimizer (27,720 choices).
for S in combinations(range(len(candidates)),3):
val=float(prior@(1-np.prod(1-r[list(S)],axis=0)))
if val>exact_value: exact_value=val; exact=S
violations=0; min_slack=1
for _ in range(1500):
p=rng.permutation(len(candidates))
A=p[:2]; B=p[:5]; j=p[6]
ga=float(prior@(r[j]*np.prod(1-r[A],axis=0)))
gb=float(prior@(r[j]*np.prod(1-r[B],axis=0)))
min_slack=min(min_slack,ga-gb)
violations+=int(ga+1e-12<gb)
assert maxerr<1e-12 and violations==0
return {'n':n,'candidates':len(candidates),'seed':20261024,
'greedy_packets':[int(candidates[j]) for j in chosen], 'greedy_success':scores,
'exact_three_packet_success':exact_value,
'exact_three_packets':[int(candidates[j]) for j in exact],
'three_packet_greedy_ratio':scores[3]/exact_value,
'sets_exhaustively_checked':comb(len(candidates),3),
'zeta_direct_max_error':maxerr,'submodularity_checks':1500,
'submodularity_violations':violations,'minimum_diminishing_return_slack':min_slack}
def make_figures(report):
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
from check_local_global import product_gram
plt.rcParams.update({'font.family':'DejaVu Sans','font.size':10,'axes.spines.top':False,
'axes.spines.right':False,'axes.labelcolor':'#14222B','text.color':'#14222B',
'figure.facecolor':'white','axes.prop_cycle':plt.cycler(color=['#187F70','#AD5269','#6C7890'])})
ss=np.linspace(.015,.985,110)
fig,axs=plt.subplots(1,2,figsize=(9,3.1),layout='constrained')
for ax,n,kind in [(axs[0],2,'AND'),(axs[1],3,'MAJORITY')]:
f=np.array([int(x==2**n-1) if kind=='AND' else int(x.bit_count()>n//2) for x in range(2**n)])
d=1-2*f; local=[]; glob=[]
for s in ss:
_,R=product_gram([s]*n)
H=(R*d[None,:])@R/(2**n)
glob.append((1+np.sum(abs(np.linalg.eigvalsh(H))))/2)
local.append((1+np.trace(d[:,None]*H))/2)
ax.plot(ss,glob,label='Optimal collective readout',lw=2)
ax.plot(ss,local,label='Bitwise Helstrom, then f',lw=1.8)
ax.fill_between(ss,local,glob,color='#73E2C0',alpha=.25)
ax.set(title=f'{kind} on {n} bits',xlabel='Pure-state overlap s',ylabel='Success probability',ylim=(.48,1.01))
axs[0].legend(fontsize=8)
fig.savefig(OUT/'local_global_boundary.pdf'); plt.close(fig)
fig,axs=plt.subplots(1,2,figsize=(9,3.1),layout='constrained')
q=np.linspace(0,1,301)
for w in [3,5,8]:
vals=sum(comb(w,j)*q**j*(1-q)**(w-j) for j in range(3,w+1))
axs[0].plot(q,vals,label=f'{w} active symbols',lw=1.8)
axs[0].set(xlabel='Local conclusive activation q',ylabel='Optimal refusal probability',title='Refuse the at-most-two grammar')
axs[0].legend(fontsize=8)
axs[1].plot(q,q**2+2*q**3-2*q**4,lw=2,label='Three overlapping forbidden sets')
axs[1].plot(q,q**3,lw=1.8,label='One three-symbol certificate')
axs[1].set(xlabel='Local conclusive activation q',ylabel='Optimal refusal probability',title='Grammar changes the response law')
axs[1].legend(fontsize=8)
fig.savefig(OUT/'grammar_reliability.pdf'); plt.close(fig)
c=report['compiler']; fig,ax=plt.subplots(figsize=(7,2.7),layout='constrained')
ax.plot(range(5),c['greedy_success'],'o-',color='#187F70',lw=2,label='Greedy complete-certificate packets')
ax.scatter([3],[c['exact_three_packet_success']],marker='D',color='#AD5269',s=55,label='Exhaustive optimum at three packets',zorder=3)
ax.set(xlabel='Independent packet budget',ylabel='Expected sound refusal',xticks=range(5),ylim=(0,.55))
ax.legend(fontsize=8)
fig.savefig(OUT/'certificate_compiler.pdf'); plt.close(fig)
def main():
report={'status':'finite synthetic verification, not experimental quantum hardware',
'periods':check_periods(),'homology':check_homology(),'compiler':check_compiler()}
(ROOT/'nirael_results.json').write_text(json.dumps(report,indent=2))
make_figures(report)
print(json.dumps(report,indent=2))
if __name__=='__main__': main()