"""2kwas: independent check of iis:2611.00281 (the e_2 Cauchy kernel: sharp exponent, five-dimensional grid).

Kernel K_beta(x, y) = e2(1 - x o y)^(-beta) for points x, y in (-1, 1)^n.
Our own code, written from the paper's definitions (the authors' verify_grid.py and Lean project are not run).

usage: python3 -I grid_check.py > grid_check.out
"""
from fractions import Fraction as Fr
from math import comb
import itertools
import random
import numpy as np

# ------------------------------------------------------------------ 1. the grid, all ordered pairs
DIG = [-3, -1, 1, 3]            # coordinate = digit / 4
WT = {-3: -1, -1: 3, 1: -3, 3: 1}
pts = list(itertools.product(DIG, repeat=5))
w = {p: WT[p[0]] * WT[p[1]] * WT[p[2]] * WT[p[3]] * WT[p[4]] for p in pts}
print("grid points:", len(pts), " ordered pairs:", len(pts) ** 2)


def e2_int(t):
    s1 = sum(t); s2 = sum(x * x for x in t)
    return (s1 * s1 - s2) // 2


# 1 - x_i y_i = (16 - d_i d'_i)/16, so e2(1 - x o y) = e2(t)/256 with integer t_i = 16 - d_i d'_i
byE = {}
minE = None
for p in pts:
    wp = w[p]
    for q in pts:
        t = [16 - a * b for a, b in zip(p, q)]
        E = e2_int(t)
        byE[E] = byE.get(E, 0) + wp * w[q]
        minE = E if minE is None else min(minE, E)
Q = sum(Fr(256 * c, E) for E, c in byE.items() if c)
print("smallest e2(t) over all pairs:", minE, "(> 0, so every entry is finite and positive)")
# spot check of the scaling against the literal definition 1/e2(1 - x o y) in fractions
random.seed(281)
ok_scale = True
for _ in range(2000):
    p, q = random.choice(pts), random.choice(pts)
    x = [Fr(a, 4) for a in p]; y = [Fr(b, 4) for b in q]
    f = [1 - a * b for a, b in zip(x, y)]
    e2 = sum(f[i] * f[j] for i in range(5) for j in range(i + 1, 5))
    ok_scale &= (1 / e2 == Fr(256, e2_int([16 - a * b for a, b in zip(p, q)])))
print("1/e2(1 - x o y) == 256/e2(t) on 2000 random pairs:", ok_scale)
print("v^T K_1 v (all 1,048,576 ordered pairs, exact) =", Q)
print("  = %.12e" % float(Q))
print("  -1/50000 < v^T K_1 v:", Fr(-1, 50000) < Q, "   v^T K_1 v < -1/51000:", Q < Fr(-1, 51000))
print("  numerator and denominator digits:", len(str(Q.numerator)), len(str(Q.denominator)))

# ------------------------------------------------------------------ 2. the paper's six-product recursion
pair = {}
for a in DIG:
    for b in DIG:
        pair[a * b] = pair.get(a * b, 0) + WT[a] * WT[b]
print("pair weights by product p:", dict(sorted(pair.items())), " (paper: 18, -12, 2 for p = 1, 3, 9 and their negatives)")


def rec(n, s, e):
    if n == 0:
        return Fr(256, e)
    return sum(c * rec(n - 1, s + (16 - p), e + s * (16 - p)) for p, c in pair.items())


Q6 = rec(5, 0, 0)
print("six-product recursion gives the same value:", Q6 == Q)

# ------------------------------------------------------------------ 3. floating point: the 1024 x 1024 matrix
X = np.array(pts, dtype=float) / 4.0
V = np.array([w[p] for p in pts], dtype=float)
F = 1.0 - X[:, None, :] * X[None, :, :]
s1 = F.sum(2); s2 = (F ** 2).sum(2)
K = 2.0 / (s1 ** 2 - s2)
ev = np.linalg.eigvalsh(K)
print("float: v^T K v = %.6e ; smallest eigenvalue of K = %.6e ; number of negative eigenvalues below -1e-12: %d"
      % (V @ K @ V, ev.min(), int((ev < -1e-12).sum())))


# ------------------------------------------------------------------ 4. Taylor coefficients a_alpha of e2(1 - z)^(-beta)
def taylor(n, box, beta):
    """a_alpha * C(n,2)^beta for all alpha in {0..box}^n, exact (beta rational), via
    e2(1 - z) = C(n,2) (1 - G / C(n,2)),  G = (n-1) e1(z) - e2(z),  and the binomial series."""
    N = comb(n, 2)
    G = {}
    for i in range(n):
        m = [0] * n; m[i] = 1; G[tuple(m)] = n - 1
    for i in range(n):
        for j in range(i + 1, n):
            m = [0] * n; m[i] = 1; m[j] = 1; G[tuple(m)] = -1
    out = {tuple([0] * n): Fr(1)}
    power = {tuple([0] * n): 1}
    ck = Fr(1)                                     # binom(beta + k - 1, k)
    for k in range(1, n * box + 1):
        new = {}
        for m, c in power.items():
            for g, d in G.items():
                mm = tuple(a + b for a, b in zip(m, g))
                if max(mm) <= box:
                    new[mm] = new.get(mm, 0) + c * d
        power = new
        ck = ck * (beta + k - 1) / k
        for m, c in power.items():
            out[m] = out.get(m, 0) + ck * Fr(c, N ** k)
    return out


