"""Checks for the oscillator returns and four-site comparison in Foundations.

Run with Python 3, NumPy and SciPy. Computes both dynamics from their local
rules and compares with the closed formulas. All errors are absolute.
"""

import numpy as np
from scipy.linalg import expm


def oscillator_returns():
    """Propagate the second oscillator one period of the first at a time."""
    steps = np.arange(25)
    for detuning in (0.0, np.sqrt(2) / 200):
        angle = 2 * np.pi * (1 / 3 + detuning)
        rotation = expm(np.array([[0.0, -angle], [angle, 0.0]]))
        start = np.array([1.0, 0.0])  # (p / amplitude, m omega q / amplitude)
        for n in steps:
            point = np.linalg.matrix_power(rotation, n) @ start
            phase = 2 * np.pi * (n % 3 / 3 + n * detuning)
            expected = np.array([np.cos(phase), np.sin(phase)])
            np.testing.assert_allclose(point, expected, rtol=0, atol=5e-13)
    assert 3 * np.sqrt(2) / 200 < 2 * 0.03 < 9 * np.sqrt(2) / 200


def spin_laplacian():
    """Construct sum (I-P)/2 on four spins, then restrict to one flipped spin."""
    full = np.zeros((16, 16))
    for state in range(16):
        for site in range(4):
            other = (site + 1) % 4
            changed = ((state >> site) ^ (state >> other)) & 1
            swapped = state ^ (changed << site) ^ (changed << other)
            full[state, state] += 0.5
            full[swapped, state] -= 0.5
    one_flip = [1 << site for site in range(4)]
    return full[np.ix_(one_flip, one_flip)]


def walk_generator():
    generator = np.zeros((4, 4))
    for source in range(4):
        for direction in (-1, 1):
            generator[(source + direction) % 4, source] += 0.5
            generator[source, source] -= 0.5
    return generator


def main():
    oscillator_returns()
    laplacian = spin_laplacian()
    generator = walk_generator()
    np.testing.assert_array_equal(laplacian, -generator)
    np.testing.assert_allclose(np.linalg.eigvalsh(laplacian), [0, 1, 1, 2],
                               rtol=0, atol=2e-15)
    error = 0.0
    for time in np.linspace(0, 2 * np.pi, 129):
        quantum = np.abs(expm(-1j * time * laplacian)[:, 0])**2
        walk = expm(time * generator)[:, 0]
        expected = (np.sin(time / 2)**4, (1 - np.exp(-time))**2 / 4)
        error = max(error, abs(quantum[2] - expected[0]), abs(walk[2] - expected[1]),
                    abs(quantum.sum() - 1), abs(walk.sum() - 1))
    assert error < 2e-13, error
    assert np.isclose(abs(expm(-1j * np.pi * laplacian)[2, 0])**2, 1)
    assert expm(np.pi * generator)[2, 0] < 0.25
    # Squaring Markov probabilities again would lose normalization.
    assert np.sum(expm(generator)[:, 0]**2) < 0.5

    plus = np.array([1, 0, 1, 0]) / np.sqrt(2)
    minus = np.array([1, 0, -1, 0]) / np.sqrt(2)
    np.testing.assert_array_equal(plus**2, minus**2)
    unitary = expm(-0.5j * np.pi * laplacian)
    odd = [1, 3]
    weights = [sum(abs((unitary @ state)[odd])**2) for state in (plus, minus)]
    np.testing.assert_allclose(weights, [1, 0], rtol=0, atol=2e-13)

    print("Oscillator rotations agree through 24 crossings.")
    print(f"Four-site probabilities and normalizations: max error {error:.3g}")
    print("Odd-site weights for equal populations and opposite phases:", weights)


if __name__ == "__main__":
    main()
