#!/usr/bin/env python3
"""
Guideng Math Paper 24.  The Slow Pair.
Numerical verification of every statement.  Requires numpy and sympy.

Conventions (Papers 5, 8, 17): a number of K is a real array of k = 1, 2, 4, 8 entries with the
product of the doubling; a root is (x, y); X = (t; a, u) acts by
    G(X)(x, y) = ((t+a) x + u y, conj(u) x + (t-a) y),        Gb(X) = G(X) - 2t.
E_0 = (1; 0, 0) and E_1, ..., E_{k+1} are the odd units.  D = sum_mu G(E_mu) d_mu,
Db = sum_mu Gb(E_mu) d_mu.  A pair of constant m:  D psi = m chi,  Db chi = m psi.
"""
import numpy as np, sympy as sp, sys, math

rng = np.random.default_rng(24)
results = []
def check(label, cond, note=''):
    results.append(bool(cond)); print('[%s] %2d. %s%s' % ('ok' if cond else 'FAIL', len(results), label, ('   (' + note + ')') if note else ''))
NAME = {1: 'R', 2: 'C', 4: 'H', 8: 'O'}

def conj(x):
    c = -x.copy(); c[0] = x[0]; return c
def mul(x, y):
    n = len(x)
    if n == 1: return x * y
    h = n // 2; a, b, c, d = x[:h], x[h:], y[:h], y[h:]
    return np.concatenate([mul(a, c) - mul(conj(d), b), mul(d, a) + mul(b, conj(c))])
def Gam(X, k):
    def act(p):
        x, y = p[:k], p[k:]; t, a, u = X[0], X[1], X[2:]
        return np.concatenate([(t + a) * x + mul(u, y), mul(conj(u), x) + (t - a) * y])
    return np.column_stack([act(e) for e in np.eye(2 * k)])
def units(k): return [np.eye(k + 2)[j] for j in range(k + 2)]
def rmul(q, k):                       # the root times a number q of K on the right, as a matrix on the 2k numbers of a root
    def act(p): return np.concatenate([mul(p[:k], q), mul(p[k:], q)])
    return np.column_stack([act(e) for e in np.eye(2 * k)])

# ---------------------------------------------------------------- Section 2: the setting
for k in (1, 2, 4, 8):
    E = units(k); G = [Gam(e, k) for e in E]; I = np.eye(2 * k)
    ok = np.allclose(G[0], I) and all(np.allclose(g, g.T) for g in G)
    ok &= all(np.allclose(G[i] @ G[j] + G[j] @ G[i], 2 * (i == j) * I) for i in range(1, k + 2) for j in range(1, k + 2))
    check('%s  Section 2: G(E_0) = 1; the G(E_j) of the odd units are symmetric, square to 1 and anticommute, so D_s^2 is the Laplacian' % NAME[k], ok)

# ---------------------------------------------------------------- Sections 3, 4: the free pair, wave by wave
# (Lemma 3.2, Theorems 3.3, 3.4, 4.2, 4.3)
def setup(k, m, kmax, nmodes=24, dim_used=None):
    """a pair made of finitely many waves: fields are sums over wave vectors q of cos(q.x) c_q + sin(q.x) s_q"""
    d = 2 * k; ns = k + 1
    qs = []
    for _ in range(nmodes):
        q = rng.normal(size=ns); q *= rng.uniform(0.2, 1.0) * kmax / np.linalg.norm(q); qs.append(q)
    amp = [(rng.normal(size=2 * d), rng.normal(size=2 * d)) for _ in qs]      # (cos part, sin part) of (psi, chi) at t = 0
    Gs = [Gam(e, k) for e in units(k)[1:]]
    return d, qs, amp, Gs
def wave_state(d, q, amp, Gs, m, t):
    """exact solution for one wave vector: complex amplitude z = c - i s of exp(i q.x); d_t z = A z, A^2 = -(m^2+|q|^2)"""
    Gq = sum(q[j] * Gs[j] for j in range(len(Gs))); I = np.eye(d)
    A = np.block([[-1j * Gq, m * I], [-m * I, 1j * Gq]]); w = math.sqrt(m * m + q @ q)
    z0 = amp[0] - 1j * amp[1]
    return (math.cos(w * t) * np.eye(2 * d) + math.sin(w * t) / w * A) @ z0, A, Gq, w
