// Check the pendulum's derivatives against central differences, as a test should.
//
// The second model below makes a common mistake: its Jacobian was written for small swings
// about hanging, where the pull of gravity is proportional to the angle. The check catches it.
#include <cstdio>

#include "NMPC/Check.h"
#include "pendulum.h"
#include "trace.h"

struct SmallAngle : Pendulum {
    template <class A, class B>
    void step_jacobian(int k, const State& x, const Control& u, A& a, B& b) const {
        Pendulum::step_jacobian(k, State(0.0, x(1)), u, a, b);  // the slope at hanging, wherever the rod is
    }
};

template <class Problem>
bool report(const char* name, const Problem& problem, const Pendulum::State& x, const Pendulum::Control& u) {
    const NMPC::CheckResult<double> step = NMPC::check_step_jacobian(problem, 0, x, u, 1e-7);
    const NMPC::CheckResult<double> cost = NMPC::check_residual_jacobians(problem, 0, x, u, 1e-7);
    const NMPC::CheckResult<double> end = NMPC::check_terminal_jacobian(problem, x, 1e-7);
    std::printf("%s at angle %.2f rad:\n", name, x(0));
    std::printf("  step_jacobian       %s  worst error %.2g at row %d, column %d\n",
                step.passed ? "passed" : "FAILED", step.error, step.row, step.column);
    std::printf("  residual_jacobians  %s  worst error %.2g\n", cost.passed ? "passed" : "FAILED", cost.error);
    std::printf("  terminal_jacobian   %s  worst error %.2g\n", end.passed ? "passed" : "FAILED", end.error);
    return step.passed && cost.passed && end.passed;
}

int main(int argc, char** argv) {
    Trace trace(argc, argv);
    const Pendulum pendulum;
    const SmallAngle mistaken;

    const Pendulum::State probe(2.0, -1.5);  // well up one side and moving, so every term matters
    const Pendulum::Control torque = Pendulum::Control::Constant(0.2);
    const bool right = report("pendulum.h", pendulum, probe, torque);
    const bool wrong = report("small-angle Jacobian", mistaken, probe, torque);

    // For the figure: the same check at rest at every angle, and the entry it compares.
    for (int i = -31; i <= 31; i++) {
        const Pendulum::State x(0.1 * i, 0.0);
        const Pendulum::Control none = Pendulum::Control::Zero();
        Eigen::Matrix<double, 2, 2> a, a_mistaken;
        Eigen::Matrix<double, 2, 1> b;
        pendulum.step_jacobian(0, x, none, a, b);
        mistaken.step_jacobian(0, x, none, a_mistaken, b);
        const auto good = NMPC::check_step_jacobian(pendulum, 0, x, none, 1e-7);
        const auto bad = NMPC::check_step_jacobian(mistaken, 0, x, none, 1e-7);
        trace.row("angles", {x(0), pendulum.step(0, x, none)(1), a(1, 0), good.error, double(good.passed),
                             a_mistaken(1, 0), bad.error, double(bad.passed), double(bad.row), double(bad.column)});
    }
    return right && !wrong ? 0 : 1;
}
