// The pendulum of the SFWA NMPC guide, described as a problem the solver can plan for:
// a model, its derivatives, a cost and a torque limit.
//
// Adapted from examples/pendulum/pendulum.cpp in https://github.com/sfwa/nmpc (MIT licence).
#ifndef GUIDE_PENDULUM_H
#define GUIDE_PENDULUM_H

#include <cmath>

#include "NMPC/Solver.h"

constexpr double kPi = 3.14159265358979323846;

// Everything you would measure or tune, with its units.
struct Tuning {
    double length = 0.5;         // m
    double mass = 0.2;           // kg, at the end of a massless rod
    double damping = 0.005;      // N m s/rad
    double torque_limit = 0.35;  // N m, about a third of the 0.98 N m that holds the rod level

    double angle_weight = 3.0;     // per rad from inverted
    double rate_weight = 0.3;      // per rad/s
    double torque_weight = 0.5;    // per unit of the torque limit
    double terminal_weight = 4.0;  // per rad and per rad/s, at the end of the plan
};

struct Pendulum {
    using Scalar = double;
    enum { NX = 2, NU = 1, NR = 3, NT = 2, Stages = 100 };
    using State = Eigen::Matrix<double, 2, 1>;    // angle from hanging down (rad), rate (rad/s)
    using Control = Eigen::Matrix<double, 1, 1>;  // motor torque (N m)

    double dt = 0.02;     // length of one stage, s; 100 stages look 2 s ahead
    int substeps = 2;     // steps of the model within one stage
    double g = 9.80665;   // m/s^2
    Tuning tuning;

    // Small changes to this state are ordinary vectors.
    static State retract(const State& x, const State& d) { return x + d; }
    static State difference(const State& x, const State& y) { return x - y; }

    double inertia() const { return tuning.mass * tuning.length * tuning.length; }
    double weight_torque() const { return tuning.mass * g * tuning.length; }

    // Angular acceleration: the motor, less friction, less the pull of gravity.
    double acceleration(const State& x, double torque) const {
        const double friction = tuning.damping * x(1);
        const double gravity = weight_torque() * std::sin(x(0));  // weight times its lever arm
        return (torque - friction - gravity) / inertia();
    }

    // One substep: the rate first, then the angle from the new rate.
    State substep(const State& x, double torque, double h) const {
        const double rate = x(1) + h * acceleration(x, torque);
        return State(x(0) + h * rate, rate);
    }

    // One stage of the plan holds the torque for dt seconds.
    State step(int, const State& x, const Control& u) const {
        const double h = dt / substeps;
        State next = x;
        for (int i = 0; i < substeps; i++) {
            next = substep(next, u(0), h);
        }
        return next;
    }

    // How the next state moves when the state (a) or the torque (b) changes a little.
    template <class A, class B>
    void step_jacobian(int, const State& x, const Control& u, A& a, B& b) const {
        const double h = dt / substeps;
        a.setIdentity();
        b.setZero();
        State s = x;
        for (int i = 0; i < substeps; i++) {
            // The slope of the acceleration at this substep's state.
            const double da_dangle = -weight_torque() * std::cos(s(0)) / inertia();
            const double da_drate = -tuning.damping / inertia();
            Eigen::Matrix<double, 2, 2> m;  // the substep's own Jacobian
            m(1, 0) = h * da_dangle;
            m(1, 1) = 1.0 + h * da_drate;
            m(0, 0) = 1.0 + h * m(1, 0);
            m(0, 1) = h * m(1, 1);
            Eigen::Matrix<double, 2, 1> n;  // and its response to torque
            n(1) = h / inertia();
            n(0) = h * n(1);
            a = (m * a).eval();  // chain it onto the substeps before
            b = (m * b + n).eval();
            s = substep(s, u(0), h);
        }
    }

    // The cost of a stage is half the sum of these three numbers squared.
    template <class R>
    void stage_residual(int, const State& x, const Control& u, R& r) const {
        const double s = std::sqrt(dt);  // so that the weights are per second
        r << s * tuning.angle_weight * (x(0) - kPi),
             s * tuning.rate_weight * x(1),
             s * tuning.torque_weight * u(0) / tuning.torque_limit;
    }

    // The end of the plan is scored once, on where the pendulum is left.
    template <class R>
    void terminal_residual(const State& x, R& r) const {
        r << tuning.terminal_weight * (x(0) - kPi), tuning.terminal_weight * x(1);
    }

    template <class JX, class JU>
    void residual_jacobians(int, const State&, const Control&, JX& jx, JU& ju) const {
        const double s = std::sqrt(dt);
        jx.setZero();
        ju.setZero();
        jx(0, 0) = s * tuning.angle_weight;
        jx(1, 1) = s * tuning.rate_weight;
        ju(2, 0) = s * tuning.torque_weight / tuning.torque_limit;
    }

    template <class JX>
    void terminal_jacobian(const State&, JX& jx) const {
        jx = tuning.terminal_weight * JX::Identity();
    }

    // What the motor can deliver at stage k. The solver never plans outside it.
    void control_bounds(int, Control& lower, Control& upper) const {
        lower(0) = -tuning.torque_limit;
        upper(0) = tuning.torque_limit;
    }

    // Typical sizes: about a radian, a few radians per second, the torque limit.
    State state_scale = State(1.0, 5.0);
    Control control_scale = Control::Constant(0.35);
};

#endif
