Nullius Labs
No. 008◐ REPRODUCED2026-11-25

Disproved: Ehrhart polynomials of symmetric edge polytopes of complete multipartite graphs have roots on Re z=-1/2 and interlace

A public claim that this conjecture is false. We rebuilt the claimed counterexample from scratch and two separately written checkers confirmed it in exact arithmetic. Both sides of this check came from the same AI model, because the second model was unavailable. Machine-checked; not peer reviewed.

Source paper · original claim

Rerun it yourself: download the certificate and a checker, then

python3 checker_b.py certificate.json

Statement, as tested

Download statement.md
# Ehrhart polynomials of symmetric edge polytopes of complete multipartite graphs have roots on Re z=-1/2 and interlace

Source: https://arxiv.org/abs/1612.07538


Public claim to check: https://github.com/1337isnot1337/solved-conjectures/tree/main/results/hkm-ehrhart

Conjecture 4.10 (A. Higashitani, M. Kummer, M. Michalek, 'Interlacing Ehrhart polynomials of reflexive polytopes', Selecta Math. 23 (2017), arXiv:1612.07538). Definitions from the paper: for a graph G=(V,E) the symmetric edge polytope P_G in R^|V| is the convex hull of {e_v - e_w, e_w - e_v : {v,w} in E}; its Ehrhart polynomial is H_P(s) = |sP ∩ Z^|V|| for integers s >= 0, extended to a polynomial; R denotes the line {z in C : Re z = -1/2}. For a line L = alpha + R*beta and polynomials f, g with deg f = d = deg g + 1, all zeros on L, zeros of f being alpha + t_i*beta and of g being alpha + s_j*beta, f is L-interlaced by g if after relabelling t_1 <= s_1 <= t_2 <= ... <= s_{d-1} <= t_d. Write H_{a_1,...,a_k} for the Ehrhart polynomial of P_G with G the complete k-partite graph with part sizes a_1,...,a_k. Conjecture: (i) for every complete k-partite graph of type (a_1,...,a_k), H_{a_1,...,a_k} has all its roots on R; (ii) if a_1 >= ... >= a_k, then H_{a_1,...,a_k} and H_{a_1 - 1,a_2,...,a_k} R-interlace. (Definitions were read from the arXiv HTML; the wording of 4.10 itself came through a machine summary of the tail of the page and agrees with the repository's restatement.)

What the repository offers: G = K_{2,2,2,2,2,2} (six parts of size two, 12 vertices; the cocktail-party graph), whose degree-11 Ehrhart polynomial is claimed to have exactly seven roots on Re z = -1/2 and four roots off it, refuting (i); and the pair K_{2,2,2,2,2,2}, K_{2,2,2,2,2,1}, claimed to violate a Wronskian inequality necessary for interlacing, refuting (ii). Proof with an exact lattice-point count and Descartes/sign-change root certificates in results/hkm-ehrhart/PROOF.md; exact verifier results/hkm-ehrhart/verify.py (also check_sturm.py, check_interlace.py); a second pair whose polynomials both stay on the line but fail to interlace is in INTERLACING-CL.md; Lean statement described in FORMALIZATION.md.
{"conjecture": "Higashitani-Kummer-Michalek Conjecture 4.10 (arXiv:1612.07538), clause (i)", "object": "complete multipartite graph, given by its part sizes", "parts": [2,2,2,2,2,2]}

Certificate format

Download CERTIFICATE.md
# Certificate: a counterexample to clause (i) of HKM Conjecture 4.10

## What the certificate is

`certificate.json` is a JSON object. Only one key matters:

- `"parts"`: a list of positive integers `[a_1, ..., a_k]`, the part sizes of a
  complete k-partite graph G. Here `[2,2,2,2,2,2]`, i.e. G = K_{2,2,2,2,2,2}
  (12 vertices, 60 edges; vertices 0,1 form part 0, vertices 2,3 part 1, etc.;
  two vertices are adjacent iff they are in different parts).

The other keys (`"conjecture"`, `"object"`) are human-readable labels and are ignored.

Claim settled: the Ehrhart polynomial H of the symmetric edge polytope P_G
(convex hull of all e_v - e_w, e_w - e_v over edges {v,w}) has degree 11 and
only 7 of its 11 roots (with multiplicity) on the line Re z = -1/2. So clause (i)
of the conjecture ("all roots on R") is false, hence the conjecture is false.
(Clause (ii) is not needed and is not checked.)

## What `verify.py` does (exact integers / fractions only, stdlib only)

1. Builds G and the generators ±(e_v - e_w) of P_G from `parts`.
2. Computes H(m) = |mP ∩ Z^12| for m = 0..14 using the membership lemma below.
3. Cross-checks the lemma-based count directly from the definition for m = 0,1,2,3:
   every integer zero-sum vector z with positive mass ≤ m is either written
   explicitly as a sum of ≤ m generators (so z ∈ mP, as 0 ∈ P), or separated by
   a linear functional L whose value on every generator is verified to be ≤ 1
   while L(z) > m (so z ∉ mP). Vectors with positive mass > m are outside mP
   because the 0/1 indicator functional of the positive support is ≤ 1 on every
   generator. The counts (1, 121, 4303, 70663) agree.
4. Interpolates the degree-11 polynomial through m = 0..11 (P_G has dimension
   11 because G is connected, so H has degree 11 and 12 values determine it)
   and checks it also reproduces m = 12, 13, 14.
5. Writes H(-1/2 + i t) = A(t) + i B(t) with A, B ∈ Q[t]. 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 gcd(A,B). The verifier checks gcd(A,B) is squarefree and counts
   its real roots with Sturm's theorem (exact rational arithmetic): 7.
   Since 7 < 11, four roots of H are off the line. Prints `VERIFIED`.

## The membership lemma used in step 2 (with proof)

Let the vertex set be partitioned into parts A_1..A_k, k ≥ 2. For an integer
vector z with coordinate sum 0 let p_i (q_i) be the sum of the positive
(absolute values of the negative) coordinates of z in A_i, and p = Σ p_i = Σ q_i.

**Lemma.** For integer m ≥ 0: z ∈ mP_G iff p ≤ m and p_i + q_i ≤ m for all i.

*Necessity.* The functions z ↦ Σ max(z_v,0) and z ↦ Σ_{v∈A_i} |z_v| are convex
and positively homogeneous, and are ≤ 1 on every generator e_u - e_v (u, v in
different parts, so at most one of them is in A_i). Hence they are ≤ m on mP.

*Sufficiency.* Regard z as p positive unit tokens and p negative unit tokens
sitting on vertices. Join a positive and a negative token when their vertices
lie in different parts. A set S of positive tokens meeting two parts is joined
to all p negative tokens; a set S inside part i is joined to exactly p - q_i
negative tokens. So the maximum Hall deficiency is h = max(0, max_i (p_i + q_i - p)),
and by the deficiency form of Hall's theorem there is a matching of size p - h.
Each matched pair is one generator e_u - e_v. The remaining h positive and h
negative tokens are paired arbitrarily; a pair in different parts is one
generator, a pair u, v in the same part is two generators
(e_u - e_w) + (e_w - e_v) with w in another part. So z is a sum of at most
(p - h) + 2h = max(p, max_i(p_i + q_i)) ≤ m generators. As 0 ∈ P (midpoint of
g and -g), z/m is a convex combination of generators and 0, so z ∈ mP. ∎

Counting: with the lemma, H(m) = number of ways to choose for each part an
integer vector with l1-norm ≤ m (classified by its positive mass u and negative
mass v, tabulated by brute enumeration), such that total positive mass = total
negative mass ≤ m. This is a small convolution.

## Result printed by the verifier

H(0..11) = 1, 121, 4303, 70663, 697975, 4811431, 25393537, 109149169,
398945035, 1279269867, 3683468685, 9693557805; roots on Re z = -1/2: 7 of 11.

## Provenance

The graph was taken from the public claim
https://github.com/1337isnot1337/solved-conjectures/tree/main/results/hkm-ehrhart .
None of the claimant's code or numbers are used by `verify.py`; the counts,
the polynomial and the root count are recomputed independently (they turn out
to agree with the claim).

Checker A, written alongside the certificate

Download checker_a.py
#!/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()

Checker B, written independently from the certificate alone

Download checker_b.py
#!/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()