"""Finite RSK, last-passage and Laguerre checks. Requires NumPy and SciPy.

Run with python3 finite_growth_laws.py. All lattice paths include both endpoints.
"""

from bisect import bisect_right
from itertools import permutations
from math import exp, expm1

import numpy as np
from scipy.integrate import quad
from scipy.special import eval_laguerre, roots_laguerre
from scipy.stats import gamma


def row_shape(word):
    """Return the row lengths produced by weakly increasing row insertion."""
    rows = []
    for letter in word:
        for row in rows:
            slot = bisect_right(row, letter)
            if slot == len(row):
                row.append(letter)
                break
            row[slot], letter = letter, row[slot]
        else:
            rows.append([letter])
    return tuple(map(len, rows))


def increasing_union(word):
    """Find the longest subsequence and the largest union of two disjoint ones."""
    increasing = []
    for mask in range(1 << len(word)):
        sequence = [value for i, value in enumerate(word) if mask & (1 << i)]
        if all(a <= b for a, b in zip(sequence, sequence[1:])):
            increasing.append((mask, len(sequence)))

    longest = max(length for _, length in increasing)
    largest_union = max(
        first_size + second_size
        for first_mask, first_size in increasing
        for second_mask, second_size in increasing
        if (first_mask & second_mask) == 0
    )
    return longest, largest_union


def passage(grid):
    """Maximum weight of an up-right path through a nonnegative array."""
    rows, columns = grid.shape
    best = np.zeros((rows + 1, columns + 1))
    for i in range(1, rows + 1):
        for j in range(1, columns + 1):
            best[i, j] = grid[i - 1, j - 1] + max(best[i - 1, j], best[i, j - 1])
    return best[-1, -1]


def check_mesh():
    """Check the floor-coupling bound, then print exact 2-by-2 mesh statistics."""
    rng = np.random.default_rng(20261122)
    meshes = (0.5, 0.1, 0.025)
    for shape in [(2, 2), (4, 7), (12, 5)]:
        path_length = sum(shape) - 1
        for _ in range(30):
            clocks = rng.exponential(size=shape)
            exact = passage(clocks)
            for mesh in meshes:
                rounded = mesh * passage(np.floor(clocks / mesh))
                assert 0 <= exact - rounded < path_length * mesh

    print("\n2-by-2 geometric passage times")
    print("mesh     scaled mean      tie probability")
    for mesh in meshes:
        theta = exp(-mesh)
        geometric_mean = 4 / expm1(mesh) - 1 / expm1(2 * mesh)
        tie = (1 - theta) / (1 + theta)
        print(f"{mesh:5.3f}    {mesh * geometric_mean:.12f}   {tie:.12f}")


def joint_benchmark(t):
    """Average the conditional 2-by-2 maximum law over a Gamma(4, 1) total."""
    def contribution(total):
        # Given the total, the maximum divided by it lies in [1/2, 1].
        return (2 * t / total - 1) ** 3 * gamma.pdf(total, 4)

    probability = gamma.cdf(t, 4) + quad(contribution, t, 2 * t, epsabs=1e-14)[0]
    closed = 1 - (2 + t * t) * exp(-t) + exp(-2 * t)
    np.testing.assert_allclose(probability, closed, atol=1e-14, rtol=0)


def laguerre_cdf(size, threshold, extra=0):
    """Largest-eigenvalue CDF for square complex Wishart via a tail Gram matrix."""
    if threshold <= 0:
        return 0.0
    nodes, weights = roots_laguerre(size + extra)
    degrees = np.arange(size)[:, None]
    polynomials = eval_laguerre(degrees, threshold + nodes)
    vectors = exp(-threshold / 2) * polynomials * np.sqrt(weights)
    complement = np.eye(size) - vectors @ vectors.T
    return np.linalg.det(complement)


if __name__ == "__main__":
    for word in permutations(range(1, 7)):
        shape = row_shape(word)
        assert (shape[0], sum(shape[:2])) == increasing_union(word)

    print("RSK shape and maximum lengths covered by one or two subsequences")
    for word in [(4, 5, 6, 1, 2, 3), (6, 4, 5, 1, 2, 3)]:
        longest, both = increasing_union(word)
        print(f"word={word}  shape={row_shape(word)}  one={longest}  two={both}")

    check_mesh()
    print("\n2-by-2 largest-value CDF (conditional integration and Laguerre orbitals)")
    print("threshold    probability")
    for t in (1, 2, 4, 8):
        joint_benchmark(t)
        value = laguerre_cdf(2, t)
        exact = 1 - (2 + t * t) * exp(-t) + exp(-2 * t)
        np.testing.assert_allclose(value, exact, atol=1e-14)
        print(f"{t:9d}    {value:.12f}")

    print("\nFinite square Wishart edge")
    print("size    scaled threshold    probability")
    for size in (2, 8, 32, 64):
        for s in (-2.0, 0.0, 1.0):
            threshold = 4 * size + 2 ** (4 / 3) * size ** (1 / 3) * s
            value = laguerre_cdf(size, threshold)
            refined = laguerre_cdf(size, threshold, 8)
            np.testing.assert_allclose(value, refined, atol=1e-12, rtol=0)
            print(f"{size:4d}    {s:16.1f}    {value:.12f}")
