#!/usr/bin/env python3
"""Verifier for a counterexample to Conjecture 5 of Chen-Khare-Sahi (arXiv:2509.19649v2).

usage: python3 verify.py certificate.json

Standard library only, exact rational arithmetic only (fractions.Fraction).

What is checked (everything is recomputed here; the certificate supplies only
n, lambda, mu, q, t and the values of a linear functional L):

 A. lambda, mu are partitions of the same size with at most n parts, lambda majorizes mu,
    and q, t are rationals in (0,1).  So clause (5) of the conjecture holds.
 B. The monic Macdonald polynomials P_nu(x; q, t) of degree d = |lambda| are computed from
    the definition: the unique family, unitriangular in the monomial basis w.r.t. dominance,
    orthogonal for the q,t-Hall pairing <p_r, p_s> = delta_rs z_r prod (1-q^{r_i})/(1-t^{r_i}).
    Existence (pairwise orthogonality of ALL partitions of d) is verified, not assumed.
    They are then restricted to n variables.
 C. Independent cross-check: the restricted P_lambda, P_mu are eigenfunctions of Macdonald's
    q-difference operator D_n^1 in n variables with eigenvalues sum_i q^{nu_i} t^{n-i}, and
    those eigenvalues are pairwise distinct over the partitions of d with <= n parts, so the
    monic triangular eigenfunction is unique.
 D. EVERY product of generators of the Muirhead semiring that is homogeneous of degree d is
    enumerated by brute force (no reduction to covers): generators are M_nu (nu a nonzero
    partition with <= n parts) and M_a - M_b (a != b, a majorizes b).  L is checked to be >= 0
    on each such product.
 E. L( P_lambda/P_lambda(1) - P_mu/P_mu(1) ) < 0.

Why this settles the statement: every generator is a homogeneous polynomial, so every product
of generators is homogeneous.  If the degree-d polynomial F = P_lambda/P_lambda(1) -
P_mu/P_mu(1) (at q0,t0) were a finite nonnegative-real combination of products of generators,
then comparing degree-d components, F would be a nonnegative combination of the degree-d
products only (the empty product 1 has degree 0).  By D, L(F) >= 0, contradicting E.  Hence
clause (2') fails at (q0,t0) while clause (5) holds, so the claimed equivalence is false.
"""
import json
import sys
from fractions import Fraction as Fr
from itertools import permutations


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


# ---------------------------------------------------------------- partitions
def partitions_of(d, maxparts=None, maxpart=None):
    """Partitions of d as weakly decreasing tuples of positive ints."""
    if maxpart is None:
        maxpart = d
    if d == 0:
        return [()]
    if maxparts == 0:
        return []
    out = []
    for a in range(min(d, maxpart), 0, -1):
        for rest in partitions_of(d - a, None if maxparts is None else maxparts - 1, a):
            out.append((a,) + rest)
    return out


def pad(p, n):
    return tuple(p) + (0,) * (n - len(p))


def majorizes(a, b):
    """a majorizes b: equal size and all partial sums of a >= those of b."""
    L = max(len(a), len(b))
    a, b = pad(a, L), pad(b, L)
    if sum(a) != sum(b):
        return False
    sa = sb = 0
    for x, y in zip(a, b):
        sa += x
        sb += y
        if sa < sb:
            return False
    return True


# ---------------------------------------------------------------- polynomials (dict exponent -> Fraction)
def padd(p, r, c=1):
    out = dict(p)
    for e, v in r.items():
        w = out.get(e, 0) + c * v
        if w:
            out[e] = w
        else:
            out.pop(e, None)
    return out


def pmul(p, r):
    out = {}
    for e, a in p.items():
        for f, b in r.items():
            g = tuple(u + v for u, v in zip(e, f))
            out[g] = out.get(g, 0) + a * b
    return {e: v for e, v in out.items() if v}


def pscale(p, c):
    return {e: c * v for e, v in p.items() if c * v}


def mono(nu, n):
    """monomial symmetric polynomial m_nu in n variables (0 if nu has more than n parts)."""
    if len(nu) > n:
        return {}
    return {e: Fr(1) for e in set(permutations(pad(nu, n)))}


def Mnorm(nu, n):
    m = mono(nu, n)
    return pscale(m, Fr(1, len(m)))  # m_nu(1,...,1) = number of monomials


# ---------------------------------------------------------------- linear algebra over Q
def solve(A, b):
    """Solve A x = b exactly (A square, must be nonsingular)."""
    k = len(A)
    M = [list(A[i]) + [b[i]] for i in range(k)]
    for c in range(k):
        piv = next((r for r in range(c, k) if M[r][c] != 0), None)
        if piv is None:
            fail("singular linear system")
        M[c], M[piv] = M[piv], M[c]
        inv = 1 / M[c][c]
        M[c] = [v * inv for v in M[c]]
        for r in range(k):
            if r != c and M[r][c] != 0:
                f = M[r][c]
                M[r] = [x - f * y for x, y in zip(M[r], M[c])]
    return [M[i][k] for i in range(k)]


