"""Measure two end fields and a spin-one defect in finite spin spaces. Requires NumPy."""
import numpy as np

I = np.eye(2)
X = np.array([[0., 1.], [1., 0.]])
Y = np.array([[0., -1j], [1j, 0.]])
Z = np.diag([1., -1.])
SWAP = np.eye(4)[[0, 2, 1, 3]]


def two_end_transfer(u, p, q, closing_axis):
    eye = np.eye(8)
    near = np.kron(SWAP, I)
    far = eye.reshape(2, 2, 2, 8).swapaxes(0, 2).reshape(8, 8)
    left, right = u * eye + near, u * eye + far
    incoming = np.kron(p * I + u * Z, np.eye(4))
    closing = np.kron(q * I + (u + 1) * closing_axis, np.eye(4))
    row = closing @ right @ left @ incoming @ left @ right
    return np.trace(row.reshape(2, 4, 2, 4), axis1=0, axis2=2)


def check_boundaries():
    for p, q, angle in [(.5, -.5, 0), (.5, .5, np.pi / 4), (.5, .5, np.pi / 2)]:
        axis = Z * np.cos(angle) + X * np.sin(angle)
        h = SWAP + np.kron(Z, I) / (2 * p) + np.kron(I, axis) / (2 * q)
        # The transfer is a polynomial with real coefficients. Complex-step
        # differentiation extracts its linear term to O(step squared).
        step = 1e-8
        deriv = two_end_transfer(1j * step, p, q, axis).imag / step
        ref = two_end_transfer(0, p, q, axis)
        np.testing.assert_allclose(ref, 2 * p * q * np.eye(4), atol=1e-14)
        np.testing.assert_allclose(deriv / (4 * p * q) - .5 * np.eye(4), h, atol=1e-13)
        first, second = [two_end_transfer(u, p, q, axis) for u in [.2, .75]]
        np.testing.assert_allclose(first @ second, second @ first, atol=1e-12)
        if q < 0:
            energy, modes = np.linalg.eigh(h)
            imbalance = np.kron(Z, I) - np.kron(I, Z)
            np.testing.assert_allclose(energy, [-np.sqrt(5), 1, 1, np.sqrt(5)])
            np.testing.assert_allclose(modes[:, 0] @ imbalance @ modes[:, 0], -4 / np.sqrt(5))
        else:
            c, s = np.cos(angle / 4), np.sin(angle / 4)
            rotation = np.array([[c, -s], [s, c]])
            triplet = np.kron(rotation, rotation) @ (np.array([0, 1, 1, 0]) / np.sqrt(2))
            np.testing.assert_allclose(h @ triplet, triplet, atol=1e-14)
    plus_x = np.array([1, 1]) / np.sqrt(2)
    reflected = np.diag([1, (1j - 1) / (1j + 1)]) @ plus_x
    np.testing.assert_allclose(Y @ reflected, reflected)
    print("End-field energies, spin imbalance, bisector triplet and reflection phase verified.")


def check_defect():
    sz = np.diag([1., 0., -1.])
    raising = np.sqrt(2) * np.diag([1., 1.], 1)
    sx, sy = (raising + raising.T) / 2, (raising - raising.T) / (2j)
    coupling = np.kron(X, sx) + np.kron(Y, sy) + np.kron(Z, sz)
    eigenvalues, modes = np.linalg.eigh(coupling)
    state = np.eye(6)[:, 3]  # ordinary down spin, spin-one site at m=1
    weights = abs(modes.conj().T @ state) ** 2
    np.testing.assert_allclose(eigenvalues, [-2, -2, 1, 1, 1, 1])
    np.testing.assert_allclose([weights[:2].sum(), weights[2:].sum()], [2 / 3, 1 / 3])
    np.testing.assert_allclose(eigenvalues ** 2 @ weights - (eigenvalues @ weights) ** 2, 2)
    print("Defect probabilities: doublet 2/3, quartet 1/3; variance 2.")


if __name__ == "__main__":
    check_boundaries()
    check_defect()
