#!/usr/bin/env python3
"""Independent checker for a claimed counterexample to Conjecture 7.3 of
Caiolo-Ferroni-Hoster, "Dual Chow polynomials of matroids and posets"
(arXiv:2605.28474).

Usage: python3 checker.py certificate.json

Definitions used (taken from the paper, Sections 2-4):
  mu          = zeta^{-1}                                    (Sec. 2.1)
  chi         = mu * zeta^rev                                (Def. 2.8)
  kappa*      = (chi^rev)^sgn,
                kappa*_{st}(x) = (-1)^{rho_st} sum_{s<=w<=t} mu_{sw} x^{rho_sw}
  kbar_{st}   = kappa*_{st}/(x-1) (s<t),  kbar_{ss} = -1     (Sec. 2.3)
  H*          = -(kbar)^{-1}                                 (Def. 2.4 + Def. 3.1)
  F*          = H* . (f*)^rev with f* = mu^sgn               (Def. 2.7, Sec. 4)
                F*_{st} = sum_w H*_{sw} (-x)^{rho_wt} mu_{wt}

Everything is exact integer / rational arithmetic.  The matroid of the
certificate is far too large to enumerate (about 7.4e9 points), so the checker

 (A) implements the definitions literally on explicit finite posets and tests
     that implementation against every worked example in the paper;
 (B) expands the same definitions into a sum over chains whose weights depend
     only on the ranks in the chain (flag f-vector formula), and tests (B)
     against (A);
 (C) counts the flag f-vector of the certificate's lattice of flats from the
     structure of the construction, with a parametrised counting routine
     (prime q, extension degree n; the certificate is n = 4), and tests that
     routine against brute-force enumeration of the matroid *from its basis
     rule* for (q,n) = (2,2), (3,2), (2,3), including a check of the matroid
     axioms there;
 (D) checks the finite algebraic facts on which the structural proof for the
     real parameters rests (q prime, modulus irreducible, the n^2 maps
     t -> z^i t^(q^j) are F_q-linearly independent, sample tests of the basis
     oracle);
 (E) computes H* and F* for the certificate, and decides the existence of a
     non-real zero with an exact Sturm-sequence root count (cross-checked by
     the gamma-discriminant argument and by sympy if available).

VERIFIED is printed only if H*_M has a non-real zero (this alone refutes
Conjecture 7.3).  The status of F* is reported as well.
"""
import sys
import json
import random
from fractions import Fraction
from itertools import combinations, product
from math import comb


class Fail(Exception):
    pass


def need(cond, msg):
    if not cond:
        raise Fail(msg)


# ----------------------------------------------------------------------------
# integer polynomials: lists of ints, constant term first, no trailing zeros
# ----------------------------------------------------------------------------
def ptrim(a):
    a = list(a)
    while a and a[-1] == 0:
        a.pop()
    return a


def padd(a, b):
    n = max(len(a), len(b))
    r = [0] * n
    for i, v in enumerate(a):
        r[i] += v
    for i, v in enumerate(b):
        r[i] += v
    return ptrim(r)


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


def pmul(a, b):
    if not a or not b:
        return []
    r = [0] * (len(a) + len(b) - 1)
    for i, u in enumerate(a):
        if u:
            for j, v in enumerate(b):
                r[i + j] += u * v
    return ptrim(r)


def pshift(a, k):
    return ([0] * k + list(a)) if a else []


def pdiv_xm1(a):
    """exact division by (x-1); raises if not divisible"""
    a = ptrim(a)
    if not a:
        return []
    # synthetic division from the top
    out = [0] * (len(a) - 1)
    carry = 0
    for i in range(len(a) - 1, 0, -1):
        carry = a[i] + carry
        out[i - 1] = carry
    need(a[0] + carry == 0, "internal: kernel not divisible by x-1")
    return ptrim(out)


def pstr(a):
    return "[" + ", ".join(str(v) for v in a) + "]"


# ----------------------------------------------------------------------------
# (A) literal implementation of the definitions on an explicit bounded poset
# ----------------------------------------------------------------------------
def raw_dual_chow(ranks, up):
    """ranks[i]: rank of element i; up[i]: list of elements strictly above i.
    Element 0 is the minimum, the last element is the maximum.
    Returns (H*_{0,1}, F*_{0,1}) computed literally from the definitions."""
    N = len(ranks)
    top = N - 1
    order = sorted(range(N), key=lambda i: ranks[i])
    # Moebius function mu[s][t] for s <= t, by mu_st = -sum_{s<=w<t} mu_sw
    mu = [None] * N
    kbar = [None] * N
    for s in range(N):
        above = sorted(up[s], key=lambda i: ranks[i])
        acc = {t: 0 for t in above}
        m = {s: 1}
        for t in up[s]:
            acc[t] += 1
        for w in above:
            m[w] = -acc[w]
            if m[w]:
                for t in up[w]:
                    acc[t] += m[w]
        mu[s] = m
        # kappa*_{st} = (-1)^{rho_st} sum_{s<=w<=t} mu_sw x^{rho_sw}
        kap = {t: [] for t in above}
        for w in [s] + above:
            if m[w] == 0:
                continue
            term = pshift([m[w]], ranks[w] - ranks[s])
            if w != s:
                kap[w] = padd(kap[w], term)
            for t in up[w]:
                kap[t] = padd(kap[t], term)
        kb = {}
        for t in above:
            sg = -1 if (ranks[t] - ranks[s]) % 2 else 1
            kb[t] = pdiv_xm1(pscale(kap[t], sg))
        kbar[s] = kb
    # H*_{s,top}: from kbar . H* = -delta:  H*_{st} = sum_{s<w<=t} kbar_sw H*_wt
    Htop = [None] * N
    for s in reversed(order):
        if s == top:
            Htop[s] = [1]
            continue
        acc = []
        for w in up[s]:
            acc = padd(acc, pmul(kbar[s][w], Htop[w]))
        Htop[s] = acc
    # H*_{0,t}: from H* . kbar = -delta:  H*_{0t} = sum_{0<=w<t} H*_{0w} kbar_wt
    Hbot = [None] * N
    Hbot[0] = [1]
    pend = [[] for _ in range(N)]
    for w in order:
        if w != 0:
            Hbot[w] = pend[w]
        for t in up[w]:
            pend[t] = padd(pend[t], pmul(Hbot[w], kbar[w][t]))
    need(Hbot[top] == Htop[0], "internal: left and right inverse recursions disagree")
    # F*_{0,top} = sum_w H*_{0w} (-x)^{rho_{w,top}} mu_{w,top}
    F = []
    for w in range(N):
        mw = mu[w].get(top, 0)
        if mw == 0:
            continue
        d = ranks[top] - ranks[w]
        F = padd(F, pshift(pscale(Hbot[w], mw * (-1) ** d), d))
    return Htop[0], F


