#!/usr/bin/env python3
"""Verifier for a counterexample to clause (i) of Conjecture 4.10 of
Higashitani-Kummer-Michalek (arXiv:1612.07538).

usage: python3 verify.py certificate.json

The certificate only names the part sizes of a complete multipartite graph G.
Everything else is recomputed here with exact integer / rational arithmetic
(Python standard library only).  See CERTIFICATE.md for the mathematics.
"""
import sys, json
from fractions import Fraction as Fr
from itertools import product, combinations_with_replacement


def fail(msg):
    print("FAILED:", msg)
    sys.exit(1)


# ----------------------------------------------------------------------------
# 0. The graph and the generators of P_G, straight from the definition
# ----------------------------------------------------------------------------
def build_graph(parts):
    part_of = []
    for i, a in enumerate(parts):
        part_of += [i] * a
    n = len(part_of)
    edges = [(u, v) for u in range(n) for v in range(u + 1, n) if part_of[u] != part_of[v]]
    gens = []
    for u, v in edges:
        for s, t in ((u, v), (v, u)):
            g = [0] * n
            g[s] = 1
            g[t] = -1
            gens.append(tuple(g))
    return part_of, n, edges, gens


# ----------------------------------------------------------------------------
# 1. Lattice point count of mP_G through the membership lemma (CERTIFICATE.md):
#    integer z with coordinate sum 0 lies in mP  iff  p(z) <= m and
#    for every part i: (l1 norm of z restricted to part i) <= m,
#    where p(z) = sum of positive coordinates.
# ----------------------------------------------------------------------------
def local_table(a, m):
    """By brute enumeration: number of integer vectors on a coordinates with
    positive mass u, negative mass v, u+v<=m.  Returns dict (u,v)->count."""
    tab = {}
    for vec in product(range(-m, m + 1), repeat=a):
        u = sum(x for x in vec if x > 0)
        v = -sum(x for x in vec if x < 0)
        if u + v <= m:
            tab[u, v] = tab.get((u, v), 0) + 1
    return tab


def count_lemma(parts, m):
    table = {(0, 0): 1}
    cache = {}
    for a in parts:
        if a not in cache:
            cache[a] = local_table(a, m)
        loc = cache[a]
        nxt = {}
        for (p, q), c in table.items():
            for (u, v), w in loc.items():
                if p + u <= m and q + v <= m:
                    k = (p + u, q + v)
                    nxt[k] = nxt.get(k, 0) + c * w
        table = nxt
    # coordinate sum zero <=> positive mass == negative mass
    return sum(table.get((p, p), 0) for p in range(m + 1))


# ----------------------------------------------------------------------------
# 2. Definition-level cross-check of the count for small m.
#    Every integer point of mP has coordinate sum 0 and p(z) <= m (the linear
#    functional "indicator of the positive support" is <= 1 on every generator;
#    this is re-checked below for the functionals actually used).
#    For each such z we exhibit either
#      * an explicit decomposition z = sum of <= m generators  (=> z in mP,
#        because 0 = (g + (-g))/2 is in P), or
#      * a linear functional L with L(g) <= 1 for ALL generators g (checked by
#        looping over the generators) and L(z) > m  (=> z not in mP).
# ----------------------------------------------------------------------------
def decompose(z, budget, part_of, n):
    """Search z = sum of <= budget generators e_u - e_v (u,v in different parts)."""
    if not any(z):
        return True
    if budget == 0:
        return False
    if sum(x for x in z if x > 0) > budget:
        return False
    u = next(i for i in range(n) if z[i] > 0)
    order = [v for v in range(n) if z[v] < 0] + [v for v in range(n) if z[v] >= 0]
    for v in order:
        if part_of[v] == part_of[u]:
            continue
        z[u] -= 1
        z[v] += 1
        ok = decompose(z, budget - 1, part_of, n)
        z[u] += 1
        z[v] -= 1
        if ok:
            return True
    return False


def brute_count(parts, m, part_of, n, gens):
    checked_functionals = set()
    total = 0
    for p in range(m + 1):
        multisets = list(combinations_with_replacement(range(n), p))
        for pos in multisets:
            pos_set = set(pos)
            for neg in multisets:
                if pos_set.intersection(neg):
                    continue
                z = [0] * n
                for i in pos:
                    z[i] += 1
                for i in neg:
                    z[i] -= 1
                # try a separating functional supported on one part
                separated = False
                for i in range(len(parts)):
                    L = tuple((1 if z[v] > 0 else -1 if z[v] < 0 else 0) if part_of[v] == i else 0
                              for v in range(n))
                    val = sum(a * b for a, b in zip(L, z))
                    if val > m:
                        if L not in checked_functionals:
                            if max(sum(a * b for a, b in zip(L, g)) for g in gens) > 1:
                                fail("functional not bounded by 1 on generators")
                            checked_functionals.add(L)
                        separated = True
                        break
                if separated:
                    continue
                if not decompose(z, m, part_of, n):
                    fail("lemma cross-check: no decomposition found for %r at m=%d" % (z, m))
                total += 1
    return total


# ----------------------------------------------------------------------------
# 3. Exact polynomial arithmetic over Q (coefficient lists, increasing degree)
# ----------------------------------------------------------------------------
def trim(a):
    a = list(a)
    while a and a[-1] == 0:
        a.pop()
    return a


def padd(a, b):
    r = [Fr(0)] * max(len(a), len(b))
    for i, x in enumerate(a):
        r[i] += x
    for i, x in enumerate(b):
        r[i] += x
    return trim(r)


