"""Reproduce finite block experiments and their figures. Run from any directory."""
from pathlib import Path
from fractions import Fraction
from datetime import datetime, timezone
import csv, json, math
import numpy as np
from scipy.linalg import svdvals, block_diag
import sympy as sp
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
from matplotlib.colors import LinearSegmentedColormap
R=Path(__file__).resolve().parents[1]
D=R/'numerical_results'; F=R/'research_figures'; M=R/'operator_matrices'
for p in (D,F,M): p.mkdir(exist_ok=True)
started=datetime.now(timezone.utc).isoformat()
def save_json(p,d):p.write_text(json.dumps(d,indent=2,allow_nan=False)+'\n')
def table(name,header,rows):
    with (D/(name+'.csv')).open('w',newline='') as f:
        w=csv.writer(f);w.writerow(header);w.writerows(rows)
def shift(d):return np.eye(d,k=-1)
def norm(x):return float(svdvals(x)[0])
def power(a,k):return np.linalg.matrix_power(a,k)
teal='#096957'; gold='#b76a25'; navy='#1b3c49'
plt.rcParams.update({'font.family':'DejaVu Sans','axes.spines.top':False,'axes.spines.right':False,'axes.edgecolor':'#89979a','axes.labelcolor':navy,'xtick.color':navy,'ytick.color':navy,'axes.titleweight':'bold','figure.facecolor':'#fbfaf5','axes.facecolor':'#fbfaf5','svg.fonttype':'none','font.size':10})
cm=LinearSegmentedColormap.from_list('ink',['#f7f3e8','#87c6af','#075d53'])
figures=[]
def canvas():return plt.subplots(figsize=(7.2,4.25),layout='constrained')
def finish(fig,ax,stem,title,caption,source):
    ax.set_title(title,loc='left',fontsize=15,pad=14,color=navy)
    fig.savefig(F/(stem+'.png'),dpi=150);fig.savefig(F/(stem+'.svg'));plt.close(fig)
    figures.append(dict(id=stem,title=title,caption=caption,source=source))
def grid(ax):ax.grid(axis='y',alpha=.18)
ranks=[]; flag=[]
for d in [3,5,8,12]:
    J=sp.zeros(d)
    for j in range(d-1):J[j+1,j]=sp.Rational(1,2)
    for k in range(d+1):
        a=J**k; rank=a.rank()
        assert rank == d-k == len((J**(d-k)).nullspace())
        for col in a.columnspace():assert (J**(d-k))*col==sp.zeros(d,1)
        ranks.append((d,k,rank,k))
    for j in range(d):
        v=sp.zeros(d,1);v[j]=1
        if j+1<d:v[j+1]=sp.I
        orbit=sp.Matrix.hstack(*[(J**k)*v for k in range(d)])
        assert orbit.rank()==d-j
        flag.append((d,j,orbit.rank(),d-j))
table('ranks',['dimension','power','rank','nullity'],ranks);table('cyclic_orbits',['dimension','first_nonzero_index','orbit_rank','tail_dimension'],flag)
fig,ax=canvas()
for d in [3,5,8,12]:
    a=np.array([r for r in ranks if r[0]==d]);ax.plot(a[:,1],a[:,2],'.-',label=f'd = {d}')
