#!/usr/bin/env python3
"""check_05_v2.py -- exact checks for Unfolding Universe Paper 05 v2.
Integers and fractions for the roots, registers and histories; sympy for the frame identities.
Every check prints one line. The last line reads "checks passed: True"."""
import itertools
from fractions import Fraction as Fr
import numpy as np
import sympy as sp

ok = True
def check(name, cond):
    global ok
    ok = ok and bool(cond)
    print(("PASS  " if cond else "FAIL  ") + name)

print("Part I. Frames")
a, t = sp.symbols('a t', positive=True)
phi = sp.Function('phi')(t); af = sp.Function('a', positive=True)(t)
L = sp.Matrix([[sp.cosh(phi), sp.sinh(phi), 0, 0], [sp.sinh(phi), sp.cosh(phi), 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]])
F = af*L
om = sp.simplify(F.inv()*F.diff(t))
check("Theorem 2: F^{-1} dF = L^{-1} dL + d(log a) I for F = a L", sp.simplify(om - (L.inv()*L.diff(t) + sp.diff(sp.log(af), t)*sp.eye(4))).is_zero_matrix)
check("Theorem 2: (1/4) tr(F^{-1} dF) = d log a, and L^{-1} dL has trace zero", sp.simplify(om.trace()/4 - sp.diff(sp.log(af), t)) == 0 and sp.simplify((L.inv()*L.diff(t)).trace()) == 0)
check("Corollary 3: det of the conformal coframe is a^4; of the cosmic-time coframe diag(1,a,a,a) it is a^3", sp.simplify((a*sp.eye(4)).det() - a**4) == 0 and sp.diag(1, a, a, a).det() == a**3)
K = sp.diag(-3, 1, 1, 1)
check("Proposition 4: diag(1,a,a,a) = a^(3/4) exp((1/4) log a K) with K = diag(-3,1,1,1)",
      sp.simplify(a**sp.Rational(3, 4)*sp.diag(*[sp.exp(sp.log(a)*K[i, i]/4) for i in range(4)]) - sp.diag(1, a, a, a)).is_zero_matrix)
Ks = [sp.diag(*[(-3 if i == j else 1) for i in range(4)]) for j in range(4)]
check("Proposition 4: the four placements of -3 have trace zero, sum to zero and span three dimensions",
      all(k.trace() == 0 for k in Ks) and sum(Ks, sp.zeros(4, 4)).is_zero_matrix and sp.Matrix([[k[i, i] for i in range(4)] for k in Ks]).rank() == 3)
eta = sp.diag(-1, 1, 1, 1)
check("Proposition 4: K is not a conformal Lorentz generator: K eta + eta K is not a multiple of eta", not any(sp.simplify(K*eta + eta*K - c*eta).is_zero_matrix for c in (0, 2, -6, sp.Rational(-3, 2))) and (K*eta + eta*K) == sp.diag(6, 2, 2, 2))
check("Proposition 5: the half weights of Q and Qbar add to the weight one of P", Fr(1, 2) + Fr(1, 2) == 1)

check("Proposition 4(5): K0 = 2 eta - I, and diag(1,a,a,a) = sqrt(a) exp((1/2) log a eta)", K == 2*eta - sp.eye(4) and
      sp.simplify(sp.sqrt(a)*sp.diag(*[sp.exp(sp.log(a)*eta[i, i]/2) for i in range(4)]) - sp.diag(1, a, a, a)).is_zero_matrix)
bet = sp.symbols('beta', real=True)
lhs6 = sp.diag(a**bet, a, a, a)
rhs6 = a**((bet + 3)/4)*sp.diag(*[a**((1 - bet)*K[i, i]/4) for i in range(4)])
check("Proposition 4(6): diag(a^beta,a,a,a) = a^((beta+3)/4) exp((1/4)(1-beta) log a K0)", sp.simplify(sp.powsimp(lhs6 - rhs6, force=True)).is_zero_matrix)
check("Proposition 4(6): H ~ a^(-beta) gives density ~ a^(-2 beta) = a^(-3(1+w)) with w = 2 beta/3 - 1; values 1/3, 0, -1/3, -1 at beta = 2, 3/2, 1, 0",
      sp.simplify(-3*(1 + (2*bet/3 - 1)) + 2*bet) == 0 and [sp.Rational(2, 3)*b - 1 for b in (2, sp.Rational(3, 2), 1, 0)] == [sp.Rational(1, 3), 0, sp.Rational(-1, 3), -1])
