"""Reconstruct the two-site separated coordinates from local swaps. Requires NumPy."""
from itertools import product

import numpy as np

I = np.eye(2)
X = np.array([[0., 1.], [1., 0.]])
HADAMARD = np.array([[1., 1.], [1., -1.]]) / np.sqrt(2)
ROTATE = np.kron(HADAMARD, HADAMARD)


def auxiliary_swap(site):
    """Tensor order is auxiliary spin, physical site 1, physical site 2."""
    swap = np.zeros((8, 8))
    for column, bits in enumerate(product(range(2), repeat=3)):
        row = list(bits)
        row[0], row[site] = row[site], row[0]
        swap[np.ravel_multi_index(row, (2, 2, 2)), column] = 1
    return swap


P1, P2 = auxiliary_swap(1), auxiliary_swap(2)


def operators(u, offset):
    row = ((u - offset) * np.eye(8) + P2) @ (u * np.eye(8) + P1)
    twisted = (np.kron(X, np.eye(4)) @ row).reshape(2, 4, 2, 4)
    return twisted[0, :, 1, :], np.trace(twisted, axis1=0, axis2=2)


def verify_generic_case():
    d0, t0 = operators(0, 3)
    d1, t1 = operators(1, 3)
    _, t3 = operators(3, 3)
    eye = np.eye(4)
    q = -(d1 + eye) @ (d1 + 4 * eye) / 2
    np.testing.assert_allclose(q, np.diag([1, 0, 0, 1]))
    np.testing.assert_allclose(-d0 @ q / 2, np.diag([0, 0, 0, 1]))
    covector = eye[0]
    f = np.stack([covector, covector @ t0, covector @ t3, covector @ t0 @ t3])
    inv = np.linalg.inv(f)
    metric = inv.T @ inv
    vectors = []
    for a, b in [(2 * np.sqrt(2), 2 * np.sqrt(2)), (-2 * np.sqrt(2), -2 * np.sqrt(2)),
                 (2, -4), (-2, 4)]:
        w = np.array([1, a, b, a * b])
        v = inv @ w
        value = a + (b - a) / 3
        np.testing.assert_allclose(t1 @ v, value * v, atol=1e-14)
        np.testing.assert_allclose(w @ metric @ w, v @ v)
        jacobian = [[8 * a - b, -a], [b, a + 4 * b]]
        np.testing.assert_allclose(np.linalg.det(jacobian), 288 if a == b else -288)
        if a == b:
            np.testing.assert_allclose(v @ v, 3)
            one_site = v.reshape(2, 2)
            rho = one_site @ one_site.T / (v @ v)
            np.testing.assert_allclose(np.trace(rho @ rho), 17 / 18)
            vectors.append(v / np.linalg.norm(v))
    probability = abs(np.vdot(*vectors)) ** 2
    np.testing.assert_allclose(probability, 1 / 9)
    print(f"Four joint eigenpolynomials verified. Cross-projection probability {probability:.12f}.")


def numerical_overlaps(h):
    """Compute unsigned right-eigenvector overlaps in the two physical bases."""
    d, transfer = operators(.25, h)
    coordinate = d[1:3, 1:3]
    mixed = (ROTATE.T @ transfer @ ROTATE)[1:3, 1:3]
    measured = []
    for matrix in (coordinate, mixed):
        _, modes = np.linalg.eig(matrix)
        measured.append(abs(np.vdot(modes[:, 0], modes[:, 1])))
    return measured


def verify_limits():
    for h in np.linspace(.025, 2, 80):
        if abs(h - 1) < 1e-10:
            continue
        prediction = [1 / np.hypot(1, h), min(h, 1 / h)]
        np.testing.assert_allclose(numerical_overlaps(h), prediction, atol=1e-12)
    for h, use_transfer in [(0, False), (1, True)]:
        d, t = operators(.25, h)
        m = ((ROTATE.T @ t @ ROTATE) if use_transfer else d)[1:3, 1:3]
        nilpotent = m - np.trace(m) / 2 * I
        assert np.linalg.matrix_rank(nilpotent, tol=1e-12) == 1
        np.testing.assert_allclose(nilpotent @ nilpotent, 0, atol=1e-14)
    print("The singular coordinate and transfer blocks have rank-one nilpotent parts at h=0 and h=1.")


if __name__ == "__main__":
    verify_generic_case()
    verify_limits()
