// Hold the pendulum inverted while a torque the model does not know about acts on it.
//
//   ./correction <off|on> [filter cutoff in Hz]
//
// From 0.5 s a steady 0.03 N m pushes the rod, as an off-centre load would. The inner loop is
// the plan's torque plus its stored-gain feedback. With the correction on, it also compares the
// angular acceleration it measures with the one the model expects, and cancels the difference.
#include <algorithm>
#include <cmath>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <cstring>

#include "NMPC/InnerLoop.h"
#include "NMPC/Policy.h"
#include "pendulum.h"
#include "trace.h"

// The pendulum problem, with the correction's share of the motor taken out of the plan's range.
struct Corrected : Pendulum {
    double held = 0.0;  // torque the correction is applying, N m
    void control_bounds(int, Control& lower, Control& upper) const {
        lower(0) = -tuning.torque_limit - held;
        upper(0) = tuning.torque_limit - held;
    }
};

// Repeatable gyroscope noise with a standard deviation of one: the sum of twelve uniform numbers.
double noise() {
    static std::uint32_t state = 12345u;
    double sum = -6.0;
    for (int i = 0; i < 12; i++) {
        state = state * 1664525u + 1013904223u;
        sum += (state >> 8) / 16777216.0;
    }
    return sum;
}

int main(int argc, char** argv) {
    Trace trace(argc, argv);
    const bool correcting = argc > 1 ? std::strcmp(argv[1], "on") == 0 : true;
    const double cutoff = argc > 2 && argv[2][0] != '-' ? std::atof(argv[2]) : 3.0;

    using Solver = NMPC::Solver<Corrected>;
    static Solver::Workspace workspace;
    Solver solver(workspace);
    Corrected pendulum;
    pendulum.substeps = 20;
    NMPC::Options<double> options;
    static NMPC::Policy<Corrected> plan;

    NMPC::Incremental<double, 1, 1> correction;  // one measured quantity, one actuator
    correction.design(cutoff, 1000.0);           // low-pass cutoff and inner-loop rate, Hz
    correction.gain(0) = -pendulum.inertia();    // rad/s^2 of surprise to N m against it
    correction.allocation(0, 0) = 1.0;           // all of it goes to the one motor
    correction.limit(0) = 0.1;                   // the most it may hold, N m

    const double motor_limit = pendulum.tuning.torque_limit;
    const double unknown = 0.03;      // the torque the model leaves out, N m
    const double gyro_sigma = 0.001;  // rad/s of noise on each rate reading
    Pendulum::State x(kPi, 0.0), predicted = x;
    solver.reset(x, Pendulum::Control::Zero());
    double applied = 0.0, last_rate = 0.0;
    double offset_sum = 0.0;
    int offset_count = 0;

    for (long tick = 0; tick < 3000; tick++) {
        if (tick % 20 == 0) {
            if (tick > 0) solver.advance(pendulum, 1);
            pendulum.held = correction.held(0);  // the next plan leaves this much of the motor alone
            if (!solver.solve(pendulum, predicted, options).usable()) return 1;
            plan = solver.policy();
            plan.origin = tick;
            plan.ticks_per_stage = 20;
        }
        const auto stage = plan.at(tick);
        if ((tick - plan.origin) % 20 == 0) predicted = stage.x;

        // What the gyroscope shows of the last millisecond, against what the model expected of it.
        const double rate = x(1) + gyro_sigma * noise();
        const double measured = (rate - last_rate) / 0.001;                 // rad/s^2
        const double expected = pendulum.acceleration(x, applied);          // from the model
        NMPC::Vector<double, 1> surprise;
        surprise(0) = measured - expected;
        if (correcting && tick > 0) correction.update(surprise);
        last_rate = rate;

        // The three terms of the inner loop: the plan, its error law, and the correction.
        const double nominal = plan.feedback(stage.index, x, predicted)(0);
        applied = std::clamp(nominal + correction.held(0), -motor_limit, motor_limit);

        if (tick % 10 == 0) {
            trace.row("samples", {tick * 0.001, x(0) - kPi, x(1), applied, correction.held(0), nominal});
        }
        if (tick >= 2000) {
            offset_sum += x(0) - kPi;
            offset_count++;
        }
        const double push = tick >= 500 ? unknown : 0.0;
        x = pendulum.substep(x, applied + push, 0.001);
        predicted = pendulum.substep(predicted, stage.u(0), 0.001);
    }

    double offset = offset_sum / offset_count;
    if (std::abs(offset) < 5e-5) offset = 0.0;  // print a plain zero, not -0.0000
    std::printf("correction %s", correcting ? "on" : "off");
    if (correcting) std::printf(" (%.0f Hz)", cutoff);
    std::printf(": the rod settles %.4f rad from inverted; the correction holds %.3f N m\n",
                offset, correction.held(0));
    trace.value("offset", offset);
    trace.value("held", correction.held(0));
    return 0;
}
