"""Finite detectors and finite sampling in ballistic transport. Requires NumPy and SciPy."""
from math import log, pi

import numpy as np
from scipy.linalg import eigh_tridiagonal, expm
from scipy.special import airy, gammaln, jv, logsumexp


def edge_readings(time):
    """Density at site j=t for two translated initial XX walls and their mixture."""
    if time != int(time) or time < 1:
        raise ValueError("Use a positive integer time in the chosen hopping units.")
    orders = np.arange(time, 2*time+60)
    squares = jv(orders, time)**2
    added_tail = jv(np.arange(orders[-1]+1, 3*time+120), time)**2
    assert added_tail.sum() < 1e-15
    scale = (time/2)**(1/3)
    single = squares.sum()
    shifted = squares[1:].sum()
    mixed = (single+shifted)/2
    assert abs(single-shifted-squares[0]) < 1e-14
    return scale*single, scale*mixed


def diagonalize_front():
    """Independent wavefunction evolution from occupied orbitals far from the ends."""
    n, time = 160, 32
    sites = np.arange(n)-n//2
    energy, modes = eigh_tridiagonal(np.zeros(n), np.full(n-1, -.5))
    observation = modes[np.flatnonzero(sites == time)[0]]*np.exp(-1j*time*energy)
    probabilities = abs(observation @ modes.T)**2
    single = probabilities[sites <= 0].sum()
    shifted = probabilities[sites < 0].sum()
    calculated = np.array([single, (single+shifted)/2])*(time/2)**(1/3)
    np.testing.assert_allclose(calculated, edge_readings(time), rtol=0, atol=2e-14)


def zero_transfer_cost(channels):
    """Log-sum of the probabilities of equal independent Bin(M,4/5), Bin(M,1/5)."""
    successes = np.arange(channels+1)
    log_coefficients = (gammaln(channels+1)-gammaln(successes+1)
                        -gammaln(channels-successes+1))
    # For complementary fillings the two probability factors are (.8*.2)^M.
    log_probability = logsumexp(2*log_coefficients+channels*log(.8*.2))
    return -log_probability/channels


def measured_transit():
    """Compose the measured evolution at each dimer interval, with no fitted rates."""
    h = np.array([[0., -1.], [-1., 0.]])
    for steps in [1, 2, 10, 100, 1000]:
        unitary = expm(-1j*h*pi/(2*steps))
        transition = abs(unitary)**2
        observed = np.linalg.matrix_power(transition, steps)[1, 0]
        predicted = (1-np.cos(pi/steps)**steps)/2
        assert abs(observed-predicted) < 2e-13
        print(f"dimer intervals {steps:4d}: final right probability {observed:.9f}")


if __name__ == "__main__":
    diagonalize_front()
    exact = airy(0)[1]**2
    for t in [32, 64, 128, 256, 512, 1024, 2048]:
        bare, mixed = edge_readings(t)
        print(f"edge t={t:4d}: {bare:.9f}, {mixed:.9f}; limit {exact:.9f}")
    measured_transit()
    limit = 2*log(5/4)
    for m in (16, 64, 256, 1024, 4096):
        cost = zero_transfer_cost(m)
        assert limit < cost < limit + log(2*m+1)/m
        print(f"{m:4d} crossing channels: cost per channel {cost:.9f}; limit {limit:.9f}")