# ----------------------------------------------------------------------------
# (B) the same definitions expanded over chains: weights depending on ranks only
# ----------------------------------------------------------------------------
def chain_weights(r):
    """For every subset S of {1..r-1} return polynomials (wH[S], wF[S]) with
         H*_P = sum_S f_S wH[S],   F*_P = sum_S f_S wF[S]
    for every graded bounded poset P of rank r, where f_S is the number of
    chains 0 < t_1 < ... < t_k < 1 whose rank set is exactly S.

    Derivation (Lemma 2.1 applied to a = -kbar):
       H*_{st} = sum over chains s=s_0<...<s_m=t of prod kbar_{s_{i-1} s_i},
       kbar_{ab} = (-1)^{rho_ab}/(x-1) * sum_{a<=w<=b} mu_{aw} x^{rho_aw},
       mu_{aw}   = sum over chains a=c_0<...<c_k=w of (-1)^k.
    Merging all chosen elements into one chain T, a segment of T between two
    consecutive s-elements a<b with j interior elements arises in exactly two
    ways: w=b (k=j+1) or w = last interior element (or a itself if j=0) (k=j).
    """
    res = {}
    for S in product([0, 1], repeat=r - 1):
        rk = [0] + [i + 1 for i in range(r - 1) if S[i]] + [r]
        n = len(rk) - 1
        # seg[i][j]: weight of a segment from T[i] to T[j] (a kbar factor)
        seg = {}
        for i in range(n + 1):
            for j in range(i + 1, n + 1):
                inner = j - i - 1
                d = rk[j] - rk[i]
                num = padd(pshift([(-1) ** (inner + 1)], d),
                           pshift([(-1) ** inner], rk[j - 1] - rk[i]))
                num = pscale(num, (-1) ** d)
                seg[i, j] = pdiv_xm1(num)
        # W[j] = H*-type weight of the chain T[0..j] with T[j] an s-element
        W = [None] * (n + 1)
        W[0] = [1]
        for j in range(1, n + 1):
            acc = []
            for i in range(j):
                acc = padd(acc, pmul(W[i], seg[i, j]))
            W[j] = acc
        # F*: choose w = T[j]; the elements after it form a mu-chain to the top
        Fw = []
        for j in range(n + 1):
            d = r - rk[j]
            k = n - j
            Fw = padd(Fw, pshift(pscale(W[j], (-1) ** k * (-1) ** d), d))
        key = tuple(i + 1 for i in range(r - 1) if S[i])
        res[key] = (W[n], Fw)
    return res


def polys_from_flags(r, flags):
    wts = chain_weights(r)
    need(set(wts) == set(flags), "internal: flag vector has wrong index set")
    H, F = [], []
    for S, (wH, wF) in wts.items():
        H = padd(H, pscale(wH, flags[S]))
        F = padd(F, pscale(wF, flags[S]))
    return H, F


# ----------------------------------------------------------------------------
# explicit matroids given by a list of bases (bitmasks); lattice of flats
# ----------------------------------------------------------------------------
def bits(mask):
    out = []
    i = 0
    while mask:
        if mask & 1:
            out.append(i)
        mask >>= 1
        i += 1
    return out


def flats_from_bases(nE, r, bases):
    """bases: set of bitmasks of r-subsets.  Independent sets are the subsets of
    bases; flats of rank k are closures of independent k-sets."""
    indep = [None] * (r + 1)
    indep[r] = set(bases)
    for k in range(r - 1, -1, -1):
        cur = set()
        for B in indep[k + 1]:
            m = B
            while m:
                low = m & -m
                cur.add(B ^ low)
                m ^= low
        indep[k] = cur
    full = (1 << nE) - 1
    flats = [None] * (r + 1)
    for k in range(r):
        fl = set()
        nxt = indep[k + 1]
        for I in indep[k]:
            c = I
            for e in range(nE):
                b = 1 << e
                if not (I & b) and (I | b) not in nxt:
                    c |= b
            fl.add(c)
        flats[k] = sorted(fl)
    flats[r] = [full]
    return indep, flats


