"""Thinned Airy determinant and its Barnes G normalization.

Run with Python, NumPy, SciPy and mpmath. Values refer to the unitary soft
edge and the independent retention probability gamma = 1/2.
"""
from math import log, pi

import mpmath as mp
import numpy as np
from scipy.special import airy, roots_legendre


def log_gap(left, gamma, order, right):
    """Gauss–Legendre quadrature of the Airy kernel on [left, right]."""
    nodes, weights = roots_legendre(order)
    position = (nodes + 1) * (right - left) / 2 + left
    weight = weights * (right - left) / 2
    ai, derivative = airy(position)[:2]
    separation = np.subtract.outer(position, position)
    np.fill_diagonal(separation, 1.0)  # Analytical diagonal supplied below.
    kernel = (np.outer(ai, derivative) - np.outer(derivative, ai)) / separation
    np.fill_diagonal(kernel, derivative**2 - position * ai**2)
    weighted_kernel = np.sqrt(np.outer(weight, weight)) * kernel
    eigenvalues = np.linalg.eigvalsh(weighted_kernel)
    assert eigenvalues.min() > -1e-11 and eigenvalues.max() < 1 + 1e-11
    return float(np.log1p(-gamma * eigenvalues).sum())


def leading_terms(left, v):
    distance = -left
    return (-2 * v * distance**1.5 / (3 * pi)
            + (v / (2 * pi))**2 * log(8 * distance**1.5))


if __name__ == "__main__":
    mp.mp.dps = 35
    gamma = 0.5
    v = -log(1 - gamma)
    constant = float(2 * mp.log(abs(mp.barnesg(1 + 1j * v / (2 * pi)))))
    print(f"Real logarithm of the Barnes product: {constant:.12f}")
    for left in (-4, -8, -16, -24):
        coarse = log_gap(left, gamma, 120, 12)
        refined = log_gap(left, gamma, 180, 16)
        intermediate = log_gap(left, gamma, 180, 12)
        extracted = refined - leading_terms(left, v)
        assert abs(extracted - constant) < 0.001
        assert max(abs(coarse - intermediate), abs(intermediate - refined)) < 2e-12
        print(f"s={left:3d}, log F={refined:.10f}, extracted c={extracted:.10f}, "
              f"extracted minus Barnes={extracted-constant:+.8f}, "
              f"change in order={abs(coarse-intermediate):.2e}, "
              f"change in upper endpoint={abs(intermediate-refined):.2e}")
