"""Finite Schur, Macdonald and q-TASEP examples. Python 3.9+, NumPy, SciPy."""

from collections import Counter
from fractions import Fraction as F
from itertools import combinations_with_replacement
from math import prod

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


def schur_checks():
    # A matrix of mass two is an unordered pair of (possibly equal) sites.
    shapes = Counter()
    for sites in combinations_with_replacement(range(4), 2):
        entries = Counter(sites)
        first_row = entries[0] + max(entries[1], entries[2]) + entries[3]
        shapes[first_row, 2 - first_row] += 1
    assert shapes == {(2, 0): 9, (1, 1): 1}

    # Bayes forward growth from (1) with new letter b, terminal letters c,d.
    b, c, d = F(2, 3), F(1, 2), F(1, 4)
    no_box = (1 - b * c) * (1 - b * d)
    row = no_box * b * (c**2 + c*d + d**2) / (c+d)
    column = no_box * b * c*d / (c+d)
    assert (row, column) == (F(35, 162), F(5, 81))

    empty_at_first = 1 - F(1, 4)
    empty_at_both = empty_at_first * (1 - F(1, 6))
    covariance = empty_at_both * (1 - empty_at_first)
    assert covariance == F(5, 32)
    print("Two-box Schur counts:", dict(shapes))
    print("Forward row/column probabilities:", row, column)
    print("Across-level empty-site covariance:", covariance)


def macdonald_shape():
    q, t = F(1, 2), F(1, 4)
    # The Macdonald scalar product is diagonal in power sums.
    norm_p11 = 2 * ((1-q) / (1-t))**2  # squared norm of p_1^2
    norm_p2 = 2 * (1-q**2) / (1-t**2)  # squared norm of p_2
    norm_column = (norm_p11 + norm_p2) / 4
    # P_(1,1) = (p_1^2 - p_2)/2; choose P_(2) = p_2 + c P_(1,1)
    # orthogonal to P_(1,1).
    c = norm_p2 / (2 * norm_column)
    norm_row = (c/2)**2 * norm_p11 + (1-c/2)**2 * norm_p2
    row = (2+c)**2 / norm_row
    column = 1 / norm_column

    # Independent expansion of the one-pair Cauchy factor F through z^2.
    linear = (1-t) / (1-q)
    quadratic = linear * (1-t*q) / (1-q**2)
    row_from_series = (2*quadratic + linear**2)**2 / quadratic
    total_from_series = 4*quadratic + 6*linear**2
    assert (row, row+column) == (row_from_series, total_from_series)
    assert column / (row+column) == F(45, 574)
    print("Macdonald row and column coefficients:", row, column)


def confluent_operator():
    q = t = F(1, 2)
    v = F(1, 4)  # v = bx, with two equal letters in each alphabet.
    single = (1-v) / (1-t*v)
    value = single**2
    derivative = 2 * single * (t-1) / (1-t*v)**2  # dR/dv
    confluent = (1+t)*value + (t-1)*v*derivative

    def excess_length_series(s):
        return (1+s) / (1-s)**3

    shorter_row_moment = (1-v**2) / (1-q*v**2)
    excess_moment = excess_length_series(q*v) / excess_length_series(v)
    from_shapes = shorter_row_moment * (1 + t*excess_moment)
    assert confluent == from_shapes == F(426, 343)
    print("Confluent operator and Schur shape sum:", confluent)


def gap_equilibrium():
    q = rho = 0.5
    weights = [1.0]
    for g in range(1, 90):
        weights.append(weights[-1] * rho / (1-q**g))
    mass = sum(weights)
    empty = 1/mass
    speed = sum(w * (1-q**g) for g, w in enumerate(weights)) / mass
    normalizer = prod(1-rho*q**j for j in range(90))
    assert abs(empty-normalizer) < 2e-15
    assert abs(speed-rho) < 2e-15
    print("Stationary blocked fraction and speed in units of a2:", empty, speed)


def follower_no_jump(q=0.5, time=1.0, moment_order=20, max_gap=14):
    # Backward equations for u_j = E[Y1^j Y2^(m-j)], at unit jump scales.
    m = moment_order
    dual = np.zeros((m+1, m+1))
    for j in range(m+1):
        left = 1 - q**j
        right = 1 - q**(m-j)
        dual[j, j] = -left-right
        if j < m:
            dual[j, j+1] = right
    moment = (expm(time*dual) @ np.ones(m+1))[0]
    moment_lower = (moment - q**m) / (1 - q**m)

    # Forward equations in a column convention, killed at the follower's
    # first jump or when the leader jumps past max_gap.
    physical = np.diag([-1 - (1-q**g) for g in range(max_gap+1)])
    physical += np.eye(max_gap+1, k=-1)
    surviving = expm(time*physical)[:, 0].sum()
    omitted = poisson.sf(max_gap, time)
    assert moment_lower <= surviving <= surviving + omitted <= moment
    print("No-jump interval from one moment:", moment_lower, moment)
    print("Direct surviving mass and Poisson cutoff bound:", surviving, omitted)


if __name__ == "__main__":
    schur_checks()
    macdonald_shape()
    confluent_operator()
    gap_equilibrium()
    follower_no_jump()