def slow_parts(z, d, m, t):           # divide out the rest loop
    c, s = math.cos(m * t), math.sin(m * t); psi, chi = z[:d], z[d:]
    return c * psi - s * chi, s * psi + c * chi
for k in (1, 2, 4, 8):
    nm = NAME[k]; m = 5.0; kmax = 0.4; T = 37.0
    d, qs, amp, Gs = setup(k, m, kmax)
    r = dict(sq=True, exact=True, smooth=True, dens=True); num = den = num2 = den2 = rip = 0.0; tot0 = tot = 0.0
    for q, am in zip(qs, amp):
        z, A, Gq, w = wave_state(d, q, am, Gs, m, T)
        r['sq'] &= np.allclose(A @ A, -(m * m + q @ q) * np.eye(2 * d))
        a, b = slow_parts(z, d, m, T)
        h = 1e-5
        a2, b2 = slow_parts(wave_state(d, q, am, Gs, m, T + h)[0], d, m, T + h)
        a1, b1 = slow_parts(wave_state(d, q, am, Gs, m, T - h)[0], d, m, T - h)
        da, db = (a2 - a1) / (2 * h), (b2 - b1) / (2 * h)
        C, S = math.cos(2 * m * T), math.sin(2 * m * T); Da, Db_ = 1j * Gq @ a, 1j * Gq @ b      # D_s on exp(i q.x)
        r['exact'] &= np.allclose(da, -(C * Da + S * Db_), atol=1e-6) and np.allclose(db, -S * Da + C * Db_, atol=1e-6)
        # the smoothed roots  u + (1/2m) N D_s u,  N = [[S, -C], [-C, -S]]:  their rate is (1/2m) J Laplacian u, exactly
        def smooth(a_, b_, t_):
            C_, S_ = math.cos(2 * m * t_), math.sin(2 * m * t_); Da_, Db2 = 1j * Gq @ a_, 1j * Gq @ b_
            return a_ + (S_ * Da_ - C_ * Db2) / (2 * m), b_ + (-C_ * Da_ - S_ * Db2) / (2 * m)
        A2, B2 = smooth(a2, b2, T + h); A1, B1 = smooth(a1, b1, T - h); lap = -(q @ q)
        r['smooth'] &= np.allclose((A2 - A1) / (2 * h), -lap * b / (2 * m), atol=1e-6) and np.allclose((B2 - B1) / (2 * h), lap * a / (2 * m), atol=1e-6)
        # the slow law for phi = a + i b:  i d_t phi = -(1/2m) Laplacian phi, started from the same roots
        a0, b0 = slow_parts(wave_state(d, q, am, Gs, m, 0.0)[0], d, m, 0.0)
        ph = np.exp(-1j * (q @ q) * T / (2 * m))
        # here two different i's are in play (the wave's and the rest loop's); keep them apart: rotate (a0,b0) by the angle
        th = (q @ q) * T / (2 * m); pa, pb = math.cos(th) * a0 + math.sin(th) * b0, -math.sin(th) * a0 + math.cos(th) * b0
        num += np.linalg.norm(a - pa) ** 2 + np.linalg.norm(b - pb) ** 2; den += np.linalg.norm(a0) ** 2 + np.linalg.norm(b0) ** 2
        As, Bs = smooth(a, b, T); A0, B0 = smooth(a0, b0, 0.0)
        qa, qb = math.cos(th) * A0 + math.sin(th) * B0, -math.sin(th) * A0 + math.cos(th) * B0
        num2 += np.linalg.norm(As - qa) ** 2 + np.linalg.norm(Bs - qb) ** 2
        tot0 += np.linalg.norm(a0) ** 2 + np.linalg.norm(b0) ** 2; tot += np.linalg.norm(z) ** 2
        r['dens'] &= np.isclose(np.linalg.norm(a) ** 2 + np.linalg.norm(b) ** 2, np.linalg.norm(z) ** 2)
    err, err2 = math.sqrt(num / den), math.sqrt(num2 / den)
    check('%s  Lemma 3.2: wave by wave the generator of a pair squares to -(m^2 + |q|^2)' % nm, r['sq'])
    check('%s  Theorem 3.3: the exact law of the slow roots: d_t a = -(C D a + S D b), d_t b = -S D a + C D b' % nm, r['exact'])
    check('%s  Theorem 3.4: the size of the slow roots is the density of the pair, kept exactly' % nm, r['dens'] and np.isclose(tot, tot0))
    check('%s  Theorem 4.2: the rate of the smoothed roots is (1/2m) J Laplacian u, exactly' % nm, r['smooth'])
    bound = kmax / m + T * kmax ** 3 / (4 * m * m)
    check('%s  Theorem 4.3: the slow law holds within k/m + t k^3/4m^2' % nm, err <= bound, 'error %.4f, bound %.4f' % (err, bound))
    bound2 = T * kmax ** 3 / (4 * m * m)
    check('%s  Theorem 4.3: for the smoothed roots within t k^3/4m^2' % nm, err2 <= bound2, 'error %.5f, bound %.5f' % (err2, bound2))

