"""Finite pairing sectors, Richardson states, collisions and BCS projection.

Run: python3 finite_pairing.py
Energies are measured in units of the half-bandwidth in the size sequence.
"""

from itertools import combinations
from math import sqrt

import numpy as np
from scipy.optimize import brentq, root
from scipy.sparse import coo_matrix, diags
from scipy.sparse.linalg import eigsh


def pair_basis(pair_energies, pair_count):
    """Return the kinetic diagonal and the real matrix of S+ S-."""
    level_count = len(pair_energies)
    occupied = list(combinations(range(level_count), pair_count))
    addresses = {state: i for i, state in enumerate(occupied)}
    kinetic, rows, cols, elements = [], [], [], []
    for source, state in enumerate(occupied):
        kinetic.append(sum(pair_energies[level] for level in state))
        rows.append(source)
        cols.append(source)
        elements.append(float(pair_count))
        empty = set(range(level_count)).difference(state)
        for old in state:
            for new in empty:
                target = tuple(sorted((set(state) - {old}) | {new}))
                rows.append(addresses[target])
                cols.append(source)
                elements.append(1.0)
    hopping = coo_matrix((elements, (rows, cols)), shape=(len(occupied),) * 2).tocsr()
    return np.array(kinetic), hopping


def ground_state(kinetic, hopping, coupling):
    hamiltonian = diags(kinetic) - coupling * hopping
    initial = np.ones(len(kinetic)) / sqrt(len(kinetic))
    values, vectors = eigsh(hamiltonian, k=1, which="SA", v0=initial, tol=1e-13)
    energy, vector = values[0], vectors[:, 0]
    residual = np.linalg.norm(hamiltonian @ vector - energy * vector)
    return energy, vector, residual


