"""Reproduce finite matrix-ensemble and determinant examples with NumPy and SciPy."""

from math import exp, pi, sqrt

import numpy as np
from numpy.polynomial.legendre import leggauss
from scipy.integrate import quad
from scipy.linalg import eigvalsh
from scipy.stats import ncx2


def integrate(fun, low, high):
    return quad(fun, low, high, epsabs=2e-13, epsrel=2e-13)[0]


def two_gaussian_levels():
    """Check angular moments in GUE and GOE and the conditional GUE density."""
    for real in (False, True):
        # cos(theta) is uniform on the GUE sphere; theta is uniform on the GOE circle.
        def angular_average(f):
            if real:
                return integrate(lambda theta: f((1 + np.cos(theta)) / 2) / pi, 0, pi)
            return integrate(f, 0, 1)

        second = angular_average(lambda q: q * q)
        np.testing.assert_allclose(second, 3 / 8 if real else 1 / 3)
        off_diagonal = (4 if real else 6) * angular_average(lambda q: q * (1 - q))
        np.testing.assert_allclose(off_diagonal, 0.5 if real else 1.0)

    for x in (0.0, 1.0, -1.5):
        def conditional(y):
            return 2 * (y - x) ** 2 * np.exp(-y * y) / (sqrt(pi) * (1 + 2 * x * x))

        np.testing.assert_allclose(integrate(conditional, -np.inf, np.inf), 1)
        mean = integrate(lambda y: y * conditional(y), -np.inf, np.inf)
        np.testing.assert_allclose(mean, -2 * x / (1 + 2 * x * x), atol=1e-13)


def dyson_gap(gap=2.0, initial=2.0, time=np.log(2)):
    """Check the noncentral chi-square CDF by integrating an axial Gaussian."""
    decay = exp(-time)
    variance = -np.expm1(-2 * time) / 2
    center, radius = initial * decay / 2, gap / 2
    predicted = ncx2.cdf(radius**2 / variance, 3, center**2 / variance)

    def slice_mass(z):
        axial = exp(-((z - center) ** 2) / (2 * variance)) / sqrt(2 * pi * variance)
        disk_probability = -np.expm1(-(radius**2 - z * z) / (2 * variance))
        return axial * disk_probability

    direct = integrate(slice_mass, -radius, radius)
    np.testing.assert_allclose(direct, predicted, atol=1e-14, rtol=0)
    return predicted


def circular_trace(size, frequency):
    """Return E[|Tr(U^frequency)|^2] for a Haar unitary of the given size."""
    # The periodic trapezoid rule is exact for the resolved Fourier polynomial.
    count = 4 * (size + abs(frequency) + 1)
    theta = 2 * pi * np.arange(count) / count
    kernel = np.exp(1j * np.outer(theta, np.arange(size))).sum(axis=1)
    pairs = size**2 - abs(kernel) ** 2
    result = size + np.mean(pairs * np.exp(1j * frequency * theta))
    target = size**2 if frequency == 0 else min(size, abs(frequency))
    np.testing.assert_allclose(result, target, atol=1e-12, rtol=0)
    return result.real


def normalized_bulk_pair(size, displacement):
    """GUE distinct-point intensity divided by the two local intensities."""
    x = np.array([0.0, pi * displacement / sqrt(2 * size)])
    previous = np.zeros(2)
    current = pi**(-0.25) * np.exp(-x * x / 2)
    gram = np.zeros((2, 2))
    for level in range(size):
        gram += np.outer(current, current)
        following = (
            sqrt(2 / (level + 1)) * x * current - sqrt(level / (level + 1)) * previous
        )
        previous, current = current, following
    if displacement != 0:
        numerator = current[0] * previous[1] - previous[0] * current[1]
        christoffel_darboux = sqrt(size / 2) * numerator / (x[0] - x[1])
        np.testing.assert_allclose(
            christoffel_darboux, gram[0, 1], atol=2e-12, rtol=1e-13
        )
    return np.linalg.det(gram) / (gram[0, 0] * gram[1, 1])


def wishart_and_jacobi():
    """Check square Wishart moments and two-dimensional Jacobi odds."""
    # Ordered square Wishart coordinates x = minimum and d = maximum - minimum.
    def moment(a, b):
        min_part = integrate(lambda x: 2 * x**a * np.exp(-2 * x), 0, np.inf)
        gap_part = integrate(lambda d: d ** (2 + b) * np.exp(-d) / 2, 0, np.inf)
        return min_part * gap_part

    moments = [moment(0, 0), moment(1, 0), moment(0, 1), moment(1, 1)]
    np.testing.assert_allclose(moments, [1, 0.5, 3, 1.5], atol=1e-13)

    a = np.array([[2.0, 1.0], [1.0, 2.0]])
    b = np.diag([1.0, 3.0])
    odds = eigvalsh(a, b)
    np.testing.assert_allclose(odds, (4 + np.array([-1, 1]) * sqrt(7)) / 3, atol=1e-14)
    np.testing.assert_allclose(eigvalsh(a, a + b), odds / (1 + odds), atol=1e-14)

    nodes, weights = leggauss(80)
    for threshold in (1.0, 3.0, 10.0):
        odds_nodes = (1 + nodes) * threshold / 2
        scaled_weights = weights * threshold / 2
        first, second = odds_nodes[:, None], odds_nodes[None, :]
        pair = 6 * (first - second) ** 2 / (1 + first) ** 4 / (1 + second) ** 4
        probability = scaled_weights @ pair @ scaled_weights
        expected = (threshold / (1 + threshold)) ** 4
        np.testing.assert_allclose(probability, expected, atol=1e-13)


def pfaffian_and_regularization():
    """Enumerate endpoint counts and check finite-rank regularized determinants."""
    # Four-site endpoint count law by direct unordered pair enumeration.
    weights = np.zeros(3)
    for x in range(4):
        for y in range(x + 1, 4):
            endpoint_count = int(x == 0) + int(y == 3)
            weights[endpoint_count] += (y - x) / 10
    np.testing.assert_allclose(weights, [0.1, 0.6, 0.3])
    for s in (0.0, 1.0, 2.0):
        value = weights @ ((1 - s) ** np.arange(3))
        np.testing.assert_allclose(value, 1 - 1.2 * s + 0.3 * s * s, atol=1e-14)

    for rank in (10, 100, 1000):
        eigenvalues = 1 / np.arange(1, rank + 1)
        regularized = np.exp(np.sum(np.log1p(eigenvalues) - eigenvalues))
        expected = (rank + 1) * np.exp(-eigenvalues.sum())
        np.testing.assert_allclose(regularized, expected, rtol=1e-13)
        print(f"Regularized determinant det_2(I + A) at rank {rank} = {regularized}")


if __name__ == "__main__":
    two_gaussian_levels()
    print(f"Dyson gap CDF at gap 2, initial gap 2, time log(2) = {dyson_gap()}")
    trace_moments = ", ".join(f"{circular_trace(5, k):.12g}" for k in range(9))
    print(f"CUE trace moments for N = 5 and frequencies 0 through 8 = [{trace_moments}]")
    displacements = (0.25, 0.5, 1.0)
    for size in (8, 16, 64, 256):
        ratios = ", ".join(f"{normalized_bulk_pair(size, d):.12g}" for d in displacements)
        print(
            f"GUE normalized pair intensity at N = {size}, separations {displacements} =",
            f"[{ratios}]",
        )
    wishart_and_jacobi()
    pfaffian_and_regularization()
