// A steady torque the model does not know about: a fan blows on the weight. A filter can
// only explain it if its state has somewhere to put it. The first filter has the two
// states of pendulum.h. The second adds the unknown torque as a third.
#include <cmath>
#include <cstdio>
#include <cstdlib>

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

enum PushKey { Push = 2 };
using PushedState = UKF::StateVector<
    UKF::Field<Angle, real_t>, UKF::Field<Rate, real_t>,
    UKF::Field<Push, real_t>>;  // N m, an unknown steady torque
using PushedFilter = UKF::Core<PushedState, Frame, UKF::IntegratorRK4>;

namespace UKF {
template <>
template <>
PushedState PushedState::derivative<>() const {
    PushedState rate_of_change;
    rate_of_change.set_field<Angle>(get_field<Rate>());
    rate_of_change.set_field<Rate>((get_field<Push>() - kDamping * get_field<Rate>() -
                                    kWeightTorque * std::sin(get_field<Angle>())) / kInertia);
    rate_of_change.set_field<Push>(0.0);  // expected to stay as it is
    return rate_of_change;
}

template <>
template <>
real_t Frame::expected_measurement<PushedState, BobX>(const PushedState& state) {
    return kLength * std::sin(state.get_field<Angle>());
}
}  // namespace UKF

int main(int argc, char** argv) {
    Trace trace(argc, argv);
    const real_t fan_torque = argument(argc, argv, 1, 0.15);  // N m
    const real_t dt = 0.05, camera_sigma = 0.03, gust_intensity = 0.05;
    Bench bench;
    bench.torque = fan_torque;

    Tracker two;
    two.state << 0.0, 0.0;
    two.covariance.setZero();
    two.covariance.diagonal() << 0.5 * 0.5, 2.0 * 2.0;
    two.process_noise_covariance = interval_noise(dt, gust_intensity);
    two.measurement_covariance.set_field<BobX>(camera_sigma * camera_sigma);

    PushedFilter three;
    three.state << 0.0, 0.0, 0.0;  // no push assumed to begin with
    three.covariance.setZero();
    three.covariance.diagonal() << 0.5 * 0.5, 2.0 * 2.0, 0.2 * 0.2;  // but it could be 0.2 N m
    three.process_noise_covariance.setZero();
    three.process_noise_covariance.topLeftCorner<2, 2>() = interval_noise(dt, gust_intensity);
    three.process_noise_covariance(2, 2) = 1e-4 * dt;  // the push may change slowly
    three.measurement_covariance.set_field<BobX>(camera_sigma * camera_sigma);

    double sum_two = 0.0, sum_three = 0.0, rate_two = 0.0, rate_three = 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 (!two.step(dt, frame) || !three.step(dt, frame)) return 1;
        const real_t innovation_two = two.innovation.get_field<BobX>();
        const real_t innovation_three = three.innovation.get_field<BobX>();
        if (k > 20) {
            sum_two += innovation_two;
            sum_three += innovation_three;
            rate_two += std::pow(two.state.get_field<Rate>() - bench.rate, 2);
            rate_three += std::pow(three.state.get_field<Rate>() - bench.rate, 2);
            scored++;
        }
        if (k % 20 == 0) {
            std::printf("t %.0f s  push estimate %5.3f +/- %.3f N m  innovation: two states %6.3f m, three states %6.3f m\n",
                        k * dt, three.state.get_field<Push>(), std::sqrt(three.covariance(2, 2)),
                        innovation_two, innovation_three);
        }
        trace.row("frames", {k * dt, frame.get_field<BobX>(), bench.angle, bench.rate,
                             two.state.get_field<Angle>(), two.state.get_field<Rate>(),
                             std::sqrt(two.covariance(0, 0)), innovation_two,
                             three.state.get_field<Angle>(), three.state.get_field<Rate>(),
                             std::sqrt(three.covariance(0, 0)), innovation_three,
                             three.state.get_field<Push>(), std::sqrt(three.covariance(2, 2))});
    }
    std::printf("true push %.3f N m\n", fan_torque);
    std::printf("mean innovation after 1 s: two states %.4f m, three states %.4f m\n", sum_two / scored,
                sum_three / scored);
    std::printf("rate error after 1 s: two states %.2f rad/s RMS, three states %.2f rad/s RMS\n",
                std::sqrt(rate_two / scored), std::sqrt(rate_three / scored));
    trace.value("fan_torque", fan_torque);
    trace.value("push", three.state.get_field<Push>());
    trace.value("push_sigma", std::sqrt(three.covariance(2, 2)));
    trace.value("mean_innovation_two", sum_two / scored);
    trace.value("mean_innovation_three", sum_three / scored);
    trace.value("rate_error_two", std::sqrt(rate_two / scored));
    trace.value("rate_error_three", std::sqrt(rate_three / scored));
    return 0;
}