ax.set(xlabel='Power k',ylabel='Exact rank');ax.legend(frameon=False);grid(ax)
finish(fig,ax,'01-rank','One dimension lost at each power','Exact rational elimination for t = J/2. The nilpotency index equals the block dimension.','numerical_results/ranks.csv')
fig,ax=canvas()
a=np.array([r for r in flag if r[0]==8]);ax.bar(a[:,1],a[:,2],color=teal);ax.set(xlabel='First occupied basis coordinate (zero-based)',ylabel='Cyclic subspace dimension');grid(ax)
finish(fig,ax,'02-orbit','The leading coordinate fixes the orbit','The complex test vector starts at coordinate j. Its orbit spans the full tail of dimension 8 − j, as in §2 (B).','numerical_results/cyclic_orbits.csv')
tau=Fraction(1,192); t1=float(tau)*shift(3);e=np.eye(3)
np.savetxt(M/'tower_stage_one.csv',t1,delimiter=',',fmt='%.17g')
assert 24*tau==Fraction(1,8)
fig,ax=canvas();im=ax.imshow(t1,cmap=cm);fig.colorbar(im,ax=ax,label='Matrix element');ax.set(xticks=[0,1,2],yticks=[0,1,2],xlabel='Input slot',ylabel='Output slot')
finish(fig,ax,'03-stage','The first tower operator','For d = 1 the multipliers are (−1, 0, 1). With ε = 1 the step is S = τ₁J₃, τ₁ = 1/192.','operator_matrices/tower_stage_one.csv')
# On C³ the entire ideal is span(J²). Its unit ball gives the exact maximized pairing.
amp=np.linspace(1/np.sqrt(8),1,33);surface=np.outer(amp,amp)
table('reach_grid',['abs_v0','abs_w2','max_real_pairing'],[(a,b,a*b) for a in amp for b in amp])
fig,ax=canvas();im=ax.imshow(surface,extent=[amp[0],1,amp[0],1],origin='lower',cmap=cm,aspect='auto');fig.colorbar(im,ax=ax,label='Maximum real pairing');ax.set(xlabel='Endpoint amplitude |v₀|',ylabel='Endpoint amplitude |w₂|')
finish(fig,ax,'04-reach','Reach has an exact first-stage minimum','The unit ball of the ideal is {aJ² : |a| ≤ 1}. Choosing its phase gives |v₀w₂|. At the admissible corner this equals 1/8.','numerical_results/reach_grid.csv')
# A separate, moderate-size input to the step lemma. This does not use the recursive tau budget.
d=3; m=4; tau_test=.5; weight=.25
u=np.array([-1]+[.5j,-.5j]*m+[1],complex); slots=len(u);q=d*slots
J=weight*shift(d);x=np.kron(np.eye(slots),J);y=np.kron(np.diag(u),J)+tau_test*np.kron(shift(slots),np.eye(d))
g=np.column_stack([power(x,i)@power(y,j)@np.eye(q)[:,0] for j in range(slots) for i in range(d)])
wrap=np.zeros((q,q));wrap[np.arange(d,q,d),np.arange(d-1,q-1,d)]=1
Rmap=np.linalg.solve(g.T,(g@wrap).T).T
eps=tau_test/(2*norm(Rmap));S=x+eps*Rmap
np.savez_compressed(M/'step_30.npz',x=x,y=y,g=g,R=Rmap,S=S,u=u,epsilon=eps)
z=sp.Symbol('z')
prod=sp.expand((1-z**2)*(1+z**2/4)**4)
assert sp.rem(prod-1,z**3,z)==0
res={'commutator':norm(x@y-y@x),'y_to_D':norm(power(y,slots)),'S_to_d_minus_epsilon_y':norm(power(S,d)-eps*y),'cyclic_basis_transport':norm(S@g-g@(np.kron(np.eye(slots),shift(d))+eps*wrap))}
assert max(res.values())<1e-11
first=np.eye(q)[:,0]; last=np.eye(q)[:,-1]
# W± and the normalization from the manuscript. For t=J/4 and d=3, L(t)=16.
L=1/weight**2;beta=12*L*tau_test
wminus=(y@y-S@y)/2;wplus=(y@y+S@y)/2
phases=np.linspace(0,2*np.pi,25);splits=[]
for theta in phases:
    phase=np.exp(1j*theta);target=block_diag(J@J/weight**2,*[np.zeros((d,d))]*(slots-2),phase*J@J/weight**2)
    G=(wminus+phase*wplus)/(weight**2*(1+beta))
    splits.append((theta,norm(G),norm(G-target),24*L*tau_test))
assert all(row[1]<=1+1e-12 and row[2]<=row[3] for row in splits)
table('split_sweep',['phase_rad','operator_norm','split_error','paper_bound'],splits)
fig,ax=canvas();a=np.array(splits);ax.plot(a[:,0],a[:,2],color=teal,label='Measured error');ax.axhline(a[0,3],color=gold,ls='--',label='24 Lτ');ax.set(yscale='log',xlabel='Phase at the last slot (radians)',ylabel='Spectral norm');ax.legend(frameon=False);grid(ax)
finish(fig,ax,'05-split','Separating the two endpoint slots','25 phase choices in a 30-dimensional Lemma 3.2 input. The constructive normalization makes the general bound conservative here.','numerical_results/split_sweep.csv')
fig,ax=canvas();im=ax.imshow(abs(S),cmap=cm,interpolation='nearest');fig.colorbar(im,ax=ax,label='Absolute value');ax.set(xlabel='Column',ylabel='Row')
finish(fig,ax,'06-coupling','Ten coupled copies of a three-dimensional block','The matrix S = x + εR is assembled in slot coordinates from the paper’s cyclic basis. This input tests the step lemma independently of the tower.','operator_matrices/step_30.npz')
pert=[]
for scale in np.linspace(0,1,21):
    ep=scale*tau_test/norm(Rmap);T=x+ep*Rmap
    pert.append((scale,ep,norm(T-x),norm(T),norm(power(T,d)-ep*y)))
