"""Exact checks for the cluster, determinant and square-grid dimer examples.

Run with Python 3 and SymPy. No random data or fitted coefficients.
"""
from itertools import permutations

import sympy as sp


def mutate(B, k):
    """Skew-symmetric matrix mutation, without relabeling vertices."""
    def entry(i, j):
        if i == k or j == k:
            return -B[i, j]
        left, right = B[i, k], B[k, j]
        return B[i, j] + max(left, 0)*max(right, 0) - max(-left, 0)*max(-right, 0)
    return sp.Matrix(B.rows, B.cols, entry)


def cluster():
    x, y = sp.symbols("x y", positive=True)
    for b in (1, 2, 3):
        B = sp.Matrix([[0, b], [-b, 0]])
        assert mutate(B, 0).extract([1, 0], [1, 0]) == B
    terms = [x, y]
    for _ in range(5):
        terms.append(sp.cancel((1 + terms[-1])/terms[-2]))
    assert terms[-2:] == [x, y]

    u = sp.Matrix([1, -2, 1, 0])
    v = sp.Matrix([0, 1, -2, 1])
    B = u*v.T - v*u.T
    order = [1, 2, 3, 0]
    assert mutate(B, 0).extract(order, order) == B
    assert B.rank() == 2
    assert B*sp.ones(4, 1) == B*sp.Matrix(range(4)) == sp.zeros(4, 1)
    alpha, beta, k = sp.symbols("alpha beta k")
    after = (alpha*y + beta)/(x*y**2)
    def integral(a, b):
        return a*b + alpha*(1/a + 1/b) + beta/(a*b)
    assert sp.cancel(integral(y, after) - integral(x, y)) == 0
    D = (1-k*x)**2 - 4*x**2*(x+1)
    print("Cubic discriminant on the all-ones seed:", sp.discriminant(D.subs(k, 4), x))
    somos = [sp.Integer(1)]*4
    for _ in range(7):
        a, b, c, d = somos[-4:]
        somos.append((b*d+c*c)/a)
    print("Somos-4:", somos)
    for b in (2, 3):
        poles = [-1, 0]
        for _ in range(7):
            poles.append(max(0, b*poles[-1]) - poles[-2])
        print("Pole orders at x=0, b =", b, poles)


def minors():
    A = sp.Matrix([[1, 2, 1], [3, 4, 5], [2, 1, 6]])
    blocks = [A[i:i+2, j:j+2].det() for i, j in ((0, 0), (0, 1), (1, 0), (1, 1))]
    nw, ne, sw, se = blocks
    assert A[1, 1]*A.det() == nw*se - ne*sw
    print("Contiguous 2-by-2 minors and determinant:", blocks, A.det())


def planar_ladder():
    # Rows B=(top left, top right, bottom center); columns
    # W=(bottom left, bottom right, top center).
    a, b, c, d, e, f, g = weights = sp.symbols("a b c d e f g", positive=True)
    K = sp.Matrix([[a, 0, d], [0, c, e], [f, g, -b]])
    matchings = []
    for perm in permutations(range(3)):
        weight = abs(sp.prod(K[i, j] for i, j in enumerate(perm)))
        if weight:
            matchings.append(weight)
    Z = sum(matchings)
    assert sp.expand(K.det() + Z) == 0
    numbers = dict(zip(weights, (2, 3, 5, 7, 11, 13, 17)))
    K = K.subs(numbers)
    Q = K.inv()
    print("Ladder matching weights:", [w.subs(numbers) for w in matchings],
          "total", Z.subs(numbers))
    for i in range(3):
        assert sum(K[i, j]*Q[j, i] for j in range(3)) == 1
    selected = [K[0, 0]*Q[0, 0], K[1, 1]*Q[1, 1],
                K[0, 0]*K[1, 1]*Q.extract([0, 1], [0, 1]).det()]
    print("Left rung, right rung and both:", selected)


def toroidal_grid():
    z, w, x, y, v, s, t = sp.symbols("z w x y v s t", nonzero=True)
    # After tree gauge: a_E=b_E=a_N=1. Entries with i are vertical.
    K = sp.Matrix([[1+x/z, sp.I*(1+v/w)], [sp.I*(t+s*w), y+z]])
    # Enumerate all matchings without the Kasteleyn phases.
    horizontal = [left*right for left in (1, x/z) for right in (y, z)]
    vertical = [up*down for up in (1, v/w) for down in (t, s*w)]
    P = sum(horizontal + vertical)
    assert sp.expand(K.det() - P) == 0
    print("Normalized torus polynomial:", sp.expand(P))
    for value in (1, 2):
        H = (x+y+t+v*s).subs({x:value, y:sp.Rational(1,value), v:1, t:1, s:1})
        print("Unit boundary coefficients, x =", value, "H =", H)


if __name__ == "__main__":
    cluster()
    minors()
    planar_ladder()
    toroidal_grid()
