"""Explicit non-PSD generalized Cauchy matrix M_2 for n = 8 (MathOverflow 114101).

Points x^S = h * 1_S for all S subset of [8] (m = 256, every |x_j| <= h < 1), test vector c_S = (-1)^|S|.
x^S o x^T = h^2 1_{S cap T}, so M_ST depends only on r = |S cap T|, and
c^T M c = sum_r C(8,r) (-1)^(8-r) / e_2(1 - h^2 1_r), the 8th difference in r.
Checked exactly with Fractions and by building the 256 x 256 matrix in floats.
"""
import itertools
from fractions import Fraction
from math import comb
import numpy as np

n = 8

def e2(v):
    return sum(a * b for a, b in itertools.combinations(v, 2))

def form_exact(h):
    u = h * h
    return sum(comb(n, r) * (-1) ** (n - r) * Fraction(1) / e2([1 - u] * r + [1] * (n - r)) for r in range(n + 1))

for h in [Fraction(1, 8), Fraction(1, 4), Fraction(1, 2), Fraction(3, 4), Fraction(4, 5), Fraction(9, 10)]:
    q = form_exact(h)
    assert isinstance(q, Fraction)
    print(f"h = {h}: c^T M c = {q} ~ {float(q):.4e}")

h = 0.5
subsets = list(itertools.product([0, 1], repeat=n))
X = np.array(subsets, float) * h
M = np.array([[1.0 / e2(1 - X[i] * X[j]) for j in range(len(X))] for i in range(len(X))])
c = np.array([(-1) ** sum(s) for s in subsets], float)
print("float check h=1/2: c^T M c =", c @ M @ c, " min eigenvalue =", np.linalg.eigvalsh(M).min())