for n, box, beta in ((3, 8, Fr(1)), (4, 6, Fr(1)), (5, 3, Fr(1)), (5, 3, Fr(3, 2)), (6, 2, Fr(2))):
    co = taylor(n, box, beta)
    neg = sorted((sum(m), m, c) for m, c in co.items() if c < 0)
    line = "n=%d beta=%s: Taylor coefficients for every alpha in {0..%d}^%d (%d of them): %s" % (
        n, beta, box, n, len(co), "all >= 0" if not neg else "%d negative" % len(neg))
    if neg:
        d0 = neg[0][0]
        first = sorted(set(tuple(sorted(m, reverse=True)) for dd, m, c in neg if dd == d0))
        line += "; lowest total degree of a negative one: %d, e.g. alpha = %s (coefficient %s times C(n,2)^-beta)" % (
            d0, first[0], [c for dd, m, c in neg if dd == d0 and tuple(sorted(m, reverse=True)) == first[0]][0])
        print(line)
        a33 = co.get((3, 3, 3, 3, 3)) if n == 5 else None
        if a33 is not None:
            print("      alpha = (3,3,3,3,3): coefficient %s (%s)" % (a33, "negative" if a33 < 0 else "nonnegative"))
    else:
        print(line)


def taylor_deg(n, D, beta):
    """the same coefficients for every alpha of total degree <= D (no bound on single exponents)"""
    N = comb(n, 2)
    G = {}
    for i in range(n):
        m = [0] * n; m[i] = 1; G[tuple(m)] = n - 1
    for i in range(n):
        for j in range(i + 1, n):
            m = [0] * n; m[i] = 1; m[j] = 1; G[tuple(m)] = -1
    out = {tuple([0] * n): Fr(1)}
    power = {tuple([0] * n): 1}
    ck = Fr(1)
    for k in range(1, D + 1):
        new = {}
        for m, c in power.items():
            for g, d in G.items():
                mm = tuple(a + b for a, b in zip(m, g))
                if sum(mm) <= D:
                    new[mm] = new.get(mm, 0) + c * d
        power = new
        ck = ck * (beta + k - 1) / k
        for m, c in power.items():
            out[m] = out.get(m, 0) + ck * Fr(c, N ** k)
    return out


for n, D, beta in ((4, 20, Fr(1)), (5, 15, Fr(1)), (5, 15, Fr(3, 2)), (5, 15, Fr(7, 5))):
    co = taylor_deg(n, D, beta)
    neg = [(sum(m), tuple(sorted(m, reverse=True))) for m, c in co.items() if c < 0]
    if not neg:
        print("n=%d beta=%s: all %d Taylor coefficients of total degree <= %d are >= 0" % (n, beta, len(co), D))
    else:
        d0 = min(d for d, s in neg)
        shapes = sorted(set(s for d, s in neg if d == d0))
        print("n=%d beta=%s: %d Taylor coefficients of total degree <= %d; all of degree < %d are >= 0; negative ones of degree %d: "
              "exponent patterns %s; %d negative in all" % (n, beta, len(co), D, d0, d0, shapes, len(neg)))

# ------------------------------------------------------------------ 5. the paper's converse construction at a negative coefficient
# points x = t*j, 0 <= j_i <= alpha_i, weights prod (-1)^(alpha_i - j_i) C(alpha_i, j_i); exact form for small rational t
co5 = taylor(5, 3, Fr(1))
alpha = min((m for m, c in co5.items() if c < 0), key=lambda m: (sum(m), m))
print("construction of the paper at alpha =", alpha, "(a_alpha * 10 =", co5[alpha], ")")
grid = list(itertools.product(*[range(a + 1) for a in alpha]))
wj = {j: np.prod([(-1) ** (a - b) * comb(a, b) for a, b in zip(alpha, j)]) for j in grid}
for t in (Fr(1, 4), Fr(1, 8), Fr(1, 16)):
    byE2 = {}
    for j in grid:
        for k in grid:
            f = [1 - t * t * a * b for a, b in zip(j, k)]
            s1_ = sum(f); s2_ = sum(x * x for x in f)
            e2 = (s1_ * s1_ - s2_) / 2
            byE2[e2] = byE2.get(e2, 0) + int(wj[j]) * int(wj[k])
    qf = sum(c / e2 for e2, c in byE2.items() if c)
    scale = qf / t ** (2 * sum(alpha))
    print("  t = %s: %d points, quadratic form = %.6e, divided by t^(2|alpha|) = %.6f (limit a_alpha (prod alpha_i!)^2 = %.6f)"
          % (t, len(grid), float(qf), float(scale), float(Fr(co5[alpha], 10) * np.prod([__import__('math').factorial(a) for a in alpha]) ** 2)))

# ------------------------------------------------------------------ 6. floating point: random point sets in dimensions 2..4
rng = np.random.default_rng(281)
worst = {}
for n in (2, 3, 4):
    m = 1.0
    for trial in range(300):
        N = 40
        Y = rng.uniform(-1, 1, size=(N, n)) * rng.uniform(0.2, 0.999)
        Fm = 1.0 - Y[:, None, :] * Y[None, :, :]
        S1 = Fm.sum(2); S2 = (Fm ** 2).sum(2)
        Km = 2.0 / (S1 ** 2 - S2)
        e = np.linalg.eigvalsh(Km)
        m = min(m, e.min() / e.max())
    worst[n] = m
print("random point sets (300 sets of 40 points per dimension): smallest eigenvalue / largest eigenvalue:",
      {n: "%.2e" % v for n, v in worst.items()}, "(no clearly negative eigenvalue)")
