"""Enumerate Ising spins, bonds and winding sectors on a two-by-two square."""
from collections import Counter, defaultdict
from itertools import product
from math import asinh, cosh, exp, isclose, log, sinh, tanh


def square_bonds(periodic):
    """Return (site, neighbor, crosses x seam, crosses y seam) for each bond."""
    bonds = []
    for y, x in product(range(2), repeat=2):
        site = x + 2*y
        if periodic or x == 0:
            bonds.append((site, (1-x) + 2*y, x, 0))
        if periodic or y == 0:
            bonds.append((site, x + 2*(1-y), 0, y))
    return bonds


def spin_sum(bonds, coupling, twist=(0, 0)):
    partition = diagonal = 0.0
    for spins in product((-1, 1), repeat=4):
        alignment = sum((-1)**(hx*twist[0] + hy*twist[1]) * spins[i]*spins[j]
                        for i, j, hx, hy in bonds)
        weight = exp(coupling * alignment)
        partition += weight
        diagonal += weight * spins[0] * spins[3]
    return partition, diagonal / partition


def winding_polynomials(bonds):
    polynomials = defaultdict(Counter)
    for selected in product((0, 1), repeat=len(bonds)):
        degrees = [0] * 4
        wind_x = wind_y = 0
        for keep, (i, j, hx, hy) in zip(selected, bonds):
            if keep:
                degrees[i] += 1
                degrees[j] += 1
                wind_x += hx
                wind_y += hy
        if all(degree % 2 == 0 for degree in degrees):
            polynomials[wind_x % 2, wind_y % 2][sum(selected)] += 1
    return polynomials


if __name__ == "__main__":
    critical = asinh(1) / 2
    for periodic, expected in ((False, 1/3), (True, 4/5)):
        bonds = square_bonds(periodic)
        partition, correlation = spin_sum(bonds, critical)
        assert isclose(correlation, expected, abs_tol=1e-14)
        print(len(bonds), "bonds: Z =", partition, "diagonal correlation =", correlation)

    torus = square_bonds(True)
    sectors = winding_polynomials(torus)
    for winding, counts in sorted(sectors.items()):
        print("Winding", winding, "counts by number of bonds:", dict(sorted(counts.items())))

    for coupling in (.13, .372, critical, .8):
        dual = -log(tanh(coupling)) / 2
        z, _ = spin_sum(torus, coupling)
        dual_sum = sum(spin_sum(torus, dual, twist)[0] for twist in product((0, 1), repeat=2))
        assert isclose(z, sinh(2*coupling)**4 * dual_sum / 2, rel_tol=2e-14)
        # A twist of the original spins weights a winding loop by its seam sign.
        for tx, ty in product((0, 1), repeat=2):
            graph_sum = sum((-1)**(wx*tx + wy*ty) * count * tanh(coupling)**degree
                            for (wx, wy), counts in sectors.items() for degree, count in counts.items())
            twisted, _ = spin_sum(torus, coupling, (tx, ty))
            assert isclose(twisted, 16 * cosh(coupling)**8 * graph_sum, rel_tol=2e-14)