print("\nPart II. The roots and the projector")
roots = []
for i, j in itertools.combinations(range(8), 2):
    for s1 in (2, -2):
        for s2 in (2, -2):
            r = [0]*8; r[i] = s1; r[j] = s2; roots.append(r)
for s in itertools.product((1, -1), repeat=8):
    if s.count(-1) % 2 == 0: roots.append(list(s))
V = np.array(roots, dtype=np.int64).T
VA, VB = V[:, :112], V[:, 112:]
I8 = np.eye(8, dtype=np.int64); I240 = np.eye(240, dtype=np.int64)
check("240 roots, each of squared length 8", V.shape == (8, 240) and set((V*V).sum(axis=0)) == {8})
check("Theorem 6: V_A V_A^T = 112 I, V_B V_B^T = 128 I, V V^T = 240 I",
      (VA@VA.T == 112*I8).all() and (VB@VB.T == 128*I8).all() and (V@V.T == 240*I8).all())
G = V.T@V
check("Theorem 7: P = V^T V/240 is a projector: (V^T V)^2 = 240 V^T V, symmetric, trace 8", (G@G == 240*G).all() and (G == G.T).all() and np.trace(G) == 8*240)
A = (G == 4).astype(np.int64); Am = (G == -4).astype(np.int64); J = (G == -8).astype(np.int64)
check("inner products of roots take the values 8, 4, 0, -4, -8 with counts 1, 56, 126, 56, 1", all(sorted(zip(*np.unique(G[k], return_counts=True))) == [(-8, 1), (-4, 56), (0, 126), (4, 56), (8, 1)] for k in range(240)))
check("Theorem 8: graph form 240 P = 8(I - J) + 4(A_+ - A_-), and A_- = A_+ J", (G == 8*(I240 - J) + 4*(A - Am)).all() and (Am == A@J).all())
poly = (A + 4*I240)@(A + 2*I240)@(A - 8*I240)@(A - 56*I240)
check("Theorem 8: spectral form (A+4)(A+2)(A-8)(A-56) = -2240 V^T V", (poly == -2240*G).all())
tr = [int(np.trace(np.linalg.matrix_power(A, k))) for k in range(5)]
ev = [56, 28, 8, -4, -2]
M = sp.Matrix([[e**k for e in ev] for k in range(5)])
mult = list(M.solve(sp.Matrix(tr)))
check("Theorem 8: A has eigenvalues 56, 28, 8, -4, -2 with multiplicities 1, 8, 35, 84, 112", mult == [1, 8, 35, 84, 112] and
      ((A - 56*I240)@(A - 28*I240)@(A - 8*I240)@(A + 4*I240)@(A + 2*I240) == 0).all())
check("Theorem 8: A V^T = 28 V^T, A 1 = 56 1, V 1 = 0", (A@V.T == 28*V.T).all() and (A.sum(axis=1) == 56).all() and (V.sum(axis=1) == 0).all())
check("Theorem 8: P = (I - J)(2I + A_+)/60, and P J = J P = -P", (60*G == 240*((I240 - J)@(2*I240 + A))).all() and (G@J == -G).all() and (J@G == -G).all())
# the ladder
import random as _rl
_rl.seed(21)
us = [np.array([_rl.randint(-3, 3) for _ in range(8)], dtype=object) for _ in range(140)]
Vo = V.astype(object); Ao = A.astype(object); Io = np.eye(240, dtype=object)
def Wk(u, k): return np.array([int(x)**k for x in (Vo.T@u)], dtype=object)
def rank_mod(rows, pr=1000003):
    M = [[int(x) % pr for x in r] for r in rows]; rk = 0; ncol = len(M[0])
    for c in range(ncol):
        piv = next((i for i in range(rk, len(M)) if M[i][c]), None)
        if piv is None: continue
        M[rk], M[piv] = M[piv], M[rk]; inv = pow(M[rk][c], pr - 2, pr)
        M[rk] = [(x*inv) % pr for x in M[rk]]
        for i in range(len(M)):
            if i != rk and M[i][c]:
                f = M[i][c]; M[i] = [(x - f*y) % pr for x, y in zip(M[i], M[rk])]
        rk += 1
    return rk
