"""Finite quench measurements. Run with Python 3, NumPy, SciPy and mpmath."""
from itertools import combinations

import mpmath as mp
import numpy as np
from scipy.linalg import expm


def dimer_readout():
    length = 6
    hop = np.roll(np.eye(length), 1, axis=0)
    h = -(hop + hop.T)
    time = np.pi / 2
    evolve = expm(-1j * time * h)
    for odd, even in [(np.sqrt(3) / 2, .5), (.5, np.sqrt(3) / 2)]:
        orbital = np.array([odd, even])
        initial = np.kron(np.eye(length // 2), np.outer(orbital, orbital))
        evolved = evolve @ initial @ evolve.conj().T
        expected_difference = -(odd**2 - even**2) / 3
        np.testing.assert_allclose(evolved[0,0]-evolved[1,1], expected_difference, atol=1e-14)
        print("Odd and even densities at Jt=pi/2:", evolved.diagonal().real[:2])


def sector_swaps(length):
    """Column action of a periodic spin exchange in the half-filled sector."""
    masks = [sum(1 << j for j in pair) for pair in combinations(range(length), length // 2)]
    index = {mask: i for i, mask in enumerate(masks)}
    permutations = []
    for j in range(length):
        k = (j + 1) % length
        def image(mask):
            if ((mask >> j) ^ (mask >> k)) & 1:
                return mask ^ (1 << j) ^ (1 << k)
            return mask
        permutations.append(np.array([index[image(mask)] for mask in masks]))
    return masks, index, permutations


def four_site_overlap():
    masks, index, swaps = sector_swaps(4)
    delta = 2
    h = np.zeros((6, 6))
    adjacent = []
    for i, mask in enumerate(masks):
        interfaces = sum(s[i] != i for s in swaps)
        for s in swaps:
            if s[i] != i:
                h[s[i], i] += .5
        h[i, i] -= delta * interfaces / 2
        if interfaces == 2:
            adjacent.append(i)
    single = np.eye(6)[:,index[5]]
    symmetric = (single + np.eye(6)[:,index[10]]) / np.sqrt(2)
    time = np.pi / np.sqrt(delta**2 + 8)
    for initial, expected in [(symmetric, 2 / 3), (single, 1 / 3)]:
        amplitudes = expm(-1j * h * time) @ initial
        probability = np.sum(abs(amplitudes[adjacent])**2)
        np.testing.assert_allclose(probability, expected)
        print("Peak adjacent-pair probability:", probability)


def odd_charge():
    length = 10
    masks, index, swaps = sector_swaps(length)
    for pattern, expected in [([0,1,2,3,4],4), ([0,2,4,6,8],0)]:
        translations = {sum(1 << ((j+r) % length) for j in pattern) for r in range(length)}
        state = np.zeros(len(masks), dtype=int)
        state[[index[mask] for mask in translations]] = 1
        result = np.zeros_like(state)
        for j, first in enumerate(swaps):
            second = swaps[(j+1) % length]
            # Every transposition is its own inverse. Indexing an entire ket
            # applies these swaps in the opposite order from composition on labels.
            result += state[second][first] - state[first][second]
        np.testing.assert_equal(state @ result, 0)
        np.testing.assert_equal(result @ result, expected * (state @ state))
        print("Odd-charge squared norm:", (result @ result) / (state @ state),
              "output multiplicities:", np.unique(result, return_counts=True))


def winding():
    # Directly subtracting the two double-precision observables would lose
    # the tiny quarter-flux correction. Use independent high-precision sums.
    with mp.workdps(65):
        length = 64
        for flux in [0, mp.pi / 2]:
            for z in [length, 2 * length]:
                momenta = [(2 * mp.pi * j + flux) / length for j in range(length)]
                ring = mp.fsum(mp.cos(z * mp.cos(k)) for k in momenta) / length
                difference = ring - mp.besselj(0, z)
                images = 2*mp.fsum(mp.cos(p*flux)*mp.besselj(p*length,z) for p in range(1,7))
                assert abs(difference - images) < mp.mpf("1e-55")
                print(f"z={z}, flux={mp.nstr(flux,4)}: ring minus line = {mp.nstr(difference,12)}")


def split_pairs():
    # Place one point source in the middle of each equal cell of [0,1].
    distances = (np.arange(1000) + .5) / 1000
    for time in np.linspace(0, 1.25, 51):
        fast = distances < 2 * time
        slow = distances < time
        split = np.count_nonzero(fast != slow) / distances.size
        transported = (fast.sum() + slow.sum()) / distances.size
        arrivals = np.minimum([2 * time, time], 1)
        np.testing.assert_allclose([split, transported], [arrivals[0]-arrivals[1], arrivals.sum()])
    print("Finite source: split pairs and transported carriers agree at 51 observation times.")


if __name__ == "__main__":
    dimer_readout()
    four_site_overlap()
    odd_charge()
    winding()
    split_pairs()