# the turn of the slow law is the rest loop and not its opposite
k = 2; m = 5.0; T = 37.0; d, qs, amp, Gs = setup(k, m, 0.4); num = num_o = den = 0.0
for q, am in zip(qs, amp):
    a, b = slow_parts(wave_state(d, q, am, Gs, m, T)[0], d, m, T); a0, b0 = am[0][:d] - 1j * am[1][:d], am[0][d:] - 1j * am[1][d:]
    th = (q @ q) * T / (2 * m)
    for sgn in (1, -1):
        pa, pb = math.cos(th) * a0 + sgn * math.sin(th) * b0, -sgn * math.sin(th) * a0 + math.cos(th) * b0
        e = np.linalg.norm(a - pa) ** 2 + np.linalg.norm(b - pb) ** 2
        if sgn == 1: num += e
        else: num_o += e
    den += np.linalg.norm(a0) ** 2 + np.linalg.norm(b0) ** 2
check('Theorem 4.3: with the opposite turn the slow law fails', math.sqrt(num_o / den) > 10 * math.sqrt(num / den),
      'errors %.3f and %.3f' % (math.sqrt(num / den), math.sqrt(num_o / den)))

# ---------------------------------------------------------------- Section 5: the unseen turn and its field
for k in (1, 2, 4, 8):
    nm = NAME[k]; ok = True; comm = True
    for _ in range(20):
        psi = rng.normal(size=2 * k); q = rng.normal(size=k); q /= np.linalg.norm(q)
        pq = np.concatenate([mul(psi[:k], q), mul(psi[k:], q)])
        cut = lambda p: np.concatenate([[p[:k] @ p[:k] + p[k:] @ p[k:], p[:k] @ p[:k] - p[k:] @ p[k:]], 2 * mul(p[:k], conj(p[k:]))])
        ok &= np.allclose(cut(pq), cut(psi))
        X = rng.normal(size=k + 2); comm &= np.allclose(Gam(X, k) @ pq, np.concatenate([mul((Gam(X, k) @ psi)[:k], q), mul((Gam(X, k) @ psi)[k:], q)]))
    if k < 8:
        check('%s  Lemma 5.1: the cut does not see a number of size one on the right of the root, and the action passes through it' % nm, ok and comm)
    else:
        check('O  Lemma 5.1 fails: for the octonions the number on the right is seen, and the action does not pass through it', (not ok) and (not comm))
    # numbers without real part: 0, 1, 3 directions; right multiplication by one is skew, so the flow is kept
    if k in (2, 4):
        sk = all(np.allclose(rmul(np.eye(k)[j], k), -rmul(np.eye(k)[j], k).T) for j in range(1, k))
        real = True
        for _ in range(20):
            psi = rng.normal(size=2 * k); X = rng.normal(size=k + 2); u = np.concatenate([[0.0], rng.normal(size=k - 1)])
            real &= abs(psi @ (Gam(X, k) @ rmul(u, k) @ psi)) < 1e-10
        check('%s  Theorem 5.3(b): <psi, G(X)(psi u)> = 0 for u without real part: the field does not change the flow' % nm, sk and real)