def blocked_spectrum():
    """Build the original fermion operators on six ordered modes."""
    orbitals = [0, 1, 3]
    modes = 2 * len(orbitals)
    dim = 2**modes
    kinetic = np.zeros((dim, dim))
    removal = []
    for mode in range(modes):
        matrix = np.zeros_like(kinetic)
        bit = 1 << mode
        for state in range(dim):
            if state & bit:
                lower_occupancy = bin(state & (bit - 1)).count("1")
                matrix[state ^ bit, state] = (-1)**lower_occupancy
        removal.append(matrix)
        kinetic += orbitals[mode//2] * (matrix.T @ matrix)
    pair = sum(removal[2*j+1] @ removal[2*j] for j in range(len(orbitals)))
    hamiltonian = kinetic - pair.T @ pair  # g = 1
    sector = [s for s in range(dim) if bin(s).count("1") == 3]
    spectrum = np.linalg.eigvalsh(hamiltonian[np.ix_(sector, sector)])
    expected = [4.] * 8
    for left, right in combinations(orbitals, 2):
        splitting = np.hypot(left-right, 1)
        expected.extend([3 - splitting, 3 + splitting] * 2)
    error = np.max(abs(spectrum - np.sort(expected)))
    print("three-fermion spectrum: 20 states, largest energy error", error)
    assert error < 1e-13


def pair_addition():
    for detuning in (0., 0.5):
        kinetic, hopping = pair_basis([-detuning, detuning], 1)
        energies, states = np.linalg.eigh(np.diag(kinetic) - hopping.toarray())
        weights = abs(states.T @ np.ones(2))**2
        expected = 1 + np.array([1, -1]) / np.hypot(1, detuning)
        np.testing.assert_allclose(weights, expected, atol=1e-14, rtol=0)
        print("detuning, pair-addition energies and weights:", detuning, energies, weights)


def two_regular_pairs():
    levels = np.array([0., 2., 5., 9.])
    g = 0.5
    kinetic, hopping = pair_basis(levels, 2)
    hamiltonian = np.diag(kinetic) - g * hopping.toarray()
    def equations(roots):
        level_sum = np.sum(1 / (levels[:, None] - roots), axis=0)
        return 1/g - level_sum - 2/(roots - roots[::-1])
    solved = root(equations, [-0.45, 1.3], tol=1e-12)
    assert solved.success and np.max(abs(equations(solved.x))) < 1e-12
    def one_pair(energy):
        return 1/g - np.sum(1/(levels-energy))
    independent = [brentq(one_pair, -2, -1e-10), brentq(one_pair, 1e-10, 2-1e-10)]
    for label, roots in [("coupled", solved.x), ("independent", independent)]:
        left, right = [1/(levels-energy) for energy in roots]
        vector = np.array([left[i]*right[j] + left[j]*right[i]
                           for i, j in combinations(range(len(levels)), 2)])
        vector /= np.linalg.norm(vector)
        action = hamiltonian @ vector
        energy = np.dot(vector, action)
        residual = np.linalg.norm(action - energy*vector)
        print(label, "roots, mean energy, energy residual:", roots, energy, residual)
        if label == "coupled":
            assert abs(energy - sum(roots)) < 1e-12 and residual < 1e-12
            assert abs(energy - np.linalg.eigvalsh(hamiltonian)[0]) < 1e-12
        else:
            assert residual > 0.59


def collision():
    critical = 3 - sqrt(5)
    kinetic, hopping = pair_basis([0, 2, 4], 2)
    reference_projector = None
    collision_vector = np.array([(2+sqrt(5))/4, (1+sqrt(5))/8, 1/4])
    collision_vector /= np.linalg.norm(collision_vector)
    at_collision = np.diag(kinetic) - critical * hopping.toarray()
    assert np.linalg.norm(at_collision @ collision_vector) < 1e-14
    print("limiting vector:", collision_vector)
    print("g, root sum, root product, discriminant, spectral gap, projector distance")
    for offset in (0, -0.01, 0.01, -0.001, 0.001, -0.0001, 0.0001):
        g = critical + offset
        values, vectors = np.linalg.eigh(np.diag(kinetic) - g * hopping.toarray())
        t = values[0]
        u = t * (g*t + t*t - 6*t + 8) / (4*g + 3*t - 12)
        discriminant = t*t - 4*u
        projector = np.outer(vectors[:, 0], vectors[:, 0])
        if reference_projector is None:
            reference_projector = projector
            np.testing.assert_allclose(projector, np.outer(collision_vector, collision_vector),
                                       atol=1e-14, rtol=0)
        distance = np.linalg.norm(projector - reference_projector, ord="fro")
        print(f"{g:.8f} {t:.8f} {u:.8f} {discriminant:.8f} "
              f"{values[1]-t:.8f} {distance:.8f}")
        if offset:
            roots = np.roots([1, -t, u])
            for i, root in enumerate(roots):
                rhs = sum(1/(d-root) for d in (0, 2, 4)) + 2/(root-roots[1-i])
                assert abs(rhs - 1/g) < 2e-8


def size_sequence():
    bulk_coupling = 2.0
    print("levels, exact E/L, product E/L, exact C, product C, energy residual")
    for levels in (4, 6, 8, 10, 12, 14):
        epsilon = (2*np.arange(levels) + 1 - levels) / levels
        kinetic, hopping = pair_basis(2*epsilon, levels//2)
        g = bulk_coupling / levels
        energy, vector, residual = ground_state(kinetic, hopping, g)
        exact_c = (vector @ (hopping @ vector)) / levels**2
        def gap_equation(delta):
            return g*np.sum(1/(2*np.hypot(epsilon, delta))) - 1
        delta = brentq(gap_equation, 0.0, bulk_coupling, xtol=1e-14)
        quasienergy = np.hypot(epsilon, delta)
        occupation = (1 - epsilon/quasienergy) / 2
        pair_amplitude = delta/(2*quasienergy)
        product_c = (pair_amplitude.sum()**2 + occupation @ occupation) / levels**2
        product_energy = 2*(epsilon @ occupation) - g*levels**2*product_c
        dg = 1e-4
        plus = ground_state(kinetic, hopping, (bulk_coupling+dg)/levels)[0]
        minus = ground_state(kinetic, hopping, (bulk_coupling-dg)/levels)[0]
        assert abs((minus-plus)/(2*dg*levels) - exact_c) < 5e-9
        assert residual < 2e-10
        print(f"{levels:2} {energy/levels:.7f} {product_energy/levels:.7f} "
              f"{exact_c:.7f} {product_c:.7f} {residual:.2e}")
        # Keep only configurations with M occupied pair levels.
        u = np.sqrt(1 - occupation)
        v_over_u = np.sqrt(occupation) / u
        configs = combinations(range(levels), levels//2)
        projected = np.prod(u) * np.array([np.prod(v_over_u[list(state)]) for state in configs])
        probability = np.dot(projected, projected)
        projected /= np.sqrt(probability)
        projected_energy = projected @ (kinetic*projected - g*(hopping @ projected))
        projected_c = (projected @ (hopping @ projected)) / levels**2
        print("   number projection: probability, E/K, C, fidelity",
              probability, projected_energy/levels, projected_c, abs(vector @ projected)**2)
        assert 0 < probability < 1 and projected_energy >= energy - 1e-12


if __name__ == "__main__":
    blocked_spectrum()
    pair_addition()
    two_regular_pairs()
    collision()
    size_sequence()
