// The pendulum of the SFWA UKF guide as a filter sees it: a state, a model of how the
// state changes, and a model of what a camera reports.
#ifndef GUIDE_UKF_PENDULUM_H
#define GUIDE_UKF_PENDULUM_H

#include <cmath>

#include <Eigen/Core>
#include <Eigen/Geometry>
#include <UKF/Core.h>
#include <UKF/MeasurementVector.h>

constexpr real_t kLength = 0.5;       // m, pivot to the centre of the weight
constexpr real_t kMass = 0.2;         // kg, at the end of a massless rod
constexpr real_t kDamping = 0.005;    // N m s/rad, friction at the pivot
constexpr real_t kGravity = 9.80665;  // m/s^2
constexpr real_t kInertia = kMass * kLength * kLength;         // kg m^2
constexpr real_t kWeightTorque = kMass * kGravity * kLength;   // N m, with the rod level

// What the filter estimates. Each field has a key, a type and, by convention, a unit.
enum StateKey { Angle, Rate };
using State = UKF::StateVector<
    UKF::Field<Angle, real_t>,  // rad, from hanging straight down
    UKF::Field<Rate, real_t>>;  // rad/s

// What the camera reports in one frame: how far the weight is to the side of the pivot.
enum SensorKey { BobX = 10 };
using Frame = UKF::FixedMeasurementVector<UKF::Field<BobX, real_t>>;  // m

// The filter: this state, this measurement, and a fourth-order integrator for the model.
using Tracker = UKF::Core<State, Frame, UKF::IntegratorRK4>;

namespace UKF {

// The process model: how fast each field is changing, for any state.
template <>
template <>
inline State State::derivative<>() const {
    State 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);
    return rate_of_change;
}

// The measurement model: what the camera would report if the pendulum were in this state.
template <>
template <>
inline real_t Frame::expected_measurement<State, BobX>(const State& state) {
    return kLength * std::sin(state.get_field<Angle>());
}

}  // namespace UKF

// How far the model can be wrong after dt seconds. Draughts push the weight at random:
// an angular acceleration with intensity q, in rad^2/s^3, acting for the whole interval.
inline State::CovarianceMatrix interval_noise(real_t dt, real_t q) {
    State::CovarianceMatrix noise;
    noise << dt * dt * dt / 3, dt * dt / 2,
             dt * dt / 2,      dt;
    return q * noise;
}

#endif
