"""Check the rational polynomial identities and the sharp six-point witness."""

from itertools import combinations

import sympy as sp


def main():
    vertices = tuple(range(6))
    edges = tuple(combinations(vertices, 2))
    triples = tuple(combinations(vertices, 3))
    pairs = [(s, tuple(i for i in vertices if i not in s)) for s in triples if 0 in s]
    edge = dict(zip(edges, sp.symbols("e:15")))
    total = sum(edge.values())
    degrees = [sum(w for key, w in edge.items() if i in key) for i in vertices]
    x_from_edges = [d / 2 - total / 6 for d in degrees]
    assert sp.expand(sum(x_from_edges)) == 0
    for s, t in pairs:
        difference = (sum(edge[e] for e in combinations(s, 2))
                      - sum(edge[e] for e in combinations(t, 2)))
        assert sp.expand(difference - 2 * sum(x_from_edges[j] for j in s)) == 0

    x = list(sp.symbols("x:5"))
    x.append(-sum(x))
    ell = [sum(x[i] for i in s) for s, _ in pairs]
    p2 = sum(xi**2 for xi in x)
    p4 = sum(xi**4 for xi in x)
    b = 3 * p2
    assert sp.expand(sum(y**2 for y in ell) - b) == 0
    assert sp.expand(sum(y**4 for y in ell) - 3 * (p2**2 - p4)) == 0
    for (s, t), y in zip(pairs, ell):
        gaps = sum((x[i]-x[j])**2 for group in (s, t)
                   for i, j in combinations(group, 2))
        assert sp.expand(b - 2*y**2 - gaps) == 0
    fourth_gap = sum((x[i]**2-x[j]**2)**2 for i, j in edges)
    assert sp.expand(5*b**2 - 18*sum(y**4 for y in ell) - 9*fourth_gap) == 0

    a, b, c, d, e = sp.symbols("A B C D E")
    lhs = 71*(a+b)**2 - 62*(c+6*d+e)
    rhs = (62*(a**2-c) + 372*(a*b/2-d)
           + 62*(5*b**2/18-e) + (3*a-22*b/3)**2)
    assert sp.expand(lhs-rhs) == 0

    height = 2 * sp.sqrt(11)
    trial = {key: (height+3)/3 if max(key)<3 else
             (height-3)/3 if min(key)>=3 else -height/6 for key in edges}
    values = [sum(trial[key] for key in combinations(s, 2)) for s in triples]
    second = sp.simplify(sum(y**2 for y in values))
    fourth = sp.simplify(sum(y**4 for y in values))
    assert (second, fourth) == (124, 8804)
    assert sp.cancel(fourth/second**2) == sp.Rational(71, 124)
    print("All polynomial identities pass. Witness moments: 124 and 8804. Best ratio: 71/124.")


if __name__ == "__main__":
    main()
