"""Make the figure atlas directly from saved CSVs, mesh and evidence records."""
from pathlib import Path
import json,re
import numpy as np
import matplotlib
matplotlib.use('Agg')
from matplotlib import pyplot as plt
from matplotlib.ticker import FuncFormatter
root=Path(__file__).resolve().parents[1]; dest=root/'figures'; out=root/'results'
teal='#146c65'; ochre='#b96138'; grey='#71817e'; ink='#213734'; cream='#fffef9'
plt.rcParams.update({'font.family':'DejaVu Sans','font.size':10,'axes.edgecolor':'#aeb9b1','axes.labelcolor':ink,'xtick.color':grey,'ytick.color':grey,'axes.spines.top':False,'axes.spines.right':False,'axes.grid':True,'grid.alpha':.17,'svg.fonttype':'none','savefig.facecolor':cream,'svg.hashsalt':'rh-2026'})
def table(k):return np.genfromtxt(out/k,delimiter=',',names=True)
Z=table('zeros.csv'); C=table('critical_line.csv'); P=table('primes.csv'); N=table('count.csv'); S=table('spacings.csv'); E=table('euler.csv'); F=table('equation.csv')
D=np.load(out/'field.npz'); V=D['real']+1j*D['imag']; X,Y=np.meshgrid(D['sigma'],D['t'])
atlas=[]
def begin(title,data,note,board,proj=None):
    global f,ax
    i=len(atlas)+1; key=f'fig-{i:02d}'
    atlas.append(dict(id=key,title=title,data=data,note=note,board=board))
    f=plt.figure(figsize=(8,4.65),facecolor=cream)
    ax=f.add_subplot(111,projection=proj); ax.set_facecolor(cream)
    f.subplots_adjust(left=.12,right=.94,top=.8,bottom=.17)
    f.text(.08,.945,f'NUMBER THEORY    /    FIGURE  {i:02d}',size=9,color=teal,weight='bold')
    f.text(.08,.863,title,size=17,color=ink,fontfamily='DejaVu Serif')
    f.text(.08,.045,data,size=8,color=grey)
def end(x='',y=''):
    ax.set_xlabel(x);ax.set_ylabel(y)
    path=dest/atlas[-1]['id']
    f.savefig(path.with_suffix('.png'),dpi=180); f.savefig(path.with_suffix('.svg')); plt.close(f)