# Theorem 5.3(c): Db_a D_a psi = -Box_a psi + 2 sum_{mu<nu} S(E_mu,E_nu) psi f_{mu nu}, for C and H.
# Fields are polynomials with whole coefficients, differentiated in symbols; each identity is then
# evaluated at three random points.
t_, x1, x2 = sp.symbols('t x1 x2'); VARS = [t_, x1, x2]
def smul(x, y):                       # the doubling product on sympy entries
    n = len(x)
    if n == 1: return [x[0] * y[0]]
    h = n // 2; a, b, c, d = x[:h], x[h:], y[:h], y[h:]; cj = lambda v: [v[0]] + [-e for e in v[1:]]
    return [u - v for u, v in zip(smul(a, c), smul(cj(d), b))] + [u + v for u, v in zip(smul(d, a), smul(b, cj(c)))]
def rpoly(deg=2):
    return sum(sp.Integer(int(rng.integers(-3, 4))) * t_ ** i * x1 ** j * x2 ** l for i in range(deg + 1) for j in range(deg + 1 - i) for l in range(deg + 1 - i - j))
def iszero(exprs):
    f = sp.lambdify(VARS, list(exprs), 'numpy'); worst = 0.0
    for _ in range(3):
        v = np.array(f(*rng.uniform(-1, 1, size=3)), dtype=float); worst = max(worst, np.abs(v).max())
    return worst < 1e-7
def dfs(p, mu): return [sp.diff(e, VARS[mu]) for e in p]
eta3 = [1, -1, -1]
for k in (2, 4):
    nm = NAME[k]; d = 2 * k
    Gm = [sp.Matrix(Gam(e, k).astype(int)) for e in units(k)[:3]]; Gbm = [Gm[0] - 2 * sp.eye(d)] + Gm[1:]   # Gb(E_0) = -1, Gb(E_j) = G(E_j)
    psi = [rpoly(2) for _ in range(d)]
    a = [[sp.Integer(0)] + [rpoly(1) for _ in range(k - 1)] for _ in range(3)]              # a_mu, without real part
    rm = lambda p, q: smul(p[:k], q) + smul(p[k:], q)
    nab = lambda mu, p, aa=a: [u + v for u, v in zip(dfs(p, mu), rm(p, aa[mu]))]
    app = lambda Ms, p, aa=a: [sum((Ms[mu] * sp.Matrix(nab(mu, p, aa)))[i] for mu in range(3)) for i in range(d)]
    Da = lambda p: app(Gm, p); Dba = lambda p: app(Gbm, p)
    lhs = Dba(Da(psi))
    box = [nab(0, nab(0, psi))[i] - nab(1, nab(1, psi))[i] - nab(2, nab(2, psi))[i] for i in range(d)]
    f = lambda mu, nu: [dfs(a[nu], mu)[i] - dfs(a[mu], nu)[i] + smul(a[nu], a[mu])[i] - smul(a[mu], a[nu])[i] for i in range(k)]
    S = lambda mu, nu: (Gbm[mu] * Gm[nu] + (eta3[mu] if mu == nu else 0) * sp.eye(d)) / 2          # Gb(X) G(Y) = -eta(X,Y) + 2 S(X,Y)
    rhs = [-box[i] for i in range(d)]
    for mu in range(3):
        for nu in range(mu + 1, 3):
            term = 2 * S(mu, nu) * sp.Matrix(rm(psi, f(mu, nu))); rhs = [rhs[i] + term[i] for i in range(d)]
    check('%s  Theorem 5.3(c): the two steps do not commute by the curl: [nabla_mu, nabla_nu] psi = psi f_{mu nu}' % nm,
          iszero([nab(0, nab(1, psi))[i] - nab(1, nab(0, psi))[i] - rm(psi, f(0, 1))[i] for i in range(d)]) and
          iszero([nab(1, nab(2, psi))[i] - nab(2, nab(1, psi))[i] - rm(psi, f(1, 2))[i] for i in range(d)]))
    check('%s  Theorem 5.3(c): Db_a D_a psi = -Box_a psi + 2 sum S(E_mu,E_nu) psi f_{mu nu}: the field acts through its curl, as a change of view' % nm,
          iszero([lhs[i] - rhs[i] for i in range(d)]))
    # Theorem 5.3(a): the law keeps its form when the unseen number turns from place to place
    th = rpoly(2)
    q = [sp.cos(th), sp.sin(th)] if k == 2 else [sp.cos(th), sp.Integer(0), sp.sin(th) * sp.Rational(3, 5), sp.sin(th) * sp.Rational(4, 5)]   # size one
    qc = [q[0]] + [-e for e in q[1:]]
    psi2 = rm(psi, q)
    a2 = [[u - v for u, v in zip(smul(qc, smul(a[mu], q)), smul(qc, dfs(q, mu)))] for mu in range(3)]
    lhs2 = app(Gm, psi2, a2); want = rm(Da(psi), q)
    check('%s  Theorem 5.3(a): psi -> psi q, a -> conj(q) a q - conj(q) dq carries D_a psi to (D_a psi) q' % nm,
          iszero([lhs2[i] - want[i] for i in range(d)]) and iszero([sum(e * e for e in q) - 1]))

