"""Guideng Math Paper 21.  Two Roots Make a Move.
Checks every numbered statement.  Run:  python3 verify_two_roots_make_a_move.py
Roots, cuts and the action G(X) are those of Papers 4 and 5; placed roots and the moves of the
space are those of Paper 18.  Everything is real linear algebra on the coordinates."""
import numpy as np, itertools
rng = np.random.default_rng(21)
ok = lambda a, b, t=1e-8: np.allclose(a, b, rtol=0, atol=t)
RES = []
def check(name, cond, extra=''):
    RES.append(bool(cond)); print(('PASS  ' if cond else 'FAIL  ') + name + ('   [' + extra + ']' if extra else ''))
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))])
NAME = {1: 'R', 2: 'C', 4: 'H', 8: 'O'}
def span_add(basis, M):
    v = M.ravel().astype(float).copy()
    for b in basis: v = v - (v @ b) * b
    nv = np.linalg.norm(v)
    if nv > 1e-7 * max(1, np.linalg.norm(M)): basis.append(v / nv); return True
    return False
def inspan(basis, M):
    v = M.ravel().astype(float).copy()
    for b in basis: v = v - (v @ b) * b
    return np.linalg.norm(v) < 1e-6 * max(1, np.linalg.norm(M))

class Sys:
    def __init__(s, k):
        s.k, s.n, s.N = k, k + 2, 5 * k; E2 = np.eye(2 * k)
        def act(X, 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])
        s.G = lambda X: np.column_stack([act(X, b) for b in E2])
        s.flat = lambda X: np.concatenate([[-X[0]], X[1:]]); s.sig = lambda X: np.concatenate([[X[0]], -X[1:]])
        s.Gb = lambda X: s.G(s.flat(X))
        s.eta = lambda X, Y: X[0] * Y[0] - X[1:] @ Y[1:]
        s.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:]))])
        s.beta = lambda p, q: (s.cut(p + q) - s.cut(p) - s.cut(q)) / 2
        s.S = lambda X, Y: 0.25 * (s.Gb(X) @ s.G(Y) - s.Gb(Y) @ s.G(X)); s.Sp = lambda X, Y: 0.25 * (s.G(X) @ s.Gb(Y) - s.G(Y) @ s.Gb(X))
    # a root times a number, on the right;  the row of a root:  e^dagger p = conj(x_e) x_p + conj(y_e) y_p
    def rt(s, e, th): k = s.k; return np.concatenate([mul(e[:k], th), mul(e[k:], th)])
    def row(s, e, p): k = s.k; return mul(conj(e[:k]), p[:k]) + mul(conj(e[k:]), p[k:])
    def omK(s, W, Z): k = s.k; return s.row(W[:2 * k], Z[2 * k:]) - s.row(W[2 * k:], Z[:2 * k])     # the form with values in K
    def om(s, W, Z): k = s.k; return W[:2 * k] @ Z[2 * k:] - W[2 * k:] @ Z[:2 * k]                  # the form of Paper 18
    def A(s, W):                                                                                    # the action of a placed root
        k, N = s.k, s.N; M = np.zeros((N, N))
        for j, th in enumerate(np.eye(k)): M[:4 * k, 4 * k + j] = np.concatenate([s.rt(W[:2 * k], th), s.rt(W[2 * k:], th)])
        for j, Z in enumerate(np.eye(4 * k)): M[4 * k:, j] = -s.omK(W, Z)
        return M
    def emb(s, M4): M = np.zeros((s.N, s.N)); M[:4 * s.k, :4 * s.k] = M4; return M
    def T(s, a): k = s.k; Z0 = np.zeros((2 * k, 2 * k)); return s.emb(np.block([[Z0, Z0], [s.G(s.sig(a)), Z0]]))
    def M(s, b): k = s.k; Z0 = np.zeros((2 * k, 2 * k)); return s.emb(np.block([[Z0, s.G(b)], [Z0, Z0]]))
    def moves(s):
        basis, ms = [], []
        for e in np.eye(s.n):
            for X in (s.T(e), s.M(e)):
                if span_add(basis, X): ms.append(X)
        i = 0
        while i < len(ms):
            for j in range(i):
                C = ms[i] @ ms[j] - ms[j] @ ms[i]
                if span_add(basis, C): ms.append(C / max(1, np.linalg.norm(C)))
            i += 1
        return basis, ms