def pmul(a, b):
    if not a or not b:
        return []
    r = [Fr(0)] * (len(a) + len(b) - 1)
    for i, x in enumerate(a):
        for j, y in enumerate(b):
            r[i + j] += x * y
    return trim(r)


def pscale(a, c):
    return trim([x * c for x in a])


def prem(a, b):
    a = trim(a)
    b = trim(b)
    while len(a) >= len(b) and a:
        c = a[-1] / b[-1]
        s = len(a) - len(b)
        for i, y in enumerate(b):
            a[i + s] -= c * y
        a = trim(a)
    return a


def pgcd(a, b):
    a, b = trim(a), trim(b)
    while b:
        a, b = b, prem(a, b)
    return pscale(a, 1 / a[-1]) if a else []


def pdiff(a):
    return trim([i * a[i] for i in range(1, len(a))])


def peval(a, x):
    r = Fr(0)
    for c in reversed(a):
        r = r * x + c
    return r


def interpolate(xs, ys):
    """Lagrange interpolation, exact."""
    res = []
    for i, xi in enumerate(xs):
        num = [Fr(1)]
        den = Fr(1)
        for j, xj in enumerate(xs):
            if j != i:
                num = pmul(num, [Fr(-xj), Fr(1)])
                den *= (xi - xj)
        res = padd(res, pscale(num, Fr(ys[i]) / den))
    return res


def sign(x):
    return (x > 0) - (x < 0)


def variations(seq):
    s = [x for x in seq if x != 0]
    return sum(1 for a, b in zip(s, s[1:]) if a != b)


def count_distinct_real_roots(f):
    """Sturm's theorem on the whole real line; f must be squarefree, deg >= 1."""
    chain = [trim(f), pdiff(f)]
    while chain[-1]:
        r = prem(chain[-2], chain[-1])
        chain.append(pscale(r, -1))
    chain.pop()
    plus = [sign(c[-1]) for c in chain]
    minus = [sign(c[-1]) * (-1) ** (len(c) - 1) for c in chain]
    return variations(minus) - variations(plus)


# ----------------------------------------------------------------------------
def main():
    if len(sys.argv) != 2:
        fail("usage: python3 verify.py certificate.json")
    with open(sys.argv[1]) as fh:
        cert = json.load(fh)
    parts = cert["parts"]
    if not (isinstance(parts, list) and len(parts) >= 2
            and all(isinstance(a, int) and not isinstance(a, bool) and 1 <= a <= 3 for a in parts)
            and sum(parts) <= 14):
        fail("parts must be a list of >=2 integers in 1..3 with at most 14 vertices")
    part_of, n, edges, gens = build_graph(parts)
    d = n - 1  # dim P_G = n-1 since G is connected (k >= 2 parts); deg H = d
    print("graph: complete multipartite with parts", parts, "| vertices", n, "| edges", len(edges))

    # --- lattice point counts
    M = d + 3
    vals = [count_lemma(parts, m) for m in range(M + 1)]
    print("H(0..%d) =" % M, vals)

    # --- definition-level cross-check for small dilates
    for m in range(0, 4):
        b = brute_count(parts, m, part_of, n, gens)
        if b != vals[m]:
            fail("brute force count %d != lemma count %d at m=%d" % (b, vals[m], m))
        print("definition-level cross-check m=%d: %d lattice points, agrees" % (m, b))

    # --- Ehrhart polynomial: degree d, determined by d+1 values
    H = interpolate(list(range(d + 1)), vals[:d + 1])
    if len(H) != d + 1:
        fail("interpolant does not have degree n-1")
    for m in range(M + 1):
        if peval(H, m) != vals[m]:
            fail("interpolant disagrees with count at m=%d" % m)
    print("Ehrhart polynomial coefficients (increasing degree):", [str(c) for c in H])

    # --- restrict to the line: z = -1/2 + i t, H(z) = A(t) + i B(t), A,B in Q[t]
    # powers of (-1/2 + i t) as pairs (real poly, imag poly)
    A, B = [], []
    pr, pi = [Fr(1)], []
    for c in H:
        A = padd(A, pscale(pr, c))
        B = padd(B, pscale(pi, c))
        # multiply (pr + i pi) by (-1/2 + i t)
        nr = padd(pscale(pr, Fr(-1, 2)), pscale(pmul(pi, [Fr(0), Fr(1)]), -1))
        ni = padd(pscale(pi, Fr(-1, 2)), pmul(pr, [Fr(0), Fr(1)]))
        pr, pi = nr, ni
    # sanity: the leading coefficient of A + iB is c_d * i^d, nonzero
    if max(len(A), len(B)) != d + 1:
        fail("unexpected degree on the line")
    # A real t0 is a root of multiplicity k of t -> H(-1/2 + i t) iff (t-t0)^k
    # divides both A and B, i.e. divides G = gcd(A,B).  So the number of roots of
    # H on Re z = -1/2, counted with multiplicity, equals the number of real roots
    # of G counted with multiplicity.
    G = pgcd(A, B)
    degG = len(G) - 1
    print("deg gcd(A,B) =", degG)
    if degG <= 0:
        on_line = 0
    else:
        if len(pgcd(G, pdiff(G))) != 1:
            fail("gcd(A,B) not squarefree; this verifier does not handle that case")
        on_line = count_distinct_real_roots(G)
    print("roots of H on Re z = -1/2 (with multiplicity):", on_line, "of", d)
    if on_line >= d:
        fail("all roots are on the line; not a counterexample")
    print("=> %d roots of H lie off the line Re z = -1/2; clause (i) of Conjecture 4.10 fails" % (d - on_line))
    print("VERIFIED")
    sys.exit(0)


if __name__ == "__main__":
    main()
