"""Exact small exclusion processes. Python 3, NumPy and SciPy.

Matrices evolve probability columns. Site i is bit i, in left-to-right
order. Closed paths reflect at the ends unless the ring seam is included.
"""
from itertools import combinations
from math import comb, sqrt

import numpy as np
from scipy.linalg import expm


def sector(length, particles):
    return [sum(1 << j for j in positions)
            for positions in combinations(range(length), particles)]


def generator(states, edges, contacts=()):
    """Edges are (i,j,right,left); contacts are (site,injection,removal)."""
    indices = {state: i for i, state in enumerate(states)}
    matrix = np.zeros((len(states), len(states)))
    for col, state in enumerate(states):
        for i, j, right, left in edges:
            a, b = (state >> i) & 1, (state >> j) & 1
            if a != b:
                dest = state ^ (1 << i) ^ (1 << j)
                rate = right if a else left
                matrix[indices[dest], col] += rate
                matrix[col, col] -= rate
        for site, injection, removal in contacts:
            rate = removal if state & (1 << site) else injection
            matrix[indices[state ^ (1 << site)], col] += rate
            matrix[col, col] -= rate
    np.testing.assert_allclose(matrix.sum(axis=0), 0., atol=1e-13)
    return matrix


def stationary(matrix):
    linear = matrix.copy()
    linear[-1] = 1
    target = np.zeros(len(matrix))
    target[-1] = 1
    prob = np.linalg.solve(linear, target)
    assert min(prob) > -1e-13
    np.testing.assert_allclose(matrix @ prob, 0., atol=1e-13)
    return prob


def open_moments(length, backward, alpha, gamma, delta, beta):
    states = list(range(1 << length))
    edges = [(j, j+1, 1., backward) for j in range(length-1)]
    contacts = [(0, alpha, gamma), (length-1, delta, beta)]
    prob = stationary(generator(states, edges, contacts))
    bits = (np.array(states)[:, None] >> np.arange(length)) & 1
    mean = prob @ bits
    centered = bits-mean
    cov = (centered.T * prob) @ centered
    j_left = alpha*(1-mean[0])-gamma*mean[0]
    bond = bits[:, :-1]*(1-bits[:, 1:]) - backward*(1-bits[:, :-1])*bits[:, 1:]
    np.testing.assert_allclose(prob @ bond, j_left, atol=1e-13)
    np.testing.assert_allclose(beta*mean[-1]-delta*(1-mean[-1]), j_left, atol=1e-13)
    return prob, mean, cov, j_left


def catalan(number):
    return comb(2*number, number)//(number+1)


def tasep_profile(length):
    """Unit injection, hopping, extraction; the finite matrices are path counters."""
    identity = np.eye(length+1, dtype=object)
    up = np.diag(np.ones(length, dtype=int), 1)
    occupied = identity + up
    transfer = occupied + identity + up.T
    endpoint = np.zeros(length+1, dtype=object)
    endpoint[0] = 1
    powers = [endpoint]
    for _ in range(length):
        powers.append(transfer @ powers[-1])
    norm = powers[-1][0]
    assert norm == catalan(length+1)
    return np.array([powers[i] @ occupied @ powers[length-i-1] / norm
                     for i in range(length)], dtype=float)


def ssep_covariance(length, i, j, left, right, a=1., b=1.):
    """Off-diagonal covariance, 1-based i<j, contact lengths a=r/κL, b=r/κR."""
    total = length-1+a+b
    return -(left-right)**2*(i-1+a)*(length-j+b)/(total**2*(total-1))


def check_reservoirs():
    for delta in (1., 2., 4.):
        prob, mean, _, current = open_moments(3, .5, 1., 2., delta, 1.)
        q = generator(range(8), [(0,1,1,.5), (1,2,1,.5)], [(0,1,2), (2,delta,1)])
        flux = q * prob
        production = sum((flux[i,j]-flux[j,i])*np.log(flux[i,j]/flux[j,i])
                         for i,j in combinations(range(8),2) if flux[i,j] > 0)
        np.testing.assert_allclose(production, current*np.log(2/delta), atol=1e-14)
        if delta == 2:
            z = np.array([.5, 1., 2.])
            exact = [np.prod([v if n & (1 << i) else 1 for i,v in enumerate(z)])
                     for n in range(8)]
            np.testing.assert_allclose(prob, exact/np.sum(exact), atol=1e-14)
        print("right injection, density, current", delta, mean, current)
    for length in range(2, 9):
        _, mean, _, current = open_moments(length, 0, 1, 0, 0, 1)
        np.testing.assert_allclose(mean, tasep_profile(length), atol=1e-13, rtol=0)
        np.testing.assert_allclose(current, catalan(length)/catalan(length+1), atol=1e-13)
        for a,b in [(1,1), (2,.5)]:
            left, right = .75, .25
            _, _, cov, _ = open_moments(length, 1, left/a, (1-left)/a, right/b, (1-right)/b)
            for i,j in combinations(range(length), 2):
                answer = ssep_covariance(length, i+1, j+1, left, right, a, b)
                np.testing.assert_allclose(cov[i,j], answer, atol=1e-13, rtol=0)
            if a == b == 1:
                correction = -(left-right)**2*(length+2)*(length-1)/(12*(length+1))
                np.testing.assert_allclose(cov.sum()-cov.trace(), correction, atol=1e-13, rtol=0)