begin('The first zeros in the critical strip','results/zeros.csv','The first eleven positive ordinates through t = 54 fall on the sampled line. Off-line space is shown for orientation.',0)
ax.axvspan(0,1,color='#dcece6');ax.axvline(.5,color=ochre,lw=1);sel=Z['height']<=54;ax.scatter(np.full(sum(sel),.5),Z['height'][sel],s=19,color=teal,zorder=4);ax.set_xlim(-.25,1.25);ax.set_ylim(0,55);end('Real part σ','Imaginary part t')
begin('Two components of ζ on the line','results/critical_line.csv','Both coordinates vanish at a critical-line zero. A crossing of one component alone is insufficient.',1)
for k,v,c in [('real','Real',teal),('imaginary','Imaginary',ochre)]:ax.plot(C['t'],C[k],label=v,color=c)
ax.legend(frameon=False,ncol=2);end('Height t at σ = ½','Value')
begin('Hardy Z turns the search into a sign test','results/critical_line.csv · results/brackets.csv','Z(t) is real for real t and has the same modulus as ζ(½+it). Eleven sign brackets were refined independently.',2)
ax.axhline(0,color=grey,lw=.8);ax.plot(C['t'],C['Hardy_Z'],color=teal);r=table('brackets.csv');ax.scatter(r['bisected_height'],np.zeros(len(r)),s=20,color=ochre,zorder=4);end('Height t','Hardy Z(t)')
begin('Relief of the zeta magnitude','results/field.npz','Height is log(1 + |ζ|) on the sampled strip. A finite mesh smooths sharp features near a zero.',1,'3d')
ax.plot_surface(X,Y,np.log1p(abs(V)),cmap='viridis',linewidth=0,antialiased=True,rasterized=True);ax.set_zlabel('log(1 + |ζ|)',labelpad=2);ax.view_init(30,-55);ax.set_box_aspect((1.5,3,1));end('σ','t')
begin('Phase across the critical strip','results/field.npz','Color encodes arg ζ in radians, with a cyclic scale. At a zero the phase itself is undefined.',1)
im=ax.pcolormesh(X,Y,np.angle(V),cmap='twilight',vmin=-np.pi,vmax=np.pi,shading='auto',rasterized=True);f.colorbar(im,ax=ax,label='Radians',ticks=[-np.pi,0,np.pi],format=FuncFormatter(lambda v,_: '−π' if v<0 else 'π' if v>0 else '0'));end('Real part σ','Height t')
begin('One hundred indexed ordinates','results/zeros.csv · sources/lmfdb.txt','The hundredth ordinate is 236.524229665816… . Heights were computed at 45 decimal places and compared by index.',2)
ax.plot(Z['index'],Z['height'],color=teal);ax.scatter(Z['index'][::5],Z['height'][::5],color=teal,s=15);end('Index n','Ordinate γₙ')
begin('Reference precision sets the comparison scale','results/zeros.csv','Absolute differences compare local ordinates with finite LMFDB decimals. Function residuals are a separate diagnostic.',2)
ax.semilogy(Z['index'],Z['absolute_difference'],'.',color=teal,label='|γ − reference|');ax.semilogy(Z['index'],Z['zeta_residual'],'.',color=ochre,label='|ζ(½+iγ)|');ax.legend(frameon=False);end('Index n','Absolute value (log scale)')
begin('Counting the indexed zeros','results/count.csv','Steps count the local list through t < γ₁₀₀. The smooth Riemann–von Mangoldt term omits the fluctuating remainder.',2)
ax.step(N['T'],N['indexed_count'],where='post',label='Indexed count',color=teal);ax.plot(N['T'],N['smooth_term'],'--',label='Smooth term',color=ochre);ax.legend(frameon=False);end('Height T','Count')
begin('The fluctuation around the smooth count','results/count.csv','The smooth term is T/(2π)·[log(T/(2π))−1] + 7/8. Sampling uses a 0.25 height step.',2)
ax.plot(N['T'],N['difference'],color=teal,lw=.9);ax.axhline(0,color=grey,lw=.7);end('Height T','Count − smooth term')
begin('Local spacing between adjacent zeros','results/spacings.csv','99 gaps are scaled by log(t̄/(2π))/(2π) at their midpoint. Sample size and height restrict any distributional inference.',2)
ax.hist(S['local_mean_normalized'],bins=np.arange(0,2.81,.2),color=teal,edgecolor=cream);ax.axvline(np.mean(S['local_mean_normalized']),color=ochre,label='Sample mean');ax.legend(frameon=False);end('Locally normalized gap','Number of gaps')
begin('How primes accumulate','results/primes.csv','Each step counts one additional prime. Integer levels through 200 come directly from the sieve.',3)
sel=P['x']<=200;ax.step(P['x'][sel],P['pi'][sel],where='post',color=teal);end('Integer x','π(x)')
begin('Prime-counting approximations','results/primes.csv','Li(x) = Ei(log x) uses the conventional offset. At the upper endpoint the sieve gives exactly 78,498 primes.',3)
for k,label,c,ls in [('pi','π(x)',teal,'-'),('li','Li(x)',ochre,'--'),('x_over_logx','x / log x',grey,':')]:ax.semilogx(P['x'],P[k]/P['pi'],ls,color=c,label=label)
ax.set_xlim(10,1e6);ax.legend(frameon=False);end('x (log scale)','Estimate / exact count')
begin('Errors against the exact prime count','results/primes.csv','Signed errors use estimate minus exact. The two approximations have different bias over the sampled range.',3)
for k,label,c in [('li','Li(x) − π(x)',teal),('x_over_logx','x / log x − π(x)',ochre)]:ax.semilogx(P['x'],P[k]-P['pi'],color=c,label=label)
ax.legend(frameon=False);end('x (log scale)','Signed count error')
begin('Prime powers in the Chebyshev sum','results/primes.csv','ψ(x) adds log p at every prime power pᵏ. The curve is a finite sample of the error in a sum central to the author’s account.',3)
ax.semilogx(P['x'],(P['psi']-P['x'])/np.sqrt(P['x']),color=teal,lw=1);end('x (log scale)','(ψ(x) − x) / √x')
begin('Convergence of the Euler product','results/euler.csv','Products use all primes through each cutoff. As σ approaches 1 from above, the omitted prime tail decays more slowly.',1)
for s in np.unique(E['sigma']):
 r=E[E['sigma']==s];ax.loglog(r['last_prime'],r['absolute_error'],'.-',label=f'σ = {s:g}')
ax.legend(frameon=False,ncol=2);end('Largest included prime','Absolute error')
begin('Precision and the functional equation','results/equation.csv','Each side uses an Euler–Maclaurin sum (N=160, 18 correction terms). Residuals are absolute and finite-precision.',1)
for sigma in np.unique(F['sigma']):
 r=F[F['sigma']==sigma];ax.semilogy(r['dps'],r['absolute_residual'],'.-',label=f'{sigma:g} + {r["t"][0]:g}i')