def check_flat_axioms(nE, r, flats):
    """Flat axioms: unique minimal flat, E is a flat, and for every flat F of
    rank k<r the flats of rank k+1 containing F partition E \\ F."""
    full = (1 << nE) - 1
    need(len(flats[0]) == 1 and flats[r] == [full], "test matroid: bad bottom/top")
    for k in range(r):
        for F in flats[k]:
            cov = 0
            tot = 0
            for G in flats[k + 1]:
                if G & F == F:
                    need(G != F, "test matroid: flat repeated in two ranks")
                    need((G ^ F) & cov == 0, "test matroid: covers overlap")
                    cov |= G ^ F
                    tot += 1
            need(cov == full ^ F, "test matroid: covers do not partition")
    return True


def check_basis_exchange(bases):
    bl = list(bases)
    for A in bl:
        for B in bl:
            d = A & ~B
            add = B & ~A
            m = d
            while m:
                x = m & -m
                m ^= x
                ok = False
                y = add
                while y:
                    yy = y & -y
                    y ^= yy
                    if ((A ^ x) | yy) in bases:
                        ok = True
                        break
                need(ok, "test matroid: basis exchange fails")
    return True


def poset_from_flats(r, flats):
    elems = []
    ranks = []
    for k in range(r + 1):
        for F in flats[k]:
            elems.append(F)
            ranks.append(k)
    N = len(elems)
    start = [0] * (r + 2)
    for k in range(r + 1):
        start[k + 1] = start[k] + len(flats[k])
    up = [[] for _ in range(N)]
    for i in range(N):
        F = elems[i]
        for j in range(start[ranks[i] + 1], N):
            if elems[j] & F == F:
                up[i].append(j)
    return ranks, up


def flag_vector(r, ranks, up):
    """number of chains by exact rank set S subset of {1..r-1}"""
    N = len(ranks)
    res = {}
    for S in product([0, 1], repeat=r - 1):
        key = tuple(i + 1 for i in range(r - 1) if S[i])
        # count chains 0 < t1 < ... < tk with prescribed ranks
        cnt = {0: 1}
        for rkv in key:
            nxt = {}
            for a, c in cnt.items():
                for b in up[a]:
                    if ranks[b] == rkv:
                        nxt[b] = nxt.get(b, 0) + c
            cnt = nxt
        res[key] = sum(cnt.values())
    return res


# ----------------------------------------------------------------------------
# finite fields K = F_q[z]/(modulus)
# ----------------------------------------------------------------------------
def is_prime(q):
    if not isinstance(q, int) or isinstance(q, bool) or q < 2:
        return False
    i = 2
    while i * i <= q:
        if q % i == 0:
            return False
        i += 1
    return True


def poly_mod_q_divides(f, g, q):
    """does monic g divide f over F_q (lists, constant first)"""
    f = [v % q for v in f]
    dg = len(g) - 1
    for i in range(len(f) - 1, dg - 1, -1):
        c = f[i]
        if c:
            for j in range(dg + 1):
                f[i - dg + j] = (f[i - dg + j] - c * g[j]) % q
    return all(v == 0 for v in f[:dg])


