"""Finite-time current moments, biased rates, and a diffusive-ring trial cost.

Run with Python 3, NumPy and SciPy. Generators act on probability columns.
"""
from itertools import combinations

import numpy as np
from scipy.integrate import quad
from scipy.linalg import expm
from scipy.stats import skellam


def mean_and_variance(generator, first, second, initial, time):
    """Differentiate exp(time * Q_k) at k=0 by evolving its first two derivatives."""
    n = len(initial)
    zero = np.zeros((n, n))
    system = np.block([[generator, zero, zero],
                       [first, generator, zero],
                       [second, 2 * first, generator]])
    start = np.r_[initial, np.zeros(2*n)]
    probability, first_moment, second_moment = (expm(time * system) @ start).reshape(3, n)
    assert np.isclose(probability.sum(), 1)
    mean = first_moment.sum()
    return mean, second_moment.sum() - mean**2


def exclusion_counts():
    states = list(combinations(range(4), 2))
    jump = np.zeros((6, 6))
    cut = np.zeros_like(jump)
    for col, state in enumerate(states):
        for x in state:
            y = (x + 1) % 4
            if y in state:
                continue
            target = tuple(sorted((set(state) - {x}) | {y}))
            row = states.index(target)
            jump[row, col] += 1
            if y == 0:
                cut[row, col] += 1
    generator = jump - np.diag(jump.sum(axis=0))
    initial = np.ones(6) / 6
    for time in (1., 5., 20.):
        mean, variance = mean_and_variance(generator, cut, cut, initial, time)
        mean_all, variance_all = mean_and_variance(generator, jump, jump, initial, time)
        np.testing.assert_allclose([mean, mean_all/4], [time/3]*2)
        class_variance = 5*time/54 + np.expm1(-3*time)/324
        np.testing.assert_allclose(variance_all/16, class_variance, atol=1e-12, rtol=0)
        print("unit-rate TASEP: time, Var(cut), Var(all)/16", time, variance, variance_all/16)


def biased_ring():
    # The residence tilt adds k*F to the generator. Differentiate its stationary
    # eigenvector, imposing sum(v')=0 to remove the stationary null direction.
    generator = np.array([[-3., 1., 2.], [2., -3., 1.], [1., 2., -3.]])
    stationary = np.ones(3)/3
    indicator = np.array([1., 0., 0.])
    forcing = (indicator @ stationary - indicator) * stationary
    equations = generator.copy()
    equations[-1] = 1.
    forcing[-1] = 0.
    derivative = np.linalg.solve(equations, forcing)
    variance_rate = 2 * (indicator @ derivative)
    np.testing.assert_allclose(variance_rate, 2/21)
    print("site-zero residence variance rate", variance_rate)
    tilted = np.array([[-3., 1., 16.], [2., -3., 1.], [1/8, 2., -3.]])
    for remaining in (0., 0.2, 2., 5.):
        h = expm(remaining * tilted.T) @ np.ones(3)
        clockwise = [tilted[(x+1) % 3, x] * h[(x+1) % 3] / h[x] for x in range(3)]
        print("remaining time, clockwise rates from 0/1/2", remaining, clockwise)
    final = expm(5 * tilted) @ np.array([1., 0., 0.])
    np.testing.assert_allclose(final/final.sum(), np.array([4, 2, 1])/7, atol=1e-12)


def diffusive_trial():
    k = 2 * np.pi
    for drive, amplitude in [(2*np.pi, 0.04), (8., 0.04), (8., 0.12)]:
        def cost(x):
            sigma = 0.25 - (amplitude*np.cos(k*x))**2
            gradient = -k * amplitude * np.sin(k*x)
            return (gradient/2 - drive*sigma)**2 / (2*sigma)
        change = quad(cost, 0, 1, epsabs=2e-13)[0] - drive**2/8
        exact = np.pi**2/2 * (1 - np.sqrt(1-4*amplitude**2)) - drive**2*amplitude**2/4
        np.testing.assert_allclose(change, exact, atol=5e-14, rtol=0)
        print("drive, amplitude, cost change", drive, amplitude, change)


def reversed_contact():
    # Reverse the order of the two stages AND the sign of each recorded transfer.
    forward = skellam.pmf(1, 4, 1) * skellam.pmf(-1, 1, 2)
    reverse = skellam.pmf(1, 1, 2) * skellam.pmf(-1, 4, 1)
    ratio = forward/reverse
    np.testing.assert_allclose(ratio, 8.)
    print("zero net transfer: resolved forward/reverse ratio", ratio)


def counts_and_propensities():
    flip = np.array([[-1., 1.], [1., -1.]])
    law = np.array([0.5, 0.5])
    cut = np.array([[0., 0.], [1., 0.]])
    rate = np.diag([1., 0.])
    emission = np.diag([1., 3.])
    for time in (0.1, 1., 4.):
        _, count = mean_and_variance(flip, cut, cut, law, time)
        _, integrated_rate = mean_and_variance(flip, rate, 0*rate, law, time)
        _, modulated = mean_and_variance(flip, emission, emission, law, time)
        correction = -np.expm1(-2*time)
        expected = [time/4 + correction/8, time/4 - correction/8, 3*time - correction/2]
        np.testing.assert_allclose([count, integrated_rate, modulated], expected, atol=1e-13)
        print("time, ring count/compensator variances, modulated-Poisson variance",
              time, count, integrated_rate, modulated)


if __name__ == "__main__":
    exclusion_counts()
    biased_ring()
    diffusive_trial()
    reversed_contact()
    counts_and_propensities()
