"""Four Ising and RSOS corners, checked against complete finite-domain sums."""
from itertools import product
from math import cosh, exp, isclose, log, pi, sin, sqrt

import numpy as np


def ising():
    K = log(2)/2
    for s in (1, -1):
        C = np.array([[exp(K*(x+y)*(1+s/2)) for y in (-1,1)] for x in (-1,1)])
        direct = sum(exp(K*(2+s)*sum(rays)) for rays in product((-1,1), repeat=4))
        assert isclose(direct, np.trace(np.linalg.matrix_power(C,4)), rel_tol=1e-14)
        assert isclose(direct, (2*cosh(K*(2+s)))**4, rel_tol=1e-14)
        print("Ising center, partition sum:", s, direct)


def height_probability(corners):
    angle = pi/4
    u = angle/2
    A, B = sin(angle-u)/sin(angle), sin(u)/sin(angle)
    def weight(nw, ne, sw, se):
        sides = ((nw,ne),(ne,se),(se,sw),(sw,nw))
        if any(abs(x-y)!=1 for x,y in sides):
            return 0.
        return A*(ne==sw) + B*(nw==se)*sqrt(sin(angle*ne)*sin(angle*sw))/sin(angle*nw)
    nw,ne,sw,se = corners
    totals = []
    for s in (1,2,3):
        # Independently build matrices around the central site then sum the four rays directly.
        def matrix(f):
            return np.array([[f(i,j) for j in (1,2,3)] for i in (1,2,3)])
        corners_fixed = (matrix(lambda w,n: weight(nw,n,w,s)),
                         matrix(lambda n,e: weight(n,ne,s,e)),
                         matrix(lambda e,b: weight(s,e,b,se)),
                         matrix(lambda b,w: weight(w,s,sw,b)))
        trace = np.trace(np.linalg.multi_dot(corners_fixed))
        direct = 0.
        for n,e,b,w in product((1,2,3),repeat=4):
            direct += weight(nw,n,w,s)*weight(n,ne,s,e)*weight(s,e,b,se)*weight(w,s,sw,b)
        np.testing.assert_allclose(trace,direct,atol=1e-13)
        totals.append(direct)
    print("Outer corners NW,NE,SW,SE:",corners)
    print("RSOS raw weights:",totals,"probabilities:",np.array(totals)/sum(totals))


if __name__ == "__main__":
    ising()
    height_probability((1,1,3,1))
    height_probability((3,3,1,3))