ax.legend(frameon=False,ncol=2);end('Working decimal places','|left − right|')
begin('Imports at the theorem entry point','sources/Main.lean · MainTheoremsAll.lean · Statements.lean','Arrows are parsed Lean imports from three named files. This local slice does not count transitive theorem dependencies.',4)
ax.axis('off');pos={'Main':(.06,.52),'Statements':(.45,.78),'MainTheoremsAll':(.43,.29),'Mathlib':(.86,.82),'MainTheoremsCritical':(.83,.47),'CorGKOf':(.84,.09)}
for name in ('Main','Statements','MainTheoremsAll'):
 for target in re.findall(r'^import (.+)$',(root/'sources'/(name+'.lean')).read_text(),re.M):
  child=target.split('.')[-1];ax.annotate('',xy=pos[child],xytext=pos[name],xycoords='axes fraction',arrowprops=dict(arrowstyle='->',color=grey,lw=1.5,shrinkA=22,shrinkB=30))
for k,(x,y) in pos.items():ax.text(x,y,k,ha='center',va='center',transform=ax.transAxes,fontsize=9,bbox=dict(boxstyle='round,pad=.48',facecolor='#e2eee7',edgecolor=teal))
end()
begin('What the five exported theorems use','sources/audit.log · sources/con-leche-compare.log','The three axiom columns and statement checks are parsed from external logs. SHA-256 matching and row extraction ran locally.',5)
audit=json.loads((out/'audit.json').read_text());labels=['RH','ζ zero ordinate','Dirichlet nonvanishing','Dirichlet zeros','Primitive case']
cols=['propext','Classical.choice','Quot.sound','Comparison'];mat=np.array([[k in t['axioms'] for k in cols[:3]]+[t['comparison']] for t in audit['theorems']])
ax.imshow(mat,cmap=matplotlib.colors.ListedColormap(['#dfdcd0','#dcf0e9']),vmin=0,vmax=1,aspect='auto')
ax.set_xticks(range(4),cols,fontsize=8);ax.set_yticks(range(5),labels,fontsize=8);f.subplots_adjust(left=.26);ax.grid(False)
for i,row in enumerate(mat):
 for j,v in enumerate(row):ax.text(j,i,'yes' if v else '—',ha='center',va='center',color=teal,weight='bold')
end()
begin('A reading route through the analytic argument','sources/announcement.pdf · sources/waterloo.html','Conceptual reduction in Rubinstein’s v2 working draft. Thirteen classical hypotheses supply (M); the guide flags their full exposition as open.',4)
ax.axis('off')
for x,y,label in [(.17,.73,'13 classical\nhypotheses'),(.52,.73,'Weighted prime-power\nupper bound (M)'),(.52,.27,'Two character\nestimates'),(.87,.5,'Ordinary\nRH')]:
 ax.text(x,y,label,ha='center',va='center',color=ink,transform=ax.transAxes,bbox=dict(boxstyle='round,pad=.7',edgecolor=teal,facecolor='#e2eee7'))
for a,b in [((.28,.73),(.39,.73)),((.66,.71),(.81,.55)),((.63,.29),(.81,.45))]:
 ax.annotate('',xy=b,xytext=a,xycoords='axes fraction',arrowprops=dict(arrowstyle='->',lw=1.5,color=ochre))
end()
begin('From indexed roots to independent checks','results/numerical_timeline.json','The timestamps come from the local numerical pipeline. Elapsed time describes this machine and run.',5)
from datetime import datetime
stages=json.loads((out/'numerical_timeline.json').read_text())
times=[datetime.fromisoformat(s['utc']) for s in stages];sec=[(t-times[0]).total_seconds() for t in times]
labels=['Started','Reference comparison','Grid and sign brackets','Prime counts and products','Assertions passed']
ax.hlines(range(5),0,sec,color='#afc9bf',lw=3);ax.scatter(sec,range(5),color=teal);ax.set_yticks(range(5),labels,fontsize=8);ax.invert_yaxis();f.subplots_adjust(left=.30);end('Seconds since start','')
begin('Balancing a chain of theta lifts','results/chain_balance.csv · reading-guide.tex, § I.8','At X = 10,000, the two-term quantity X/m + m reaches 200 at m = 100. The full inequality includes the additional rank and column parameters k and n.',4)
m=np.arange(20,501);v=10000/m
np.savetxt(out/'chain_balance.csv',np.column_stack((m,v,m,v+m)),delimiter=',',header='m,X_over_m,per_step_term,two_term_sum',comments='',fmt='%.12g')
for a,label,c in [(v,'Endpoint cost X/m',teal),(m,'Accumulated cost m',grey),(v+m,'Two-term sum',ochre)]:ax.plot(m,a,label=label,color=c)
ax.scatter([100],[200],color=ochre,zorder=5);ax.legend(frameon=False);end('Chain length m','Two error terms (X = 10,000)')
(dest/'index.json').write_text(json.dumps(atlas,indent=2,ensure_ascii=False))

