// The same tracker with the library's two ways of storing uncertainty: UKF::Core keeps the
// covariance P, and UKF::SquareRootCore keeps a factor L with P = L L^T. A post hides the
// weight from the camera for one second, during which both filters only predict.
#include <algorithm>
#include <cmath>
#include <cstdio>

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

using CovarianceFilter = UKF::Core<State, Frame, UKF::IntegratorRK4>;
using RootFilter = UKF::SquareRootCore<State, Frame, UKF::IntegratorRK4>;

int main(int argc, char** argv) {
    Trace trace(argc, argv);
    const real_t dt = 0.05, camera_sigma = 0.03, gust_intensity = 0.05;
    Bench bench;

    CovarianceFilter filter;
    filter.state << 0.0, 0.0;
    filter.covariance.setZero();
    filter.covariance.diagonal() << 0.5 * 0.5, 2.0 * 2.0;                  // variances
    filter.process_noise_covariance = interval_noise(dt, gust_intensity);  // Q for one frame
    filter.measurement_covariance.set_field<BobX>(camera_sigma * camera_sigma);

    RootFilter root;
    root.state << 0.0, 0.0;
    root.root_covariance.setZero();
    root.root_covariance.diagonal() << 0.5, 2.0;             // standard deviations
    root.process_noise_root_covariance =
        interval_noise(dt, gust_intensity).llt().matrixL();  // a factor of Q
    root.measurement_root_covariance.set_field<BobX>(camera_sigma);

    double largest = 0.0;
    for (int k = 1; k <= 80; k++) {
        bench.advance(dt);
        const real_t picture = bench.camera(camera_sigma);
        const bool hidden = k > 30 && k <= 50;  // from 1.5 s to 2.5 s
        if (hidden) {
            // No frame: move the clock on, and let the uncertainty grow.
            if (!filter.a_priori_step(dt) || !root.a_priori_step(dt)) return 1;
        } else {
            Frame frame;
            frame.set_field<BobX>(picture);
            if (!filter.step(dt, frame) || !root.step(dt, frame)) return 1;
        }
        const State::CovarianceMatrix from_root = root.root_covariance * root.root_covariance.transpose();
        largest = std::max({largest, (filter.state - root.state).cwiseAbs().maxCoeff(),
                            (filter.covariance - from_root).cwiseAbs().maxCoeff()});
        if (k % 5 == 0) {
            std::printf("t %4.2f s  %s  angle %6.3f +/- %.3f rad (true %6.3f)  rate %6.2f +/- %.2f rad/s\n",
                        k * dt, hidden ? "hidden " : "frame  ", filter.state.get_field<Angle>(),
                        std::sqrt(filter.covariance(0, 0)), bench.angle, filter.state.get_field<Rate>(),
                        std::sqrt(filter.covariance(1, 1)));
        }
        trace.row("frames", {k * dt, hidden ? NAN : picture, bench.angle, bench.rate,
                             filter.state.get_field<Angle>(), filter.state.get_field<Rate>(),
                             std::sqrt(filter.covariance(0, 0)), std::sqrt(filter.covariance(1, 1)),
                             filter.covariance(0, 1)});
    }
    // Where will the rod be in one second? Predict on a copy, so the live filter is undisturbed.
    CovarianceFilter forecast = filter;
    for (int k = 0; k < 20; k++) {  // in steps the integrator can follow, each with its own noise
        if (!forecast.a_priori_step(dt)) return 1;
    }
    std::printf("forecast for 5.00 s: angle %.3f +/- %.3f rad\n", forecast.state.get_field<Angle>(),
                std::sqrt(forecast.covariance(0, 0)));
    std::printf("largest difference between the two filters, in any state or covariance entry: %.1e\n", largest);
    std::printf("P from Core:            [%.6f %.6f; %.6f %.6f]\n", filter.covariance(0, 0),
                filter.covariance(0, 1), filter.covariance(1, 0), filter.covariance(1, 1));
    std::printf("L from SquareRootCore:  [%.6f %.6f; %.6f %.6f]\n", root.root_covariance(0, 0),
                root.root_covariance(0, 1), root.root_covariance(1, 0), root.root_covariance(1, 1));
    trace.value("largest_difference", largest);
    return largest < 1e-6 ? 0 : 1;
}
