// The same pendulum under the best linear feedback about the inverted position, with its
// torque clipped to what the motor can deliver. It is here for comparison with swingup.cpp.
//
// The gain comes from the model and cost in pendulum.h, linearised where the rod is inverted
// and at rest: a linear quadratic regulator (LQR) for the same horizon of 100 stages.
#include <algorithm>
#include <cmath>
#include <cstdio>

#include "pendulum.h"
#include "trace.h"

int main(int argc, char** argv) {
    Trace trace(argc, argv);
    Pendulum pendulum;
    const Pendulum::State goal(kPi, 0.0);
    const Pendulum::Control none = Pendulum::Control::Zero();

    // The model and the cost as matrices, all evaluated at the goal.
    Eigen::Matrix<double, 2, 2> a;
    Eigen::Matrix<double, 2, 1> b;
    pendulum.step_jacobian(0, goal, none, a, b);
    Eigen::Matrix<double, 3, 2> jx;
    Eigen::Matrix<double, 3, 1> ju;
    pendulum.residual_jacobians(0, goal, none, jx, ju);
    Eigen::Matrix<double, 2, 2> terminal;
    pendulum.terminal_jacobian(goal, terminal);

    // Work back from the end of the horizon to the gain for its first stage.
    Eigen::Matrix<double, 2, 2> value = terminal.transpose() * terminal;
    Eigen::Matrix<double, 1, 2> gain;
    for (int k = 0; k < Pendulum::Stages; k++) {
        const double curvature = (ju.transpose() * ju + b.transpose() * value * b)(0, 0);
        gain = (b.transpose() * value * a) / curvature;
        value = jx.transpose() * jx + a.transpose() * value * (a - b * gain);
    }
    std::printf("gain: %.3f N m per rad, %.3f N m per rad/s\n", gain(0, 0), gain(0, 1));

    Pendulum::State x(0.05, 0.0);
    double highest = 0.0;
    for (int stage = 0; stage < 500; stage++) {
        const double wanted = -(gain * (x - goal))(0, 0);
        const double limit = pendulum.tuning.torque_limit;
        const Pendulum::Control torque = Pendulum::Control::Constant(std::clamp(wanted, -limit, limit));
        if (stage % 25 == 0) {
            std::printf("t %5.2f s  angle %6.3f rad  rate %6.3f rad/s  torque %6.3f N m  wanted %7.3f N m\n",
                        stage * pendulum.dt, x(0), x(1), torque(0), wanted);
        }
        trace.row("stages", {stage * pendulum.dt, x(0), x(1), torque(0), wanted});
        highest = std::max(highest, std::abs(x(0)));
        x = pendulum.step(0, x, torque);
    }
    std::printf("after 10 s: %.4f rad from inverted; largest angle reached %.3f rad\n",
                std::abs(x(0) - kPi), highest);
    trace.value("gain_angle", gain(0, 0));
    trace.value("gain_rate", gain(0, 1));
    trace.value("highest", highest);
    return 0;
}