kill = {0: [56], 1: [28], 2: [56, 8], 3: [28, -2], 4: [56, 8, -4]}
inpart = True
for k, lams in kill.items():
    for u in us[:12]:
        w = Wk(u, k)
        for lam in lams: w = Ao@w - lam*w
        inpart &= all(x == 0 for x in w)
check("Theorem 9: W_k(u) lies in the parts 1; 8; 1+35; 8+112; 1+35+84 for k = 0,...,4 (products of A - eigenvalue vanish)", inpart)
ranks = [rank_mod([Wk(u, k) for u in us]) for k in range(5)]
cum = [rank_mod([Wk(u, j) for j in range(k + 1) for u in us]) for k in range(5)]
check("Theorem 9: the spans have dimensions 1, 8, 36, 120, 120 and running totals 1, 9, 44, 156, 240", ranks == [1, 8, 36, 120, 120] and cum == [1, 9, 44, 156, 240])
Jo = J.astype(object)
check("Theorem 9: J W_k = (-1)^k W_k, so powers 5 and above add nothing", all((Jo@Wk(u, k) == (-1)**k*Wk(u, k)).all() for u in us[:6] for k in range(8)))
mom = True; proj3 = True; mk = True
for u in us[:40]:
    sv = int(u@u); x = Vo.T@u
    mom &= sum(int(t)**2 for t in x) == 240*sv and sum(int(t)**4 for t in x) == 576*sv**2 and sum(int(t)**6 for t in x) == 1920*sv**3
    w3 = Wk(u, 3); proj3 &= all(int(c) == 576*sv*int(ui) for c, ui in zip(Vo@w3, u))
    def mm(w): return 240*sum(int(t)**2 for t in w) - sum(int(c)**2 for c in Vo@w)
    mk &= mm(Wk(u, 0)) == 57600 and mm(Wk(u, 1)) == 0 and mm(Wk(u, 2)) == 138240*sv**2 and mm(w3) == 129024*sv**3 and mm(Wk(u, 4)) == 240*sum(int(t)**8 for t in x)
check("Theorem 9: M_2 = 240 s, M_4 = 576 s^2, M_6 = 1920 s^3", mom)
check("Theorem 9: V W_3(u) = 576 s u", proj3)
check("Theorem 9: m(W_k) = 57600, 0, 138240 s^2, 129024 s^3, 240 M_8", mk)
e1 = np.array([1, 0, 0, 0, 0, 0, 0, 0], dtype=object); rt = np.array(roots[0], dtype=object)
check("Theorem 9: M_8 depends on the direction: M_8(e_1) = 7296, and M_8(v)/s^4 = 9984 at a root", sum(int(t)**8 for t in Vo.T@e1) == 7296 and sum(int(t)**8 for t in Vo.T@rt) == 9984*int(rt@rt)**4)
Gam = 8*np.ones((240, 240), dtype=np.int64) - G
check("Proposition 10: cancellation array |v||v'| - v.v' = 8 - v.v' = 8*11^T - 240 P has entries 0, 4, 8, 12, 16", set(np.unique(Gam)) == {0, 4, 8, 12, 16} and all(int(Gam[i, j]) == 8 - int(V[:, i]@V[:, j]) for i in range(0, 240, 17) for j in range(240)))
half = {0: 0, 4: sp.pi/3, 8: sp.pi/2, 12: 2*sp.pi/3, 16: sp.pi}
check("Proposition 10: the entries are 16 sin^2(phi/2) at the angles between roots (cos phi = v.v'/8)", all(sp.simplify(16*sp.sin(ph/2)**2 - g) == 0 and sp.simplify(sp.cos(ph) - sp.Rational(8 - g, 8)) == 0 for g, ph in half.items()))
ones = np.ones(240, dtype=np.int64)
check("Proposition 10: spectrum 1920 once, -240 eight times, 0 on 231: Gam 1 = 1920 1, Gam V^T = -240 V^T, Gam (Gam - 1920)(Gam + 240) = 0, trace 0",
      (Gam@ones == 1920*ones).all() and (Gam@V.T == -240*V.T).all() and (Gam@(Gam - 1920*I240)@(Gam + 240*I240) == 0).all() and np.trace(Gam) == 0 and 1920 - 8*240 + 0*231 == 0)
