#!/usr/bin/env python3
"""Exact finite TASEP tests on the line, in time units s=rt. Python 3, NumPy, SciPy."""

from fractions import Fraction
from functools import lru_cache
from itertools import combinations, combinations_with_replacement, product
from math import comb, factorial, fsum

import numpy as np
from scipy.linalg import expm
from scipy.special import gammainc
from scipy.stats import poisson


@lru_cache(maxsize=2048)
def kernel_entry(m, d, s):
    """The three-particle determinant uses indices -2 through 2."""
    if m <= 0:
        return sum((-1)**j * comb(-m, j) * poisson.pmf(d + j, s)
                   for j in range(1 - m))
    tail = poisson.sf(d - 1, s)
    if m == 1:
        return tail
    if m == 2:
        return s * poisson.sf(d - 2, s) + (1 - d) * tail
    raise ValueError("This check supports at most three particles.")


def endpoint_determinant(initial, target, s):
    matrix = [[kernel_entry(i - j, x - y, s) for j, y in enumerate(initial)]
              for i, x in enumerate(target)]
    return np.linalg.det(matrix)


def endpoint_generator(initial, upper):
    """Retain losses to the outside: no right-moving path can come back."""
    states = [z for z in product(*(range(a, b + 1) for a, b in zip(initial, upper)))
              if all(x < y for x, y in zip(z, z[1:]))]
    indices = {z: i for i, z in enumerate(states)}
    q = np.zeros((len(states), len(states)))
    for j, z in enumerate(states):
        for i, x in enumerate(z):
            if i + 1 < len(z) and z[i + 1] == x + 1:
                continue
            q[j, j] -= 1
            dest = z[:i] + (x + 1,) + z[i + 1:]
            if dest in indices:
                q[indices[dest], j] += 1
    return states, q


def passage_chain(particles, jumps):
    """Cap each jump counter: further jumps cannot affect the requested passage."""
    states = [v[::-1] for v in combinations_with_replacement(range(jumps + 1), particles)]
    states.sort(key=lambda v: (sum(v), v))
    indices = {v: i for i, v in enumerate(states)}
    q = np.zeros((len(states), len(states)))
    means = {}
    for counts in reversed(states):
        j = indices[counts]
        successors = []
        for i, completed in enumerate(counts):
            if completed < jumps and (i == 0 or completed < counts[i - 1]):
                dest = counts[:i] + (completed + 1,) + counts[i + 1:]
                successors.append(dest)
                q[indices[dest], j] += 1
                q[j, j] -= 1
        means[counts] = ((1 + sum(means[v] for v in successors)) / Fraction(len(successors))
                         if successors else Fraction(0))
    return q, means[states[0]]


def rectangle_cdf(s):
    # Integrate xy (x-y)^2 exp(-x-y) over [0,s]^2 and normalize.
    a, b, c = [factorial(j) * gammainc(j + 1, s) for j in (1, 2, 3)]
    return (a * c - b**2) / 2


def main():
    initial, upper = (0, 2, 3), (2, 4, 5)
    states, q = endpoint_generator(initial, upper)
    reflected = q - np.diag(q.sum(axis=0))
    chains = [passage_chain(2, 3), passage_chain(3, 2)]
    assert all(mean == Fraction(39, 8) for _, mean in chains)
    largest_error = 0
    for s in (0.5, 1, 2, 3):
        column = expm(s * q)[:, states.index(initial)]
        exact = [endpoint_determinant(initial, z, s) for z in states]
        largest_error = max(largest_error, np.max(np.abs(column - exact)))
        p_reflected = expm(s * reflected)[states.index(upper), states.index(initial)]
        cdf = rectangle_cdf(s)
        for cap, _ in chains:
            assert abs(expm(s * cap)[-1, 0] - cdf) < 1e-13
        print(f"s={s:g}: endpoint={column[states.index(upper)]:.10f}, "
              f"reflected={p_reflected:.10f}, passage={cdf:.10f}")
    assert largest_error < 1e-13
    print(f"{len(states)*4} determinant entries, maximum absolute error {largest_error:.3g}")
    print(f"Rectangle mean in rate-one units: {chains[0][1]}")

    # In the step model the first two particles have autonomous initial sites -1,0.
    # Its second crossing of 1->2 requires the left particle to reach site 2.
    s, last_site = 2, 17
    finite_sum = fsum(endpoint_determinant((-1, 0), pair, s)
                      for pair in combinations(range(2, last_site + 1), 2))
    tail = poisson.sf(last_site, s)  # rightmost particle jumps without interference
    error = rectangle_cdf(s) - finite_sum
    assert 0 <= error <= tail + 1e-14
    print(f"Step threshold by endpoint summation {finite_sum:.13f}, "
          f"omitted mass at most {tail:.3g}")


if __name__ == "__main__":
    main()
