// Calibrate the camera before using it. The rod is clamped at angles read from a protractor
// and the camera reports the pixel column of the weight. Two numbers describe the camera:
// how many pixels one metre covers, and the pixel column directly below the pivot.
#include <cmath>
#include <cstdio>
#include <cstring>

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

#include "trace.h"

// The coefficients are the state. They do not change while the camera stays put.
enum Coefficient { Scale, Centre };
using Lens = UKF::StateVector<
    UKF::Field<Scale, real_t>,    // pixels per metre
    UKF::Field<Centre, real_t>>;  // pixel column of the pivot
enum Channel { Column = 10 };
using Pixel = UKF::FixedMeasurementVector<UKF::Field<Column, real_t>>;
using Calibrator = UKF::SquareRootParameterEstimationCore<Lens, Pixel>;

constexpr real_t kLength = 0.5;  // m

namespace UKF {
// The measurement model takes the coefficients and the known clamp angle as an input.
template <>
template <>
real_t Pixel::expected_measurement<Lens, Column>(const Lens& lens, const real_t& clamp_angle) {
    return lens.get_field<Centre>() + lens.get_field<Scale>() * kLength * std::sin(clamp_angle);
}
}  // namespace UKF

int main(int argc, char** argv) {
    Trace trace(argc, argv);
    const bool one_angle = argc > 1 && std::strcmp(argv[1], "one") == 0;
    const real_t pixel_sigma = 1.5;  // pixels

    // The simulated camera really has 800 pixels per metre and its pivot at column 320.
    const real_t errors[] = {0.4, -1.1, 0.7, -0.3, 1.3, -0.8};  // in units of pixel_sigma
    real_t clamp_angles[6], columns[6];
    for (int i = 0; i < 6; i++) {
        clamp_angles[i] = one_angle ? 0.6 : (i % 3 - 1) * 0.6;  // rad, from the protractor
        columns[i] = 320.0 + 800.0 * kLength * std::sin(clamp_angles[i]) + pixel_sigma * errors[i];
    }

    Calibrator filter;
    filter.state << 600.0, 300.0;                       // a rough first guess
    filter.root_covariance.setZero();
    filter.root_covariance.diagonal() << 300.0, 100.0;  // standard deviations of that guess
    filter.process_noise_root_covariance.setZero();     // the coefficients stay fixed
    filter.measurement_root_covariance.set_field<Column>(pixel_sigma);

    for (int i = 0; i < 6; i++) {
        Pixel reading;
        reading.set_field<Column>(columns[i]);
        if (!filter.step(reading, clamp_angles[i])) return 1;  // no time step: a reading and its input
        std::printf("clamp %5.2f rad, column %6.1f px -> scale %6.1f +/- %5.1f px/m, centre %5.1f +/- %4.1f px\n",
                    clamp_angles[i], columns[i], filter.state.get_field<Scale>(),
                    filter.root_covariance.row(0).norm(), filter.state.get_field<Centre>(),
                    filter.root_covariance.row(1).norm());
        trace.row("readings", {clamp_angles[i], columns[i], filter.state.get_field<Scale>(),
                               filter.state.get_field<Centre>(), filter.root_covariance(0, 0),
                               filter.root_covariance(1, 0), filter.root_covariance(1, 1)});
    }

    // How well does the calibration predict the column at an angle it has not seen?
    // The predicted column is centre + scale * h, so its variance is d^T L L^T d with d = [h, 1].
    const real_t unseen = -0.3;  // rad
    const Eigen::Matrix<real_t, 2, 1> direction(kLength * std::sin(unseen), 1.0);
    const real_t column_sigma = (filter.root_covariance.transpose() * direction).norm();
    std::printf("predicted column at %.1f rad: %.1f +/- %.1f px\n", unseen,
                filter.state.get_field<Centre>() + filter.state.get_field<Scale>() * direction(0),
                column_sigma);
    trace.value("column_sigma", column_sigma);
    trace.value("scale", filter.state.get_field<Scale>());
    trace.value("centre", filter.state.get_field<Centre>());
    trace.value("scale_sigma", filter.root_covariance.row(0).norm());
    trace.value("centre_sigma", filter.root_covariance.row(1).norm());
    return 0;
}
