#!/usr/bin/env python3
"""generator_v6.py -- checks for 'The Guideng Digital Cosmology', Version 6.
Digital side: Python integers and fractions only.  Continuum reference: mpmath, 40 digits."""
from fractions import Fraction as F
from math import isqrt
import itertools, random
from mpmath import mp, mpf, quad, sqrt, findroot

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

# ---------------------------------------------------------------- E8 registers
roots = []
for i, j in itertools.combinations(range(8), 2):
    for a in (2, -2):
        for b in (2, -2):
            r = [0]*8; r[i] = a; r[j] = b; roots.append(tuple(r))
for s in itertools.product((1, -1), repeat=8):
    if s.count(-1) % 2 == 0:
        roots.append(s)
idx = {r: k for k, r in enumerate(roots)}
check("240 roots (doubled coordinates, norm^2 = 8)", len(roots) == 240 and all(sum(x*x for x in r) == 8 for r in roots))
gram = [[sum(r[i]*r[j] for r in roots) for j in range(8)] for i in range(8)]
check("tight frame  V V^T = 60 I  (240 I in doubled coordinates)",
      all(gram[i][j] == (240 if i == j else 0) for i in range(8) for j in range(8)))

def V(P):   # doubled coordinates: |V_doubled Psi|^2 = 4 |V Psi|^2
    return [sum(P[k]*roots[k][i] for k in range(240)) for i in range(8)]
def m(P):
    return 240*sum(x*x for x in P) - sum(x*x for x in V(P))

random.seed(5)
check("m(Psi) is a multiple of 8 on 500 random integer states",
      all(m([random.randint(-50, 50) for _ in range(240)]) % 8 == 0 for _ in range(500)))
e0 = [0]*240; e0[0] = 1
check("m(e_r) = 232", m(e0) == 232)
star = [0]*240; star[0] = 1; star[idx[tuple(-x for x in roots[0])]] = 1
one = [1]*240; oneA = [1]*112 + [0]*128; oneB = [0]*112 + [1]*128
check("rays: m(star)=480, m(1_A)=26880, m(1_B)=30720, m(1)=240^2",
      (m(star), m(oneA), m(oneB), m(one)) == (480, 26880, 30720, 57600))
check("all four rays lie in ker V", all(not any(V(v)) for v in (star, oneA, oneB, one)))
def lattice_move():
    u = [random.randint(-9, 9) for _ in range(8)]          # V^T u, u in Z^8 (doubled coords)
    return [sum(roots[k][i]*u[i] for i in range(8)) for k in range(240)]
good = True
for _ in range(40):
    X = random.randint(-10**6, 10**6); c = lattice_move()
    good &= m([X + c[k] for k in range(240)]) == 57600*X*X
    xa, xb = random.randint(-999, 999), random.randint(-999, 999)
    good &= m([xa*oneA[k] + xb*oneB[k] + c[k] for k in range(240)]) == 26880*xa*xa + 30720*xb*xb
