"""Fit an invariant, test a candidate confined to one shell, and change the Hamiltonian."""
import numpy as np


def design(x, p, force):
    return np.column_stack((p*force, x*p, p*p+x*force))


def main():
    # Exact dimensionless oscillator states, with analytic derivatives.
    t = np.arange(32)*2*np.pi/32
    x, p = np.cos(t), -np.sin(t)
    matrix = design(x, p, -x)
    gram = [[4, -4, 0], [-4, 4, 0], [0, 0, 16]]
    np.testing.assert_allclose(matrix.T @ matrix, gram, rtol=0, atol=1e-14)
    _, s, vt = np.linalg.svd(matrix, full_matrices=False)
    weights = vt[-1]/vt[-1, 0]
    np.testing.assert_allclose(weights, [1, 1, 0], rtol=0, atol=2e-15)
    print("Training singular values and normalized coefficients:", s, weights)
    test = t + 0.173
    x, p = 1.7*np.cos(test), -1.7*np.sin(test)
    heldout = design(x, p, -x) @ weights
    assert max(abs(heldout)) < 1e-14
    print("Withheld uncoupled derivative max:", max(abs(heldout)))
    for radius in (1.0, 1.7):
        x, p = radius*np.cos(t), -radius*np.sin(t)
        candidate = x*(x*x+p*p-1)
        # Apply the vector field to the polynomial using both partials.
        derivative = p*(3*x*x+p*p-1) - x*(2*x*p)
        amplitude = radius*(radius**2-1)
        np.testing.assert_allclose(candidate, amplitude*np.cos(t), rtol=0, atol=2e-14)
        np.testing.assert_allclose(derivative, -amplitude*np.sin(t), rtol=0, atol=2e-14)
        print("Radius and cubic slope at one quarter period:", radius, derivative[8])
    for coupling in (0.1, 0.05):
        row = design(np.array([0.]), np.array([1.]), np.array([-coupling]))
        rate = (row @ weights)[0]
        np.testing.assert_allclose(rate, -coupling, rtol=0, atol=2e-15)
        print("Coupled derivative at the test state:", rate)


if __name__ == "__main__":
    main()