def inverse(A):
    k = len(A)
    cols = [solve(A, [Fr(int(i == j)) for i in range(k)]) for j in range(k)]
    return [[cols[j][i] for j in range(k)] for i in range(k)]


# ---------------------------------------------------------------- Macdonald polynomials from the Hall pairing
def macdonald_all(d, q, t):
    """Return (parts, C) with parts = all partitions of d and C[lam] = {nu: coeff of m_nu in P_lam},
    computed in the ring of symmetric functions (realised faithfully in d variables)."""
    parts = partitions_of(d)
    N = d  # d variables: the m_nu, |nu| = d, are linearly independent
    idx = {p: i for i, p in enumerate(parts)}
    k = len(parts)
    # R[r][nu] = coefficient of m_nu in the power sum product p_r
    R = [[Fr(0)] * k for _ in range(k)]
    for r in parts:
        poly = {(0,) * N: Fr(1)}
        for part in r:
            ps = {tuple(part if j == i else 0 for j in range(N)): Fr(1) for i in range(N)}
            poly = pmul(poly, ps)
        # symmetric => constant on orbits; read off the coefficient at the sorted exponent
        for e, v in poly.items():
            if v != poly[pad(tuple(sorted((x for x in e if x), reverse=True)), N)]:
                fail("power sum product not symmetric (internal)")
        for nu in parts:
            R[idx[r]][idx[nu]] = poly.get(pad(nu, N), Fr(0))
    # <p_r,p_r> = z_r * prod (1-q^{r_i})/(1-t^{r_i})
    Z = []
    for r in parts:
        z = Fr(1)
        for i in set(r):
            mlt = r.count(i)
            z *= Fr(i) ** mlt
            for j in range(1, mlt + 1):
                z *= j
        for part in r:
            z *= (1 - q ** part) / (1 - t ** part)
        Z.append(z)
    Rinv = inverse(R)  # m_nu = sum_r Rinv[nu][r] p_r
    G = [[sum(Rinv[a][r] * Z[r] * Rinv[b][r] for r in range(k)) for b in range(k)] for a in range(k)]
    C = {}
    for lam in parts:
        lower = [nu for nu in parts if nu != lam and majorizes(lam, nu)]
        if lower:
            A = [[G[idx[a]][idx[b]] for b in lower] for a in lower]
            rhs = [-G[idx[a]][idx[lam]] for a in lower]
            c = solve(A, rhs)
        else:
            c = []
        co = {lam: Fr(1)}
        for nu, v in zip(lower, c):
            if v:
                co[nu] = v
        C[lam] = co
    # verify the defining properties: orthogonality of every pair, positivity of norms
    def ip(u, v):
        return sum(a * b * G[idx[x]][idx[y]] for x, a in u.items() for y, b in v.items())
    for i, a in enumerate(parts):
        if ip(C[a], C[a]) <= 0:
            fail("nonpositive norm for P_%s" % (a,))
        for b in parts[i + 1:]:
            if ip(C[a], C[b]) != 0:
                fail("P_%s and P_%s are not orthogonal" % (a, b))
    return parts, C


def restrict(co, n):
    out = {}
    for nu, c in co.items():
        out = padd(out, mono(nu, n), c)
    return out


# ---------------------------------------------------------------- Macdonald's operator D_n^1 (cross-check)
def operator_check(P, nu, n, q, t, d):
    """Check  sum_i prod_{j!=i} (t x_i - x_j)/(x_i - x_j) * P(.., q x_i, ..) = eta * P
    after multiplying through by Delta = prod_{i<j} (x_i - x_j)."""
    def var(i):
        return {tuple(int(i == j) for j in range(n)): Fr(1)}
    one = {(0,) * n: Fr(1)}
    delta = one
    for i in range(n):
        for j in range(i + 1, n):
            delta = pmul(delta, padd(var(i), var(j), -1))
    lhs = {}
    for i in range(n):
        # Delta * prod_{j != i} (t x_i - x_j)/(x_i - x_j)
        #   = prod_{j != i} (t x_i - x_j) * prod_{a<b, a,b != i} (x_a - x_b) * sign
        W = one
        sign = 1
        for j in range(n):
            if j != i:
                W = pmul(W, padd(pscale(var(i), t), var(j), -1))
                if j < i:
                    sign = -sign  # (x_j - x_i) = -(x_i - x_j)
        for a in range(n):
            for b in range(a + 1, n):
                if a != i and b != i:
                    W = pmul(W, padd(var(a), var(b), -1))
        shifted = {e: v * q ** e[i] for e, v in P.items()}
        lhs = padd(lhs, pmul(W, shifted), sign)
    eig = lambda p: sum(q ** pad(p, n)[i] * t ** (n - 1 - i) for i in range(n))
    eigs = [eig(p) for p in partitions_of(d, n)]
    if len(set(eigs)) != len(eigs):
        fail("eigenvalues of D_n^1 not distinct")
    rhs = pscale(pmul(delta, P), eig(nu))
    if lhs != rhs:
        fail("P_%s is not an eigenfunction of D_n^1" % (nu,))


