// A torque the filter is told about. A motor at the pivot pushes the rod with a known,
// steady torque, and the application passes it to every update as an input to the model.
#include <cmath>
#include <cstdio>

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

// An input is any type of your own. The library hands it to both models.
struct Motor {
    real_t torque;  // N m
};

namespace UKF {
template <>
template <>
State State::derivative<Motor>(const Motor& motor) const {
    State rate_of_change;
    rate_of_change.set_field<Angle>(get_field<Rate>());
    rate_of_change.set_field<Rate>((motor.torque - kDamping * get_field<Rate>() -
                                    kWeightTorque * std::sin(get_field<Angle>())) / kInertia);
    return rate_of_change;
}

// The camera takes no notice of the motor, but it is given the same inputs.
template <>
template <>
real_t Frame::expected_measurement<State, BobX, Motor>(const State& state, const Motor&) {
    return kLength * std::sin(state.get_field<Angle>());
}
}  // namespace UKF

int main(int argc, char** argv) {
    Trace trace(argc, argv);
    const real_t dt = 0.05, camera_sigma = 0.03, gust_intensity = 0.05;
    const Motor motor{0.15};
    Bench bench;
    bench.torque = motor.torque;

    Tracker told, untold;  // the same filter type; only the calls differ
    for (Tracker* filter : {&told, &untold}) {
        filter->state << 0.0, 0.0;
        filter->covariance.setZero();
        filter->covariance.diagonal() << 0.5 * 0.5, 2.0 * 2.0;
        filter->process_noise_covariance = interval_noise(dt, gust_intensity);
        filter->measurement_covariance.set_field<BobX>(camera_sigma * camera_sigma);
    }

    double told_error = 0.0, untold_error = 0.0;
    int scored = 0;
    for (int k = 1; k <= 120; k++) {
        bench.advance(dt);
        Frame frame;
        frame.set_field<BobX>(bench.camera(camera_sigma));
        if (!told.step(dt, frame, motor)) return 1;  // inputs follow the measurement
        if (!untold.step(dt, frame)) return 1;       // the model of pendulum.h, with no motor
        if (k > 20) {
            told_error += std::pow(told.state.get_field<Rate>() - bench.rate, 2);
            untold_error += std::pow(untold.state.get_field<Rate>() - bench.rate, 2);
            scored++;
        }
    }
    told_error = std::sqrt(told_error / scored);
    untold_error = std::sqrt(untold_error / scored);
    std::printf("rate error after 1 s: %.2f rad/s RMS when the filter is given the torque, %.2f when it is not\n",
                told_error, untold_error);
    trace.value("told_error", told_error);
    trace.value("untold_error", untold_error);
    return told_error < untold_error ? 0 : 1;
}
