"""Exact finite-difference witness that M_k is not PSD, from a negative Taylor coefficient a_alpha.

Points x_i = h * i for i in the grid prod_l {0..alpha_l}; weights c_i = prod_l (-1)^(alpha_l - i_l) C(alpha_l, i_l).
Then c^T M c = sum_{beta >= alpha} a_beta h^(2|beta|) prod_l (alpha_l! S(beta_l, alpha_l))^2, whose leading term is
a_alpha (alpha!)^2 h^(2|alpha|), so it is negative for small h. Here it is evaluated exactly, grouping pairs (i, j)
by the coordinatewise product p = i o j: c^T M c = sum_p W(p) / e_k(1 - h^2 p), W(p) = prod_l w_l(p_l).
"""
import itertools, sys
from collections import defaultdict
from fractions import Fraction
from math import comb, prod

def ek(k, v):
    return sum(prod(t) for t in itertools.combinations(v, k))

def form(k, alpha, h):
    per = []
    for a in alpha:
        w = defaultdict(int)
        for s in range(a + 1):
            for t in range(a + 1):
                w[s * t] += (-1) ** (2 * a - s - t) * comb(a, s) * comb(a, t)
        per.append({q: v for q, v in w.items() if v})
    u = h * h
    total = Fraction(0)
    for combo in itertools.product(*(list(w.items()) for w in per)):
        W = prod(v for _, v in combo)
        total += W * Fraction(1) / ek(k, [1 - u * q for q, _ in combo])
    return total

if __name__ == "__main__":
    k = int(sys.argv[1]); alpha = tuple(int(x) for x in sys.argv[2].split(","))
    m = prod(a + 1 for a in alpha)
    for hs in sys.argv[3:]:
        h = Fraction(hs)
        assert max(alpha) * h < 1
        q = form(k, alpha, h)
        print(f"k={k} n={len(alpha)} alpha={alpha} m={m} h={h}: c^T M c ~ {float(q):.6e} (exact sign {'negative' if q < 0 else 'nonnegative'})", flush=True)