import random as _r
_r.seed(11); goodg = True
for _ in range(20):
    Ps = np.array([_r.randint(0, 5) for _ in range(240)], dtype=np.int64)
    Nn = V@Ps
    goodg &= int(Ps@Gam@Ps) == 8*int(Ps.sum())**2 - int(Nn@Nn)
check("Proposition 10: C(Psi) = (sum Psi|v|)^2 - |sum Psi v|^2 = Psi^T Gam Psi", goodg)
def m(Psi):
    Psi = [Fr(x) for x in Psi]
    VP = [sum(Fr(int(V[i, k]))*Psi[k] for k in range(240)) for i in range(8)]
    return 240*sum(x*x for x in Psi) - sum(x*x for x in VP)
e5 = [0]*240; e5[5] = 3
check("Theorem 7: m(x e_j) = 232 x^2 and m(X 1) = 57600 X^2", m(e5) == 232*9 and m([7]*240) == 57600*49)
import random
random.seed(5)
Psi = [random.randint(-3, 3) for _ in range(240)]
PA, PB = np.array(Psi[:112]), np.array(Psi[112:])
ua, ub = VA@PA, VB@PB
check("cross-family form of the ledger", m(Psi) == 240*(int(PA@PA) + int(PB@PB)) - int(ua@ua) - int(ub@ub) - 2*int(ua@ub))

print("\nPart III. A frame in the registers")
def even(S):
    return [sum(roots[k][i]*S[i][j]*roots[k][j] for i in range(8) for j in range(8)) for k in range(240)]
good = True
for _ in range(15):
    S = [[0]*8 for _ in range(8)]
    for i in range(8):
        for j in range(i, 8): S[i][j] = S[j][i] = random.randint(-4, 4)
    Ps = even(S); trS = sum(S[i][i] for i in range(8)); tr2 = sum(S[i][j]**2 for i in range(8) for j in range(8))
    good &= m(Ps) == 240*192*(trS**2 + 2*tr2) and all(sum(int(V[i, k])*Ps[k] for k in range(240)) == 0 for i in range(8))
check("Proposition 12: an even state has no projected part and delta^2 = 192[(tr S)^2 + 2 tr S^2]", good)
pl = [(2, 2, 0, 0, 0, 0, 0, 0), (2, -2, 0, 0, 0, 0, 0, 0), (0, 0, 2, 2, 0, 0, 0, 0), (0, 0, 2, -2, 0, 0, 0, 0)]
def frame_state(Fm):
    d = lambda r, p: sum(x*y for x, y in zip(r, p))
    return [sum(Fr(Fm[i][j])*d(r, pl[i])*d(r, pl[j]) for i in range(4) for j in range(4))/8 for r in roots]
good = True
for _ in range(10):
    a1 = Fr(random.randint(1, 6)); F0 = [[Fr(0)]*4 for _ in range(4)]
    for i in range(4):
        for j in range(i, 4): F0[i][j] = F0[j][i] = Fr(random.randint(-3, 3))
    mm = sum(F0[i][i] for i in range(4))/4
    for i in range(4): F0[i][i] -= mm
    Fm = [[(a1 if i == j else 0) + F0[i][j] for j in range(4)] for i in range(4)]
    good &= m(frame_state(Fm)) == 240*(4608*a1*a1 + 384*sum(F0[i][j]**2 for i in range(4) for j in range(4)))
