#!/usr/bin/env python3
"""Two snapshots of four-site TASEP. Run with Python 3, NumPy and SciPy."""

from itertools import combinations
from math import exp

import numpy as np
from scipy.linalg import expm


def generator_joint(s, t):
    """Propagate a probability column, keep alternating pairs, propagate again."""
    states = list(combinations(range(4), 2))
    q = np.zeros((6, 6))
    for a, state in enumerate(states):
        for source in state:
            target = (source + 1) % 4
            if target not in state:
                moved = tuple(sorted((set(state) - {source}) | {target}))
                q[states.index(moved), a] += 1
                q[a, a] -= 1
    alternating = np.array([y - x == 2 for x, y in states])
    at_s = expm(s * q)[:, states.index((0, 1))]
    after_s = expm((t - s) * q) @ (alternating * at_s)
    return after_s[alternating].sum()


def advance(states, duration, rng):
    """Superpose four independent unit-rate bond clocks over one interval."""
    attempts = rng.poisson(4 * duration, size=len(states))
    for event in range(attempts.max()):
        paths = np.flatnonzero(attempts > event)
        departure = rng.integers(4, size=len(paths))
        source_bit = 1 << departure
        target_bit = 1 << ((departure + 1) % 4)
        allowed = ((states[paths] & source_bit) != 0) & ((states[paths] & target_bit) == 0)
        states[paths[allowed]] ^= (source_bit | target_bit)[allowed]


def main():
    s, t = 0.25, 1.0  # times in inverse forward-rate units, starting at sites 1,2
    n = 50_000
    rng = np.random.Generator(np.random.PCG64(20261122))
    states = np.full(n, 0b0011)
    advance(states, s, rng)
    first = np.isin(states, (0b0101, 0b1010))
    advance(states, t - s, rng)
    second = np.isin(states, (0b0101, 0b1010))

    b_s, b_t = ((1 - exp(-3 * u)) / 3 for u in (s, t))
    joint = b_s * (1 + 2 * exp(-3 * (t - s))) / 3
    full = generator_joint(s, t)
    assert abs(joint - full) < 1e-13

    # A permutation preserves both observed histograms exactly.
    shuffled = rng.permutation(second)
    pairs = np.count_nonzero(first & second)
    shuffled_pairs = np.count_nonzero(first & shuffled)
    print(f"Six-state joint {full:.10f}; independent product {b_s * b_t:.10f}")
    print(f"Alternating at first/second time: {first.sum()}/{second.sum()} of {n} paths")
    print(f"Alternating at both: {pairs}; after permutation: {shuffled_pairs}")
    print(f"Paired frequency {pairs/n:.6f}; shuffled {shuffled_pairs/n:.6f}")


if __name__ == "__main__":
    main()
