"""Reproduce selected KdV gas and focusing NLS measurements on Integrable.org.

Run with Python 3 and NumPy. All examples use dimensionless variables.
The two-reservoir calculation uses Congy et al., Wave Motion 134 (2025),
Table 1, KdV2. It evaluates the model underlying Fig. 4, not its samples.
"""
import math

import numpy as np


def front_check(slow, fast, slow_density, fast_density):
    """Derive the two edges and check the fluxes across each independently."""
    v1, v2 = 4 * slow**2, 4 * fast**2
    overlap = math.log((fast + slow) / (fast - slow))
    a, b = overlap / slow, overlap / fast
    mixing = np.array([[1, a * slow_density], [b * fast_density, 1]])
    n1, n2 = np.linalg.solve(mixing, [slow_density, fast_density])
    closure = np.array([[1 - a*n2, a*n2], [b*n1, 1 - b*n1]])
    c1, c2 = np.linalg.solve(closure, [v1, v2])
    assert abs(n2 * (c2 - c1) - fast_density * (v2 - c1)) < 1e-13
    assert abs(n1 * (c2 - c1) - slow_density * (c2 - v1)) < 1e-13
    assert abs((v1 - c1) / (a * (v2 - c1)) - fast_density) < 1e-13
    assert abs((c2 - v2) / (b * (c2 - v1)) - slow_density) < 1e-13
    return n1, n2, c1, c2


def gas_fronts():
    for fast_density in (0.03, 0.06):
        print("reservoir inversion", front_check(1, 2, .04, fast_density))
    n1, n2, c1, c2 = front_check(.7, 1, .08, .12)
    left, middle, right = .48, 4 * (.7*n1 + n2), .224
    edges = np.array([196*c1, 196*c2])
    print("KdV2 mean fields and fronts", (left, middle, right), edges)
    assert abs(middle - .5953491890200195) < 1e-13
    width = 75
    # Midpoint samples of the discontinuous, unsmoothed field.
    offsets = width * ((np.arange(10000) + .5)/10000 - .5)
    for center, expected in zip(edges, [(left + middle)/2, (middle + right)/2]):
        points = center + offsets
        sample = np.where(points < edges[0], left, np.where(points < edges[1], middle, right))
        assert abs(sample.mean() - expected) < 1e-13


def dilute_condensate():
    q, dilution = 2, .75
    count = 2048
    theta = (np.arange(count) + .5) * math.pi/(2*count)
    eta = q*np.sin(theta)
    weights = dilution * eta / (2*count)
    mean = 4 * (eta @ weights)
    second = (16/3) * (eta**3 @ weights)
    print("diluted condensate: mean, mean square, variance", mean, second, second - mean**2)
    assert np.allclose([mean, second, second-mean**2], [3, 12, 3], atol=2e-13, rtol=0)


def continuous_closure():
    """Compare fixed-point iteration with direct solution of each discretization."""
    density = .03
    continuum_bound = 2 * density * (1 + math.log(8))
    print("continuum sufficient contraction bound", continuum_bound)
    for nodes in (40, 80):
        eta = 1 + (np.arange(nodes) + .5) / nodes
        distance = np.abs(eta[:, None] - eta[None, :])
        np.fill_diagonal(distance, 1)
        kernel = np.log((eta[:, None] + eta[None, :]) / distance) / eta[:, None]
        np.fill_diagonal(kernel, 0)  # A continuous s gives zero diagonal contribution.
        weights = density * kernel / nodes
        operator = np.diag(weights.sum(axis=1)) - weights
        bare = 4*eta**2
        velocity = bare.copy()
        for step in range(35):
            velocity = bare + operator @ velocity
        reference = np.linalg.solve(np.eye(nodes) - operator, bare)
        error = np.max(np.abs(velocity-reference))
        print("midpoint nodes, discrete solver disagreement", nodes, error)
        assert error < 2e-13


def detector(phi, time):
    """Evaluate both complex dressing columns at x=0 without a closed intensity formula."""
    first = np.stack([np.exp(.5j*time), np.exp(-.5j*time)])
    second = np.stack([np.exp(4.5j*time), np.exp(1j*phi-4.5j*time)])
    norm = np.sum(abs(first)**2, axis=0)
    projected = first * np.sum(first.conj()*second, axis=0) / norm
    dressed = second - projected / 2
    field = 2*first[0]*first[1].conj()/norm
    field += 6*dressed[0]*dressed[1].conj()/np.sum(abs(dressed)**2, axis=0)
    return abs(field)**2


def phase_laws():
    n = 10000
    phases = 2 * math.pi * (np.arange(n) + .5) / n
    intensity = detector(phases, np.zeros(n))
    expected = 32/(5 - 3*np.cos(phases))
    assert np.max(abs(intensity - expected)) < 5e-14
    probability = math.acos(7/9)/math.pi
    print("uniform phase: first two moments and exceedance", intensity.mean(),
          np.mean(intensity**2), probability)
    assert abs(np.mean(intensity > 12) - probability) < 2/n
    times = phases / 8
    for initial_phase in (0, .27, math.pi):
        trace = detector(initial_phase, times)
        assert np.allclose([trace.mean(), (trace**2).mean()], [8, 80], atol=1e-12, rtol=0)


def slab_traversal():
    width, advance = 3000, math.log(2)/3
    for halves in ((.02, .02), (.01, .03)):
        elapsed = 0.
        for density in halves:
            speed = (36 - 4*advance*density) / (1 - advance*density)
            elapsed += .5*width / (speed - 4)
        print("slab densities and transit time", halves, elapsed)
        assert abs(elapsed - (width - 60*advance)/32) < 2e-13


if __name__ == "__main__":
    dilute_condensate()
    continuous_closure()
    gas_fronts()
    phase_laws()
    slab_traversal()
