"""Exact uniform domino shuffling on Aztec diamonds and a finite axis sample.

No third-party packages. Each domino is its left or bottom square and 'h' or
'v'. A square is identified by its integer lower-left corner.
"""
from collections import Counter
from functools import lru_cache
from itertools import product
from math import sqrt
from random import Random
from statistics import mean, stdev


@lru_cache(None)
def diamond(n):
    return frozenset((x,y) for x in range(-n,n) for y in range(-n,n)
                     if abs(2*x+1)+abs(2*y+1)<=2*n)


def cells(tile):
    x,y,t = tile
    return ((x,y), (x+(t=="h"),y+(t=="v")))


def move(tile, order):
    x,y,t = tile
    sign = 1 if (x+y+order)%2==0 else -1
    return (0, sign) if t=="h" else (sign, 0)


def slide(tiles, n):
    next_tiles = set()
    for x,y,t in tiles:
        dx,dy = move((x,y,t),n)
        if (x+dx,y+dy,t) in tiles:
            # The immediately adjacent parallel tile points back at this one.
            continue
        next_tiles.add((x+dx,y+dy,t))
    covered = {c for tile in next_tiles for c in cells(tile)}
    assert len(covered)==2*len(next_tiles) and covered<=diamond(n+1)
    remaining = diamond(n+1).difference(covered)
    consumed = set()
    holes = []
    for x,y in sorted(remaining):
        if (x,y) in consumed:
            continue
        square = {(x,y),(x+1,y),(x,y+1),(x+1,y+1)}
        assert square<=remaining and not square.intersection(consumed)
        consumed.update(square)
        holes.append((x,y))
    return next_tiles, holes


def fill(tiles, holes, decisions):
    out = tiles.copy()
    for (x,y),h in zip(holes,decisions):
        if h:
            out.update(((x,y,"h"),(x,y+1,"h")))
        else:
            out.update(((x,y,"v"),(x+1,y,"v")))
    return frozenset(out)


def sample(n, rng):
    tiles = frozenset()
    for order in range(n):
        base,holes = slide(tiles,order)
        tiles = fill(base,holes,(rng.getrandbits(1) for _ in holes))
    return tiles


def exact_small():
    from fractions import Fraction
    law = {frozenset():Fraction(1)}
    for n in range(3):
        nxt = Counter()
        for tiles,p in law.items():
            base,holes = slide(tiles,n)
            for bits in product((0,1), repeat=len(holes)):
                nxt[fill(base,holes,bits)] += p/(2**len(holes))
        assert len(nxt)==2**((n+1)*(n+2)//2) and len(set(nxt.values()))==1
        law = nxt
        print("Exact uniform law:",n+1,len(law))


def north_front(tiles,n):
    assignment = {c:t for t in tiles for c in cells(t) if c[0]==0}
    for y in range(n-1,-n-1,-1):
        tile = assignment[0,y]
        if move(tile,n)!=(0,1):
            return (y+1)/n
    return -1.


def polar_tiles(tiles, n):
    """Tiles joined to the outer boundary by an edge-sharing path of one heading."""
    owner = {cell: tile for tile in tiles for cell in cells(tile)}
    reached = set()
    stack = []
    for tile in tiles:
        if any((x+dx, y+dy) not in owner for x, y in cells(tile)
               for dx, dy in ((1,0),(-1,0),(0,1),(0,-1))):
            reached.add(tile)
            stack.append(tile)
    while stack:
        tile = stack.pop()
        heading = move(tile, n)
        for x, y in cells(tile):
            for dx, dy in ((1,0),(-1,0),(0,1),(0,-1)):
                other = owner.get((x+dx, y+dy))
                if other is not None and other not in reached and move(other, n) == heading:
                    reached.add(other)
                    stack.append(other)
    return reached


if __name__ == "__main__":
    exact_small()
    rng = Random(20261121)
    for n in (12,24,36):
        front = [north_front(sample(n,rng),n) for _ in range(64)]
        print("Order, mean northern boundary, standard error:",n,mean(front),stdev(front)/sqrt(len(front)))
