#!/usr/bin/env python3
"""Independent checker: counterexample to clause (i) of Conjecture 4.10 of
Higashitani-Kummer-Michalek, "Interlacing Ehrhart polynomials of reflexive
polytopes" (arXiv:1612.07538).

Usage: python3 checker.py certificate.json

Definitions (checked against the arXiv TeX source, Section 2.1 and Conj. 4.10):
  * G = (V,E); P_G = conv{ e_v - e_w, e_w - e_v : {v,w} in E } in R^|V|.
  * H_P(s) = |sP cap Z^|V|| for integers s >= 0 (a polynomial of degree dim P).
  * R = { z : Re z = -1/2 }.
  * Conj 4.10(i): for every complete k-partite graph of type (a_1..a_k),
    H_{a_1..a_k} has (all) its roots on R.
The certificate is a list of part sizes.  It settles (refutes) the statement
iff the Ehrhart polynomial of that graph's P_G has a root off R, i.e. iff the
number of roots on R, counted with multiplicity, is smaller than the degree.

Everything is exact (Python ints / Fractions).  Steps:
  A. lattice-point counts H(m) through a membership criterion (proved in the
     comment of `count_lemma`);
  B. the same counts for m <= 4 straight from the definition (explicit sums of
     generators for membership, explicit separating functionals for
     non-membership) -- must agree with A;
  C. self-tests of the counting routine against formulas printed in the paper
     (H_{3,3}, H_{3,3,1} of Example 4.11, HS_{1,n}, HS_{2,n} of Prop. 4.4);
  D. interpolation, consistency checks (extra points, reflexive symmetry);
  E. exact count (Sturm) of roots on R with multiplicity.
"""
import sys
import json
from fractions import Fraction
from math import comb


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


# ----------------------------------------------------------------------------
# polynomial helpers over Q (lists of Fractions, index = degree)
# ----------------------------------------------------------------------------
def ptrim(p):
    p = list(p)
    while p and p[-1] == 0:
        p.pop()
    return p


def padd(p, q):
    n = max(len(p), len(q))
    return ptrim([(p[i] if i < len(p) else 0) + (q[i] if i < len(q) else 0) for i in range(n)])


