"""Reproduce two Research examples with Python 3 and NumPy.

Run: python3 research_program_checks.py

The ring calculation uses a stationary row probability, unit rightward rates,
and a marked crossing 0 -> 1. The determinant uses Lebesgue measure on [0,B]
and the rank-one kernel exp(-x-y). Neither example uses fitted parameters.
"""

from itertools import combinations
from math import exp

import numpy as np
from numpy.polynomial.legendre import leggauss


def marked_bond_survival():
    states = list(combinations(range(4), 2))
    index = {state: i for i, state in enumerate(states)}
    generator = np.zeros((len(states), len(states)), dtype=int)
    marked = np.zeros_like(generator)
    for i, state in enumerate(states):
        for departure in state:
            arrival = (departure + 1) % 4
            if arrival in state:
                continue
            target = tuple(sorted((set(state) - {departure}) | {arrival}))
            j = index[target]
            generator[i, j] += 1
            generator[i, i] -= 1
            if departure == 0:
                marked[i, j] = 1

    # Equal exit and entrance fluxes at every state give uniform stationarity.
    assert not generator.sum(axis=0).any() and not generator.sum(axis=1).any()
    killed = generator - marked
    derivative = np.ones(len(states), dtype=int)
    numerators = []
    for order in range(5):
        numerators.append(derivative.sum())
        print(f"  S^({order})(0) = {derivative.sum()}/{len(states)}")
        derivative = killed @ derivative
    assert numerators == [6, -2, 0, 0, 2]

    one = np.ones(len(states))
    stationary = one / len(states)
    rate = stationary @ marked @ one
    after = stationary @ marked / rate
    for s in (0., 0.2, 1., 4.):
        # The resolvent integrates the survival curve against exp(-s*time).
        resolvent_survival = np.linalg.solve(s * np.eye(len(states)) - killed, one)
        z = s + 1
        np.testing.assert_allclose(stationary @ resolvent_survival,
                                   1/z + 2/(3*z**2) + 1/(3*z**3))
        np.testing.assert_allclose(after @ resolvent_survival, 1/z + 1/z**2 + 1/z**3)
    potential = np.linalg.inv(-killed)
    mean_waits = potential @ one
    product = after @ potential @ potential @ marked @ mean_waits
    mean_gap = after @ mean_waits
    covariance = product - mean_gap**2
    np.testing.assert_allclose([stationary @ mean_waits, mean_gap, covariance],
                               [2, 3, -1/4])
    print(f"  Random-time mean wait = {stationary @ mean_waits:g}; "
          f"event-time mean gap = {mean_gap:g}; adjacent gap covariance = {covariance:g}")


def fredholm_refinement():
    for boundary in (2, 4, 8):
        exact = (1 + exp(-2 * boundary)) / 2
        for order in (4, 8, 16):
            nodes, weights = leggauss(order)
            positions = (1 + nodes) * boundary / 2
            vector = np.sqrt(weights * boundary / 2) * np.exp(-positions)
            determinant = np.linalg.det(np.eye(order) - np.outer(vector, vector))
            assert abs(determinant - (1 - vector @ vector)) < 2e-14
            print(f"  B={boundary}, n={order:2d}, det={determinant:.12f}, "
                  f"quadrature error={abs(determinant-exact):.2e}, "
                  f"cutoff error={exact-0.5:.2e}")
        assert abs(determinant - exact) < 2e-13


if __name__ == "__main__":
    print("Four-site TASEP, derivatives of no-crossing probability:")
    marked_bond_survival()
    print("Rank-one Fredholm determinant, separate error sources:")
    fredholm_refinement()
