// Refuse a reading that does not fit. Once, the detector reports a bright reflection
// 25 cm to the side of the weight. A gate compares each innovation with the spread the filter
// expected and leaves the prediction alone when the reading is too surprising.
#include <cmath>
#include <cstdio>
#include <cstring>

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

int main(int argc, char** argv) {
    Trace trace(argc, argv);
    const bool gated = !(argc > 1 && std::strcmp(argv[1], "off") == 0);
    const real_t dt = 0.05, camera_sigma = 0.03, gust_intensity = 0.05;
    Bench bench;

    Tracker filter;
    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);

    // Normalised innovation squared: the innovation in units of its expected spread, squared.
    real_t nis = 0.0;
    const real_t limit = 3.0;  // accept readings within three standard deviations
    auto within_limit = [&nis, limit](const Tracker& predicted, const Frame&) {
        const real_t variance = predicted.innovation_covariance(0, 0);
        if (!std::isfinite(variance) || variance <= 0.0) return false;
        const real_t innovation = predicted.innovation.get_field<BobX>();
        nis = innovation * innovation / variance;
        return std::isfinite(nis) && nis <= limit * limit;
    };
    auto accept_all = [&nis](const Tracker& predicted, const Frame&) {
        const real_t innovation = predicted.innovation.get_field<BobX>();
        nis = innovation * innovation / predicted.innovation_covariance(0, 0);
        return true;
    };

    double error_at_reflection = 0.0;
    int rejected = 0;
    for (int k = 1; k <= 80; k++) {
        bench.advance(dt);
        real_t picture = bench.camera(camera_sigma);
        if (k == 50) picture += 0.25;  // the reflection
        Frame frame;
        frame.set_field<BobX>(picture);
        const bool applied = gated ? filter.step_with_gate(dt, frame, within_limit)
                                   : filter.step_with_gate(dt, frame, accept_all);
        if (!applied) rejected++;
        const real_t error = filter.state.get_field<Angle>() - bench.angle;
        if (k == 50) error_at_reflection = error;
        if (k >= 48 && k <= 54) {
            std::printf("t %4.2f s  frame %6.3f m  NIS %6.2f  %s  angle error %6.3f rad\n", k * dt, picture,
                        nis, applied ? "used    " : "rejected", error);
        }
        trace.row("frames", {k * dt, 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), nis,
                             applied ? 1.0 : 0.0});
    }
    std::printf("%s: %d reading%s rejected, angle error on the frame with the reflection %.3f rad\n",
                gated ? "gate at 3 standard deviations" : "no gate", rejected, rejected == 1 ? "" : "s",
                error_at_reflection);
    trace.value("error_at_reflection", error_at_reflection);
    trace.value("rejected", rejected);
    return 0;
}