def check_duality():
    edges = [(j,j+1,x,x) for j,x in enumerate([1,2,1,3])]
    many, pair, one = [sector(5,n) for n in [3,2,1]]
    full, dual, walk = [generator(s,edges) for s in [many,pair,one]]
    kernel = np.array([[(state & test) == test for test in pair] for state in many], int)
    np.testing.assert_array_equal(full.T @ kernel, kernel @ dual)
    source, target = many.index(11), pair.index(6)  # occupied 1,2,4; probe sites 2,3 (1-based)
    physical = expm(.4*full.T) @ kernel
    dual_value = kernel @ expm(.4*dual)
    np.testing.assert_allclose(physical, dual_value, atol=1e-14)
    probabilities = np.array([bool(11 & state) for state in one]) @ expm(.4*walk)
    print("two-site occupation, independent-walk prediction", physical[source,target],
          probabilities[1]*probabilities[2])


def check_stationary_ring():
    for length, particles in [(4,2), (6,2), (6,3), (6,4)]:
        states = sector(length, particles)
        bits = (np.array(states)[:, None] >> np.arange(length)) & 1
        edges = [(j,(j+1)%length,3,1) for j in range(length)]
        q = generator(states,edges)
        derivative = (q.T @ (bits[:,1]-bits[:,-1])) @ bits[:,0] / len(states)
        expected = 2*particles*(length-particles)*(length-2*particles)
        expected /= length*(length-1)*(length-2)
        np.testing.assert_allclose(derivative,expected,atol=1e-14)
        clusters = np.sum(bits*(1-np.roll(bits,-1,axis=1)),axis=1)
        for k in range(1,min(particles,length-particles)+1):
            count = length*comb(particles-1,k-1)*comb(length-particles-1,k-1)//k
            assert count == sum(clusters==k)
        if (length,particles)==(6,3):
            print("clock waiting and inter-event means", np.mean(1/clusters), 1/np.mean(clusters))

def check_decay_modes():
    positions = list(combinations(range(6), 2))
    states = sector(6, 2)
    for p,q in ((1,0), (1,1)):
        full = generator(states, [(j,(j+1)%6,p,q) for j in range(6)])
        spectrum = np.linalg.eigvals(full)
        for h in (1,2):
            z = np.exp(2j*np.pi*h/5)
            wave = np.array([z**(x-y) + z**(y-x-1) for x,y in positions])
            energy = (p+q)*(2*np.cos(2*np.pi*h/5)-2)
            residual = np.max(abs(full @ wave-energy*wave)) / np.max(abs(wave))
            assert residual < 3e-15
            assert min(abs(spectrum-energy)) < 1.5e-14
    states = sector(4,2)
    a = np.zeros(len(states))
    for j in range(4):
        a[states.index((1 << j) | (1 << ((j+1)%4)))] = (-1)**j
    b = np.array([int(z==5)-int(z==10) for z in states])
    basis = np.stack([a,b],axis=1)
    for bias in (0.,1/sqrt(8),.8,1.):
        p,q = (1+bias)/2,(1-bias)/2
        full = generator(states,[(j,(j+1)%4,p,q) for j in range(4)])
        block = np.array([[-1,-bias],[2*bias,-2]])
        np.testing.assert_allclose(full @ basis, basis @ block, atol=1e-14)
        if np.isclose(bias,1/sqrt(8)):
            nilpotent = block+1.5*np.eye(2)
            assert np.linalg.matrix_rank(nilpotent,tol=1e-12)==1
            np.testing.assert_allclose(nilpotent @ nilpotent, 0, atol=1e-14)
            np.testing.assert_allclose(expm(block), np.exp(-1.5)*(np.eye(2)+nilpotent))


if __name__ == "__main__":
    check_reservoirs()
    check_duality()
    check_stationary_ring()
    check_decay_modes()
