"""2kwas: independent check of iis:2611.00267 (eight-cube spectrum) and iis:2611.00275 (dimensions 2..7).

Kernel: points x^s = r s, s in {-1,1}^n; entry 1 / e2(1 - x^s_i x^t_i, i = 1..n).  u = r^2.
Our own exact integer-polynomial code (no CAS, no authors' code), plus a floating-point check of the full matrices.

usage: python3 -I cube_check.py > cube_check.out
"""
from fractions import Fraction as Fr
from math import comb
import itertools
import numpy as np


# ----------------------------------------------------------------- integer polynomials in one variable (low -> high)
def trim(p):
    p = list(p)
    while len(p) > 1 and p[-1] == 0: p.pop()
    return p
def add(p, q):
    n = max(len(p), len(q)); return trim([(p[i] if i < len(p) else 0) + (q[i] if i < len(q) else 0) for i in range(n)])
def mul(p, q):
    r = [0] * (len(p) + len(q) - 1)
    for i, a in enumerate(p):
        if a:
            for j, b in enumerate(q): r[i + j] += a * b
    return trim(r)
def scal(c, p): return trim([c * a for a in p])
def ev(p, x): return sum(Fr(a) * Fr(x) ** i for i, a in enumerate(p))
def div_exact(p, q):
    """exact division of integer polynomials (q monic up to sign or leading coefficient dividing); asserts remainder 0"""
    p = [Fr(a) for a in p]; out = [Fr(0)] * (len(p) - len(q) + 1)
    for i in range(len(out) - 1, -1, -1):
        c = p[i + len(q) - 1] / q[-1]; out[i] = c
        for j, b in enumerate(q): p[i + j] -= c * b
    assert all(a == 0 for a in p), "not divisible"
    assert all(c.denominator == 1 for c in out)
    return trim([int(c) for c in out])
ONE_MINUS_U = [1, -1]; ONE_PLUS_U = [1, 1]
def pw(p, e):
    r = [1]
    for _ in range(e): r = mul(r, p)
    return r


def D(n, j):
    """e2 of the n numbers 1-u (n-j agreeing coordinates) and 1+u (j differing coordinates)"""
    return add(add(scal(comb(n - j, 2), pw(ONE_MINUS_U, 2)), scal(j * (n - j), mul(ONE_MINUS_U, ONE_PLUS_U))),
               scal(comb(j, 2), pw(ONE_PLUS_U, 2)))


def kraw(n, k, j):
    """[X^j] (1-X)^k (1+X)^(n-k)"""
    return sum((-1) ** i * comb(k, i) * comb(n - k, j - i) for i in range(0, j + 1) if i <= k and j - i <= n - k)


def P_lambda(n, k):
    Ds = [D(n, j) for j in range(n + 1)]
    tot = [0]
    for j in range(n + 1):
        c = kraw(n, k, j)
        if c == 0: continue
        prod = [1]
        for i in range(n + 1):
            if i != j: prod = mul(prod, Ds[i])
        tot = add(tot, scal(c, prod))
    return tot, Ds


def strip(p):
    """p = u^a (1-u)^b q with q(0) != 0 != q(1); returns a, b, q"""
    a = 0
    while p[0] == 0: p = p[1:]; a += 1
    b = 0
    while ev(p, 1) == 0: p = div_exact(p, ONE_MINUS_U); b += 1
    return a, b, p


def bernstein(q):
    """c_i with q(v) = sum c_i v^i (1-v)^(d-i): coefficients of (1+t)^d q(t/(1+t))"""
    d = len(q) - 1
    tot = [0]
    for i, a in enumerate(q):
        tot = add(tot, scal(a, mul([0] * i + [1], pw(ONE_PLUS_U, d - i))))
    return d, tot + [0] * (d + 1 - len(tot))


