#!/usr/bin/env python3
"""Finite inverse-chord measurements and a two-body spin-freezing test.

Python 3 with NumPy and SciPy. Run python3 haldane_shastry_measurements.py.
The polarized sector uses H/J; the singlet probe uses h=8H/J. The relative
Schrödinger calculation divides energies by 2(pi/L)^2 before comparing them.
"""

import math

import numpy as np
from scipy.linalg import eigh_tridiagonal


def spin_matrix(length, states):
    """Dimensionless h = sum csc²(pi*d/L)(P-1) in a closed spin sector."""
    index = {state: row for row, state in enumerate(states)}
    matrix = np.zeros((len(states), len(states)))
    for col, state in enumerate(states):
        for i in range(length):
            for j in range(i + 1, length):
                if ((state >> i) ^ (state >> j)) & 1:
                    swapped = state ^ (1 << i) ^ (1 << j)
                    weight = 1 / math.sin(math.pi * (i-j) / length)**2
                    matrix[index[swapped], col] += weight
                    matrix[col, col] -= weight
    return matrix


def polarized_dispersion():
    maximum_error = 0
    for length in range(2, 17):
        h = spin_matrix(length, [1 << n for n in range(length)]) / 8
        for j in range(length):
            mode = np.exp(2j * np.pi * j * np.arange(length) / length) / math.sqrt(length)
            expected = -j*(length-j)/4
            maximum_error = max(maximum_error, np.linalg.norm(h @ mode - expected*mode))
    assert maximum_error < 1e-13
    print(f"Polarized sectors L=2 through 16, maximum Fourier-vector residual {maximum_error:.2e}")


def singlet_response():
    length = 4
    states = list(range(1 << length))
    h = spin_matrix(length, states)
    energies, eigenvectors = np.linalg.eigh(h)
    ground = eigenvectors[:, 0]
    assert abs(energies[0] + 12) < 1e-14
    expected = [{}, {6: 1/6}, {4: 2/3}, {6: 1/6}]
    for j, lines in enumerate(expected):
        fourier = np.exp(2j * np.pi * j * np.arange(length) / length) / math.sqrt(length)
        sz = np.array([[0.5 - ((state >> n) & 1) for n in range(length)] for state in states])
        applied = (sz @ fourier) * ground
        amplitudes = eigenvectors.T.conj() @ applied
        frequency = energies - energies[0]
        for gap in [0, 4, 6, 12]:
            weight = sum(abs(amplitudes[np.isclose(frequency, gap)])**2)
            assert abs(weight - lines.get(gap, 0)) < 2e-14
        print(f"q = {j}/4 turns: {lines}")


def relative_level(lam, sigma, intervals):
    step = math.pi / intervals
    theta = step * np.arange(1, intervals)
    diagonal = 2/step**2 + lam*(lam+sigma)/np.sin(theta)**2
    off = np.full(intervals-2, -1/step**2)
    values = eigh_tridiagonal(diagonal, off, select="i", select_range=(0, 0),
                              eigvals_only=True)
    return values[0]


def freezing_check():
    lam = 8
    errors = []
    for intervals in [128, 256, 512]:
        singlet = relative_level(lam, -1, intervals)
        triplet = relative_level(lam, 1, intervals)
        # The allowed lowest center quantum numbers are 0 and 1, respectively.
        relative_splitting = (singlet - triplet) / lam
        full_splitting = (singlet - triplet - 1) / lam
        errors.append(abs(relative_splitting - (-2-1/lam)))
        assert abs(full_splitting - relative_splitting + 1/lam) < 1e-14
    assert all(3.9 < a/b < 4.1 for a, b in zip(errors, errors[1:]))
    assert abs(full_splitting - (-2-2/lam)) < 6e-6
    print("Two-body relative splitting at λ=8 approaches −2.125; errors:",
          ", ".join(f"{error:.3g}" for error in errors))


if __name__ == "__main__":
    polarized_dispersion()
    singlet_response()
    freezing_check()