# ---------------------------------------------------------------- Section 6: the slow pair in a field
# Theorem 6.1, for C and H:  nabla_0 (u + N D_s u / 2m) = (1/2m) J D_s^2 u + (1/2m) N [nabla_0, D_s] u  on a pair.
# For any a, b put  Ra = nabla_0 a + C D a + S D b,  Rb = nabla_0 b + S D a - C D b  (zero on a pair); the identity
# with Ra, Rb kept is tested, and it reduces to the theorem when they are zero.
for k in (2, 4):
    nm = NAME[k]; d = 2 * k; msym = sp.Rational(7, 2)
    Gm = [sp.Matrix(Gam(e, k).astype(int)) for e in units(k)[:3]]
    a = [[sp.Integer(0)] + [rpoly(1) for _ in range(k - 1)] for _ in range(3)]
    rm = lambda p, q: smul(p[:k], q) + smul(p[k:], q)
    nab = lambda mu, p: [u + v for u, v in zip(dfs(p, mu), rm(p, a[mu]))]
    Ds = lambda p: [sum((Gm[j] * sp.Matrix(nab(j, p)))[i] for j in (1, 2)) for i in range(d)]
    C_, S_ = sp.cos(2 * msym * t_), sp.sin(2 * msym * t_)
    av, bv = [rpoly(2) for _ in range(d)], [rpoly(2) for _ in range(d)]
    Da_, Db_ = Ds(av), Ds(bv)
    Ra = [nab(0, av)[i] + C_ * Da_[i] + S_ * Db_[i] for i in range(d)]
    Rb = [nab(0, bv)[i] + S_ * Da_[i] - C_ * Db_[i] for i in range(d)]
    As = [av[i] + (S_ * Da_[i] - C_ * Db_[i]) / (2 * msym) for i in range(d)]
    Bs = [bv[i] + (-C_ * Da_[i] - S_ * Db_[i]) / (2 * msym) for i in range(d)]
    D2a, D2b = Ds(Da_), Ds(Db_)
    comm = lambda p: [nab(0, Ds(p))[i] - Ds(nab(0, p))[i] for i in range(d)]
    Ea, Eb = comm(av), comm(bv); DRa, DRb = Ds(Ra), Ds(Rb); lhsA, lhsB = nab(0, As), nab(0, Bs)
    okA = iszero([lhsA[i] - (-D2b[i] / (2 * msym) + (S_ * Ea[i] - C_ * Eb[i]) / (2 * msym) + Ra[i] + (S_ * DRa[i] - C_ * DRb[i]) / (2 * msym)) for i in range(d)])
    okB = iszero([lhsB[i] - (D2a[i] / (2 * msym) + (-C_ * Ea[i] - S_ * Eb[i]) / (2 * msym) + Rb[i] + (-C_ * DRa[i] - S_ * DRb[i]) / (2 * msym)) for i in range(d)])
    check('%s  Theorem 6.1: nabla_0(u + N D_s u/2m) = (1/2m) J D_s^2 u + (1/2m) N [nabla_0, D_s] u on a pair' % nm, okA and okB)
    # [nabla_0, D_s] p = sum_j G(E_j) p f_{0j}
    fj = lambda j: [dfs(a[j], 0)[i] - dfs(a[0], j)[i] + smul(a[j], a[0])[i] - smul(a[0], a[j])[i] for i in range(k)]
    want = [sum((Gm[j] * sp.Matrix(rm(av, fj(j))))[i] for j in (1, 2)) for i in range(d)]
    check('%s  Theorem 6.1: [nabla_0, D_s] u = sum_j G(E_j) u f_{0j}, the part of the curl between time and space' % nm, iszero([Ea[i] - want[i] for i in range(d)]))