# ----------------------------------------------------------------- floating-point check of the full matrix
def matrix(n, r):
    S = np.array(list(itertools.product([-1, 1], repeat=n)), dtype=float)
    X = r * S
    N = len(S); M = np.empty((N, N))
    for a in range(N):
        prod = 1 - X[a] * X                         # (N, n): the numbers 1 - x^s_i x^t_i
        s1 = prod.sum(1); s2 = (prod ** 2).sum(1)
        M[a] = 2.0 / (s1 ** 2 - s2)                 # e2 = (s1^2 - s2)/2
    return M, S


def lam_float(n, k, r):
    u = r * r
    return sum(kraw(n, k, j) / float(ev(D(n, j), Fr(u))) for j in range(n + 1))


print("=== iis:2611.00267: n = 8")
n = 8
g = [-245, 791, -190, 4]
for m in range(n + 1):
    pl, Ds = P_lambda(n, m)
    a, b, q = strip(pl)
    if m < 8:
        # the paper's form: P lambda_m = u^m (1 - u^2) Q_m(u^2)
        assert all(cc == 0 for cc in pl[:m]), "P*lambda_m not divisible by u^m"
        rest = div_exact(pl[m:], mul(ONE_MINUS_U, ONE_PLUS_U))
        even_only = all(c == 0 for c in rest[1::2])
        Qz = rest[0::2]
        d, c = bernstein(Qz)
        print("m=%d  P*lambda = u^%d (1-u)^%d q(u);  = u^m (1-u^2) Q_m(u^2): first %d coeffs zero %s, Q_m even in u %s, "
              "deg Q_m(z) = %d, Bernstein coefficients in z all > 0: %s (min %d)" %
              (m, a, b, m, all(cc == 0 for cc in pl[:m]), even_only, d, all(x > 0 for x in c), min(c)))
        if m == 7:
            target = scal(252887040, mul([7, -1], [147, -35, 8]))
            print("      Q_7(z) == 252887040 (7 - z)(8 z^2 - 35 z + 147):", trim(Qz) == target)
    else:
        rest = div_exact(pl[8:], mul(ONE_MINUS_U, ONE_PLUS_U))
        assert all(cc == 0 for cc in pl[:8])
        print("m=8  P*lambda_8 == 505774080 u^8 (1 - u^2) g(u^2), g = 4z^3 - 190z^2 + 791z - 245:",
              all(c == 0 for c in rest[1::2]) and trim(rest[0::2]) == scal(505774080, g))
print("all D_j(u) > 0 on [0,1): every D_j is a sum of nonnegative terms with a positive one; D_j(0) =",
      [comb(8, 2)] * 1, "(each is C(8,2) = 28 at u = 0)", all(ev(D(8, j), 0) == 28 for j in range(9)))
# g: monotone and one root in (0,1)
gp = [791, -380, 12]
print("g(0) =", ev(g, 0), " g(1) =", ev(g, 1), " g' > 0 on [0,1] (convex parabola, vertex at z = 380/24, g'(1) =",
      ev(gp, 1), "):", ev(gp, 1) > 0)
lo, hi = Fr(0), Fr(1)
for _ in range(120):
    mid = (lo + hi) / 2
    if ev(g, mid) < 0: lo = mid
    else: hi = mid
zs = float(lo); rs = zs ** 0.25
print("z* = %.15f  r* = z*^(1/4) = %.10f  (paper: approximately 0.76179584)" % (zs, rs))
for r in (0.3, 0.5, 0.7, rs - 1e-4, rs + 1e-4, 0.8, 0.95):
    M, S = matrix(8, r)
    ev_m = np.linalg.eigvalsh(M)
    lam = [lam_float(8, m, r) for m in range(9)]
    pred = sorted(x for m in range(9) for x in [lam[m]] * comb(8, m))
    print("r=%.6f  matrix eigenvalues: %d positive, %d negative; smallest %.3e; Walsh-formula eigenvalues agree (max rel. diff %.1e); "
          "parity lambda_8 = %.3e" % (r, int((ev_m > 1e-12).sum()), int((ev_m < -1e-12).sum()), ev_m.min(),
          max(abs(a - b) / max(1e-300, abs(b)) for a, b in zip(sorted(ev_m), pred)), lam[8]))
