"""Exact checks for the finite-type colouring lemma in the Erdős #1029 report.

Run with Python 3. Only the standard library is needed. The proof for arbitrary
k is in the accompanying report. This script checks its finite inequalities
by summing the probabilities of the possible type counts.
"""
from fractions import Fraction as F
from itertools import combinations_with_replacement, product
from math import comb, factorial, prod


def mono_ratio(k, weights, matrix):
    """P(all edges one colour), divided by 2**(1-binomial(k,2))."""
    q = len(weights)
    total = F(0)
    for labels in combinations_with_replacement(range(q), k):
        counts = [labels.count(i) for i in range(q)]
        multiplicity = factorial(k) // prod(factorial(c) for c in counts)
        mass = multiplicity * prod(w**c for w, c in zip(weights, counts))
        red = blue = F(1)
        for i in range(q):
            for j in range(i, q):
                edges = comb(counts[i], 2) if i == j else counts[i] * counts[j]
                p = matrix[i][j]
                red *= (2*p)**edges
                blue *= (2*(1-p))**edges
        total += mass * (red + blue) / 2
    return total


def direct_ratio(k, weights, matrix):
    """Independent check using all ordered assignments and individual edges."""
    value = F(0)
    for labels in product(range(len(weights)), repeat=k):
        mass = prod(weights[i] for i in labels)
        ps = [matrix[labels[i]][labels[j]] for i in range(k) for j in range(i)]
        value += mass * (prod(ps) + prod(1-p for p in ps))
    return value * 2**(comb(k, 2)-1)


def check(k, weights, matrix):
    delta = max(abs(2*p-1) for row in matrix for p in row)
    m = comb(k, 2)
    ratio = mono_ratio(k, weights, matrix)
    # Squaring avoids irrational powers in the AM–GM bound when m is odd.
    assert ratio**2 >= (1-delta**2)**m
    assert 2*ratio >= min(weights)**k * (1+delta/5)**m
    if k <= 4:
        assert ratio == direct_ratio(k, weights, matrix)


def main():
    cases = 0
    grid = [F(i, 4) for i in range(5)]
    for a, b, c in product(grid, repeat=3):
        matrix = [[a, b], [b, c]]
        for weights in ([F(1, 2), F(1, 2)], [F(1, 5), F(4, 5)]):
            for k in range(2, 9):
                check(k, weights, matrix)
                cases += 1
    for values in product((F(0), F(1)), repeat=6):
        a, b, c, d, e, f = values
        matrix = [[a, b, c], [b, d, e], [c, e, f]]
        for k in range(2, 9):
            check(k, [F(1, 2), F(1, 3), F(1, 6)], matrix)
            cases += 1
    print(f'{cases} exact parameter checks passed.')


if __name__ == '__main__':
    main()