# Proposition 6.3: levels in a well, C rung.  V(x) = -V0 / cosh(x/w)^2, the field a_0 = i V along one direction of space
m = 20.0; w_ = 3.0; s_lev = 2; V0 = s_lev * (s_lev + 1) / (2 * m * w_ ** 2)
Lbox, N = 160.0, 512; x = (np.arange(N) - N // 2) * (Lbox / N); qk = 2 * np.pi * np.fft.fftfreq(N, d=Lbox / N)
Dx = np.real_if_close(np.fft.ifft(1j * qk[:, None] * np.fft.fft(np.eye(N), axis=0), axis=0)); Dx = np.real(Dx)
V = -V0 / np.cosh(x / w_) ** 2
# one half of the pair along E_1 (the other half is its mirror image):  d_t psi = -iV psi - psi' + m chi,  d_t chi = -iV chi + chi' - m psi
Mgen = np.block([[-1j * np.diag(V) - Dx, m * np.eye(N)], [-m * np.eye(N), -1j * np.diag(V) + Dx]])
lam = 1j * np.linalg.eigvals(Mgen)                               # rates: solutions go as exp(-i lam t)
lam = np.sort(lam.real[np.abs(lam.imag) < 1e-8])
gap = 0.5 / (2 * m * w_ ** 2)                                   # half the size of the shallowest level
below = lam[(lam > m - V0) & (lam < m - gap)]
Hs = -(Dx @ Dx) / (2 * m) + np.diag(V); Hs = (Hs + Hs.T) / 2                    # the slow law in the well: J d_t = -(1/2m) d_x^2 + V
Es = np.sort(np.linalg.eigvalsh(Hs))
E_slow = [e for e in Es if e < -0.5 / (2 * m * w_ ** 2)]                        # its levels, computed here
got = sorted(below - m)
print('      levels of the slow law: %s' % ', '.join('%.6f' % e for e in E_slow))
print('      rates of the pair less m: %s' % ', '.join('%.6f' % e for e in got))
okL = len(got) == len(E_slow) == s_lev and all(abs(g - e) < 5 * e * e / (2 * m) + 1e-6 for g, e in zip(got, E_slow))
check('C  Proposition 6.3: in the well the pair has exactly %d rates below m by more than half the shallowest level, and they are m + E_n of the slow law to within 5 E^2/2m' % s_lev, okL,
      'differences %s' % ', '.join('%.1e' % abs(g - e) for g, e in zip(got, E_slow)))
# the opposite sector sees the opposite sign of the field: no rate just above -m for a well, and two for a hill
above = lam[(lam < -m + V0) & (lam > -m + gap)]
Vh = -V; Mh = np.block([[-1j * np.diag(Vh) - Dx, m * np.eye(N)], [-m * np.eye(N), -1j * np.diag(Vh) + Dx]])
lh = 1j * np.linalg.eigvals(Mh); lh = np.sort(lh.real[np.abs(lh.imag) < 1e-8])
hill_neg = lh[(lh > -m + gap) & (lh < -m + V0)]; hill_pos = lh[(lh > m - V0) & (lh < m - gap)]
check('C  Theorem 6.2(b): the two sectors feel opposite signs of the field: a well binds the sector where the turns agree, a hill the other',
      len(above) == 0 and len(hill_neg) == s_lev and len(hill_pos) == 0 and np.allclose(sorted(-hill_neg - m), got, atol=1e-8))

print('\n%d checks, %d passed' % (len(results), sum(results)))
sys.exit(0 if all(results) else 1)