def is_irreducible(mod, q):
    """monic mod of degree n over F_q, q prime: no monic factor of degree <= n/2"""
    n = len(mod) - 1
    if n < 1 or mod[-1] % q != 1:
        return False
    for d in range(1, n // 2 + 1):
        for low in product(range(q), repeat=d):
            if poly_mod_q_divides(mod, list(low) + [1], q):
                return False
    return True


class Field:
    def __init__(self, q, mod):
        self.q = q
        self.mod = [v % q for v in mod]
        self.n = len(mod) - 1
        self.zero = tuple([0] * self.n)
        self.one = tuple([1] + [0] * (self.n - 1))

    def add(self, a, b):
        q = self.q
        return tuple((x + y) % q for x, y in zip(a, b))

    def sub(self, a, b):
        q = self.q
        return tuple((x - y) % q for x, y in zip(a, b))

    def mul(self, a, b):
        q, n, mod = self.q, self.n, self.mod
        r = [0] * (2 * n - 1)
        for i, u in enumerate(a):
            if u:
                for j, v in enumerate(b):
                    r[i + j] += u * v
        for i in range(2 * n - 2, n - 1, -1):
            c = r[i] % q
            if c:
                for j in range(n):
                    r[i - n + j] -= c * mod[j]
            r[i] = 0
        return tuple(v % q for v in r[:n])

    def pow(self, a, e):
        res = self.one
        while e:
            if e & 1:
                res = self.mul(res, a)
            a = self.mul(a, a)
            e >>= 1
        return res

    def inv(self, a):
        need(a != self.zero, "internal: inverse of zero")
        r = self.pow(a, self.q ** self.n - 2)
        need(self.mul(r, a) == self.one, "field check failed: element has no inverse")
        return r

    def frob(self, a, j):
        return self.pow(a, self.q ** j)

    def elements(self):
        return product(range(self.q), repeat=self.n)

    def graph_map(self, c, t):
        """f(t) = sum_j c_j t^(q^j)"""
        acc = self.zero
        tp = t
        for j in range(self.n):
            acc = self.add(acc, self.mul(c[j], tp))
            tp = self.pow(tp, self.q)
        return acc


def rank_mod_q(rows, q):
    rows = [list(r) for r in rows]
    rk = 0
    ncol = len(rows[0]) if rows else 0
    for col in range(ncol):
        piv = None
        for i in range(rk, len(rows)):
            if rows[i][col] % q:
                piv = i
                break
        if piv is None:
            continue
        rows[rk], rows[piv] = rows[piv], rows[rk]
        inv = pow(rows[rk][col], q - 2, q)
        rows[rk] = [(v * inv) % q for v in rows[rk]]
        for i in range(len(rows)):
            if i != rk and rows[i][col] % q:
                c = rows[i][col]
                rows[i] = [(a - c * b) % q for a, b in zip(rows[i], rows[rk])]
        rk += 1
    return rk


def frobenius_maps_independent(K):
    """The n^2 F_q-linear maps t -> z^i t^(q^j) are linearly independent over
    F_q in End_{F_q}(K).  Hence the q^(n^2) graph maps are pairwise distinct and
    are exactly all F_q-linear maps K -> K."""
    n, q = K.n, K.q
    basis = [tuple(1 if a == b else 0 for a in range(n)) for b in range(n)]
    rows = []
    for i in range(n):
        for j in range(n):
            row = []
            for b in basis:
                row.extend(K.mul(basis[i], K.frob(b, j)))
            rows.append(row)
    return rank_mod_q(rows, q) == n * n


# ----------------------------------------------------------------------------
# brute-force construction of the matroid from its basis rule (small q, n)
# ----------------------------------------------------------------------------
def normalize(v, q):
    for x in v:
        if x:
            inv = pow(x, q - 2, q)
            return tuple((y * inv) % q for y in v)
    return None


def brute_matroid(q, mod):
    """Ground set and bases exactly as in CERTIFICATE.md, for a degree-n
    extension (rank n+1, auxiliary index n-1).  Returns nE, r, set of bases."""
    K = Field(q, mod)
    n = K.n
    r = n + 1
    pts = [v for v in product(range(q), repeat=2 * n) if any(v) and normalize(v, q) == v]
    idx = {v: i for i, v in enumerate(pts)}
    aux = list(K.elements())
    aidx = {a: len(pts) + i for i, a in enumerate(aux)}
    nE = len(pts) + len(aux)
    # blocks
    nonzero = [t for t in K.elements() if any(t)]
    blocks = set()
    for c in product(aux, repeat=n):
        m = 1 << aidx[c[n - 1]]
        for t in nonzero:
            v = normalize(t + K.graph_map(c, t), q)
            m |= 1 << idx[v]
        blocks.add(m)
    need(len(blocks) == q ** (n * n), "test matroid: graphs not distinct")
    # r-subsets contained in a block
    inblock = set()
    for B in blocks:
        for sub in combinations(bits(B), r):
            m = 0
            for e in sub:
                m |= 1 << e
            inblock.add(m)
    # N-independent r-sets: geometric vectors independent (aux always distinct)
    bases = set()
    npts = len(pts)

    def reduce(v, ech):
        v = list(v)
        for piv, w in ech:
            c = v[piv]
            if c:
                v = [(a - c * b) % q for a, b in zip(v, w)]
        for i, x in enumerate(v):
            if x:
                inv = pow(x, q - 2, q)
                return i, [(y * inv) % q for y in v]
        return None

    def rec(start, mask, size, ech):
        if size == r:
            if mask not in inblock:
                bases.add(mask)
            return
        for e in range(start, nE):
            if e < npts:
                red = reduce(pts[e], ech)
                if red is None:
                    continue
                rec(e + 1, mask | (1 << e), size + 1, ech + [red])
            else:
                rec(e + 1, mask | (1 << e), size + 1, ech)

    rec(0, 0, 0, [])
    return nE, r, bases


# ----------------------------------------------------------------------------
# (C) structural flag f-vector of the construction for general (q, n)
# ----------------------------------------------------------------------------
def gauss(n, k, q):
    if k < 0 or k > n:
        return 0
    num = 1
    den = 1
    for i in range(k):
        num *= q ** n - q ** i
        den *= q ** k - q ** i
    need(num % den == 0, "internal: gaussian binomial not integral")
    return num // den


def chains_in_product(d, a, desc_ranks, q, memo):
    """number of chains with the given (descending) ranks in the lattice
    L(F_q^d) x Boolean(a); all ranks are below the rank of the current top."""
    if not desc_ranks:
        return 1
    key = (d, a, desc_ranks)
    if key in memo:
        return memo[key]
    k = desc_ranks[0]
    tot = 0
    for d2 in range(0, min(d, k) + 1):
        a2 = k - d2
        if a2 > a:
            continue
        tot += gauss(d, d2, q) * comb(a, a2) * chains_in_product(d2, a2, desc_ranks[1:], q, memo)
    memo[key] = tot
    return tot


def structural_flags(q, n):
    """Flag f-vector of the lattice of flats of the matroid built from
    K = F_(q^n): ground set PG(K x K) plus q^n auxiliary points, rank n+1.

    Flats (see notes.md for the proof):
      rank k <= n-1 : pairs (U, A), U <= K x K subspace, A set of labels,
                      dim U + |A| = k;
      rank n        : the q^(n^2) blocks (graph, {label}); and the pairs (U, A)
                      with dim U + |A| = n not contained in a block, i.e. those
                      with |A| >= 2, or |A| <= 1 and U meeting 0 x K nontrivially;
      rank n+1      : the ground set.
    The interval below a block is {(U', A') : U' <= graph, A' <= {label},
    rank <= n-1} plus the block itself."""
    t = q ** n
    r = n + 1
    memo = {}
    # hyperplane families: (count, d, a) with lower interval L(F_q^d) x B_a
    fam = []
    for d in range(0, n + 1):
        a = n - d
        total = gauss(2 * n, d, q)
        # subspaces meeting the vertical space trivially = graphs of linear
        # maps on a d-subspace of K
        trivial = gauss(n, d, q) * q ** (d * n)
        # cross-check through the decomposition by vertical intersection dimension
        dec = sum(gauss(n, j, q) * gauss(n, d - j, q) * q ** ((d - j) * (n - j))
                  for j in range(0, d + 1))
        need(dec == total, "internal: subspace count identity fails")
        if a >= 2:
            cnt = total * comb(t, a)
        else:
            cnt = (total - trivial) * comb(t, a)
        need(cnt >= 0, "internal: negative count")
        fam.append((cnt, d, a))
    fam.append((q ** (n * n), n, 1))  # blocks
    flags = {}
    for S in product([0, 1], repeat=r - 1):
        key = tuple(i + 1 for i in range(r - 1) if S[i])
        if n in key:
            rest = tuple(sorted((k for k in key if k != n), reverse=True))
            val = sum(cnt * chains_in_product(d, a, rest, q, memo) for cnt, d, a in fam)
        else:
            val = chains_in_product(2 * n, t, tuple(sorted(key, reverse=True)), q, memo)
        flags[key] = val
    return flags


# ----------------------------------------------------------------------------
# exact real-root counting
# ----------------------------------------------------------------------------
def fdeg(p):
    return len(p) - 1


def ftrim(p):
    p = list(p)
    while p and p[-1] == 0:
        p.pop()
    return p


def fdivmod(a, b):
    a = [Fraction(v) for v in a]
    b = [Fraction(v) for v in b]
    qt = [Fraction(0)] * max(len(a) - len(b) + 1, 0)
    while len(a) >= len(b) and a:
        c = a[-1] / b[-1]
        k = len(a) - len(b)
        qt[k] = c
        for i, v in enumerate(b):
            a[i + k] -= c * v
        a = ftrim(a)
    return ftrim(qt), a


def fgcd(a, b):
    a, b = ftrim(a), ftrim(b)
    while b:
        _, rem = fdivmod(a, b)
        a, b = b, rem
    return a


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


def count_real_roots(p):
    """(number of distinct real roots, number of distinct complex roots) of a
    nonzero integer polynomial, via the Sturm sequence of its squarefree part."""
    p = ftrim([Fraction(v) for v in p])
    need(len(p) >= 2, "polynomial is constant")
    g = fgcd(p, fderiv(p))
    sf, rem = fdivmod(p, g)
    need(not rem, "internal: squarefree division")
    seq = [sf, fderiv(sf)]
    while seq[-1]:
        _, rem = fdivmod(seq[-2], seq[-1])
        seq.append([-v for v in rem])
    seq.pop()

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

    def sgn(v):
        return (v > 0) - (v < 0)

    neg = [sgn(s[-1]) * (-1) ** fdeg(s) for s in seq]
    pos = [sgn(s[-1]) for s in seq]
    return variations(neg) - variations(pos), fdeg(sf)


def gamma_vector(p):
    """p palindromic of degree d = sum g_i x^i (1+x)^(d-2i); returns g or None"""
    d = len(p) - 1
    rem = list(p)
    g = []
    for i in range(d // 2 + 1):
        gi = rem[i]
        g.append(gi)
        term = pshift(pscale([comb(d - 2 * i, k) for k in range(d - 2 * i + 1)], gi), i)
        rem = padd(rem, pscale(term, -1))
        rem = rem + [0] * (d + 1 - len(rem))
    if any(rem):
        return None
    return g


# ----------------------------------------------------------------------------
# self tests tying the implementation to the paper
# ----------------------------------------------------------------------------
def eulerian(n):
    if n == 0:
        return [1]
    from itertools import permutations
    co = [0] * n
    for w in permutations(range(n)):
        co[sum(1 for i in range(n - 1) if w[i] > w[i + 1])] += 1
    return ptrim(co)


def uniform_formula(r, n):
    H = [comb(n - 1, r - 1)]
    for j in range(0, r - 1):
        c = comb(n, j) * comb(n - j - 1, r - j - 1)
        H = padd(H, pmul(pscale(eulerian(j), c), [0] + [1] * (r - j - 1)))
    F = [comb(n - 1, r - 1)]
    for j in range(0, r):
        c = comb(n, j) * comb(n - j - 1, r - j - 1)
        F = padd(F, pmul(pscale(eulerian(j), c), [0] + [1] * (r - j)))
    return H, F


def uniform_bases(r, n):
    out = set()
    for sub in combinations(range(n), r):
        m = 0
        for e in sub:
            m |= 1 << e
        out.add(m)
    return out


def complete_graph_bases(v):
    edges = list(combinations(range(v), 2))
    out = set()
    for sub in combinations(range(len(edges)), v - 1):
        par = list(range(v))

        def find(a):
            while par[a] != a:
                par[a] = par[par[a]]
                a = par[a]
            return a

        ok = True
        for e in sub:
            a, b = find(edges[e][0]), find(edges[e][1])
            if a == b:
                ok = False
                break
            par[a] = b
        if ok:
            m = 0
            for e in sub:
                m |= 1 << e
            out.add(m)
    return len(edges), out


def analyse_explicit(nE, r, bases, raw=True):
    indep, flats = flats_from_bases(nE, r, bases)
    check_flat_axioms(nE, r, flats)
    ranks, up = poset_from_flats(r, flats)
    fl = flag_vector(r, ranks, up)
    Hf, Ff = polys_from_flags(r, fl)
    if raw:
        Hr, Fr = raw_dual_chow(ranks, up)
        need(Hr == Hf and Fr == Ff,
             "self-test: chain-weight formula disagrees with the literal definition")
    return fl, Hf, Ff


def self_tests():
    # --- worked examples of the paper -------------------------------------
    # Example 4.4: U_{3,4}
    _, H, F = analyse_explicit(4, 3, uniform_bases(3, 4))
    need(H == [3, 11, 3], "self-test: Example 4.4 (U_{3,4}) not reproduced: " + pstr(H))
    # Example 4.5: partition lattices Pi_2, Pi_3, Pi_4
    for v, expect in ((3, [2, 2]), (4, [6, 18, 6]), (5, [24, 154, 154, 24])):
        nE, bs = complete_graph_bases(v)
        _, H, F = analyse_explicit(nE, v - 1, bs)
        need(H == expect, "self-test: Example 4.5 (Pi_%d) not reproduced: %s" % (v - 1, pstr(H)))
    # Proposition 6.8: Boolean matroids, Eulerian and binomial Eulerian polynomials
    for r in (1, 2, 3, 4, 5):
        _, H, F = analyse_explicit(r, r, uniform_bases(r, r))
        need(H == eulerian(r), "self-test: Prop 6.8 (H* of Boolean) fails, r=%d" % r)
        bin_eul = [1]
        for k in range(1, r + 1):
            bin_eul = padd(bin_eul, pshift(pscale(eulerian(k), comb(r, k)), 1))
        need(F == bin_eul, "self-test: Prop 6.8 (F* of Boolean) fails, r=%d" % r)
    # Proposition 6.9: uniform matroids
    for r, n in ((2, 5), (3, 5), (3, 6), (4, 6), (5, 7)):
        _, H, F = analyse_explicit(n, r, uniform_bases(r, n))
        He, Fe = uniform_formula(r, n)
        need(H == He and F == Fe, "self-test: Prop 6.9 fails for U_{%d,%d}" % (r, n))
    print("self-test: paper examples 4.4, 4.5 and Propositions 6.8, 6.9 reproduced "
          "from the literal definitions and from the chain-weight formula")

    # --- Sturm root counter ---------------------------------------------------
    need(count_real_roots([4, 39, 120, 120, 39, 4]) == (1, 5),
         "self-test: Remark 7.4 polynomial should have exactly one real zero")
    need(count_real_roots([3, 11, 3]) == (2, 2), "self-test: Sturm")
    need(count_real_roots([1, 2, 1]) == (1, 1), "self-test: Sturm (repeated root)")
    need(count_real_roots([1, 0, 1]) == (0, 2), "self-test: Sturm")
    need(count_real_roots([-6, 11, -6, 1]) == (3, 3), "self-test: Sturm")
    need(count_real_roots([1, 0, 2, 0, 1]) == (0, 2), "self-test: Sturm")
    print("self-test: Sturm root counter ok (incl. the non-real-rooted example of Remark 7.4)")

    # --- small instances of the construction, built from the basis rule ------
    for q, mod, raw, exch in ((2, [1, 1, 1], True, True),
                              (3, [1, 0, 1], True, False),
                              (2, [1, 1, 0, 1], True, False)):
        n = len(mod) - 1
        need(is_irreducible(mod, q), "self-test: test modulus reducible")
        need(frobenius_maps_independent(Field(q, mod)), "self-test: Frobenius maps dependent")
        nE, r, bases = brute_matroid(q, mod)
        if exch:
            check_basis_exchange(bases)
        fl, H, F = analyse_explicit(nE, r, bases, raw=raw)
        st = structural_flags(q, n)
        need(fl == st, "self-test: structural flag count disagrees with brute force "
                       "for q=%d n=%d" % (q, n))
        print("self-test: construction with q=%d, n=%d (|E|=%d, rank %d, %d bases): flat axioms "
              "hold; brute-force flag f-vector = structural count; H*=%s F*=%s"
              % (q, n, nE, r, len(bases), pstr(H), pstr(F)))


# ----------------------------------------------------------------------------
# the certificate's matroid: basis oracle for the real parameters
# ----------------------------------------------------------------------------
class BigMatroid:
    """Ground set: ('g', v) with v a normalized nonzero vector of F_q^(2n);
    ('a', label) with label in F_q^n.  Rank n+1."""

    def __init__(self, q, mod):
        self.K = Field(q, mod)
        self.q = q
        self.n = self.K.n

    def solve_K(self, rows, rhs):
        """Solve the K-linear system rows * c = rhs; returns None if
        inconsistent, else one solution (free variables 0) and the rank."""
        K = self.K
        m = len(rows)
        nc = len(rows[0]) if rows else 0
        A = [list(rw) + [b] for rw, b in zip(rows, rhs)]
        piv_cols = []
        rk = 0
        for col in range(nc):
            p = None
            for i in range(rk, m):
                if A[i][col] != K.zero:
                    p = i
                    break
            if p is None:
                continue
            A[rk], A[p] = A[p], A[rk]
            inv = K.inv(A[rk][col])
            A[rk] = [K.mul(inv, v) for v in A[rk]]
            for i in range(m):
                if i != rk and A[i][col] != K.zero:
                    c = A[i][col]
                    A[i] = [K.sub(a, K.mul(c, b)) for a, b in zip(A[i], A[rk])]
            piv_cols.append(col)
            rk += 1
        for i in range(rk, m):
            if A[i][nc] != K.zero:
                return None, rk
        sol = [K.zero] * nc
        for i, col in enumerate(piv_cols):
            sol[col] = A[i][nc]
        return sol, rk

    def in_some_block(self, geo, aux):
        """is the set (geometric vectors geo, aux labels aux) inside a block"""
        K, n = self.K, self.n
        if len(set(aux)) >= 2:
            return False
        rows, rhs = [], []
        for v in geo:
            u, w = tuple(v[:n]), tuple(v[n:])
            fr = [K.frob(u, j) for j in range(n)]
            if aux:
                rows.append(fr[:n - 1])
                rhs.append(K.sub(w, K.mul(aux[0], fr[n - 1])))
            else:
                rows.append(fr)
                rhs.append(w)
        if not rows:
            return True
        sol, _ = self.solve_K(rows, rhs)
        return sol is not None

    def is_basis(self, elems):
        n, q = self.n, self.q
        if len(elems) != n + 1 or len(set(elems)) != n + 1:
            return False
        geo = [e[1] for e in elems if e[0] == 'g']
        aux = [e[1] for e in elems if e[0] == 'a']
        if geo and rank_mod_q(geo, q) != len(geo):
            return False
        return not self.in_some_block(geo, aux)


def big_spot_checks(M, rng):
    K, n, q = M.K, M.n, M.q
    # coordinate axes form a basis
    axes = []
    for i in range(n + 1):
        v = [0] * (2 * n)
        v[i] = 1
        axes.append(('g', tuple(v)))
    need(M.is_basis(axes), "the first n+1 coordinate axes are not a basis")

    def rand_elt():
        return tuple(rng.randrange(q) for _ in range(n))

    trials = 12
    for _ in range(trials):
        # Frobenius is additive and F_q-linear
        a, b = rand_elt(), rand_elt()
        s = rng.randrange(q)
        sa = tuple((s * x) % q for x in a)
        for j in range(n):
            need(K.frob(K.add(a, b), j) == K.add(K.frob(a, j), K.frob(b, j)),
                 "Frobenius power is not additive")
            need(K.frob(sa, j) == tuple((s * x) % q for x in K.frob(a, j)),
                 "Frobenius power is not F_q-linear")
        need(K.frob(a, n) == a, "x^(q^n) != x in K")
        # n independent points on a graph + its label: dependent; other label: basis
        c = [rand_elt() for _ in range(n)]
        while True:
            ts = [rand_elt() for _ in range(n)]
            if rank_mod_q(ts, q) == n:
                break
        geo = [normalize(t + K.graph_map(c, t), q) for t in ts]
        need(rank_mod_q(geo, q) == n, "internal: graph points dependent")
        el = [('g', g) for g in geo]
        need(not M.is_basis(el + [('a', c[n - 1])]), "points of a block plus its label form a basis")
        other = K.add(c[n - 1], K.one)
        need(M.is_basis(el + [('a', other)]),
             "n independent graph points plus a foreign label should be a basis")
        # (n-1)-space with trivial vertical part + any label lies in exactly one block:
        # the K-linear system for c_0..c_{n-2} is uniquely solvable (Moore matrix)
        sub = ts[:n - 1]
        rows = [[K.frob(u, j) for j in range(n - 1)] for u in sub]
        rhs = [rand_elt() for _ in range(n - 1)]
        sol, rk = M.solve_K(rows, rhs)
        need(sol is not None and rk == n - 1, "Moore matrix of independent elements is singular")
        # a point with nonzero vertical component over the same base point breaks containment
        vert = normalize(tuple([0] * n) + rand_elt(), q)
        if vert is not None:
            test = el[:n - 1] + [('g', vert), ('a', c[n - 1])]
            geo2 = [e[1] for e in test if e[0] == 'g']
            if rank_mod_q(geo2, q) == n:
                need(M.is_basis(test), "a set containing a vertical point lies in a block")
    return trials


# ----------------------------------------------------------------------------
def main(argv):
    if len(argv) != 2:
        raise Fail("usage: python3 checker.py certificate.json")
    try:
        with open(argv[1], "r", encoding="utf-8") as fh:
            cert = json.load(fh)
    except Exception as exc:  # malformed input
        raise Fail("cannot read certificate: %r" % (exc,))
    need(isinstance(cert, dict), "certificate is not a JSON object")
    expected_keys = {"prime", "field_modulus", "frobenius_indices", "auxiliary_index", "rank"}
    need(set(cert.keys()) == expected_keys,
         "certificate fields are %s, expected %s" % (sorted(cert.keys()), sorted(expected_keys)))

    def is_int(v):
        return isinstance(v, int) and not isinstance(v, bool)

    q = cert["prime"]
    mod = cert["field_modulus"]
    need(is_int(q) and is_prime(q), "prime is not a prime integer")
    need(q <= 64, "prime too large for this checker's exhaustive irreducibility test")
    need(isinstance(mod, list) and len(mod) == 5 and all(is_int(v) for v in mod),
         "field_modulus is not a list of five integers")
    need(all(0 <= v < q for v in mod) and mod[4] == 1,
         "field_modulus is not a reduced monic quartic")
    need(cert["frobenius_indices"] == [0, 1, 2, 3] and all(is_int(v) for v in cert["frobenius_indices"]),
         "frobenius_indices must be [0, 1, 2, 3]")
    need(is_int(cert["auxiliary_index"]) and cert["auxiliary_index"] == 3, "auxiliary_index must be 3")
    need(is_int(cert["rank"]) and cert["rank"] == 5, "rank must be 5")
    n = 4
    r = 5
    print("certificate: q=%d, modulus=%s, K=F_q[z]/(modulus), rank %d" % (q, pstr(mod), r))

    # (A)(B)(C) self tests
    self_tests()

    # (D) algebraic facts for the real parameters
    need(is_irreducible(mod, q), "field_modulus is reducible over F_q, so K is not a field")
    K = Field(q, mod)
    need(frobenius_maps_independent(K),
         "the maps t -> z^i t^(q^j) are linearly dependent: graph maps not distinct")
    print("field: modulus irreducible, |K| = %d; the %d maps z^i t^(q^j) are F_q-independent, "
          "so the %d graphs are distinct and are all graphs of F_q-linear maps K->K"
          % (q ** n, n * n, q ** (n * n)))
    M = BigMatroid(q, mod)
    tr = big_spot_checks(M, random.Random(20261125))
    print("basis oracle: coordinate axes form a basis; %d randomized consistency rounds passed" % tr)
    npts = (q ** (2 * n) - 1) // (q - 1)
    print("ground set: %d geometric points + %d auxiliary points = %d elements"
          % (npts, q ** n, npts + q ** n))

    # (E) flag f-vector and the polynomials
    flags = structural_flags(q, n)
    for S in sorted(flags, key=lambda s: (len(s), s)):
        print("flag f_%s = %d" % (list(S), flags[S]))
    H, F = polys_from_flags(r, flags)
    print("dual Chow polynomial H* (constant term first): " + pstr(H))
    print("dual right augmented Chow polynomial F* (constant term first): " + pstr(F))

    need(len(H) == r and len(F) == r + 1, "unexpected degrees")
    need(H == H[::-1], "H* is not palindromic (contradicts Prop. 2.5)")
    need(F == F[::-1], "F* is not palindromic (contradicts rev-invariance)")
    need(all(v > 0 for v in H) and all(v > 0 for v in F), "coefficients not positive")

    # internal consistency with Prop. 4.7:  x H*(x) = sum_w (-1)^{rho_w1} F*_{0w}
    # cannot be evaluated without all intervals; instead use Prop. 2.5(1):
    # leading coefficient of H* = (-1)^r mu(0,1), computed from the flag vector.
    mu01 = sum((-1) ** (len(S) + 1) * v for S, v in flags.items())
    need(H[-1] == (-1) ** r * mu01, "leading coefficient of H* is not (-1)^r mu(0,1)")
    print("check: leading coefficient of H* equals (-1)^r mu(0,1) = %d" % H[-1])

    results = {}
    for name, P in (("H*", H), ("F*", F)):
        real, distinct = count_real_roots(P)
        g = gamma_vector(P)
        need(g is not None and len(g) == 3, "%s: gamma expansion failed" % name)
        disc = g[1] * g[1] - 4 * g[0] * g[2]
        print("%s: gamma vector %s, g1^2-4*g0*g2 = %d" % (name, pstr(g), disc))
        print("%s: degree %d, %d distinct complex zeros, %d distinct real zeros (Sturm)"
              % (name, len(P) - 1, distinct, real))
        nonreal = real < distinct
        # cross-check: gamma argument.  P(x) = (1+x)^d * Q(x/(1+x)^2), Q = g0+g1 y+g2 y^2;
        # if g0,g2>0 and disc<0 then Q>0 on R, so the only possible real zero is x=-1.
        gamma_says = (g[0] > 0 and g[2] > 0 and disc < 0)
        if gamma_says:
            need(real <= 1, "%s: Sturm count contradicts gamma argument" % name)
            need(nonreal, "%s: Sturm count contradicts gamma argument" % name)
        if disc >= 0 and g[0] > 0 and g[1] > 0 and g[2] > 0:
            need(not nonreal, "%s: Sturm count contradicts real-rooted gamma polynomial" % name)
        try:
            import sympy
            x = sympy.Symbol("x")
            sq = sympy.Poly(sympy.sqf_part(sum(c * x ** i for i, c in enumerate(P))), x)
            need(sq.degree() == distinct and sq.count_roots() == real,
                 "%s: sympy real root count disagrees with Sturm count" % name)
            print("%s: sympy agrees on the number of real zeros" % name)
        except ImportError:
            print("%s: sympy not available, cross-check skipped" % name)
        results[name] = nonreal
        print("%s has a non-real zero: %s" % (name, nonreal))

    need(results["H*"],
         "the dual Chow polynomial of this matroid has only real zeros; certificate does not "
         "refute Conjecture 7.3")
    if not results["F*"]:
        print("NOTE: F* is real-rooted here; the additional public claim about F* is NOT confirmed")
    else:
        print("the additional claim (F* has a non-real zero) is confirmed as well")
    print("Conjecture 7.3 is refuted by this matroid: H* has a non-real zero")
    print("VERIFIED")
    return 0


if __name__ == "__main__":
    try:
        code = main(sys.argv)
    except Fail as exc:
        print("REJECTED: " + str(exc))
        code = 1
    except Exception as exc:  # any unexpected failure is a rejection
        print("REJECTED: unexpected error %r" % (exc,))
        code = 1
    sys.exit(code)
