#!/usr/bin/env python3
"""check_04_v3.py -- checks for Unfolding Universe Paper 04 v3
(Guidement, Arisement and the projection identities)."""
import itertools
from fractions import Fraction as F
import numpy as np
from mpmath import mp, mpf, sqrt, quad, findroot, odefun, inf
mp.dps = 30
ok = True
def check(name, cond):
    global ok
    ok = ok and bool(cond)
    print(("PASS  " if cond else "FAIL  ") + name)

# ---------------- 1. projection identities, on the E8 registers (exact integers)
roots = []
for i, j in itertools.combinations(range(8), 2):
    for si, sj in itertools.product((2, -2), repeat=2):
        r = [0]*8; r[i] = si; r[j] = sj; roots.append(r)
for s in itertools.product((1, -1), repeat=8):
    if s.count(-1) % 2 == 0: roots.append(list(s))
V2 = np.array(roots, dtype=object).T                 # 8 x 240, entries are twice the root coordinates
check("240 roots of E8, each of squared length 2", V2.shape == (8, 240) and all(sum(x*x for x in r) == 8 for r in roots))
check("V V^T = 60 I, so Pi = V^T V / 60 is an orthogonal projector of rank 8",
      (V2.dot(V2.T) == 240*np.eye(8, dtype=object)).all())
rng = np.random.default_rng(4)
good = True; mult8 = True; shift = True
for _ in range(200):
    Psi = np.array([int(x) for x in rng.integers(-9, 10, 240)], dtype=object)
    VP = V2.dot(Psi)                                   # = 2 V Psi
    m = 240*int(Psi.dot(Psi)) - int(VP.dot(VP))        # 240 |Psi|^2 - 4 |V Psi|^2
    # Guidement G = Psi - V^T V Psi/60, computed in integers as 240 G
    G240 = 240*Psi - V2.T.dot(VP)                      # = 240 (I - Pi) Psi
    good &= (int(G240.dot(G240)) == 240*m)
    mult8 &= (m % 8 == 0)
    u = np.array([int(x) for x in rng.integers(-5, 6, 8)], dtype=object)
    Psi2 = Psi + V2.T.dot(u)                           # move inside im Pi
    VP2 = V2.dot(Psi2)
    shift &= (240*int(Psi2.dot(Psi2)) - int(VP2.dot(VP2)) == m)
check("Pythagoras: 240 |G|^2 = 240 |Psi|^2 - 4 |V Psi|^2 on 200 integer states", good)
check("that integer is a multiple of 8", mult8)
check("the Arisement does not change when the state moves inside im Pi", shift)
one = np.ones(240, dtype=object)
check("on the ray of all ones: V 1 = 0 and the Arisement of X 1 is sqrt(240) |X|", not V2.dot(one).any())

# ---------------- 2. the history: (a')^2 = Or + Om a + OL a^4
Om, Or = mpf(3153)/10000, mpf(92)/1000000; OL = 1 - Om - Or
Q = lambda a: Or + Om*a + OL*a**4
sol = odefun(lambda t, z: [z[1], Om/2 + 2*OL*z[0]**3], 0, [0, sqrt(Or)])
a = lambda eta: sol(eta)[0]
eta_now = quad(lambda x: 1/sqrt(Q(x)), [0, 1e-4, 1e-2, 1])
eta_max = quad(lambda x: 1/sqrt(Q(x)), [0, 1e-4, 1e-2, 1, 10, inf])
check("trace equation a'' = Om/2 + 2 OL a^3 reproduces (a')^2 = Q(a) at eta = 2",
      abs(sol(2)[1]**2 - Q(sol(2)[0])) < mpf(10)**-20)
print("      conformal age eta_now = %s, total conformal lifetime eta_max = %s (Hubble lengths)" % (mp.nstr(eta_now, 6), mp.nstr(eta_max, 6)))
check("a(eta_now) = 1", abs(a(eta_now) - 1) < mpf(10)**-15)

# radiation and matter only: second difference is exactly Om h^2/2, with no dark energy
arm = lambda eta: sqrt(Or)*eta + Om*eta**2/4
h = mpf(1)/50
check("radiation + matter: the second difference of a is exactly Om h^2 / 2 > 0 at every tick",
      all(abs(arm((n+1)*h) - 2*arm(n*h) + arm((n-1)*h) - Om*h*h/2) < mpf(10)**-25 for n in range(1, 60)))
check("radiation + matter never accelerates: a_{n+1} a_{n-1} < a_n^2 at every tick",
      all(arm((n+1)*h)*arm((n-1)*h) < arm(n*h)**2 for n in range(1, 200)))

