"""Verify derivatives, a batch loss gradient, and a Jacobian.

Requires Python 3 and NumPy. Run python3 08-derivatives-gradients.py.
Use --torch to compare against PyTorch's torch.func transforms.
Try smaller and larger steps and inspect the printed cubic errors.
"""

import argparse

import numpy as np


def centered_change(function, point, direction, step=1e-5):
    """Estimate the derivative along the parameterized line point + t * direction."""
    displacement = step * direction
    return (function(point + displacement) - function(point - displacement)) / (2 * step)


def nonlinear_map(point):
    a, b = point
    return np.array([a + 2 * b, a * b, a**2 - b])


def check_derivatives():
    features = np.array([[1., 2.], [3., -1.], [2., 0.]])
    labels = np.array([0., 3., 1.])
    weights = np.array([1., -1.])

    def loss(candidate):
        residual = features @ candidate - labels
        return (residual @ residual) / (2 * labels.size)

    residual = features @ weights - labels
    gradient = features.T @ residual / labels.size
    directions = np.eye(weights.size)
    numeric = np.array([centered_change(loss, weights, e) for e in directions])
    np.testing.assert_allclose(residual, [-1, 1, 1])
    np.testing.assert_allclose(gradient, [4 / 3, -1])
    np.testing.assert_allclose(numeric, gradient, rtol=1e-7, atol=1e-8)

    orthogonal = np.array([3., 4.]) / 5
    np.testing.assert_allclose(centered_change(loss, weights, orthogonal), 0, atol=1e-8)
    np.testing.assert_allclose(loss(weights), 0.5)
    np.testing.assert_allclose(loss(weights - 0.1 * gradient), 1493 / 5400)
    assert loss(weights - gradient) > loss(weights)

    point = np.array([2., 3.])
    jacobian = np.array([[1., 2.], [3., 2.], [4., -1.]])
    numeric = np.column_stack([centered_change(nonlinear_map, point, e) for e in directions])
    np.testing.assert_allclose(numeric, jacobian, rtol=1e-7, atol=1e-8)
    displacement = np.array([0.01, -0.02])
    np.testing.assert_allclose(jacobian @ displacement, [-0.03, -0.01, 0.06])
    np.testing.assert_allclose(
        nonlinear_map(point + displacement) - nonlinear_map(point),
        [-0.03, -0.0102, 0.0601],
    )

    print("Batch gradient and nonlinear Jacobian checks passed.")
    print("h          estimated cubic derivative     absolute error")
    for step in (1e-1, 1e-3, 1e-5, 1e-8, 1e-12):
        estimate = centered_change(lambda x: x**3, 2., 1., step)
        print(f"{step:<10.0e} {estimate:<30.15f} {abs(estimate - 12):.3e}")

    return features, labels, weights, gradient, point, jacobian


def check_torch(features, labels, weights, gradient, point, jacobian):
    import torch

    features = torch.from_numpy(features)
    labels = torch.from_numpy(labels)

    def loss(candidate):
        residual = features @ candidate - labels
        return residual.square().mean() / 2

    def vector_map(candidate):
        a, b = candidate.unbind()
        return torch.stack((a + 2 * b, a * b, a.square() - b))

    actual_gradient = torch.func.grad(loss)(torch.from_numpy(weights))
    actual_jacobian = torch.func.jacrev(vector_map)(torch.from_numpy(point))
    torch.testing.assert_close(actual_gradient, torch.from_numpy(gradient))
    torch.testing.assert_close(actual_jacobian, torch.from_numpy(jacobian))
    print("PyTorch gradient and Jacobian checks passed.")


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--torch", action="store_true", help="Run additional PyTorch checks.")
    options = parser.parse_args()
    results = check_derivatives()
    if options.torch:
        check_torch(*results)

    # Try it yourself:
    # 1. Add a shared bias and check its analytic derivative of 1/3.
    # 2. Replace a coordinate probe with a second unit direction.
    # 3. Use absolute value at zero and compare centered and one-sided slopes.