# ---------------------------------------------------------------- main
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)
    n = cert["n"]
    lam = tuple(cert["lambda"])
    mu = tuple(cert["mu"])
    q = Fr(cert["q"])
    t = Fr(cert["t"])
    if not (isinstance(n, int) and 1 <= n <= 4):
        fail("bad n")
    for p in (lam, mu):
        if len(p) != n or any((not isinstance(x, int)) or isinstance(x, bool) or x < 0 for x in p) \
                or list(p) != sorted(p, reverse=True):
            fail("lambda/mu must be weakly decreasing nonnegative integer n-tuples")
    d = sum(lam)
    if not (1 <= d <= 8):
        fail("degree out of supported range")
    # --- A
    if sum(mu) != d or not majorizes(lam, mu) or lam == mu:
        fail("lambda does not (strictly) majorize mu")
    if not (0 < q < 1 and 0 < t < 1):
        fail("q,t must lie in (0,1)")
    strip = lambda p: tuple(x for x in p if x)
    lam_s, mu_s = strip(lam), strip(mu)

    # functional L: value on each normalized monomial symmetric polynomial M_nu of degree d
    target_parts = partitions_of(d, n)
    w = {}
    for key, val in cert["L"].items():
        nu = tuple(int(x) for x in key.split(","))
        if len(nu) != n or list(nu) != sorted(nu, reverse=True) or sum(nu) != d or min(nu) < 0:
            fail("bad key in L: %r" % key)
        w[nu] = Fr(val)
    if set(w) != {pad(p, n) for p in target_parts}:
        fail("L must be given on exactly the partitions of d with at most n parts")

    def L(poly):
        # L(M_nu) = w[nu]  <=>  L gives each monomial x^e the value w[sorted e]
        # (well defined as a linear functional on all degree-d polynomials)
        tot = Fr(0)
        for e, v in poly.items():
            if sum(e) != d:
                fail("L applied to a polynomial of wrong degree (internal)")
            tot += v * w[tuple(sorted(e, reverse=True))]
        return tot

    for p in target_parts:  # sanity: L(M_nu) really equals the stated value
        if L(Mnorm(p, n)) != w[pad(p, n)]:
            fail("internal: L(M_nu) mismatch")

    # --- B
    parts, C = macdonald_all(d, q, t)
    for p in (lam_s, mu_s):
        if C[p][p] != 1 or any(not majorizes(p, nu) for nu in C[p]):
            fail("P not monic/triangular")
    Plam = restrict(C[lam_s], n)
    Pmu = restrict(C[mu_s], n)
    # --- C
    operator_check(Plam, lam, n, q, t, d)
    operator_check(Pmu, mu, n, q, t, d)

    one_lam = sum(Plam.values())  # value at (1,...,1)
    one_mu = sum(Pmu.values())
    if one_lam == 0 or one_mu == 0:
        fail("normalisation P(1) vanishes")
    F = padd(pscale(Plam, 1 / one_lam), pscale(Pmu, 1 / one_mu), -1)

    # --- D: every degree-d product of semiring generators, by brute force
    gens = {}  # degree -> list of polynomials
    n_gen = 0
    for k in range(1, d + 1):
        ps = partitions_of(k, n)
        lst = [Mnorm(p, n) for p in ps]
        for a in ps:
            for b in ps:
                if a != b and majorizes(a, b):
                    lst.append(padd(Mnorm(a, n), Mnorm(b, n), -1))
        gens[k] = lst
        n_gen += len(lst)

    def freeze(p):
        return tuple(sorted(p.items()))

    # prods[k] = set of all distinct polynomials that are products of generators, total degree k.
    # (multiplication is commutative, so building by appending one generator at a time
    #  reaches every multiset of generators)
    prods = {0: {freeze({(0,) * n: Fr(1)})}}
    for k in range(1, d + 1):
        cur = set()
        for g in range(1, k + 1):
            for base in prods[k - g]:
                bp = dict(base)
                for gen in gens[g]:
                    cur.add(freeze(pmul(bp, gen)))
        prods[k] = cur
    n_prod = 0
    min_val = None
    for fz in prods[d]:
        val = L(dict(fz))
        n_prod += 1
        if val < 0:
            fail("L is negative on a degree-%d product of semiring generators" % d)
        min_val = val if min_val is None else min(min_val, val)

    # --- E
    LF = L(F)
    print("n =", n, " lambda =", lam, " mu =", mu, " q =", q, " t =", t)
    print("P_lambda monomial coefficients:", {k_: str(v) for k_, v in C[lam_s].items() if len(k_) <= n})
    print("P_mu     monomial coefficients:", {k_: str(v) for k_, v in C[mu_s].items() if len(k_) <= n})
    print("P_lambda(1) =", one_lam, "  P_mu(1) =", one_mu)
    print("semiring generators of degree 1..%d: %d ; distinct degree-%d products checked: %d ; min L = %s"
          % (d, n_gen, d, n_prod, min_val))
    print("L(normalized Macdonald difference) =", LF)
    if not LF < 0:
        fail("L is not negative on the Macdonald difference")
    print("VERIFIED")


if __name__ == "__main__":
    main()