# second difference with dark energy: h^2 (Om/2 + 2 OL a^3) + O(h^4)
errs = []
for N in (50, 100, 200):
    h = mpf(1)/N; n = 2*N
    d2 = a((n+1)*h) - 2*a(n*h) + a((n-1)*h)
    errs.append(abs(d2/h**2 - (Om/2 + 2*OL*a(n*h)**3)))
check("second difference / h^2 -> Om/2 + 2 OL a^3, error falling by 4 per halving", 3.8 < errs[0]/errs[1] < 4.2 and 3.8 < errs[1]/errs[2] < 4.2)

# Hubble: centred (second order) against forward (first order); root-free squared form
def Hc(n, h): return (a((n+1)*h) - a((n-1)*h))/(2*h*a(n*h)**2)
def Hf(n, h): return (a((n+1)*h) - a(n*h))/(h*a(n*h)**2)
def H2s(n, h):
    s = lambda k: a(k*h)**2
    return (s(n+1) - s(n-1))**2/(16*h*h*s(n)**3)
Hex = lambda eta: sqrt(Q(a(eta)))/a(eta)**2
ec = [abs(Hc(2*N, mpf(1)/N) - Hex(2)) for N in (50, 100, 200)]
ef = [abs(Hf(2*N, mpf(1)/N) - Hex(2)) for N in (50, 100, 200)]
es = [abs(H2s(2*N, mpf(1)/N) - Hex(2)**2) for N in (50, 100, 200)]
check("centred Hubble rate: error falls by 4 per halving", 3.8 < ec[0]/ec[1] < 4.2 and 3.8 < ec[1]/ec[2] < 4.2)
check("forward Hubble rate: error falls by 2 per halving", 1.9 < ef[0]/ef[1] < 2.1 and 1.9 < ef[1]/ef[2] < 2.1)
check("root-free squared rate H^2 = (s_{n+1}-s_{n-1})^2 s_ref/(16 h^2 s_n^3): error falls by 4 per halving",
      3.8 < es[0]/es[1] < 4.2 and 3.8 < es[1]/es[2] < 4.2)
print("      at 100 ticks per Hubble length, eta = 2: centred error %s, forward error %s" % (mp.nstr(ec[1]/Hex(2), 3), mp.nstr(ef[1]/Hex(2), 3)))

# acceleration: a a'' - (a')^2 = OL a^4 - Om a/2 - Or ; discrete: a_{n+1} a_{n-1} > a_n^2
a_acc = findroot(lambda x: OL*x**4 - Om*x/2 - Or, 0.6)
eta_acc = quad(lambda x: 1/sqrt(Q(x)), [0, 1e-4, 1e-2, a_acc])
print("      acceleration begins at a = %s, z = %s, eta = %s" % (mp.nstr(a_acc, 6), mp.nstr(1/a_acc - 1, 6), mp.nstr(eta_acc, 6)))
h = mpf(1)/100
flips = [n for n in range(2, 420) if (a((n+1)*h)*a((n-1)*h) > a(n*h)**2) != (a((n+2)*h)*a(n*h) > a((n+1)*h)**2)]
check("three-tick test a_{n+1} a_{n-1} > a_n^2 changes sign once, at the tick of a_acc",
      len(flips) == 1 and abs(flips[0]*h - eta_acc) < 2*h)
check("before that tick the second difference is already positive", a(101*h) - 2*a(100*h) + a(99*h) > 0)
# dark energy from two readings of the second difference
h = mpf(1)/200
d2 = lambda n: (a((n+1)*h) - 2*a(n*h) + a((n-1)*h))/h**2
n1, n2 = 400, 600
OL_est = (d2(n2) - d2(n1))/(2*(a(n2*h)**3 - a(n1*h)**3)); Om_est = 2*d2(n1) - 4*OL_est*a(n1*h)**3
print("      from two ticks: OL = %s (true %s), Om = %s (true %s)" % (mp.nstr(OL_est, 7), mp.nstr(OL, 7), mp.nstr(Om_est, 7), mp.nstr(Om, 7)))
check("dark energy is the cubic part of the second difference: OL and Om recovered to 1e-4", abs(OL_est - OL) < 1e-4 and abs(Om_est - Om) < 1e-4)
print("      curve for the figure:", " ".join("(%.2f,%.3f)" % (e, a(e)) for e in [0.25*k for k in range(0, 17)]))
print("\nchecks passed:", ok)
