"""Differentiable MPC for the three-link MECS6616 reaching example."""
import jax
import jax.numpy as jnp

jax.config.update("jax_enable_x64", True)

# Arm, target, and 5 s duration follow the 2023 post (site revision 8245c2aa).
# Course simulator: roamlab/mecs6616_sp23_project4 at f173465.
LENGTH = jnp.ones(3)
MASS = jnp.full(3, 0.1)
FRICTION, GRAVITY, DT = 0.1, 9.8, 0.01
START = jnp.array([-jnp.pi / 2, 0., 0., 0., 0., 0.])
GOAL = jnp.array([2.5, -0.7])

# The original demo held a command for 10 steps but predicted only 10 steps.
# Plan 5 successive commands so the optimizer can both accelerate and brake.
HOLD, HORIZON = 10, 5
# The old planner took one unbounded gradient step with scale 1. Here we
# refine the sequence with 30 Adam steps of size 0.12, bounded at ±6 N·m.
TORQUE_LIMIT, ITERATIONS, LEARNING_RATE = 6.0, 30, 0.12

# Row i gives the distances along each link to the center of mass of rod i.
lever = (jnp.tril(jnp.ones((3, 3)), -1) + 0.5 * jnp.eye(3)) * LENGTH
inertia = lever.T @ (MASS[:, None] * lever) + jnp.diag(MASS * LENGTH**2 / 12)
gravity_arm = GRAVITY * (MASS @ lever)


def step(state, torque):
    q, dq = jnp.split(state, 2)
    theta, omega = jnp.cumsum(q), jnp.cumsum(dq)
    delta = theta[:, None] - theta[None, :]
    mass_matrix = inertia * jnp.cos(delta)
    bias = (inertia * jnp.sin(delta)) @ omega**2 + gravity_arm * jnp.cos(theta)
    # Each joint exerts equal and opposite torques on its two adjoining links.
    # The course simulator subtracts viscous drag in each link's torque equation.
    link_torque = torque - jnp.append(torque[1:], 0.) - FRICTION * dq
    alpha = jnp.linalg.solve(mass_matrix, link_torque - bias)
    ddq = jnp.diff(alpha, prepend=0.)
    return jnp.concatenate((q + DT * dq + 0.5 * DT**2 * ddq, dq + DT * ddq))


def tip(state):
    q, dq = jnp.split(state, 2)
    theta, omega = jnp.cumsum(q), jnp.cumsum(dq)
    dx, dy = LENGTH * jnp.cos(theta), LENGTH * jnp.sin(theta)
    return jnp.array([dx.sum(), dy.sum()]), jnp.array([-dy @ omega, dx @ omega])


def hold(state, torque):
    return jax.lax.fori_loop(0, HOLD, lambda _, x: step(x, torque), state)


def loss(plan, state, goal):
    def block(x, u):
        x = hold(x, u)
        position, velocity = tip(x)
        return x, (jnp.sum((position - goal)**2), velocity @ velocity)

    _, (error2, speed2) = jax.lax.scan(block, state, plan)
    # The old cost measured only distance. These example weights encourage
    # progress during the rollout and low position error and speed at its end.
    return (jnp.mean(error2 + 0.03 * speed2) + 2 * error2[-1]
            + 0.2 * speed2[-1] + 0.001 * jnp.mean(plan**2))


@jax.jit
def optimize(plan, state, goal):
    # Adam on the full rollout, with projection onto the allowed torque interval.
    def update(i, carry):
        u, first, second, best, best_cost = carry
        cost, grad = jax.value_and_grad(loss)(u, state, goal)
        best = jnp.where(cost < best_cost, u, best)
        best_cost = jnp.minimum(cost, best_cost)
        first = 0.9 * first + 0.1 * grad
        second = 0.999 * second + 0.001 * grad**2
        direction = (first / (1 - 0.9**(i + 1))) / (
            jnp.sqrt(second / (1 - 0.999**(i + 1))) + 1e-8)
        u = jnp.clip(u - LEARNING_RATE * direction, -TORQUE_LIMIT, TORQUE_LIMIT)
        return u, first, second, best, best_cost

    zeros = jnp.zeros_like(plan)
    initial = (plan, zeros, zeros, plan, jnp.inf)
    last, _, _, best, best_cost = jax.lax.fori_loop(0, ITERATIONS, update, initial)
    return jnp.where(loss(last, state, goal) < best_cost, last, best)


def report(seconds, state):
    position, velocity = tip(state)
    distance = jnp.linalg.norm(position - GOAL)
    speed = jnp.linalg.norm(velocity)
    print(f"{seconds:.0f} s   {distance:.4f} m   {speed:.4f} m/s")


def main():
    state = START
    plan = jnp.zeros((HORIZON, len(LENGTH)))
    advance = jax.jit(hold)
    report(0, state)
    for k in range(1, 51):
        plan = optimize(plan, state, GOAL)
        state = advance(state, plan[0])
        plan = jnp.concatenate((plan[1:], plan[-1:]))
        if k % 10 == 0:
            report(k * HOLD * DT, state)


if __name__ == "__main__":
    main()
