// Two sensors that report at different times: a camera, and a rate gyroscope on the rod
// which reads a little high. Each update uses whichever readings have arrived.
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <optional>

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

// The gyroscope's bias is something to estimate, so it joins the state.
enum BiasKey { GyroBias = 2 };
using BiasedState = UKF::StateVector<
    UKF::Field<Angle, real_t>, UKF::Field<Rate, real_t>, UKF::Field<GyroBias, real_t>>;

// A dynamic measurement vector names every sensor that might report.
enum GyroKey { Gyro = 11 };
using Readings = UKF::DynamicMeasurementVector<
    UKF::Field<BobX, real_t>,   // m, from the camera
    UKF::Field<Gyro, real_t>>;  // rad/s, from the gyroscope
using Fusion = UKF::Core<BiasedState, Readings, UKF::IntegratorRK4>;

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

template <>
template <>
real_t Readings::expected_measurement<BiasedState, BobX>(const BiasedState& state) {
    return kLength * std::sin(state.get_field<Angle>());
}

template <>
template <>
real_t Readings::expected_measurement<BiasedState, Gyro>(const BiasedState& state) {
    return state.get_field<Rate>() + state.get_field<GyroBias>();
}
}  // namespace UKF

// One update with whatever arrived in the last dt seconds.
bool update(Fusion& filter, real_t dt, std::optional<real_t> camera, std::optional<real_t> gyro) {
    Readings readings;  // a fresh vector holds no readings at all
    if (camera) readings.set_field<BobX>(*camera);
    if (gyro) readings.set_field<Gyro>(*gyro);
    return filter.step(dt, readings);  // with none set, this only predicts
}

int main(int argc, char** argv) {
    Trace trace(argc, argv);
    // Frames between camera pictures, at 100 updates a second: 5 is the 20 Hz of track.cpp.
    const int camera_every = int(argument(argc, argv, 1, 5));
    const real_t true_bias = argument(argc, argv, 2, 0.3);  // rad/s
    const real_t dt = 0.01, camera_sigma = 0.03, gyro_sigma = 0.05, gust_intensity = 0.05;
    Bench bench;

    Fusion filter;
    filter.state << 0.0, 0.0, 0.0;
    filter.covariance.setZero();
    filter.covariance.diagonal() << 0.5 * 0.5, 2.0 * 2.0, 0.5 * 0.5;
    // Noise settings follow the order in which the fields were declared.
    filter.process_noise_covariance.setZero();
    filter.process_noise_covariance.topLeftCorner<2, 2>() = interval_noise(dt, gust_intensity);
    filter.process_noise_covariance(2, 2) = 1e-6 * dt;  // the bias may drift, slowly
    filter.measurement_covariance.set_field<BobX>(camera_sigma * camera_sigma);
    filter.measurement_covariance.set_field<Gyro>(gyro_sigma * gyro_sigma);

    for (int tick = 1; tick <= 400; tick++) {
        bench.advance(dt);
        const real_t time = tick * dt;
        std::optional<real_t> camera, gyro;
        gyro = bench.gyro(gyro_sigma, true_bias);            // every update
        const bool hidden = tick > 100 && tick <= 200;        // a post blocks the camera for a second
        if (tick % camera_every == 0) {
            const real_t picture = bench.camera(camera_sigma);
            if (!hidden) camera = picture;
        }
        if (!update(filter, dt, camera, gyro)) return 1;
        if (tick % 50 == 0) {
            std::printf("t %.1f s  bias %6.3f +/- %.3f rad/s  angle %6.3f +/- %.3f rad (true %6.3f)%s\n",
                        time, filter.state.get_field<GyroBias>(), std::sqrt(filter.covariance(2, 2)),
                        filter.state.get_field<Angle>(), std::sqrt(filter.covariance(0, 0)), bench.angle,
                        hidden ? "  camera hidden" : "");
        }
        trace.row("ticks", {time, camera ? *camera : NAN, *gyro, bench.angle, bench.rate,
                            filter.state.get_field<Angle>(), filter.state.get_field<Rate>(),
                            filter.state.get_field<GyroBias>(), std::sqrt(filter.covariance(0, 0)),
                            std::sqrt(filter.covariance(1, 1)), std::sqrt(filter.covariance(2, 2))});
    }
    trace.value("true_bias", true_bias);
    trace.value("final_bias", filter.state.get_field<GyroBias>());
    trace.value("final_bias_sigma", std::sqrt(filter.covariance(2, 2)));
    return std::abs(filter.state.get_field<GyroBias>() - true_bias) < 0.1 ? 0 : 1;
}