# nullspace at r*: the parity vector
M, S = matrix(8, rs)
par = S.prod(1)
print("at r*: |M parity| / |parity| = %.2e (relative to the largest eigenvalue %.2e)" %
      (np.linalg.norm(M @ par) / np.linalg.norm(par), np.linalg.eigvalsh(M).max()))

print()
print("=== iis:2611.00275: n = 2..7, all k; and n = 8 at r = 1/2")
pairs = 0; allpos = True
for n in range(2, 8):
    for k in range(n + 1):
        pl, _ = P_lambda(n, k)
        a, b, q = strip(pl)
        d, c = bernstein(q)
        pairs += 1
        ok = all(x > 0 for x in c)
        allpos &= ok
        line = "n=%d k=%d  a=%d b=%d d=%d  all Bernstein coefficients > 0: %s  min %d" % (n, k, a, b, d, ok, min(c))
        if (n, k) == (7, 7): line += "  coefficients " + str(c)
        print(line)
print("pairs:", pairs, " all strictly positive:", allpos)
print("paper's n=7 parity coefficients:", [261273600, 1567641600, 5016453120, 9614868480, 8918138880, 2786918400])
lam8 = sum(Fr(kraw(8, 8, j)) / ev(D(8, j), Fr(1, 4)) for j in range(9))
print("n=8, r=1/2 (u=1/4): parity eigenvalue lambda_8 =", lam8, "=", float(lam8), " negative:", lam8 < 0)
# the same witness without any Walsh theory: the quadratic form of the parity vector, summed over all 65536 entries
# built from the coordinates x^s = s/2, in exact fractions
S8 = list(itertools.product([-1, 1], repeat=8))
rh = Fr(1, 2)
def e2(xs):
    s1 = sum(xs); s2 = sum(x * x for x in xs)
    return (s1 * s1 - s2) / 2
def par(s):
    p = 1
    for v in s: p *= v
    return p
qf = sum(Fr(par(s) * par(t)) / e2([1 - (rh * a) * (rh * b) for a, b in zip(s, t)]) for s in S8 for t in S8)
print("n=8, r=1/2: w^T M w for the parity vector w, summed entry by entry from the coordinates =", qf, "=", float(qf),
      "; equals 256 * lambda_8:", qf == 256 * lam8)
# exact values straight from the sum formula (no polynomial manipulation) at rational radii u = r^2
pts = [Fr(1, 10**4), Fr(1, 100), Fr(1, 4), Fr(1, 2), Fr(9, 10), Fr(99, 100), Fr(9999, 10**4)]
okx = all(sum(Fr(kraw(n, k, j)) / ev(D(n, j), u) for j in range(n + 1)) > 0 for n in range(2, 8) for k in range(n + 1) for u in pts)
print("exact rational check of lambda_{n,k} > 0 for n=2..7, all k, u in", [str(u) for u in pts], ":", okx)
# floating point, full matrices (only where float64 can resolve the smallest eigenvalue, ~u^n times a constant)
for n in range(2, 8):
    for r in (0.3, 0.6, 0.9, 0.99):
        M, S = matrix(n, r)
        e = np.linalg.eigvalsh(M)
        lam = sorted(x for k in range(n + 1) for x in [lam_float(n, k, r)] * comb(n, k))
        assert e.min() > 0 and max(abs(a - b) / b for a, b in zip(sorted(e), lam)) < 1e-6, (n, r)
print("float check: n=2..7, r in {0.3, 0.6, 0.9, 0.99}: all 2^n x 2^n matrices positive definite, eigenvalues = Walsh formula")
