#!/usr/bin/env python3 """Paired fixed-radius/Gaussian finite-N spacing curves. This scan uses disorder samples independent of the baseline spectral experiment. No phase-transition model or critical exponent is assumed. Reproduction from the directory containing this script and run_experiments.py: python directional_scaling.py --stage all --workers 2 --bootstrap 1000 python directional_scaling.py --stage analyze --bootstrap 1000 python directional_scaling.py --stage plot python directional_scaling.py --stage summarize The main stage uses two processes, each with one BLAS thread. Existing raw archives are reused only if their requested sample count and grid agree. The analyze stage resamples whole paired samples, saves the resampling counts, and writes CSV tables of the crossings and their sensitivity. The plot stage draws only from saved statistics and does not generate random numbers. """ import os for _key in ('OPENBLAS_NUM_THREADS','MKL_NUM_THREADS','OMP_NUM_THREADS', 'VECLIB_MAXIMUM_THREADS','NUMEXPR_NUM_THREADS'): os.environ[_key]='1' import argparse import csv import json import math import multiprocessing as mp import time from concurrent.futures import ProcessPoolExecutor, as_completed from pathlib import Path import numpy as np import scipy from scipy.linalg import eigh from scipy.special import polygamma, digamma from scipy.interpolate import PchipInterpolator from scipy.optimize import brentq from scipy.stats import f as f_distribution ROOT=Path(__file__).resolve().parents[1] OUT=ROOT/'results' FIG=OUT/'figures' from run_experiments import SYKBasis, mix, bulk_ratio SEED=2026111857 KAPPAS=np.array([0.,2.,4.,8.,12.,16.,24.,32.,48.,64.,96.,128.,np.inf]) ENSEMBLES=('gaussian','fixed_radii') THRESHOLDS=np.array([.25,.5,.75]) _BASES={} def save_json(path,obj): path.write_text(json.dumps(obj,indent=2,allow_nan=False)+'\n') def save_csv(path,records): with path.open('w',newline='') as stream: writer=csv.DictWriter(stream,fieldnames=list(records[0])) writer.writeheader();writer.writerows(records) def _sample_chunk(task): N,start,stop=task if N not in _BASES: _BASES[N]=SYKBasis(N) basis=_BASES[N] ns=stop-start spectra=np.empty((2,ns,len(KAPPAS),basis.d)) ratios=np.empty((2,ns,len(KAPPAS))) radii=np.empty((ns,2)) identity_error=0. shifted_ratio_error=0. begin=time.perf_counter() for pos,sid in enumerate(range(start,stop)): rng=np.random.default_rng(np.random.SeedSequence([SEED,N,sid])) A,B,R4,R2=basis.draw(rng) radii[pos]=R4,R2 Ad,Bd=A/R4,B/R2 for j,k in enumerate(KAPPAS): if j==0 or j==len(KAPPAS)-1: factor=R4 if j==0 else R2 E=eigh(A if j==0 else B,eigvals_only=True,check_finite=False,driver='evr') spectra[0,pos,j]=E spectra[1,pos,j]=E/factor r=bulk_ratio(E) ratios[:,pos,j]=r else: for ei,(AA,BB) in enumerate(((A,B),(Ad,Bd))): E=eigh(mix(AA,BB,k),eigvals_only=True,check_finite=False,driver='evr') spectra[ei,pos,j]=E ratios[ei,pos,j]=bulk_ratio(E) if sid==0: k=16. width=np.sqrt((R4*R4+k*k*R2*R2)/(1+k*k)) shifted=mix(Ad,Bd,k*R2/R4) identity_error=float(np.max(abs(mix(A,B,k)/width-shifted))) E=eigh(shifted,eigvals_only=True,check_finite=False,driver='evr') shifted_ratio_error=float(abs(bulk_ratio(E)-ratios[0,pos,np.where(KAPPAS==k)[0][0]])) return {'N':N,'start':start,'stop':stop,'spectra':spectra,'r':ratios,'radii':radii, 'seconds':time.perf_counter()-begin,'identity_error':identity_error, 'shifted_ratio_error':shifted_ratio_error} def run(sizes,samples,workers): OUT.mkdir(parents=True,exist_ok=True);FIG.mkdir(parents=True,exist_ok=True) config={'base_seed':SEED,'sample_seed':'SeedSequence([base_seed, N, sample_index])', 'sizes':sizes,'samples':samples,'kappas':[str(k) for k in KAPPAS], 'ensembles':list(ENSEMBLES),'parity':1,'bulk_rank_fraction':[.25,.75], 'all_three_levels_in_window':True,'endpoint_pairing':'exact scale invariance', 'old_samples_reused':False,'blas_threads_per_process':1,'worker_processes':workers, 'numpy':np.__version__,'scipy':scipy.__version__,'eigensolver':'scipy.linalg.eigh, evr, full spectrum', 'scope':'finite-size spacing crossover; no phase or critical-exponent claim'} save_json(OUT/'scaling_config.json',config) tasks=[];buffers={};timings=[] # Larger jobs are queued first; two single-thread processes bound CPU use. for N,ns in sorted(zip(sizes,samples),reverse=True): path=OUT/f'scaling_samples_N{N}.npz' if path.exists(): with np.load(path) as existing: if existing['r'].shape[1]!=ns or not np.array_equal(existing['kappas'],KAPPAS): raise ValueError(f'Existing {path.name} has different settings; move it explicitly before regeneration') print(f'Reusing existing {path.name}',flush=True) continue d=2**(N//2-1) buffers[N]={'spectra':np.empty((2,ns,len(KAPPAS),d)), 'r':np.empty((2,ns,len(KAPPAS))),'radii':np.empty((ns,2)), 'remaining':0,'worker_seconds':0.,'identity_error':0.,'shifted_ratio_error':0.} chunk=16 if N>=22 else min(128,ns) for start in range(0,ns,chunk): tasks.append((N,start,min(start+chunk,ns))) buffers[N]['remaining']+=1 wall=time.perf_counter() with ProcessPoolExecutor(max_workers=workers,mp_context=mp.get_context('spawn')) as pool: futures=[pool.submit(_sample_chunk,t) for t in tasks] for future in as_completed(futures): result=future.result();N=result['N'];start=result['start'];stop=result['stop'];b=buffers[N] for key in ('spectra','r'): b[key][:,start:stop]=result[key] b['radii'][start:stop]=result['radii'] b['remaining']-=1;b['worker_seconds']+=result['seconds'] b['identity_error']=max(b['identity_error'],result['identity_error']) b['shifted_ratio_error']=max(b['shifted_ratio_error'],result['shifted_ratio_error']) print(f'N={N}, samples {start}:{stop}, chunk {result["seconds"]:.2f} s, remaining chunks {b["remaining"]}',flush=True) if b['remaining']==0: R4,R2=b['radii'].T eta=np.log(R2/R4) np.savez_compressed(OUT/f'scaling_samples_N{N}.npz',N=N,kappas=KAPPAS, eigenvalues=b['spectra'],r=b['r'],R4=R4,R2=R2,eta=eta, u_kappa=np.exp(eta[:,None])*KAPPAS[None,:],base_seed=SEED, sample_indices=np.arange(len(R4)),ensembles=np.array(ENSEMBLES), bulk_start=b['spectra'].shape[-1]//4,bulk_stop=3*b['spectra'].shape[-1]//4) record={'N':N,'samples':len(R4),'worker_seconds':b['worker_seconds'], 'matrix_polar_identity_error':b['identity_error'], 'direct_shifted_r_error':b['shifted_ratio_error']} timings.append(record) save_json(OUT/'scaling_timing.json',{'wall_seconds_so_far':time.perf_counter()-wall,'runs':timings}) del buffers[N] print(f'Main total wall seconds {time.perf_counter()-wall:.2f}',flush=True) def isotonic_response(values): """Equal-weight PAVA, after clipping; measured endpoints are fixed at 0,1.""" y=np.clip(np.asarray(values[1:-1],float),0.,1.) blocks=[] for index,value in enumerate(y): blocks.append([float(value),1,index,index+1]) while len(blocks)>=2 and blocks[-2][0]>blocks[-1][0]: b=blocks.pop();a=blocks.pop();count=a[1]+b[1] blocks.append([(a[0]*a[1]+b[0]*b[1])/count,count,a[2],b[3]]) fit=np.empty_like(y) for value,_,start,stop in blocks:fit[start:stop]=value return np.r_[0.,fit,1.] def crossing_log(values,threshold): """Interpolate on finite positive kappa only; do not extrapolate crossings.""" x=np.log(KAPPAS[1:-1]);y=np.asarray(values)[1:-1] if thresholdy[-1]:return np.nan j=int(np.searchsorted(y,threshold,side='left')) if j==0:return float(x[0]) if y[j]==y[j-1]:return float((x[j]+x[j-1])/2) return float(x[j-1]+(threshold-y[j-1])*(x[j]-x[j-1])/(y[j]-y[j-1])) def _interval(values): v=np.asarray(values);v=v[np.isfinite(v)] return np.quantile(v,[.025,.975]) if len(v) else np.array([np.nan,np.nan]) def _radial_quadrature(N,count): d2=math.comb(N,2);d4=math.comb(N,4) # R2^2/R4^2 has the exact F(d2,d4) distribution. Midpoint quantiles # give an independent, deterministic integration over the Gaussian radii. u=(np.arange(count)+.5)/count return .5*np.log(f_distribution.ppf(u,d2,d4)) def _linear_operator(eta): # The two extra finite knots represent asymptotic endpoints only for # interpolation. Quantitative convolution comparisons exclude k=2,128. positive=np.log(KAPPAS[1:-1]) knots=np.r_[positive[0]-2.,positive,positive[-1]+2.] operator=np.zeros((len(KAPPAS),len(KAPPAS))) operator[0,0]=1.;operator[-1,-1]=1. for j,x in enumerate(positive,1): query=np.clip(x+eta,knots[0],knots[-1]) index=np.clip(np.searchsorted(knots,query,side='right')-1,0,len(knots)-2) f=(query-knots[index])/(knots[index+1]-knots[index]) operator[j]=np.bincount(index,1-f,minlength=len(knots))/len(eta) operator[j]+=np.bincount(index+1,f,minlength=len(knots))/len(eta) return operator,knots def analyze(nboot): OUT.mkdir(parents=True,exist_ok=True);FIG.mkdir(parents=True,exist_ok=True) curves=[];crossings=[];common_crossings=[];radials=[];fits=[];audits=[];all_statistics=[] paths=sorted(OUT.glob('scaling_samples_N*.npz'),key=lambda p:int(p.stem.split('N')[-1])) for path in paths: data=np.load(path);N=int(data['N']);r=data['r'];ns=r.shape[1];E=data['eigenvalues'];D=E.shape[-1] rng=np.random.default_rng(np.random.SeedSequence([SEED,N,7701])) counts=rng.multinomial(ns,np.full(ns,1/ns),size=nboot).astype(np.uint16) weights=counts/ns means=r.mean(axis=1) boot=np.stack([weights@r[ei] for ei in range(2)]) span=means[:,0]-means[:,-1] response=(means[:,[0]]-means)/span[:,None] response_boot=(boot[:,:,[0]]-boot)/(boot[:,:,0]-boot[:,:,-1])[:,:,None] iso=np.stack([isotonic_response(v) for v in response]) iso_boot=np.array([[isotonic_response(v) for v in curves_] for curves_ in response_boot]) cross=np.array([[crossing_log(v,q) for q in THRESHOLDS] for v in iso]) cross_boot=np.array([[[crossing_log(v,q) for q in THRESHOLDS] for v in curves_] for curves_ in iso_boot]) width=cross[:,2]-cross[:,0];width_boot=cross_boot[:,:,2]-cross_boot[:,:,0] common_q=(means[:,0]-.5)/span common_q_boot=(boot[:,:,0]-.5)/(boot[:,:,0]-boot[:,:,-1]) common_cross=np.array([crossing_log(iso[ei],common_q[ei]) for ei in range(2)]) common_cross_boot=np.array([[crossing_log(iso_boot[ei,bi],common_q_boot[ei,bi]) for bi in range(nboot)] for ei in range(2)]) d2,d4=math.comb(N,2),math.comb(N,4) mu=.5*(digamma(d2/2)-np.log(d2/2)-digamma(d4/2)+np.log(d4/2)) var=.25*(polygamma(1,d2/2)+polygamma(1,d4/2));sigma=float(np.sqrt(var)) eta=_radial_quadrature(N,32768);eta_coarse=_radial_quadrature(N,8192) op,knots=_linear_operator(eta);op_coarse,_=_linear_operator(eta_coarse) predicted=op@means[1];predicted_boot=boot[1]@op.T observed_difference=means[0]-means[1] observed_difference_boot=boot[0]-boot[1] correction=predicted-means[1] correction_boot=predicted_boot-boot[1] residual=means[0]-predicted;residual_boot=boot[0]-predicted_boot pchip=PchipInterpolator(knots,means[1],extrapolate=False) pchip_correction=np.zeros(len(KAPPAS));coarsened_correction=np.zeros(len(KAPPAS)) keep=np.array([0,1,3,5,7,9,11,12]) for j,x in enumerate(knots[1:-1],1): query=np.clip(x+eta,knots[0],knots[-1]) pchip_correction[j]=float(pchip(query).mean()-means[1,j]) coarsened_correction[j]=float(np.interp(query,knots[keep],means[1,keep]).mean()-np.interp(x,knots[keep],means[1,keep])) # A per-realization shifted interpolation is diagnostic only: local # spectral motion can be faster than this kappa grid resolves. sample_shift=np.empty((ns,len(KAPPAS))) for sid in range(ns): sample_shift[sid]=np.interp(knots+data['eta'][sid],knots,r[1,sid]) sample_shift[:,0]=r[1,:,0];sample_shift[:,-1]=r[1,:,-1] shifted_error=sample_shift.mean(axis=0)-means[0] for ei,en in enumerate(ENSEMBLES): common_ci=_interval(np.exp(common_cross_boot[ei])) common_crossings.append({'N':N,'ensemble':en,'common_mean_ratio_threshold':.5, 'kappa_crossing':np.exp(common_cross[ei]),'crossing_low':common_ci[0],'crossing_high':common_ci[1], 'bootstrap_valid_fraction':float(np.mean(np.isfinite(common_cross_boot[ei])))}) for j,k in enumerate(KAPPAS): ri=_interval(boot[ei,:,j]);pi=_interval(response_boot[ei,:,j]) curves.append({'N':N,'samples':ns,'ensemble':en,'kappa':str(k), 'r_mean':means[ei,j],'r_low':ri[0],'r_high':ri[1], 'response':response[ei,j],'response_low':pi[0],'response_high':pi[1], 'isotonic_response':iso[ei,j]}) for qi,q in enumerate(THRESHOLDS): finite=np.isfinite(cross_boot[ei,:,qi]);ci=_interval(np.exp(cross_boot[ei,:,qi]));wi=_interval(width_boot[ei]) crossings.append({'N':N,'samples':ns,'ensemble':en,'response_threshold':q, 'kappa_crossing':np.exp(cross[ei,qi]),'crossing_low':ci[0],'crossing_high':ci[1], 'bootstrap_valid_fraction':finite.mean(),'log_width_25_75':width[ei], 'log_width_low':wi[0],'log_width_high':wi[1], 'max_isotonic_adjustment':float(np.max(abs(iso[ei]-response[ei]))), 'eta_mean_exact':mu,'eta_sd_exact':sigma,'eta_sd_over_log_width':sigma/width[ei]}) for j,k in enumerate(KAPPAS): di=_interval(observed_difference_boot[:,j]);ci=_interval(correction_boot[:,j]);re=_interval(residual_boot[:,j]) radials.append({'N':N,'kappa':str(k),'interior_comparison':bool(j>=2 and j<=10), 'gaussian_minus_directional':observed_difference[j],'observed_low':di[0],'observed_high':di[1], 'radial_convolution_correction':correction[j],'prediction_low':ci[0],'prediction_high':ci[1], 'pchip_correction':pchip_correction[j],'coarsened_grid_correction':coarsened_correction[j], 'quadrature_change_8192_to_32768':(op_coarse@means[1]-predicted)[j], 'observed_minus_prediction':residual[j],'residual_low':re[0],'residual_high':re[1], 'sample_shift_interpolation_minus_actual':shifted_error[j]}) gaps=np.diff(E[...,D//4:3*D//4],axis=-1) recomputed=np.mean(np.minimum(gaps[...,:-1],gaps[...,1:])/np.maximum(gaps[...,:-1],gaps[...,1:]),axis=-1) expected_width=np.empty((ns,len(KAPPAS))) for j,k in enumerate(KAPPAS): expected_width[:,j]=data['R2']**2 if np.isinf(k) else (data['R4']**2+k*k*data['R2']**2)/(1+k*k) audit={'N':N,'samples':ns,'dimension':D,'all_raw_finite':bool(np.all(np.isfinite(E)) and np.all(np.isfinite(r))), 'ratio_recomputed_error':float(np.max(abs(recomputed-r))), 'endpoint_pair_difference':float(np.max(abs(r[0,:,[0,-1]]-r[1,:,[0,-1]]))), 'fixed_radius_width_error':float(np.max(abs(np.mean(E[1]**2,axis=-1)-1))), 'gaussian_width_error':float(np.max(abs(np.mean(E[0]**2,axis=-1)-expected_width))), 'min_endpoint_span_bootstrap':float(np.min(boot[:,:,0]-boot[:,:,-1])), 'minimum_valid_crossing_fraction':float(np.min(np.mean(np.isfinite(cross_boot),axis=1))), 'convolution_quadrature_max_change':float(np.max(abs(op_coarse@means[1]-predicted))), 'linear_vs_pchip_correction_max_interior':float(np.max(abs(correction[2:11]-pchip_correction[2:11]))), 'fine_vs_coarsened_correction_max_interior':float(np.max(abs(correction[2:11]-coarsened_correction[2:11])))} audits.append(audit) np.savez_compressed(OUT/f'scaling_statistics_N{N}.npz',N=N,kappas=KAPPAS,means=means, bootstrap_counts=counts,r_bootstrap=boot,response=response,response_bootstrap=response_boot, isotonic_response=iso,isotonic_response_bootstrap=iso_boot,crossing_log=cross, crossing_log_bootstrap=cross_boot,log_width=width,log_width_bootstrap=width_boot, common_ratio_crossing_log=common_cross,common_ratio_crossing_log_bootstrap=common_cross_boot, eta_mean=mu,eta_variance=var,eta_quantiles=eta,convolution_operator=op, predicted_gaussian_mean=predicted,predicted_gaussian_bootstrap=predicted_boot, pchip_correction=pchip_correction,coarsened_correction=coarsened_correction, per_sample_shifted_interpolation=sample_shift,seed=SEED,bootstrap_replicates=nboot) all_statistics.append({'N':N,'cross':cross,'cross_boot':cross_boot,'width':width,'width_boot':width_boot}) print(f'Analyzed N={N}: crossing medians {np.exp(cross[:,1])}, log widths {width}',flush=True) ns=np.array([s['N'] for s in all_statistics]);x=np.log(ns) for ei,en in enumerate(ENSEMBLES): y=np.array([s['cross'][ei,1] for s in all_statistics]) by=np.stack([s['cross_boot'][ei,:,1] for s in all_statistics]) selections=[('all_sizes',np.arange(len(ns))),('smallest_three',np.arange(min(3,len(ns)))), ('largest_three',np.arange(max(0,len(ns)-3),len(ns)))] selections += [(f'adjacent_{ns[j]}_{ns[j+1]}',np.array([j,j+1])) for j in range(len(ns)-1)] for label,index in selections: xx=x[index]-x[index].mean();den=np.sum(xx*xx) slope=float(xx@y[index]/den);bs=xx@by[index]/den;ci=_interval(bs) fits.append({'ensemble':en,'size_selection':label,'Ns':','.join(map(str,ns[index])), 'descriptive_loglog_slope':slope,'slope_low':ci[0],'slope_high':ci[1], 'interpretation':'finite-size drift summary, not a critical exponent'}) save_csv(OUT/'scaling_curves.csv',curves) save_csv(OUT/'scaling_crossings.csv',crossings) save_csv(OUT/'scaling_common_ratio_crossings.csv',common_crossings) save_csv(OUT/'scaling_radial_convolution.csv',radials) save_csv(OUT/'scaling_drift_sensitivity.csv',fits) all_pass=all(a['all_raw_finite'] and a['ratio_recomputed_error']<1e-11 and a['endpoint_pair_difference']<1e-11 and a['fixed_radius_width_error']<1e-11 and a['gaussian_width_error']<1e-11 and a['min_endpoint_span_bootstrap']>0 for a in audits) save_json(OUT/'scaling_audit.json',{'all_pass':all_pass,'checks':audits}) save_json(OUT/'scaling_analysis.json',{'bootstrap_replicates':nboot,'bootstrap_seed':'SeedSequence([base_seed,N,7701])', 'resampling_unit':'complete paired disorder sample across both ensembles and all kappa', 'intervals':'pointwise 95% percentile; not simultaneous', 'response':'(r(0)-r(kappa))/(r(0)-r(infinity)) using measured finite-N endpoints in every replicate', 'crossings':'equal-weight isotonic regression after clipping to [0,1]; linear interpolation in log kappa; no extrapolation', 'width':'log(kappa_0.75/kappa_0.25)', 'convolution':'exact F(d2,d4) radial-ratio law; midpoint quantile quadrature 32768 vs 8192; log-kappa linear interpolation', 'interpolation_sensitivity':'PCHIP and a coarsened grid; method spread is not a rigorous discretization bound', 'interior_convolution_range':[4,96],'endpoint_extension':'auxiliary endpoint knots at log(2)-2 and log(128)+2', 'fit_scope':'descriptive log-log slope of median crossing, with size-selection sensitivity; no critical exponent', 'old_samples_reused':False}) plot_results() summarize_crossings() def plot_results(): 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.mkdir(parents=True,exist_ok=True) paths=sorted(OUT.glob('scaling_statistics_N*.npz'),key=lambda p:int(p.stem.split('N')[-1])) data=[np.load(p) for p in paths] fig,axs=plt.subplots(1,2,figsize=(10.4,3.5)) for i,d in enumerate(data): N=int(d['N']);color=f'C{i}';k=d['kappas'][1:-1] for ei,style in ((1,'-'),(0,'--')): means=d['means'][ei,1:-1];ci=np.quantile(d['r_bootstrap'][ei,:,1:-1],[.025,.975],axis=0) axs[0].plot(k,means,style,color=color,label=f'N={N}' if ei==1 else None) if ei==1:axs[0].fill_between(k,ci[0],ci[1],color=color,alpha=.12) axs[1].plot(k,d['isotonic_response'][ei,1:-1],style,color=color) axs[0].set(xscale='log',xlabel=r'$\kappa$',ylabel=r'$\langle r\rangle$',title='Solid: fixed radii; dashed: Gaussian') axs[0].legend(ncol=2) axs[1].set(xscale='log',xlabel=r'$\kappa$',ylabel='Response from measured endpoints',title='Isotonic response; identical rank window') for q in THRESHOLDS:axs[1].axhline(q,color='.7',lw=.5) fig.tight_layout();fig.savefig(FIG/'scaling_directional_curves.pdf');fig.savefig(FIG/'scaling_directional_curves.png',dpi=190);plt.close(fig) fig,axs=plt.subplots(1,3,figsize=(12.0,3.5)) ns=np.array([int(d['N']) for d in data]) for qi,(q,marker) in enumerate(zip(THRESHOLDS,('v','o','^'))): for ei,style,offset in ((1,'-',-.12),(0,'--',.12)): y=np.array([np.exp(d['crossing_log'][ei,qi]) for d in data]);ci=np.array([_interval(np.exp(d['crossing_log_bootstrap'][ei,:,qi])) for d in data]).T axs[0].errorbar(ns+offset,y,yerr=[y-ci[0],ci[1]-y],marker=marker,ls=style,color=f'C{qi}',capsize=2,label=f'q={q:g}' if ei==1 else None) for ei,label,style in ((1,'Fixed radii','o-'),(0,'Gaussian','s--')): y=np.array([d['log_width'][ei] for d in data]);ci=np.array([_interval(d['log_width_bootstrap'][ei]) for d in data]).T axs[1].errorbar(ns,y,yerr=[y-ci[0],ci[1]-y],fmt=style,capsize=2,label=label) ratio=np.array([np.sqrt(d['eta_variance'])/d['log_width'][1] for d in data]) ci=np.array([_interval(np.sqrt(d['eta_variance'])/d['log_width_bootstrap'][1]) for d in data]).T axs[2].errorbar(ns,ratio,yerr=[ratio-ci[0],ci[1]-ratio],fmt='o-',capsize=2) axs[0].set(xlabel='N',ylabel=r'$\kappa_q$',title='Response crossings; solid = fixed radii');axs[0].legend() axs[1].set(xlabel='N',ylabel=r'$W_N=\log(\kappa_{.75}/\kappa_{.25})$',title='Finite-size crossover width');axs[1].legend() axs[2].set(xlabel='N',ylabel=r'$\sigma_\eta/W_N$',title='Radial spread relative to width') for ax in axs:ax.set_xticks(ns) fig.tight_layout();fig.savefig(FIG/'scaling_crossing_drift.pdf');fig.savefig(FIG/'scaling_crossing_drift.png',dpi=190);plt.close(fig) fig,axs=plt.subplots(2,2,figsize=(10.2,6.5),sharex=True) for ax,d in zip(axs.flat,data): k=d['kappas'][2:11];obs=d['means'][0]-d['means'][1];b=d['r_bootstrap'][0]-d['r_bootstrap'][1] ci=np.quantile(b,[.025,.975],axis=0);correction=d['predicted_gaussian_mean']-d['means'][1] ax.errorbar(k,obs[2:11],yerr=[obs[2:11]-ci[0,2:11],ci[1,2:11]-obs[2:11]],fmt='o',capsize=2,label='Paired direct estimate') ax.plot(k,correction[2:11],'-',label='Radial convolution: linear') ax.plot(k,d['pchip_correction'][2:11],'--',label='Radial convolution: PCHIP') ax.plot(k,d['coarsened_correction'][2:11],':',color='.45',label='Coarsened-grid sensitivity') ax.axhline(0,color='.5',lw=.5) ax.set(xscale='log',xlim=(3.2,120),xlabel=r'$\kappa$',ylabel=r'$\langle r\rangle_G-\langle r\rangle_\circ$',title=f'N={int(d["N"])}') axs[0,0].legend(fontsize=7) fig.tight_layout();fig.savefig(FIG/'scaling_radial_convolution.pdf');fig.savefig(FIG/'scaling_radial_convolution.png',dpi=190);plt.close(fig) def summarize_crossings(): paths = sorted(OUT.glob("scaling_statistics_N*.npz"), key=lambda p: int(p.stem.split("N")[-1])) stats = [np.load(path) for path in paths] sensitivity=[];trends=[] for d in stats: x=np.log(KAPPAS[1:-1]) for ei,en in enumerate(ENSEMBLES): y=d['isotonic_response'][ei,1:-1] pchip=PchipInterpolator(x,y) for qi,q in enumerate(THRESHOLDS): px=brentq(lambda z:pchip(z)-q,x[0],x[-1]) if y[0]<=q<=y[-1] else np.nan cx=np.interp(q,y[::2],x[::2]) if y[::2][0]<=q<=y[::2][-1] else np.nan sensitivity.append({'N':int(d['N']),'ensemble':en,'response_threshold':q, 'linear_crossing':np.exp(d['crossing_log'][ei,qi]),'pchip_crossing':np.exp(px), 'coarsened_grid_crossing':np.exp(cx)}) for a,b in zip(stats[:-1],stats[1:]): for ei,en in enumerate(ENSEMBLES): delta=float(b['log_width'][ei]-a['log_width'][ei]);ci=_interval(b['log_width_bootstrap'][ei]-a['log_width_bootstrap'][ei]) trends.append({'N_low':int(a['N']),'N_high':int(b['N']),'ensemble':en, 'width_difference':delta,'difference_low':ci[0],'difference_high':ci[1]}) save_csv(OUT/'scaling_crossing_interpolation.csv',sensitivity) save_csv(OUT/'scaling_width_trends.csv',trends) def main(): parser=argparse.ArgumentParser(description=__doc__) parser.add_argument('--stage',choices=['main','analyze','plot','summarize','all'],default='all') parser.add_argument('--sizes',default='10,14,18,22') parser.add_argument('--samples',default='2048,2048,512,128') parser.add_argument('--workers',type=int,default=2) parser.add_argument('--bootstrap',type=int,default=1000) args=parser.parse_args() if args.stage in ('main','all'): sizes=list(map(int,args.sizes.split(',')));samples=list(map(int,args.samples.split(','))) if len(sizes)!=len(samples):raise ValueError('sizes and samples must have the same length') run(sizes,samples,args.workers) if args.stage in ('analyze','all'):analyze(args.bootstrap) if args.stage=='plot':plot_results() if args.stage=='summarize':summarize_crossings() if __name__=='__main__':main()