"""Finite spin and gas measurements from independent matrices, roots and Fourier integrals.

Run with Python 3, NumPy and SciPy. Ring outputs use J=1 or ℏ=2m=1.
"""

from itertools import combinations
from math import atan, cos, pi, sin, sqrt

import numpy as np
from scipy.integrate import quad
from scipy.optimize import brentq, root


def sector(nsites, ndown, bonds):
    basis = list(combinations(range(nsites), ndown))
    index = {state: i for i, state in enumerate(basis)}
    matrix = np.zeros((len(basis), len(basis)))
    for col, state in enumerate(basis):
        occupied = set(state)
        for left, right in bonds:
            if (left in occupied) != (right in occupied):
                exchanged = tuple(sorted(occupied.symmetric_difference([left, right])))
                matrix[col, col] += 0.5
                matrix[index[exchanged], col] -= 0.5
    return basis, matrix


def spin_measurements():
    bonds = [(j, (j + 1) % 4) for j in range(4)]
    for label, edges, zero_count in [("ring", bonds, 1), ("two dimers", bonds[::2], 3)]:
        _, matrix = sector(4, 2, edges)
        energies = np.linalg.eigvalsh(matrix)
        assert np.sum(abs(energies) < 1e-12) == zero_count
        print(f"Four-spin {label}: zero modes {zero_count}")
        if label == "ring":
            assert np.linalg.norm(matrix @ np.ones(6)) < 1e-14
            assert abs(np.trace(matrix) / 6 - 4/3) < 1e-14
    basis, matrix = sector(6, 2, [(j, (j + 1) % 6) for j in range(6)])
    energies, vectors = np.linalg.eigh(matrix)
    adjacent = [y - x in (1, 5) for x, y in basis]
    for m, sign in [(1, 1), (2, -1)]:
        energy = 2 * (1 - cos(2 * pi * m / 5))
        matches = np.flatnonzero(abs(energies - energy) < 1e-12)
        assert len(matches) == 1
        prob = np.sum(abs(vectors[adjacent, matches[0]])**2)
        assert abs(prob - (3 + sign * sqrt(5)) / 10) < 2e-14
        print(f"Six-spin E/J={energy:.9f}, measured adjacency {prob:.9f}")
    # Use spin exchange with J=2 so t=1, then add the local down-spin field.
    for size in (4, 8, 16):
        _, partial = sector(size, 1, [(j, j + 1) for j in range(size - 1)])
        def upper(h):
            operator = 2 * partial.copy()
            operator[0, 0] += h
            return np.linalg.eigvalsh(operator)[-1]
        measured = brentq(lambda h: upper(h) - 4, 1.9, 3)
        assert abs(measured - 4*size/(2*size - 1)) < 2e-12
        print(f"Open chain N={size}: threshold h/t={measured:.9f}, upper level at 2.2t={upper(2.2):.9f}")


def three_particle_pressure():
    length = 2*pi - 2*atan(1) - 2*atan(2)
    labels = np.array([-1., 0., 1.])
    def energy(ell):
        def residual(k):
            return ell*k + 2*np.arctan(k[:, None] - k[None, :]).sum(axis=1) - 2*pi*labels
        result = root(residual, labels, tol=1e-12)
        k = result.x
        assert np.max(abs(residual(k))) < 2e-12 and np.all(np.diff(k) > 0)
        return k @ k
    expected = 4 / (length + 9/5)
    for step in (0.01, 0.005, 0.0025, 0.00125):
        pressure = (energy(length-step) - energy(length+step)) / (2*step)
        print(f"Three-boson pressure, displacement {step:g}: {pressure:.10f}")
    assert abs(pressure - expected) < 5e-7


def tonks_occupations():
    for n in (0, 1, 2, 4, 8):
        # Smooth chamber wave integrated directly; the imaginary part is zero by symmetry.
        coefficient = sqrt(2)*quad(lambda x: sin(pi*x)*cos(2*pi*n*x), 0, 1)[0]
        occupation = 2 * coefficient**2
        assert abs(occupation - 16/(pi**2 * (1-4*n*n)**2)) < 1e-13
        print(f"Two impenetrable bosons: occupation at integer mode {n}: {occupation:.10g}")
    modes = np.arange(-5000, 5001, dtype=float)
    occupations = 16 / (pi**2 * (1-4*modes**2)**2)
    assert abs(occupations.sum() - 2) < 1e-12
    # Kinetic sum converges more slowly; bound the discarded positive and negative tails.
    # For n>M, (1-4n²)² >= 9n^4, hence the error is at most 128/(9M).
    energy = np.sum((2*pi*modes)**2 * occupations)
    assert 0 < 2*pi**2 - energy < 128/(9*5000)
    print(f"Kinetic energy E L² at |n|≤5000: {energy:.9f} (limit {2*pi**2:.9f})")


if __name__ == "__main__":
    spin_measurements()
    three_particle_pressure()
    tonks_occupations()
