"""Exact, finite stochastic-vertex, q-Boson and transfer checks. Python 3.9+."""
from collections import defaultdict
from fractions import Fraction as F
from itertools import product
from math import prod


def vertex(m, h, capacity, q, u):
    """Map (north occupation, east carrier) to conditional probability."""
    if h == 0:
        empty = (q**m - u) / (1-u)
    else:
        empty = u*(q**(m-capacity) - 1) / (1-u)
    assert 0 <= empty <= 1
    outputs = {}
    for east, mass in [(0, empty), (1, 1-empty)]:
        if mass:
            north = m+h-east
            assert 0 <= north <= capacity
            outputs[north, east] = mass
    return outputs


def sweep(bottom, west, capacity, q, u):
    """Joint law of the vertical outputs and final carrier for one open row."""
    states = {((), west): F(1)}
    for m in bottom:
        next_states = defaultdict(F)
        for (top, h), weight in states.items():
            for (north, east), p in vertex(m, h, capacity, q, u).items():
                next_states[top+(north,), east] += weight*p
        states = next_states
    assert sum(states.values()) == 1
    return states


def local_balance():
    for p, r in [(F(1, 3), F(1, 2)), (F(1, 2), F(1, 2))]:
        law = defaultdict(F)
        for m, h in product(range(2), repeat=2):
            incoming = (p if m else 1-p)*(r if h else 1-r)
            for out, weight in vertex(m, h, 1, F(1, 2), F(1, 4)).items():
                law[out] += incoming*weight
        north = law[1, 0] + law[1, 1]
        east = law[0, 1] + law[1, 1]
        covariance = law[1, 1] - north*east
        if p == F(1, 3):
            assert (north, east, covariance) == (p, r, 0)
        else:
            assert (north, east, covariance) == (F(5, 12), F(7, 12), F(1, 144))
        print("Entrance p,r; outgoing probabilities and covariance:", p, r, north, east, covariance)


def periodic_rows():
    capacity, q, u = 2, F(1, 2), F(1, 8)
    for length in range(1, 5):
        for bottom in product(range(capacity+1), repeat=length):
            closed = defaultdict(F)
            for west in range(2):
                for (top, east), weight in sweep(bottom, west, capacity, q, u).items():
                    if east == west:
                        assert sum(top) == sum(bottom)
                        closed[top] += weight
            expected = 1 + q**sum(bottom) * ((1-u*q**(-capacity))/(1-u))**length
            assert sum(closed.values()) == expected
            if bottom == (1, 0):
                assert expected == F(57, 49)
                assert closed[0, 1]/expected == F(4, 19)
                print("Closed row mass and normalized move probability:", expected, closed[0, 1]/expected)


def quadrant():
    rates = (1, F(2), F(4))  # b_v=2/3, b_h=1/3 on the q>1 branch
    height = defaultdict(F)
    for (middle, first_exit), weight in sweep((1, 1), 0, *rates).items():
        for (top, second_exit), conditional in sweep(middle, 0, *rates).items():
            assert sum(top) + first_exit + second_exit == 2
            height[sum(top)] += weight*conditional
            if middle == top == (1, 0):
                assert weight*conditional == F(4, 27)  # pictured path history
    assert [height[k] for k in range(3)] == [F(11, 81), F(2, 3), F(16, 81)]
    print("Quadrant heights zero, one, two:", *(height[k] for k in range(3)))


def boson_ring():
    q = F(1, 2)
    for length in [2, 3, 4]:
        previous_partition = F(1)
        for mass in range(1, 5):
            factors = [F(1)]
            for k in range(1, mass+1):
                factors.append(factors[-1]/(1-q**k))
            weights = {k: prod(factors[m] for m in k)
                       for k in product(range(mass+1), repeat=length) if sum(k) == mass}
            partition = sum(weights.values())
            balance = defaultdict(F)
            currents = [F(0)]*length
            for k, weight in weights.items():
                for i, m in enumerate(k):
                    if not m:
                        continue
                    flux = weight*(1-q**m)/partition
                    target = list(k)
                    target[i] -= 1
                    target[i-1] += 1
                    balance[k] -= flux
                    balance[tuple(target)] += flux
                    currents[i] += flux
            assert all(net == 0 for net in balance.values())
            assert all(j == previous_partition/partition for j in currents)
            if (length, mass) == (3, 2):
                assert currents[0] == F(3, 10)
                print("Three-site ring partition, bond current:", partition, currents[0])
            previous_partition = partition


def transfer_paths():
    transfer = [[2, 1], [2, 3]]
    h, perron = [1, 2], 4
    kernel = [[F(t*h[j], perron*h[i]) for j, t in enumerate(row)]
              for i, row in enumerate(transfer)]
    bridge_weights = [transfer[0][j]*transfer[j][0] for j in range(2)]
    bridge_kernel = [kernel[0][j]*kernel[j][0] for j in range(2)]
    assert [F(w, sum(bridge_weights)) for w in bridge_weights] == [
        p/sum(bridge_kernel) for p in bridge_kernel]
    free_weights = [transfer[0][j]*sum(transfer[j]) for j in range(2)]
    free_step = [F(w, sum(free_weights)) for w in free_weights]
    assert free_step == [F(6, 11), F(5, 11)]
    print("Two-row, free-end first step:", *free_step)


if __name__ == "__main__":
    local_balance()
    periodic_rows()
    quadrant()
    boson_ring()
    transfer_paths()
