#!/usr/bin/env python3 """Independent heteroscedastic Gaussian and free-fermion checks. The conditional variance mixture is a synthetic control, not an approximation to the actual SYK form factor. It establishes that a nonzero unconditional fourth cumulant can arise without a conditional fourth cumulant. """ import os for key in ('OPENBLAS_NUM_THREADS','OMP_NUM_THREADS','MKL_NUM_THREADS'): os.environ[key]='1' import math import json import argparse import csv import numpy as np from scipy.linalg import eigh from run_experiments import OUT,SEED,SYKBasis,moment_estimates,records_csv,save_json def run(): OUT.mkdir(parents=True,exist_ok=True) rng=np.random.default_rng(SEED+811) N=10;d2=math.comb(N,2);d4=math.comb(N,4) kappas=[0.,1.,4.,16.,64.,math.inf] nblocks,blocksize=100,20000 # Store scalar block estimates and global raw moments rather than 2M vectors. sums=np.zeros((len(kappas)+1,6),complex) blocks=np.empty((nblocks,len(kappas)+1)) for b in range(nblocks): R2sq=rng.chisquare(d2,blocksize)/d2 R4sq=rng.chisquare(d4,blocksize)/d4 z0=(rng.standard_normal(blocksize)+1j*rng.standard_normal(blocksize))/np.sqrt(2) for j,k in enumerate(kappas+[None]): if k is None: z=z0 else: w4,w2=(0.,1.) if np.isinf(k) else (1/(1+k*k),k*k/(1+k*k)) z=z0*np.sqrt(w4*R4sq+w2*R2sq) C,P,k4,q4=moment_estimates(z[:,None]);blocks[b,j]=q4[0] sums[j]+=[np.sum(z),np.sum(abs(z)**2),np.sum(z*z), np.sum(z*abs(z)**2),np.sum(abs(z)**4),blocksize] records=[] for j,k in enumerate(kappas+[None]): n=float(sums[j,5].real);raw=sums[j]/n;mu=raw[0] m11=raw[1].real-abs(mu)**2;m20=raw[2]-mu*mu m22=(raw[4]-4*np.real(mu.conjugate()*raw[3])+2*np.real(mu.conjugate()**2*raw[2]) +4*abs(mu)**2*raw[1]-3*abs(mu)**4).real C=n/(n-1)*m11 k4=n*n/((n-1)*(n-2)*(n-3))*((n+1)*m22-(n-1)*(2*m11*m11+abs(m20)**2)) if k is None:theory=0. else: w4,w2=(0.,1.) if np.isinf(k) else (1/(1+k*k),k*k/(1+k*k)) theory=4*(w4*w4/d4+w2*w2/d2) # Block standard errors are diagnostics, not confidence bounds for SYK. rec={'N':N,'kappa':str(k) if k is not None else 'whitened', 'samples':int(n),'q4_theory':theory,'q4_global_estimate':float(k4/C**2), 'q4_block_standard_error':float(blocks[:,j].std(ddof=1)/np.sqrt(nblocks)), 'paired_excess_over_whitened':float((blocks[:,j]-blocks[:,-1]).mean()), 'paired_excess_standard_error':float((blocks[:,j]-blocks[:,-1]).std(ddof=1)/np.sqrt(nblocks)), 'conditional_q4_theory':0.} records.append(rec) records_csv(OUT/'heteroscedastic_gaussian_control.csv',records) np.savez_compressed(OUT/'heteroscedastic_gaussian_control.npz',raw_sums=sums,block_q4=blocks,seed=SEED+811, nblocks=nblocks,blocksize=blocksize,N=N,kappas=np.array(kappas)) # Validate the quadratic many-body spectrum against sums of one-body modes. N=14;basis=SYKBasis(N,None);g=rng.standard_normal(math.comb(N,2));B=basis.assemble(2,g) coeff=g*(1/np.sqrt(N))/np.sqrt(basis.hs2) K=np.zeros((N,N));q=0 for i in range(N): for j in range(i+1,N):K[i,j]=coeff[q];K[j,i]=-coeff[q];q+=1 lambdas=eigh(1j*K,eigvals_only=True)[N//2:] subset_sums=np.array([sum(lambdas[a]*(((b>>a)&1)-.5) for a in range(N//2)) for b in range(2**(N//2))]) err=float(np.max(abs(np.sort(subset_sums)-eigh(B,eigvals_only=True)))) save_json(OUT/'synthetic_controls_validation.json',{ 'model':'xi|R is proper complex normal with conditional variance w4 R4^2+w2 R2^2', 'conditional_fourth_cumulant_exact':0, 'unconditional_q4_exact':'4*(w4^2/d4+w2^2/d2)', 'sample_count':nblocks*blocksize,'block_count':nblocks,'block_size':blocksize, 'free_fermion_full_spectrum_max_error':err,'free_fermion_N':N,'free_fermion_pass':err<1e-11, 'scope':'synthetic Gaussian variance-mixture illustration; no identification with actual SYK conditional distribution'}) plot_results() print(json.dumps({'free_fermion_error':err,'synthetic_q4_results':records},indent=2),flush=True) def plot_results(): """Redraw the stored synthetic control without drawing new samples.""" with (OUT/'heteroscedastic_gaussian_control.csv').open() as fh: records=list(csv.DictReader(fh)) for row in records: for key in ('q4_global_estimate','q4_block_standard_error','q4_theory'): row[key]=float(row[key]) figure_dir = OUT / "figures" figure_dir.mkdir(parents=True, exist_ok=True) import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt from plot_style import configure configure() plt.rcParams.update({'font.size':9,'axes.spines.top':False,'axes.spines.right':False,'pdf.fonttype':42}) fig,ax=plt.subplots(figsize=(5.2,3.3)) y=np.array([r['q4_global_estimate'] for r in records]);se=np.array([r['q4_block_standard_error'] for r in records]) ax.errorbar(np.arange(len(records)),y,yerr=1.96*se,fmt='o',capsize=3,label='Monte Carlo; 1.96 block SE') ax.plot(np.arange(len(records)),[r['q4_theory'] for r in records],'x',ms=8,label='Exact variance-mixture formula') ax.axhline(0,color='0.5',lw=.8) ax.set(xticks=np.arange(7),xticklabels=['0','1','4','16','64',r'$\infty$','Whitened'], xlabel=r'Mixture parameter $\kappa$',ylabel=r'$Q_\xi/C_\xi^2$',title='Conditional Gaussian control (N=10 radial laws)') ax.legend(fontsize=8);fig.tight_layout();fig.savefig(figure_dir/'heteroscedastic_control.pdf');fig.savefig(figure_dir/'heteroscedastic_control.png',dpi=180) def main(): parser=argparse.ArgumentParser(description=__doc__) parser.add_argument('--stage',choices=['run','plot'],default='run') args=parser.parse_args() if args.stage=='plot':plot_results() else:run() if __name__=='__main__':main()