table('perturbation',['budget_fraction','epsilon','perturbation_norm','operator_norm','identity_residual'],pert)
fig,ax=canvas();a=np.array(pert);ax.plot(a[:,0],a[:,2],color=gold,label='‖S − x‖');ax.plot(a[:,0],a[:,3],color=teal,label='‖S‖');ax.set(xlabel='Fraction of the perturbation budget',ylabel='Spectral norm');ax.legend(frameon=False);grid(ax)
finish(fig,ax,'07-budget','Tuning the coupling','The parameter sweep spends between zero and the full τ = 1/2 allowance. The zero-coupling endpoint is the uncoupled control.','numerical_results/perturbation.csv')
fig,ax=canvas();ax.scatter(u.real,u.imag,s=[90]*len(u),color=teal);ax.annotate('×4',(0,.5),xytext=(7,0),textcoords='offset points');ax.annotate('×4',(0,-.5),xytext=(7,0),textcoords='offset points');ax.axhline(0,c='gray',lw=.6);ax.axvline(0,c='gray',lw=.6);ax.set(xlim=(-1.2,1.2),ylim=(-.7,.7),xlabel='Real part',ylabel='Imaginary part');ax.set_aspect('equal')
table('multipliers',['slot','real','imag'],[(i,v.real,v.imag) for i,v in enumerate(u)])
finish(fig,ax,'08-multipliers','Cancellation through degree two','The ten multipliers give (1 − z²)(1 + z²/4)⁴ ≡ 1 mod z³. Multiplicities are printed at the two repeated roots.','numerical_results/multipliers.csv')
sing=svdvals(g);table('basis_spectrum',['index','singular_value'],enumerate(sing,1))
fig,ax=canvas();ax.semilogy(np.arange(1,q+1),sing,'o-',ms=3,color=teal);ax.set(xlabel='Singular value index',ylabel='Singular value of the basis matrix');grid(ax)
finish(fig,ax,'09-conditioning','The cyclic basis has unequal scales','Singular values measure the sensitivity of moving from chain coordinates to slot coordinates. Raw powers can underflow before exact algebraic nilpotency.','numerical_results/basis_spectrum.csv')
mu=Fraction(1,8);L1=1/tau**2;tau2=mu/16/(24*L1);nu=math.ceil(3*tau2**-3);D2=2*nu+7
bounds=[(n,2.**(-n-2),sum(2.**(-j-2) for j in range(2,n+1))) for n in range(2,13)]
table('tail_bounds',['level_m','gamma_m_over_mu_upper','partial_sum_upper_n1'],bounds)
fig,ax=canvas();a=np.array(bounds);ax.bar(a[:,0],a[:,1],color=teal,label='Individual allowance');ax.plot(a[:,0],a[:,2],'.-',color=gold,label='Cumulative allowance');ax.axhline(.25,c=navy,ls=':',label='Uniform bound ¼');ax.set(xlabel='Level m, with base index n = 1',ylabel='Bound in units of μ₁');ax.legend(frameon=False);grid(ax)
finish(fig,ax,'10-tail','The error budget is summable','Section 4 gives γₘ/μ₁ ≤ 2⁻ᵐ⁻² for m > 1. These are analytic upper bounds. The finite matrices at later levels were not assembled.','numerical_results/tail_bounds.csv')
checks={'started_utc':started,'finished_utc':datetime.now(timezone.utc).isoformat(),'tower':{'dimension':3,'tau1':str(tau),'mu1':str(mu),'L1':str(L1),'tau2_choice':str(tau2),'lemma31_explicit_slots_next':str(D2),'next_dimension_explicit_recipe':str(3*D2)},'lemma_test':{'dimension':q,'tau':tau_test,'epsilon':eps,'basis_condition':float(sing[0]/sing[-1]),'perturbation_norm':norm(S-x),'operator_norm':norm(S),'split_max_error':max(r[2] for r in splits),'split_bound':24*L*tau_test,'residuals':res},'exact_rank_cases':len(ranks),'exact_orbit_cases':len(flag),'figures':len(figures)}
save_json(D/'computation_verification.json',checks);save_json(F/'index.json',figures)
print(json.dumps(checks,indent=2))
