// Swing the pendulum up and hold it inverted with a motor too weak to lift it.
//
// Every 20 ms the controller shifts its plan by one stage, improves it once from the
// measured state, and applies the plan's first torque. Run with a number to allow more
// than one solver iteration per stage: ./swingup 5
#include <cmath>
#include <cstdio>
#include <cstdlib>

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

int main(int argc, char** argv) {
    Trace trace(argc, argv);

    using Solver = NMPC::Solver<Pendulum>;
    static Solver::Workspace workspace;  // holds the plan; a solve allocates nothing
    Solver solver(workspace);
    Pendulum pendulum;
    NMPC::Options<double> options;  // the defaults allow one iteration per solve
    if (argc > 1 && argv[1][0] != '-') options.max_iterations = std::atoi(argv[1]);

    Pendulum::State x(0.05, 0.0);                // nearly hanging, at rest
    solver.reset(x, Pendulum::Control::Zero());  // the first plan applies no torque

    double upright_since = -1.0;
    for (int stage = 0; stage < 500; stage++) {
        if (stage > 0) solver.advance(pendulum, 1);  // drop the stage that has just passed
        const NMPC::Result<double> result = solver.solve(pendulum, x, options);
        if (!result.usable()) return 1;

        const Pendulum::Control torque = solver.policy().u[0];  // the plan's first command
        if (stage % 25 == 0) {
            std::printf("t %5.2f s  angle %6.3f rad  rate %6.3f rad/s  torque %6.3f N m  cost %8.3f\n",
                        stage * pendulum.dt, x(0), x(1), torque(0), result.cost_after);
        }
        const bool upright = std::abs(x(0) - kPi) < 0.05 && std::abs(x(1)) < 0.1;
        if (!upright) upright_since = -1.0;
        else if (upright_since < 0.0) upright_since = stage * pendulum.dt;
        trace.row("stages", {stage * pendulum.dt, x(0), x(1), torque(0), result.cost_before,
                             result.cost_after, double(result.stages_on_bound)});
        if (trace.on()) {
            std::vector<double> plan;
            for (int k = 0; k < Pendulum::Stages; k++) plan.push_back(solver.policy().u[k](0));
            trace.row("plans", plan);
        }
        x = pendulum.step(0, x, torque);  // the simulated pendulum moves on by one stage
    }

    const double error = std::abs(x(0) - kPi);
    std::printf("after 10 s: %.4f rad from inverted, rate %.4f rad/s\n", error, x(1));
    trace.value("upright_since", upright_since);
    trace.value("iterations", options.max_iterations);
    return error < 0.01 && std::abs(x(1)) < 0.05 ? 0 : 1;
}
