"""Domain-wall sums, rational rapidity moves, and a confluent Izergin check.

Requires Python 3 and SymPy. Integers and Rational inputs stay exact.
"""
from itertools import product
from math import factorial

import sympy as sp


def row_transitions(bottom, weights, left, right):
    """Sum local weights from left to right, with fixed horizontal end bits."""
    states = [(left, (), 1)]
    if len(bottom) != len(weights):
        raise ValueError("One weight triple is required per vertex")
    for lower, (a, b, c) in zip(bottom, weights):
        layer = []
        for h, top, weight in states:
            if h == lower:
                layer.append((h, top+(lower,), weight*a))
            else:
                layer.extend([(h, top+(lower,), weight*b), (lower, top+(h,), weight*c)])
        states = layer
    return [(top,w) for h,top,w in states if h==right]


def weighted_rows(x, ys, eta, bottom):
    """Domain-wall row with rational six-vertex weights."""
    return row_transitions(bottom, [(x-y+eta, x-y, eta) for y in ys], 1, 0)


def periodic_ice(n):
    """Counts by vertical down-arrow number on an n by n unit-weight torus."""
    sectors = []
    for down in range(n+1):
        words = [word for word in product((0, 1), repeat=n) if sum(word) == down]
        indices = {word:i for i, word in enumerate(words)}
        row = sp.zeros(len(words))
        for j, bottom in enumerate(words):
            for seam in (0, 1):
                for top, weight in row_transitions(bottom, [(1, 1, 1)]*n, seam, seam):
                    row[indices[top], j] += weight
        sectors.append((row**n).trace())
    return sectors


def direct(xs, ys, eta):
    n = len(ys)
    lower = {(0,)*n:1}
    for x in xs:
        upper = {}
        for bottom, subtotal in lower.items():
            for top, w in weighted_rows(x, ys, eta, bottom):
                upper[top] = upper.get(top,0) + subtotal*w
        lower = upper
    return lower[(1,)*n]


def determinant(xs, ys, eta):
    A = sp.Matrix([[sp.sympify(x-y)*(x-y+eta) for y in ys] for x in xs])
    vandermonde = sp.prod((xs[j]-xs[i])*(ys[i]-ys[j])
                          for i in range(len(xs)) for j in range(i+1,len(xs)))
    return sp.factor(sp.prod(A)*A.applyfunc(lambda a:eta/a).det()/vandermonde)


def homogeneous(n, t, eta):
    z = sp.symbols("z")
    f = eta/(z*(z+eta))
    H = sp.Matrix(n, n, lambda i,j: sp.diff(f,z,i+j).subs(z,t)/(factorial(i)*factorial(j)))
    return sp.factor((t*(t+eta))**(n*n)*H.det())


def patch_operators():
    words = list(product((0,1),repeat=3))
    def local(i,j,u):
        P = sp.zeros(8)
        for c,word in enumerate(words):
            output = list(word)
            output[i],output[j] = output[j],output[i]
            P[words.index(tuple(output)),c] = 1
        return u*sp.eye(8)+P
    A, B, C = local(0,1,2), local(0,2,5), local(1,2,3)
    diff = A*B*C-C*B*A
    assert diff == sp.zeros(8)
    for i, word in enumerate(words):
        if word[0] == word[2] == 0:
            B[i,i] += 1
    diff = A*B*C-C*B*A
    print("First changed patch entries:",[(words[i],words[j],diff[i,j]) for i in range(8)
                                         for j in range(8) if diff[i,j]][:3])


if __name__ == "__main__":
    patch_operators()
    for xs,ys in [([4,6],[1,2]),([4,6,8],[0,1,2])]:
        observed = direct(xs,ys,1)
        assert observed == determinant(xs,ys,1) == direct(xs[::-1],ys,1)
        print("Distinct rapidities:",xs,ys,observed)
    for n in range(1,6):
        direct_sum = direct([2]*n,[0]*n,1)
        assert homogeneous(n,2,1)==direct_sum
        print("Homogeneous width, partition sum:",n,direct_sum)
    x = sp.symbols("x")
    ys = [0,2,5]
    values = [(y, direct([y,7,9],ys,1)) for y in ys]
    polynomial = sp.interpolate(values,x)
    assert sp.expand(direct([x,7,9],ys,1) - polynomial) == 0
    assert polynomial.subs(x,6) == determinant([6,7,9],ys,1)
    print("Interpolation nodes, polynomial and value at 6:",values,polynomial,polynomial.subs(x,6))
    for n in (2,4,6):
        counts = periodic_ice(n)
        print("Square-ice width, periodic sectors and total:",n,counts,sum(counts))