check("Proposition 12: for a symmetric frame a I + F0 on four orthogonal roots, delta^2 = 4608 a^2 + 384 |F0|^2", good)
good = True
for av in (Fr(1, 2), Fr(2), Fr(7, 3)):
    good &= m(frame_state([[av if i == j else 0 for j in range(4)] for i in range(4)])) == 240*4608*av*av
    good &= m(frame_state([[(1 if i == 0 else av) if i == j else 0 for j in range(4)] for i in range(4)])) == 240*192*(3 + 6*av + 15*av*av)
check("Proposition 12: conformal frame gives delta^2 = 4608 a^2; cosmic-time frame gives 192(3 + 6a + 15a^2)", good)

print("\nPart IV. Histories on the ray")
U = [[1, 1, 0], [0, 1, 1], [0, 0, 1]]
def history(p, q, N):
    st = [0, p + q, 2*q]; out = []
    for n in range(N):
        out.append(st[0]); st = [sum(U[i][j]*st[j] for j in range(3)) for i in range(3)]
    return out
good = True; law = True
for p, q in [(1, 0), (0, 1), (1, 1), (3, 2), (5, 7)]:
    x = history(p, q, 40)
    good &= all(x[n] == p*n + q*n*n for n in range(40))
    law &= all((x[n+1] - x[n-1])**2 == 16*q*x[n] + 4*p*p for n in range(1, 39))
check("Theorem 13: one fixed integer update gives x_n = p n + q n^2 from the start (0, p+q, 2q)", good)
check("Theorem 13: the centred law (x_{n+1} - x_{n-1})^2 = 16 q x_n + 4 p^2 holds at every tick", law)
check("Theorem 13: ledger on the ray m_n = 57600 x_n^2, so (1+z)^2 = (x_obs/x_em)^2", m([history(3, 2, 6)[5]]*240) == 57600*(3*5 + 2*25)**2)
check("Proposition 10: on the ray C = 8 m", int((7*ones)@Gam@(7*ones)) == 8*m([7]*240))
good = True
for p, q in [(1, 0), (0, 1), (1, 1), (3, 2), (5, 7)]:
    x = history(p, q, 40)
    for n in range(1, 39):
        Pn, Qn = p + q*n, q*n
        good &= 2*(Pn + Qn) == x[n+1] - x[n-1] and Pn - Qn == p and Pn*Qn == q*x[n] and (Pn + Qn)**2 == (Pn - Qn)**2 + 4*Pn*Qn and q*x[n] == Qn*(Qn + p)
check("Proposition 14: P = p + qn, Q = qn have sum (x_{n+1} - x_{n-1})/2, difference p, product q x_n; (P+Q)^2 = (P-Q)^2 + 4PQ is the centred law; q x_n = Q(Q + p)", good)
# Hubble estimators, in units c = dEta = 1, with reference m_r
def H2_centred(mm, n, mr): return Fr(mr*(mm[n+1] - mm[n-1])**2, 16*mm[n]**3)
def H2_forward(mm, n, mr): return Fr(mr*(mm[n+1] - mm[n])**2, 4*mm[n]**3)
rad = [57600*n*n for n in range(60)]; mat = [57600*n**4 for n in range(60)]
mr = 57600
check("Proposition 15: on a = n the centred estimator is exact, H^2 = 1/n^4", all(H2_centred(rad, n, mr) == Fr(1, n**4) for n in range(1, 50)))
check("Proposition 15: on a = n^2 the centred estimator is H^2 = (4/n^6)(1 + 1/n^2)^2", all(H2_centred(mat, n, mr) == Fr(4, n**6)*(1 + Fr(1, n*n))**2 for n in range(1, 50)))
check("Proposition 15: the forward estimator is H^2 = (1/n^4)(1 + 1/(2n))^2 on a = n", all(H2_forward(rad, n, mr) == Fr(1, n**4)*(1 + Fr(1, 2*n))**2 for n in range(1, 50)))
n_ = sp.symbols('n', positive=True)
fwd = sp.series(sp.sqrt(((n_ + 1)**4 - n_**4)**2/(4*n_**12))/(2/n_**3), n_, sp.oo, 2)
check("Proposition 15: on a = n^2 the forward estimator is off by 3/(2n) to leading order", sp.simplify(fwd.removeO() - (1 + sp.Rational(3, 2)/n_)) == 0)
print("\nchecks passed:", ok)