def pmul(p, q):
    if not p or not q:
        return []
    r = [Fraction(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 ptrim(r)


def pscale(p, c):
    return ptrim([a * c for a in p])


def pdivmod(p, q):
    q = ptrim(q)
    if not q:
        raise ZeroDivisionError
    r = ptrim(p)
    quo = [Fraction(0)] * max(0, len(r) - len(q) + 1)
    while len(r) >= len(q):
        c = r[-1] / q[-1]
        s = len(r) - len(q)
        quo[s] = c
        for i, b in enumerate(q):
            r[i + s] -= c * b
        r = ptrim(r)
    return ptrim(quo), r


def pgcd(p, q):
    p, q = ptrim(p), ptrim(q)
    while q:
        p, q = q, pdivmod(p, q)[1]
    if p:
        p = pscale(p, 1 / p[-1])
    return p


def pderiv(p):
    return ptrim([p[i] * i for i in range(1, len(p))])


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


def pcompose_shift(p, c):
    """p(x + c)"""
    r = []
    for a in reversed(p):
        r = padd(pmul(r, [Fraction(c), Fraction(1)]), [a])
    return ptrim(r)


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


def distinct_real_roots(p):
    """Number of distinct real roots of p != 0 (Sturm's theorem; the chain
    p, p', -rem, ... is valid at +-infinity also when p is not squarefree)."""
    p = ptrim(p)
    if not p:
        raise ValueError("zero polynomial")
    if len(p) == 1:
        return 0
    chain = [p, pderiv(p)]
    while chain[-1]:
        r = pdivmod(chain[-2], chain[-1])[1]
        chain.append(pscale(r, -1))
    chain.pop()

    def var(signs):
        s = [x for x in signs if x != 0]
        return sum(1 for i in range(len(s) - 1) if s[i] != s[i + 1])

    at_pinf = [sign(q[-1]) for q in chain]
    at_minf = [sign(q[-1]) * (-1 if (len(q) - 1) % 2 else 1) for q in chain]
    return var(at_minf) - var(at_pinf)


def real_roots_with_multiplicity(p):
    """sum of multiplicities of the real roots of p != 0.
    #roots of multiplicity >= j equals #distinct real roots of the (j-1)-fold
    iterate of g -> gcd(g, g')."""
    g = ptrim(p)
    total = 0
    while len(g) > 1:
        total += distinct_real_roots(g)
        g = pgcd(g, pderiv(g))
    return total


def roots_on_critical_line(H):
    """Number of roots z of H (with multiplicity) with Re z = -1/2.
    F(t) = H(-1/2 + i t) = A(t) + i B(t), A, B in Q[t].  For real t0,
    (t-t0)^k | F  iff  (t-t0)^k | A and B (conjugate F), iff (t-t0)^k | gcd(A,B).
    z -> t is an affine change of variable, so multiplicities are preserved."""
    G = pcompose_shift(H, Fraction(-1, 2))          # G(y) = H(-1/2 + y), y = i t
    A = [Fraction(0)] * len(G)
    B = [Fraction(0)] * len(G)
    for j, c in enumerate(G):
        if j % 2 == 0:
            A[j] = c * (-1) ** (j // 2)
        else:
            B[j] = c * (-1) ** ((j - 1) // 2)
    A, B = ptrim(A), ptrim(B)
    if not A and not B:
        raise ValueError("H is zero")
    g = pgcd(A, B) if (A and B) else (A or B)
    return real_roots_with_multiplicity(g), A, B, g


# ----------------------------------------------------------------------------
# the graph and polytope
# ----------------------------------------------------------------------------
def build(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:
        g = [0] * n
        g[u], g[v] = 1, -1
        gens.append(tuple(g))
        gens.append(tuple(-x for x in g))
    return n, part_of, edges, gens


def rank(rows):
    M = [[Fraction(x) for x in r] for r in rows]
    rk = 0
    ncol = len(M[0]) if M else 0
    for c in range(ncol):
        piv = next((i for i in range(rk, len(M)) if M[i][c] != 0), None)
        if piv is None:
            continue
        M[rk], M[piv] = M[piv], M[rk]
        for i in range(len(M)):
            if i != rk and M[i][c] != 0:
                f = M[i][c] / M[rk][c]
                M[i] = [a - f * b for a, b in zip(M[i], M[rk])]
        rk += 1
    return rk


def count_lemma(parts, m):
    """|m P_G cap Z^n| for the complete multipartite graph with k >= 2 parts.

    Criterion.  For integer z with coordinate sum 0 let p_i / q_i be the sum of
    the positive / minus the negative coordinates of z inside part i and
    p = sum p_i = sum q_i.  Then  z in mP  iff  p <= m and p_i+q_i <= m for all i.
    (Points of mP have coordinate sum 0, so other integer points are not in mP.)

    Proof (checked by the author of this checker).  =>: z -> sum max(z_v,0) and
    z -> sum_{v in A_i} |z_v| are convex, positively homogeneous and <= 1 on
    every generator e_u - e_v (u, v in different parts), hence <= m on mP.
    <=: view z as p positive and p negative unit tokens; a positive token in
    part i may be paired with any negative token outside part i (p - q_i of
    them).  A set of positive tokens meeting two parts sees all negative
    tokens; a set inside part i has deficiency <= p_i + q_i - p.  By the
    defect form of Hall's theorem there is a matching of size p - h,
    h = max(0, max_i(p_i + q_i - p)); each matched pair is a generator.  The 2h
    left-over tokens are paired arbitrarily, each pair costing <= 2 generators
    (e_u - e_w) + (e_w - e_v), w in another part (k >= 2).  So z is a sum of
    <= p + h = max(p, max_i(p_i+q_i)) <= m generators; since 0 = (g + (-g))/2
    is in P, z is in mP.                                                    QED
    Step B below re-derives the counts for small m without this criterion.

    Count: per part, T[u][v] = #integer vectors on the part with positive mass
    u and negative mass v (u + v <= m); then convolve over the parts and keep
    total positive mass = total negative mass <= m.
    """
    def table(a):
        T = {(0, 0): 1}
        for _ in range(a):
            N = {}
            for (u, v), c in T.items():
                N[(u, v)] = N.get((u, v), 0) + c          # coordinate 0
                for t in range(1, m - u - v + 1):
                    N[(u + t, v)] = N.get((u + t, v), 0) + c   # coordinate +t
                    N[(u, v + t)] = N.get((u, v + t), 0) + c   # coordinate -t
            T = N
        return T

    cache = {}
    D = {(0, 0): 1}
    for a in parts:
        if a not in cache:
            cache[a] = table(a)
        T = cache[a]
        N = {}
        for (U, V), c in D.items():
            for (u, v), t in T.items():
                if U + u <= m and V + v <= m:
                    key = (U + u, V + v)
                    N[key] = N.get(key, 0) + c * t
        D = N
    return sum(c for (U, V), c in D.items() if U == V)


BASE = 16  # coordinates stay in [-4, 4] in step B, so the encoding is injective


def enc(z):
    return sum(x * BASE ** i for i, x in enumerate(z))


def count_definition(parts, m):
    """|mP cap Z^n| straight from the definition, m <= 4.

    S = all sums of at most m generators.  S subset mP because 0 in P.
    Every integer point of mP has coordinate sum 0 and positive mass p <= m:
    the 0/1 indicator L of its positive support satisfies L(e_u - e_v) <= 1 on
    every generator, hence L <= m on mP, and L(z) = p.
    All zero-sum integer z with p <= m are enumerated; each is either found in
    S, or a linear functional L is exhibited with L(g) <= 1 for all generators
    g (checked explicitly) and L(z) > m, so z is not in mP.  If neither works
    the routine gives up (returns None)."""
    assert m <= 4
    n, part_of, edges, gens = build(parts)
    genc = [enc(g) for g in gens]
    S = {0}
    frontier = {0}
    for _ in range(m):
        new = set()
        for x in frontier:
            for g in genc:
                y = x + g
                if y not in S:
                    new.add(y)
        S |= new
        frontier = new
    # nonnegative integer vectors of each mass j <= m
    by_mass = [[] for _ in range(m + 1)]

    def rec(i, left, cur):
        if i == n:
            z = tuple(cur)
            by_mass[sum(z)].append((z, enc(z), sum(1 << t for t in range(n) if z[t])))
            return
        for t in range(left + 1):
            cur.append(t)
            rec(i + 1, left - t, cur)
            cur.pop()

    rec(0, m, [])
    functional_ok = {}

    def valid(L):
        if L not in functional_ok:
            functional_ok[L] = all(sum(a * b for a, b in zip(L, g)) <= 1 for g in gens)
        return functional_ok[L]

    inside = 0
    outside = 0
    k = len(parts)
    for j in range(m + 1):
        lst = by_mass[j]
        for (za, ea, ma) in lst:
            for (zb, eb, mb) in lst:
                if ma & mb:
                    continue
                if ea - eb in S:
                    inside += 1
                    continue
                z = [a - b for a, b in zip(za, zb)]
                sep = False
                for i in range(k):
                    L = tuple(sign(z[v]) if part_of[v] == i else 0 for v in range(n))
                    if sum(a * b for a, b in zip(L, z)) > m and valid(L):
                        sep = True
                        break
                if not sep:
                    return None
                outside += 1
    if inside != len(S):
        return None  # cannot happen: every element of S has positive mass <= m
    return inside


def interpolate(vals):
    """Polynomial of degree <= len(vals)-1 through (j, vals[j]), Newton form
    sum_j c_j * binom(x, j) with c_j the forward differences at 0."""
    d = list(vals)
    coeffs = []
    while d:
        coeffs.append(d[0])
        d = [d[i + 1] - d[i] for i in range(len(d) - 1)]
    H = []
    basis = [Fraction(1)]            # binom(x, j)
    for j, c in enumerate(coeffs):
        H = padd(H, pscale(basis, Fraction(c)))
        basis = pmul(basis, [Fraction(-j, j + 1), Fraction(1, j + 1)])
    return H


def ehrhart(parts, extra=3):
    """Ehrhart polynomial of P_G (G complete multipartite, k >= 2, connected,
    so dim P_G = n-1 -- the rank is verified by the caller for the certificate).
    Interpolates H(0..d) and insists that `extra` further values fit."""
    d = sum(parts) - 1
    vals = [count_lemma(parts, m) for m in range(d + 1 + extra)]
    H = interpolate(vals[:d + 1])
    for m in range(d + 1, d + 1 + extra):
        if peval(H, m) != vals[m]:
            return None, vals
    return H, vals


def poly_from_delta(delta, d):
    """sum_i delta_i * binom(s + d - i, d)  (paper, Section 2.1)"""
    H = []
    for i, de in enumerate(delta):
        b = [Fraction(1)]
        for t in range(d):           # binom(s + d - i, d) = prod_{t<d} (s + d - i - t)/(t+1)
            b = pmul(b, [Fraction(d - i - t, t + 1), Fraction(1, t + 1)])
        H = padd(H, pscale(b, Fraction(de)))
    return H


def delta_from_series_numer(factors):
    num = [Fraction(1)]
    for f in factors:
        num = pmul(num, [Fraction(c) for c in f])
    return num


def self_tests():
    F = Fraction
    # Example 4.11 of the paper
    H33 = [F(1), F(113, 30), F(23, 4), F(16, 3), F(9, 4), F(9, 10)]
    H331 = [F(1), F(43, 10), F(481, 60), F(33, 4), F(37, 6), F(49, 20), F(49, 60)]
    got, _ = ehrhart([3, 3])
    if got != H33:
        fail("self-test: H_{3,3} differs from Example 4.11 of the paper")
    got, _ = ehrhart([3, 3, 1])
    if got != H331:
        fail("self-test: H_{3,3,1} differs from Example 4.11 of the paper")
    # paper lists 5 resp. 6 roots, all with real part -1/2
    if roots_on_critical_line(H33)[0] != 5 or roots_on_critical_line(H331)[0] != 6:
        fail("self-test: root counter disagrees with Example 4.11 of the paper")
    # Prop 4.4: HS_{1,n} = (1+t)^n/(1-t)^{n+1}; HS_{2,n} = (1+t)^{n-1}(1+2nt+t^2)/(1-t)^{n+2}
    for nn in (1, 2, 3, 4):
        want = poly_from_delta(delta_from_series_numer([[1, 1]] * nn), nn)
        if ehrhart([1, nn])[0] != want:
            fail("self-test: H_{1,%d} differs from Prop. 4.4" % nn)
        want = poly_from_delta(delta_from_series_numer([[1, 1]] * (nn - 1) + [[1, 2 * nn, 1]]), nn + 1)
        if ehrhart([2, nn])[0] != want:
            fail("self-test: H_{2,%d} differs from Prop. 4.4" % nn)
    # hand-computable: segment [-1,1] and the hexagon (triangle graph)
    if ehrhart([1, 1])[0] != [F(1), F(2)] or ehrhart([1, 1, 1])[0] != [F(1), F(3), F(3)]:
        fail("self-test: K_2 / K_3 Ehrhart polynomial wrong")
    # definition-based counter against lemma-based counter on small graphs
    for ps in ([1, 1], [1, 1, 1], [2, 2], [3, 3], [3, 3, 1], [2, 2, 2], [1, 2, 3]):
        for m in range(5):
            if count_definition(ps, m) != count_lemma(ps, m):
                fail("self-test: definition count != criterion count for %s, m=%d" % (ps, m))
    # root counter on polynomials with known roots
    x2p1 = [F(1), F(0), F(1)]
    tests = [
        ([F(1, 2), F(1)], 1),                                   # root -1/2
        (pmul([F(1, 2), F(1)], [F(1, 2), F(1)]), 2),            # double root -1/2
        ([F(0), F(1)], 0),                                      # root 0
        (pcompose_shift(x2p1, F(1, 2)), 2),                     # -1/2 +- i
        (pmul(pcompose_shift(x2p1, F(1, 2)), pcompose_shift(x2p1, F(1, 2))), 4),
        (pmul(pcompose_shift(x2p1, F(1, 2)), x2p1), 2),         # plus +-i (off)
        (pmul([F(1), F(1)], [F(0), F(1)]), 0),                  # roots -1, 0
    ]
    for p, want in tests:
        if roots_on_critical_line(p)[0] != want:
            fail("self-test: root counter wrong on a known polynomial")


def main():
    if len(sys.argv) != 2:
        fail("usage: python3 checker.py certificate.json")
    try:
        with open(sys.argv[1]) as fh:
            cert = json.load(fh)
    except Exception as e:
        fail("cannot read certificate: %r" % (e,))
    if not isinstance(cert, dict) or "parts" not in cert:
        fail("certificate must be a JSON object with key 'parts'")
    parts = cert["parts"]
    if not isinstance(parts, list) or not parts:
        fail("'parts' must be a non-empty list")
    for a in parts:
        if type(a) is not int or a < 1:
            fail("'parts' must consist of positive integers")
    k, n = len(parts), sum(parts)
    if k < 2:
        fail("need at least two parts (otherwise G has no edge and P_G is empty)")
    if n > 13:
        fail("graph too large for this checker (more than 13 vertices)")
    print("graph: complete %d-partite graph with part sizes %s (%d vertices)" % (k, parts, n))

    self_tests()
    print("self-tests against the paper's formulas (Ex. 4.11, Prop. 4.4): ok")

    # --- the object -----------------------------------------------------
    nv, part_of, edges, gens = build(parts)
    if len(edges) != (n * n - sum(a * a for a in parts)) // 2 or len(set(gens)) != 2 * len(edges):
        fail("internal: edge/generator count")
    for g in gens:
        u = g.index(1)
        v = g.index(-1)
        if sorted(g) != [-1] + [0] * (n - 2) + [1] or part_of[u] == part_of[v]:
            fail("internal: bad generator")
    d = rank(gens)
    if d != n - 1:
        fail("dim P_G = %d, expected %d" % (d, n - 1))
    # P_G is a lattice polytope of dimension d, so H is a polynomial of degree d (Ehrhart).

    # --- lattice point counts -------------------------------------------
    H, vals = ehrhart(parts, extra=3)
    print("H(0..%d) = %s" % (len(vals) - 1, vals))
    if H is None:
        fail("values H(%d..%d) do not lie on the degree-%d interpolant" % (d + 1, d + 3, d))
    if len(H) - 1 != d:
        fail("interpolated polynomial has degree %d, expected %d" % (len(H) - 1, d))
    if vals[0] != 1 or vals[1] != 2 * len(edges) + 1:
        fail("H(0), H(1) not as expected (P_G must contain exactly its vertices and 0)")
    if H[-1] <= 0:
        fail("leading coefficient not positive")

    mmax = 4 if n <= 12 else 3
    for m in range(mmax + 1):
        c = count_definition(parts, m)
        if c is None:
            fail("could not decide membership from the definition at m=%d" % m)
        if c != vals[m]:
            fail("definition-based count %d != criterion-based count %d at m=%d" % (c, vals[m], m))
    print("counts for m = 0..%d reconfirmed directly from the definition: %s" % (mmax, vals[:mmax + 1]))

    # P_G is reflexive ([MHN+11, Prop 4.2], quoted in the paper), so H(-1-s) = (-1)^d H(s).
    # Not needed for the conclusion, but its failure would reveal a wrong polynomial.
    Hrefl = pcompose_shift([c * (-1) ** i for i, c in enumerate(H)], Fraction(1))  # H(-(s+1))
    if Hrefl != pscale(H, (-1) ** d):
        fail("H violates the functional equation of a reflexive polytope")
    # delta-vector: nonnegative integers, palindromic, sum = d! * leading coefficient
    delta = []
    for i in range(d + 1):
        delta.append(sum((-1) ** j * comb(d + 1, j) * vals[i - j] for j in range(i + 1)))
    if any(x < 0 for x in delta) or delta != delta[::-1] or poly_from_delta(delta, d) != H:
        fail("delta-vector inconsistent: %s" % delta)
    print("delta-vector: %s" % delta)
    print("H(x) = " + " + ".join("(%s)x^%d" % (c, i) for i, c in enumerate(H)))

    # --- roots on Re z = -1/2 ---------------------------------------------
    on_line, A, B, g = roots_on_critical_line(H)
    try:
        import sympy
        t = sympy.symbols("t")
        gs = sympy.Poly(sum(sympy.Rational(c.numerator, c.denominator) * t ** i for i, c in enumerate(g)), t)
        # independent cross-check of the Sturm count (with multiplicity)
        cnt = 0
        for fac, mult in sympy.factor_list(gs.as_expr(), t)[1]:
            cnt += mult * sympy.Poly(fac, t).count_roots()
        if cnt != on_line:
            fail("sympy real-root count %d disagrees with Sturm count %d" % (cnt, on_line))
        print("sympy cross-check of the real-root count: ok")
    except Exception as e:  # fail() raises SystemExit, which is not caught here
        print("sympy cross-check skipped (%s); the exact Sturm count stands on its own" % type(e).__name__)
    print("roots of H on Re z = -1/2 (with multiplicity): %d of %d" % (on_line, d))
    if on_line > d:
        fail("internal: more roots on the line than the degree")
    if on_line == d:
        fail("all %d roots of H lie on Re z = -1/2: not a counterexample to clause (i)" % d)
    print("%d root(s) of H_{%s} lie off the line Re z = -1/2, so clause (i) of Conjecture 4.10 fails"
          % (d - on_line, ",".join(map(str, parts))))
    print("VERIFIED")
    sys.exit(0)


if __name__ == "__main__":
    main()