for k in (1, 2, 4, 8):
    s = Sys(k); nm = NAME[k]; n, N = s.n, s.N; assoc = k < 8
    rv = lambda m: rng.normal(size=m)
    e, e2, ch, ch2, p = rv(2 * k), rv(2 * k), rv(2 * k), rv(2 * k), rv(2 * k)
    W, W2, Z = rv(4 * k), rv(4 * k), rv(4 * k); th = rv(k)
    z2 = np.zeros(2 * k); Q = lambda x: s.A(np.concatenate([z2, x])); Sm = lambda x: s.A(np.concatenate([x, z2]))
    # Lemma 2.1
    lhs = s.rt(e, s.row(e, p)); rhs = 0.5 * s.G(s.cut(e)) @ p
    if assoc:
        check('Lemma 2.1 (%s): a root times its own row is half its cut acting, e(e^dagger p) = (1/2) G(c(e)) p; Re of the K-form is the form of Paper 18' % nm,
              ok(lhs, rhs) and ok(s.omK(W, Z)[0], s.om(W, Z)) and ok(s.omK(W, Z), -conj(s.omK(Z, W))))
    else:
        x, y, pp, qq = e[:k], e[k:], p[:k], p[k:]; asc = lambda a, b, c: mul(mul(a, b), c) - mul(a, mul(b, c))
        check('Theorem 5.1 (O): e(e^dagger p) - (1/2) G(c(e)) p = -([x, conj y, q], [y, conj x, p]), two associators, and it is not zero',
              ok(lhs - rhs, -np.concatenate([asc(x, conj(y), qq), asc(y, conj(x), pp)])) and not ok(lhs, rhs))
    # Definition 3.1 and Theorem 3.2
    AW, AW2 = s.A(W), s.A(W2); AC = AW @ AW2 + AW2 @ AW; v = np.concatenate([Z, th]); out = AC @ v
    zpart = -(np.concatenate([s.rt(W[:2 * k], s.omK(W2, Z)), s.rt(W[2 * k:], s.omK(W2, Z))]) + np.concatenate([s.rt(W2[:2 * k], s.omK(W, Z)), s.rt(W2[2 * k:], s.omK(W, Z))]))
    im = s.omK(W, W2).copy(); im[0] = 0; tpart = -2 * mul(im, th)
    okA = ok((s.A(W) @ v)[:4 * k], np.concatenate([s.rt(W[:2 * k], th), s.rt(W[2 * k:], th)])) and ok((s.A(W) @ v)[4 * k:], -s.omK(W, Z))
    if assoc:
        check('Theorem 3.2 (%s): two placed roots: {A_W, A_W\'}(Z, th) = (-W om(W\',Z) - W\' om(W,Z), -2 Im om(W,W\') th)' % nm, okA and ok(out[:4 * k], zpart) and ok(out[4 * k:], tpart))
        check('Theorem 3.3(a) (%s): two roots make a translation, {Q_e, Q_e\'} = T_a with a = sigma beta(e,e\'); Q_e^2 = (1/2) T with a = sigma c(e)' % nm,
              ok(Q(e) @ Q(e2) + Q(e2) @ Q(e), s.T(s.sig(s.beta(e, e2)))) and ok(Q(e) @ Q(e), 0.5 * s.T(s.sig(s.cut(e)))))
        check('Theorem 3.3(b) (%s): two mirror roots make minus the mirror of a translation, {S_c, S_c\'} = -M_b with b = beta(c,c\')' % nm,
              ok(Sm(ch) @ Sm(ch2) + Sm(ch2) @ Sm(ch), -s.M(s.beta(ch, ch2))) and ok(Sm(ch) @ Sm(ch), -0.5 * s.M(s.cut(ch))))
        C = Q(e) @ Sm(ch) + Sm(ch) @ Q(e)
        blk = lambda a, b: np.column_stack([s.rt(a, s.row(b, x)) for x in np.eye(2 * k)])          # x -> a (b^dagger x)
        d = s.row(e, ch) - s.row(ch, e); Lth = np.column_stack([mul(d, t) for t in np.eye(k)])
        okC = ok(C[:2 * k, :2 * k], blk(ch, e)) and ok(C[2 * k:4 * k, 2 * k:4 * k], -blk(e, ch)) and ok(C[4 * k:, 4 * k:], Lth) \
            and ok(C[:2 * k, 2 * k:4 * k], 0) and ok(C[2 * k:4 * k, :2 * k], 0) and ok(C[:4 * k, 4 * k:], 0) and ok(C[4 * k:, :4 * k], 0)
        check('Theorem 3.3(c) (%s): a root and a mirror root: {Q_e, S_c} = (c e^dagger on roots, -e c^dagger on mirror roots, e^dagger c - c^dagger e on the odd number)' % nm, okC)
    # Theorem 4.1: carried by the moves
    basis, ms = s.moves()
    Dm = s.T(np.eye(n)[0]) @ s.M(np.eye(n)[0]) - s.M(np.eye(n)[0]) @ s.T(np.eye(n)[0])
    a_, b_ = rv(n), rv(n)
    car = lambda g: ok(g @ AW - AW @ g, s.A((g @ np.concatenate([W, np.zeros(k)]))[:4 * k]))
    c41 = car(s.T(a_)) and car(s.M(b_)) and all(car(g) for g in ms[:12])
    wts = ok(Dm @ Q(e) - Q(e) @ Dm, Q(e)) and ok(Dm @ Sm(ch) - Sm(ch) @ Dm, -Sm(ch)) and ok(Dm @ s.T(a_) - s.T(a_) @ Dm, 2 * s.T(a_)) and ok(Dm @ s.M(b_) - s.M(b_) @ Dm, -2 * s.M(b_))
    spec = ok(s.T(a_) @ Sm(ch) - Sm(ch) @ s.T(a_), Q(s.G(s.sig(a_)) @ ch)) and ok(s.M(b_) @ Q(e) - Q(e) @ s.M(b_), Sm(s.G(b_) @ e)) \
        and ok(s.T(a_) @ Q(e), Q(e) @ s.T(a_)) and ok(s.M(b_) @ Sm(ch), Sm(ch) @ s.M(b_))
    if assoc:
        check('Theorem 4.1 (%s): [g, A_W] = A_(gW) for every move g of the space; [T_a, S_c] = Q with root G(sigma a) c; [M_b, Q_e] = S with mirror root G(b) e; weights 1, -1, 2, -2 under the scale'
              % nm, c41 and wts and spec and len(ms) == (n + 1) * (n + 2) // 2, 'moves of the space: %d' % len(ms))
    # Theorem 4.2: closure
    odd, oddm = [], []
    for x in np.eye(4 * k):
        if span_add(odd, s.A(x)): oddm.append(s.A(x))
    ev = list(basis); evm = list(ms); extra = []
    for i in range(len(oddm)):
        for j in range(i + 1):
            C = oddm[i] @ oddm[j] + oddm[j] @ oddm[i]
            if span_add(ev, C): evm.append(C); extra.append(C)
    allin = all(inspan(ev, C) for C in [oddm[i] @ oddm[j] + oddm[j] @ oddm[i] for i in range(len(oddm)) for j in range(i + 1)])
    closed_odd = all(inspan(odd, g @ o - o @ g) for g in evm for o in (oddm if assoc else oddm[:6] + oddm[-6:]))
    closed_ev = all(inspan(ev, evm[i] @ evm[j] - evm[j] @ evm[i]) for i in range(len(evm)) for j in range(i)) if len(evm) < 60 else None
    if assoc:
        want = {1: (10, 0), 2: (15, 1), 4: (28, 3)}[k]
        check('Theorem 4.2 (%s): the actions and the moves close: odd part %d, even part %d + %d' % (nm, len(oddm), len(ms), len(extra)),
              len(oddm) == 4 * k and (len(ms), len(extra)) == want and closed_odd and closed_ev and allin)
        if k == 2:
            i_ = np.array([0.0, 1.0]); Ri = np.zeros((N, N))
            for j, x in enumerate(np.eye(2 * k)): Ri[:2 * k, j] = s.rt(x, i_); Ri[2 * k:4 * k, 2 * k + j] = s.rt(x, i_)
            for j, t in enumerate(np.eye(k)): Ri[4 * k:, 4 * k + j] = 4 * mul(i_, t)
            check('Theorem 4.2 (C): the one more even move is i on every root and mirror root and 4i on the odd number', inspan(ev, Ri) and not inspan(basis, Ri))
        if k == 4:
            okq = True
            for u in (1, 2, 3):
                q = np.zeros(4); q[u] = 1; Lq = np.zeros((N, N))
                for j, t in enumerate(np.eye(k)): Lq[4 * k:, 4 * k + j] = mul(q, t)
                Wq = np.concatenate([s.rt(W[:2 * k], q), s.rt(W[2 * k:], q)])
                okq &= inspan(ev, Lq) and not inspan(basis, Lq) and ok(Lq @ AW - AW @ Lq, -s.A(Wq))
            check('Theorem 4.2 (H): the three more even moves turn the odd number, th -> q th, do not move placed roots, and [L_q, A_W] = -A_(Wq)', okq)
    else:
        notT = not inspan(basis, Q(e) @ Q(e2) + Q(e2) @ Q(e))
        check('Theorem 5.1 (O): two roots do not make a translation or any move of the space, and a bracket of an even part with an action is not an action',
              notT and not closed_odd, 'even brackets found: %d beyond the 66 moves' % len(extra))
print('\n%d checks; %s' % (len(RES), 'all pass' if all(RES) else 'FAILURES: %d' % (len(RES) - sum(RES))))
