"""Six finite spin-chain measurements. Requires Python 3.9+, NumPy and SciPy.

Run with "bonds", "frames" or "bands" to reproduce a local measurement.
The "sectors" and default "all" calculations use ../xxx/xxz_towers.py.
For a standalone download put xxz_towers.py beside this file.
"""

from itertools import permutations
from math import acos, atan, cos, pi, sin, sqrt
from pathlib import Path
import runpy

import numpy as np
from scipy.linalg import expm


def common_xxz_tools():
    sibling = Path(__file__).with_name("xxz_towers.py")
    path = sibling if sibling.is_file() else sibling.parent.parent / "xxx/xxz_towers.py"
    functions = runpy.run_path(str(path))
    return functions["block"], functions["lowest"]


def sector_crossings_and_towers():
    block, lowest = common_xxz_tools()
    for length in (8, 12, 16):
        minima = []
        for m in range(length//2+1):
            _, H = block(length, length//2-m, 2.)
            if H.shape[0] <= 2:
                ev = np.linalg.eigvalsh(H.toarray())
            else:
                ev, _ = lowest(H, 2 if m == 0 else 1)
            minima.append(ev[0])
            if m == 0:
                neutral = ev[1]-ev[0]
        slopes = (np.asarray(minima[1:])-minima[0])/np.arange(1, length//2+1)
        assert np.argmin(slopes) == 0
        print(f"Easy axis L={length}: neutral {neutral:.8f}, first field {min(slopes):.8f}")

        states, H = block(length, length//2, 1.)
        ev, vec = lowest(H, 12)
        ground = vec[:, 0]
        index = {word: j for j, word in enumerate(states)}
        spin = np.zeros(len(states))
        dimer = np.zeros(len(states))
        for i, word in enumerate(states):
            for j in range(length):
                k = (j+1) % length
                a, b = (word >> j) & 1, (word >> k) & 1
                sign = (-1)**j
                spin[i] += sign*(.5-a)*ground[i]
                if a != b:
                    dimer[i] -= sign*.5*ground[i]
                    flipped = word ^ (1 << j) ^ (1 << k)
                    dimer[index[flipped]] += sign*.5*ground[i]
        gaps = []
        for probe in (spin, dimer):
            weights = abs(vec.T @ probe)/np.linalg.norm(probe)
            level = next(j for j in range(1, len(ev)) if weights[j] > 1e-6)
            assert np.linalg.norm(H@vec[:, level]-ev[level]*vec[:, level]) < 3e-12
            gaps.append((ev[level]-ev[0])*length/pi**2)
        triplet, singlet = gaps
        print(f"Isotropic L={length}: triplet {triplet:.8f}, singlet {singlet:.8f},"
              f" weighted mean {(3*triplet+singlet)/4:.8f}")


def spin_operators(s):
    weights = np.arange(s, -s-1, -1)
    plus = np.diag(np.sqrt(s*(s+1)-weights[1:]*(weights[1:]+1)), 1)
    return (plus+plus.T)/2, (plus-plus.T)/(2j), np.diag(weights)


def local_spin_measurements():
    spin = spin_operators(1)
    pauli = [2*matrix for matrix in spin_operators(.5)]
    unit = np.eye(3)
    dot = []
    for i, j in ((0, 1), (1, 2), (2, 0)):
        terms = []
        for s in spin:
            factors = [s if n in (i, j) else unit for n in range(3)]
            terms.append(np.kron(np.kron(factors[0], factors[1]), factors[2]))
        dot.append(sum(terms))

    # Magnetic labels (+,0,-) are indexed by (0,1,2).
    symmetric = np.zeros((3, 3, 3))
    for word, amplitude in [((0, 1, 1), 1), ((0, 0, 2), -2)]:
        for perm in set(permutations(word)):
            symmetric[perm] = amplitude/sqrt(15)
    symmetric = symmetric.ravel()
    antisymmetric = np.zeros((3, 3, 3))
    for perm in permutations(range(3)):
        inversions = sum(perm[i] > perm[j] for i, j in ((0, 1), (0, 2), (1, 2)))
        antisymmetric[perm] = (-1)**inversions/sqrt(6)
    antisymmetric = antisymmetric.ravel()
    polarized = np.eye(27)[0]
    identity = np.eye(27)
    pair_singlet = (dot[0]@dot[0]-identity)/3
    assert np.isclose(symmetric @ pair_singlet @ symmetric, 5/9)
    for name, H, expected in (
        ("Fused", sum(X-X@X for X in dot), (-10, -6, 0)),
        ("Bilinear", sum(dot), (-2, -3, 3)),
        ("Permutation", sum(X+X@X-identity for X in dot), (3, -3, 3)),
    ):
        for vector, energy in zip((symmetric, antisymmetric, polarized), expected):
            assert np.linalg.norm(H@vector-energy*vector) < 2e-14
        es, ea, e3 = expected
        print(f"{name} trimer (symmetric S=1, antisymmetric, S=3): {expected}; ratio {(es-e3)/(ea-e3):.8f}")

    A = sum(np.kron(np.kron(p, s), np.eye(2)) for p, s in zip(pauli, spin))
    B = sum(np.kron(np.kron(np.eye(2), s), p) for p, s in zip(pauli, spin))
    C = sum(np.kron(np.kron(p, np.eye(3)), p) for p in pauli)
    density9 = 2*A+2*B+A@B+B@A-7*C/4+3*np.eye(12)/4
    assert np.allclose(np.linalg.eigvalsh(density9), np.repeat([-7, -1, 2, 5], [3, 1, 3, 5]))
    assert np.isclose(density9[4, 7], 4.)
    print("Mixed triple: 9H eigenvalues -7,-1,2,5; multiplicities 3,1,3,5.")


def floquet_frames():
    size = 16
    layers = [np.zeros((size, size)), np.zeros((size, size))]
    for j in range(4):
        k = (j+1) % 4
        flipped = [word ^ ((((word >> j) ^ (word >> k)) & 1)*((1 << j)+(1 << k)))
                   for word in range(size)]
        layers[j % 2] += np.eye(size)[:, flipped]-np.eye(size)
    A, B = layers
    H = A+B
    for step in (.25, .125, .0625):
        alpha = atan(step)
        V, W = expm(1j*alpha*A/2), expm(1j*alpha*B)
        boundary, midpoint = V@V@W, V@W@V
        assert np.allclose(midpoint, V.conj().T@boundary@V)
        print(f"Floquet d={step:g}: commutator norms"
              f" {np.linalg.norm(H@boundary-boundary@H):.8f},"
              f" {np.linalg.norm(H@midpoint-midpoint@H):.8f}")


def one_magnon_bands():
    eta = pi/3
    lam = np.arcsinh(sin(eta))
    a = np.sinh(lam+1j*eta)
    t, r = 1j*sin(eta)/a, np.sinh(lam)/a
    phase = t/abs(t)
    gate = np.array([[t, r], [r, t]])
    gate8 = np.eye(8, dtype=complex)
    for start in (0, 1):
        layer = np.eye(8, dtype=complex)
        for j in range(start, 8, 2):
            sites = [j, (j+1) % 8]
            layer[np.ix_(sites, sites)] = gate
        gate8 = layer@gate8
    for k in (0., pi/2, pi, -pi/2):
        basis = np.kron(np.exp(1j*k*np.arange(4))[:, None]/2, np.eye(2))
        projected = basis.conj().T@gate8@basis
        reduced = projected/phase**2
        assert np.allclose(gate8@basis, basis@projected)
        assert abs(np.linalg.det(reduced)-1) < 1e-13
        expected = (1-cos(k))/2
        assert abs(np.trace(reduced)/2-expected) < 1e-13
        print(f"Eight sites, cell momentum k/pi={k/pi:g}: relative band phase {acos(expected)/pi:.7f} pi")


if __name__ == "__main__":
    import argparse
    runs = {"sectors": sector_crossings_and_towers, "bonds": local_spin_measurements,
            "frames": floquet_frames, "bands": one_magnon_bands}
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("measurement", nargs="?", default="all", choices=["all", *runs])
    measurement = parser.parse_args().measurement
    for key, calculation in runs.items():
        if measurement in (key, "all"):
            calculation()