check("m(X 1 + V^T u) = 240^2 X^2  and  m(X_A 1_A + X_B 1_B + V^T u) = 26880 X_A^2 + 30720 X_B^2", good)
def reflect(v, r):
    d = sum(a*b for a, b in zip(v, r))                       # (v.r) in doubled coords: multiple of 4
    return tuple(a - (d*b)//4 for a, b in zip(v, r))
good = True
for _ in range(20):
    r = random.choice(roots); perm = [idx[reflect(v, r)] for v in roots]
    P = [random.randint(-9, 9) for _ in range(240)]
    Pp = [0]*240
    for k in range(240): Pp[perm[k]] = P[k]
    good &= m(Pp) == m(P)
check("m is invariant under Weyl reflections (P commutes with the Weyl group)", good)

# ------------------------------------- register representation, ledger, no selection (Section 8)
import numpy as np
Rm = np.array(roots, dtype=np.int64)                    # doubled coordinates
G4 = Rm @ Rm.T                                          # 4 <r,s>
I240 = np.eye(240, dtype=np.int64); J = np.ones((240, 240), dtype=np.int64)
def orbits(perms, n=240):
    par = list(range(n))
    def find(x):
        while par[x] != x:
            par[x] = par[par[x]]; x = par[x]
        return x
    for p in perms:
        for k in range(n): par[find(k)] = find(p[k])
    out = {}
    for k in range(n): out.setdefault(find(k), []).append(k)
    return list(out.values())
refl_perm = lambda r: [idx[reflect(v, r)] for v in roots]
check("the Weyl group is transitive on the 240 registers", len(orbits([refl_perm(r) for r in roots[:120]] + [refl_perm(r) for r in roots[120:]])) == 1)
r0 = roots[0]
stab = [refl_perm(r) for r in roots if sum(a*b for a, b in zip(r, r0)) == 0]
orb = orbits(stab)
sig = sorted((len(o), int(G4[0, o[0]])//4) for o in orb)
check("stabilizer of a root: five orbits, sizes 1,1,56,56,126 at inner products -2,2,-1,1,0",
      sig == [(1, -2), (1, 2), (56, -1), (56, 1), (126, 0)] and all(len({int(G4[0, k]) for k in o}) == 1 for o in orb))
A = (G4 == 4).astype(np.int64)
ev = [56, 28, 8, -4, -2]
M = I240.copy()
for e in ev: M = M @ (A - e*I240)
check("(A-56)(A-28)(A-8)(A+4)(A+2) = 0", not M.any())
mult = []
for e in ev:
    E = I240.copy(); den = 1
    for f in ev:
        if f != e: E = E @ (A - f*I240); den *= (e - f)
    mult.append(F(int(np.trace(E)), den))
check("eigenspaces of A have dimensions 1, 8, 35, 84, 112", mult == [1, 8, 35, 84, 112])
check("A V^T = 28 V^T  (the eigenspace of 28 is im P)", np.array_equal(A @ Rm, 28*Rm))
Gam4 = 8*J - G4                                         # 4 Gamma,  Gamma_rs = 2 - <r,s>
ones = np.ones(240, dtype=np.int64)
check("Gamma 1 = 480 1  and  Gamma V^T = -60 V^T", np.array_equal(Gam4 @ ones, 1920*ones) and np.array_equal(Gam4 @ Rm, -240*Rm))
check("Gamma (Gamma - 480)(Gamma + 60) = 0", not (Gam4 @ (Gam4 - 1920*I240) @ (Gam4 + 240*I240)).any())
check("multiplicities 1 and 8: tr Gamma = 0, tr Gamma^2 = 480^2 + 8*60^2",
      int(np.trace(Gam4)) == 0 and int(np.trace(Gam4 @ Gam4)) == 1920**2 + 8*240**2)
good = True
for _ in range(40):
    P_ = np.array([random.randint(-50, 50) for _ in range(240)], dtype=object)
    good &= int(P_ @ (Gam4.astype(object) @ P_)) == 8*int(sum(P_))**2 - sum(x*x for x in V(list(P_)))
    X = random.randint(-10**6, 10**6); u = [random.randint(-9, 9) for _ in range(8)]
    c = [sum(roots[k][i]*u[i] for i in range(8)) for k in range(240)]       # V^T u_true with u_true = 2u
    Q_ = np.array([X + c[k] for k in range(240)], dtype=object)
    good &= int(Q_ @ (Gam4.astype(object) @ Q_)) == 4*(2*m(list(Q_)) - 3600*4*sum(x*x for x in u))
    good &= m(list(Q_)) == 240*sum(int(x)*int(x) for x in Q_) - sum(x*x for x in V(list(Q_)))
check("Psi^T Gamma Psi = 2 (sum Psi)^2 - |V Psi|^2,  and  = 2 m - 3600 |u|^2 on X 1 + V^T u", good)
def U_equivariant(P_, q):                               # a nonlinear update commuting with the Weyl group
    return [P_[k] + 2*q + sum(P_[s]**3 for s in range(240) if G4[k, s] == 4) - P_[k]**2 for k in range(240)]
state = [3]*240
for _ in range(3): state = U_equivariant(state, 7)
check("a nonlinear Weyl-equivariant update keeps a history started on the ray 1 on the ray", len(set(state)) == 1 and not any(V(state)))
perm = refl_perm(roots[17]); Pq = [random.randint(-3, 3) for _ in range(240)]
lhs = U_equivariant([Pq[perm.index(k)] for k in range(240)], 7); rhs0 = U_equivariant(Pq, 7); rhs = [rhs0[perm.index(k)] for k in range(240)]
check("that update commutes with a Weyl reflection on a random state", lhs == rhs)

# ------------------------------------------------- radiation + matter: exact laws
good = True
for _ in range(200):
    p, q = random.randint(1, 10**6), random.randint(1, 10**6)
    x = [0, p + q]
    for n in range(1, 40): x.append(2*x[n] - x[n-1] + 2*q)
    for n in range(1, 39):
        good &= x[n] == p*n + q*n*n
        good &= (x[n+1] - x[n-1])**2 == 16*q*x[n] + 4*p*p                       # centred law
        good &= 8*(x[n+1] - x[n])**2 == 8*p*p + 4*q*(4*(x[n+1] + x[n]) - (x[n+1] - 2*x[n] + x[n-1]))  # Paper 6
        good &= (x[n+1] - x[n])**2 == 4*q*F(x[n] + x[n+1], 2) + p*p - q*q       # staggered law
check("x_n = p n + q n^2; centred, corrected-midpoint and staggered laws exact at every tick", good)

# ------------------------------------------------------------- Planck 2018 run
Om = F(3153, 10000); Or = F(92, 1000000); OL = 1 - Om - Or
mOm, mOr, mOL = (mpf(v.numerator)/v.denominator for v in (Om, Or, OL))
Q = lambda a: mOr + mOm*a + mOL*a**4
eta = lambda a: quad(lambda s: 2*s/sqrt(Q(s*s)), [0, sqrt(a)/3, sqrt(a)])       # s^2 = a removes nothing singular but spreads nodes
AGE = eta(1); CHI = AGE - eta(mpf(1)/2); DL = 2*CHI
H1 = sqrt(mOm*8 + mOr*16 + mOL)
AT = findroot(lambda a: mOL*a**4 - mOm*a/2 - mOr, 0.6); ZT = 1/AT - 1
print("reference: d_L(1) = %s, H(1) = %s, z_t = %s, conformal age = %s" %
      (mp.nstr(DL, 8), mp.nstr(H1, 8), mp.nstr(ZT, 6), mp.nstr(AGE, 8)))

S = 2**80
def history(N, start):
    h = F(1, N)
    q = round(h*h*S*Om/4)                      # matter integer  (second difference = 2q)
    R = int(h*h*S*S*Or)
    if start == "centred":
        p = isqrt(R); X1 = p + q               # p^2 = radiation integer
    else:                                      # Version 4 start: v0 (v0 - 2q) = R
        X1 = (2*q + isqrt(4*R + 4*q*q))//2; p = None
    L = 2*OL*h*h
    X = [0, X1]
    while X[-2] < S:
        x = X[-1]; X.append(2*x - X[-2] + 2*q + (L.numerator*x**3)//(L.denominator*S*S))
    return X, p, q, L

def tick_of(X, T):                             # fractional tick with X = T, rational, third-order
    n = next(k for k in range(len(X)-1) if X[k] <= T < X[k+1])
    d = X[n+1] - X[n]; D = X[n+1] - 2*X[n] + X[n-1] if n else 0
    t = F(T - X[n], d)
    return n + t + t*(1 - t)*F(D, 2*d)
def lagrange(f, t):                            # three-point rational interpolation at fractional tick t
    n = max(1, int(t)); s = t - n
    return f(n-1)*s*(s-1)/2 + f(n)*(1-s*s) + f(n+1)*s*(s+1)/2
def observables(N, start):
    X, p, q, L = history(N, start)
    h = F(1, N)
    t0 = tick_of(X, S); t1 = tick_of(X, S//2)
    dl = 2*(t0 - t1)*h
    Hn = lambda n: F(S*(X[n+1] - X[n-1]), 2*X[n]*X[n])/h
    Hz = lagrange(Hn, t1)
    acc = lambda n: 4*X[n]*(X[n+1] - 2*X[n] + X[n-1]) - (X[n+1] - X[n-1])**2
    n = next(k for k in range(2, len(X)-1) if acc(k) >= 0) - 1          # acc(n) < 0 <= acc(n+1)
    d = acc(n+1) - acc(n); D = acc(n+1) - 2*acc(n) + acc(n-1)
    t = F(-acc(n), d); tt = n + t + t*(1 - t)*F(D, 2*d)
    zt = F(S, 1)/lagrange(lambda k: F(X[k]), tt) - 1
    rel = lambda v, ref: float((mpf(v.numerator)/v.denominator - ref)/ref)
    return (len(X), int(t0)+1, rel(dl, DL), rel(Hz, H1), rel(zt, ZT), rel(t0*h, AGE)), (p, q, L)

print("\n ticks/(c/H0)  ticks-to-today   d_L(1)       H(1)         z_t          age        | age, Version-4 start")
rows = []
for N in (250, 500, 1000, 2000, 4000):
    o, (p, q, L) = observables(N, "centred"); o4, _ = observables(N, "v4")
    rows.append(o)
    print("%8d %14d    %+.1e   %+.1e   %+.1e   %+.1e   |  %+.1e" % (N, o[1], o[2], o[3], o[4], o[5], o4[5]))
    lam = L/(S*S)                                           # Delta^2 X = 2q + lam X^3
    kap = lam*F(p)**6/(512*F(q)**4)
    h = F(1, N)
    oM, oR, oLam = 4*F(q)/(S*h*h), F(p*p)/(S*S*h*h), lam*S*S/(2*h*h)
    check("N=%d: kappa = lam p^6/(512 q^4) equals Omega_r^3 Omega_L/Omega_m^4 of the update, exactly" % N,
          kap == oR**3*oLam/oM**4)
    check("N=%d: kappa agrees with the Planck value to 7 digits" % N,
          abs(float(kap/(Or**3*OL/Om**4)) - 1) < 1e-7)
Xh, _, _, _ = history(250, "centred")
good = True
for n in range(0, len(Xh), 40):
    c = lattice_move()
    good &= m([Xh[n] + c[k] for k in range(240)]) == 57600*Xh[n]**2
check("run history carried on the Weyl-invariant ray: m(Psi_n) = 240^2 X_n^2 at every tick checked", good)
ratio = lambda c: [abs(rows[i][c]/rows[i+1][c]) for i in range(4)]
print("error ratios per halving:  H(1)", ["%.2f" % r for r in ratio(3)], "  age", ["%.2f" % r for r in ratio(5)])
check("second-order convergence of H(1) and of the conformal age", all(3 < r < 5 for r in ratio(3) + ratio(5)))
kP = Or**3*OL/Om**4
print("kappa = %.6e   j = %.4e" % (float(kP), float(442368*kP/(256*kP - 27))))

# ---------------------------------------------------- exact law with Lambda (Euler)
def euler_C(a0, y0, a1, y1, lam): return ((y0 + y1)/(a1 - a0))**2 - lam*(a0 + a1)**2
a = [F(0), F(1), F(44, 5)]; y = [F(1), F(2), F(1939, 25)]       # Paper 9 samples of y^2 = 1 + 2a + a^4
check("Paper 9 samples lie on y^2 = 1 + 2a + a^4", all(yy*yy == 1 + 2*aa + aa**4 for aa, yy in zip(a, y)))
check("Euler form of the Friedmann law on Paper 9 samples: C = 8 at both ticks",
      euler_C(a[0], y[0], a[1], y[1], 1) == 8 == euler_C(a[1], y[1], a[2], y[2], 1))
from mpmath import odefun
hh = mpf(1)/4
sol = odefun(lambda t, z: [z[1], mOm/2 + 2*mOL*z[0]**3], 0, [0, sqrt(mOr)])
pts = [sol(k*hh) for k in range(0, 13)]
Cs = [((pts[k][1] + pts[k+1][1])/(pts[k+1][0] - pts[k][0]))**2 - mOL*(pts[k][0] + pts[k+1][0])**2 for k in range(12)]
check("Euler form on the Planck continuum history, tick 1/4: C constant to 1e-25",
      max(abs(c - Cs[0]) for c in Cs) < mpf(10)**-25)
print("   C(1/4) = %s   (4/h^2 = 64)" % mp.nstr(Cs[0], 12))

print("\nchecks passed:", ok)
