"""Check four twist determinants against matching enumeration on a 2x2 torus.

Run with Python 3. The arguments are the positive integer activities of the
same-cell, east and north edges. With no arguments, run both article examples.
"""

from argparse import ArgumentParser
from itertools import permutations, product
from math import prod


CELLS = tuple(product(range(2), repeat=2))
DIRECTIONS = ((0, 0), (1, 0), (0, 1))
PARITIES = CELLS
TWISTS = tuple(product((1, -1), repeat=2))


def edges(cell, weights):
    """Yield (white endpoint, activity, east and north seam exponents)."""
    x, y = cell
    for (dx, dy), weight in zip(DIRECTIONS, weights):
        target = ((x + dx) % 2, (y + dy) % 2)
        yield target, weight, (x + dx) // 2, (y + dy) // 2


def enumerate_matchings(weights):
    sectors = dict.fromkeys(PARITIES, 0)
    for matching in product(*(edges(cell, weights) for cell in CELLS)):
        if len({target for target, _, _, _ in matching}) != len(CELLS):
            continue
        p = sum(edge[2] for edge in matching) % 2
        q = sum(edge[3] for edge in matching) % 2
        sectors[p, q] += prod(edge[1] for edge in matching)
    return sectors


def twist_determinant(weights, z, w):
    matrix = [[0] * len(CELLS) for _ in CELLS]
    for row, cell in enumerate(CELLS):
        for target, weight, east, north in edges(cell, weights):
            matrix[row][CELLS.index(target)] += weight * z**east * w**north
    total = 0
    for perm in permutations(range(len(CELLS))):
        inversions = sum(left > right for j, right in enumerate(perm) for left in perm[:j])
        total += (-1)**inversions * prod(matrix[j][col] for j, col in enumerate(perm))
    return total


def check(weights):
    determinants = {(z, w): twist_determinant(weights, z, w) for z, w in TWISTS}
    sectors = enumerate_matchings(weights)
    for (p, q), weight in sectors.items():
        projected = sum(z**p * w**q * value for (z, w), value in determinants.items())
        assert abs(projected) == 4 * weight
    print("activities", weights, "twisted determinants", determinants)
    print("winding parity weights", sectors, "partition sum", sum(sectors.values()))


if __name__ == "__main__":
    parser = ArgumentParser(description=__doc__)
    parser.add_argument("weights", nargs="*", type=int)
    args = parser.parse_args()
    if args.weights and (len(args.weights) != 3 or min(args.weights) <= 0):
        parser.error("supply three positive integer edge activities")
    for example in ([tuple(args.weights)] if args.weights else [(1, 1, 1), (1, 2, 3)]):
        check(example)
