"""Rational-complex verification of the chain identities for one additional coupling."""
from pathlib import Path
import json
import sympy as s
R=Path(__file__).resolve().parents[1]
d,D=3,10;q=d*D
def shift(n):
 return s.Matrix(n,n,lambda i,j:int(i==j+1))
J=shift(d)/4;tau=s.Rational(1,2);eps=s.Rational(1,64)
u=[-1]+[s.I/2,-s.I/2]*4+[1]
x=s.kronecker_product(s.eye(D),J);y=s.kronecker_product(s.diag(*u),J)+tau*s.kronecker_product(shift(D),s.eye(d))
e=s.eye(q)[:,0];columns=[];a=e
for j in range(D):
 b=a
 for i in range(d):columns.append(b);b=x*b
 a=(y*a).applyfunc(s.expand)
g=s.Matrix.hstack(*columns);wrap=s.zeros(q)
for j in range(D-1):wrap[d*(j+1),d*(j+1)-1]=1
operator_R=g*wrap*g.inv();T=(x+eps*operator_R).applyfunc(s.expand)
assert g.det()!=0 and x*y==y*x and (y**D).applyfunc(s.expand)==s.zeros(q)
assert (T**d-eps*y).applyfunc(s.expand)==s.zeros(q)
# Raising the exact cubic identity to the tenth power now gives T^30 = 0.
last=(eps**9*x**2*y**9*e).applyfunc(s.expand)
assert last!=s.zeros(q,1)
v=e;orbit=[]
for k in range(q):orbit.append(v);v=(T*v).applyfunc(s.expand)
assert s.Matrix.hstack(*orbit).rank()==q and orbit[-1]==last and v==s.zeros(q,1)
# The spectral norm is bounded above by the exact Frobenius norm.
frobenius_squared=s.simplify(s.trace((eps*operator_R).H*(eps*operator_R)))
result={'dimension':q,'epsilon':str(eps),'tau':str(tau),'basis_determinant':str(g.det()),'cyclic_rank':q,'nilpotency_index':q,'commutator_zero':True,'S_cubed_equals_epsilon_y':True,'last_nonzero_orbit_coordinates':{str(k):str(v) for k,v in enumerate(last) if v!=0},'perturbation_frobenius_squared':str(frobenius_squared),'frobenius_bound_certifies_budget':bool(frobenius_squared<=tau**2)}
assert result['frobenius_bound_certifies_budget']
(R/'numerical_results/exact_30d.json').write_text(json.dumps(result,indent=2)+'\n')
