blob: 3216c23fd08578a6db6fcd0398b0c20cd2c766fb [file] [log] [blame]
Austin Schuhbb4aae72021-10-08 22:12:25 -07001#include "Eigen/Dense"
2#include "Eigen/Geometry"
3
Austin Schuhbb4aae72021-10-08 22:12:25 -07004#include "absl/strings/str_format.h"
Austin Schuhbb4aae72021-10-08 22:12:25 -07005#include "aos/events/logging/log_reader.h"
6#include "aos/events/shm_event_loop.h"
7#include "aos/init.h"
8#include "aos/network/team_number.h"
9#include "aos/time/time.h"
10#include "aos/util/file.h"
milind-ue53bf552021-12-11 14:42:00 -080011#include "ceres/ceres.h"
12#include "frc971/analysis/in_process_plotter.h"
Austin Schuhbb4aae72021-10-08 22:12:25 -070013#include "frc971/control_loops/drivetrain/improved_down_estimator.h"
milind-u8c72d532021-12-11 15:02:42 -080014#include "frc971/control_loops/quaternion_utils.h"
Jim Ostrowski977850f2022-01-22 21:04:22 -080015#include "frc971/vision/vision_generated.h"
milind-u8c72d532021-12-11 15:02:42 -080016#include "frc971/wpilib/imu_batch_generated.h"
17#include "y2020/vision/calibration_accumulator.h"
18#include "y2020/vision/charuco_lib.h"
Austin Schuhbb4aae72021-10-08 22:12:25 -070019#include "y2020/vision/sift/sift_generated.h"
20#include "y2020/vision/sift/sift_training_generated.h"
21#include "y2020/vision/tools/python_code/sift_training_data.h"
Austin Schuhbb4aae72021-10-08 22:12:25 -070022
23DEFINE_string(config, "config.json", "Path to the config file to use.");
24DEFINE_string(pi, "pi-7971-2", "Pi name to calibrate.");
Austin Schuhbb4aae72021-10-08 22:12:25 -070025
26namespace frc971 {
27namespace vision {
28namespace chrono = std::chrono;
29using aos::distributed_clock;
30using aos::monotonic_clock;
31
Austin Schuh5b379072021-12-26 16:01:04 -080032constexpr double kGravity = 9.8;
33
milind-ue53bf552021-12-11 14:42:00 -080034// The basic ideas here are taken from Kalibr.
35// (https://github.com/ethz-asl/kalibr), but adapted to work with AOS, and to be
36// simpler.
37//
38// Camera readings and IMU readings come in at different times, on different
39// time scales. Our first problem is to align them in time so we can actually
40// compute an error. This is done in the calibration accumulator code. The
41// kalibr paper uses splines, while this uses kalman filters to solve the same
42// interpolation problem so we can get the expected vs actual pose at the time
43// each image arrives.
44//
45// The cost function is then fed the computed angular and positional error for
46// each camera sample before the kalman filter update. Intuitively, the smaller
47// the corrections to the kalman filter each step, the better the estimate
48// should be.
49//
50// We don't actually implement the angular kalman filter because the IMU is so
51// good. We give the solver an initial position and bias, and let it solve from
52// there. This lets us represent drift that is linear in time, which should be
53// good enough for ~1 minute calibration.
54//
55// TODO(austin): Kalman smoother ala
56// https://stanford.edu/~boyd/papers/pdf/auto_ks.pdf should allow for better
57// parallelism, and since we aren't causal, will take that into account a lot
58// better.
59
60// This class takes the initial parameters and biases, and computes the error
61// between the measured and expected camera readings. When optimized, this
62// gives us a cost function to minimize.
63template <typename Scalar>
64class CeresPoseFilter : public CalibrationDataObserver {
Austin Schuhbb4aae72021-10-08 22:12:25 -070065 public:
Austin Schuh5b379072021-12-26 16:01:04 -080066 typedef Eigen::Transform<Scalar, 3, Eigen::Affine> Affine3s;
67
milind-ue53bf552021-12-11 14:42:00 -080068 CeresPoseFilter(Eigen::Quaternion<Scalar> initial_orientation,
69 Eigen::Quaternion<Scalar> imu_to_camera,
Austin Schuh5b379072021-12-26 16:01:04 -080070 Eigen::Matrix<Scalar, 3, 1> gyro_bias,
71 Eigen::Matrix<Scalar, 6, 1> initial_state,
72 Eigen::Quaternion<Scalar> board_to_world,
73 Eigen::Matrix<Scalar, 3, 1> imu_to_camera_translation,
74 Scalar gravity_scalar,
75 Eigen::Matrix<Scalar, 3, 1> accelerometer_bias)
milind-u8c72d532021-12-11 15:02:42 -080076 : accel_(Eigen::Matrix<double, 3, 1>::Zero()),
77 omega_(Eigen::Matrix<double, 3, 1>::Zero()),
Austin Schuh5b379072021-12-26 16:01:04 -080078 imu_bias_(gyro_bias),
milind-ue53bf552021-12-11 14:42:00 -080079 orientation_(initial_orientation),
Austin Schuh5b379072021-12-26 16:01:04 -080080 x_hat_(initial_state),
milind-ue53bf552021-12-11 14:42:00 -080081 p_(Eigen::Matrix<Scalar, 6, 6>::Zero()),
Austin Schuh5b379072021-12-26 16:01:04 -080082 imu_to_camera_rotation_(imu_to_camera),
83 imu_to_camera_translation_(imu_to_camera_translation),
84 board_to_world_(board_to_world),
85 gravity_scalar_(gravity_scalar),
86 accelerometer_bias_(accelerometer_bias) {}
milind-ue53bf552021-12-11 14:42:00 -080087
Austin Schuh5b379072021-12-26 16:01:04 -080088 Scalar gravity_scalar() { return gravity_scalar_; }
Austin Schuhbb4aae72021-10-08 22:12:25 -070089
Austin Schuh5b379072021-12-26 16:01:04 -080090 virtual void ObserveCameraUpdate(
91 distributed_clock::time_point /*t*/,
92 Eigen::Vector3d /*board_to_camera_rotation*/,
93 Eigen::Quaternion<Scalar> /*imu_to_world_rotation*/,
94 Affine3s /*imu_to_world*/) {}
95
96 // Observes a camera measurement by applying a kalman filter correction and
97 // accumulating up the error associated with the step.
Austin Schuhbb4aae72021-10-08 22:12:25 -070098 void UpdateCamera(distributed_clock::time_point t,
milind-u8c72d532021-12-11 15:02:42 -080099 std::pair<Eigen::Vector3d, Eigen::Vector3d> rt) override {
100 Integrate(t);
milind-ue53bf552021-12-11 14:42:00 -0800101
Austin Schuh5b379072021-12-26 16:01:04 -0800102 const Eigen::Quaternion<Scalar> board_to_camera_rotation(
milind-ue53bf552021-12-11 14:42:00 -0800103 frc971::controls::ToQuaternionFromRotationVector(rt.first)
104 .cast<Scalar>());
Austin Schuh5b379072021-12-26 16:01:04 -0800105 const Affine3s board_to_camera =
106 Eigen::Translation3d(rt.second).cast<Scalar>() *
107 board_to_camera_rotation;
108
109 const Affine3s imu_to_camera =
110 imu_to_camera_translation_ * imu_to_camera_rotation_;
milind-ue53bf552021-12-11 14:42:00 -0800111
112 // This converts us from (facing the board),
113 // x right, y up, z towards us -> x right, y away, z up.
114 // Confirmed to be right.
milind-ue53bf552021-12-11 14:42:00 -0800115
116 // Want world -> imu rotation.
117 // world <- board <- camera <- imu.
Austin Schuh5b379072021-12-26 16:01:04 -0800118 const Eigen::Quaternion<Scalar> imu_to_world_rotation =
119 board_to_world_ * board_to_camera_rotation.inverse() *
120 imu_to_camera_rotation_;
milind-ue53bf552021-12-11 14:42:00 -0800121
Austin Schuh5b379072021-12-26 16:01:04 -0800122 const Affine3s imu_to_world =
123 board_to_world_ * board_to_camera.inverse() * imu_to_camera;
124
125 const Eigen::Matrix<Scalar, 3, 1> z =
126 imu_to_world * Eigen::Matrix<Scalar, 3, 1>::Zero();
127
128 Eigen::Matrix<Scalar, 3, 6> H = Eigen::Matrix<Scalar, 3, 6>::Zero();
129 H(0, 0) = static_cast<Scalar>(1.0);
130 H(1, 1) = static_cast<Scalar>(1.0);
131 H(2, 2) = static_cast<Scalar>(1.0);
132 const Eigen::Matrix<Scalar, 3, 1> y = z - H * x_hat_;
133
134 const Eigen::Matrix<double, 3, 3> R =
135 (::Eigen::DiagonalMatrix<double, 3>().diagonal() << ::std::pow(0.01, 2),
136 ::std::pow(0.01, 2), ::std::pow(0.01, 2))
137 .finished()
138 .asDiagonal();
139
140 const Eigen::Matrix<Scalar, 3, 3> S =
141 H * p_ * H.transpose() + R.cast<Scalar>();
142 const Eigen::Matrix<Scalar, 6, 3> K = p_ * H.transpose() * S.inverse();
143
144 x_hat_ += K * y;
145 p_ = (Eigen::Matrix<Scalar, 6, 6>::Identity() - K * H) * p_;
146
147 const Eigen::Quaternion<Scalar> error(imu_to_world_rotation.inverse() *
milind-ue53bf552021-12-11 14:42:00 -0800148 orientation());
149
150 errors_.emplace_back(
151 Eigen::Matrix<Scalar, 3, 1>(error.x(), error.y(), error.z()));
Austin Schuh5b379072021-12-26 16:01:04 -0800152 position_errors_.emplace_back(y);
milind-ue53bf552021-12-11 14:42:00 -0800153
Austin Schuh5b379072021-12-26 16:01:04 -0800154 ObserveCameraUpdate(t, rt.first, imu_to_world_rotation, imu_to_world);
Austin Schuhbb4aae72021-10-08 22:12:25 -0700155 }
156
milind-ue53bf552021-12-11 14:42:00 -0800157 virtual void ObserveIMUUpdate(
158 distributed_clock::time_point /*t*/,
159 std::pair<Eigen::Vector3d, Eigen::Vector3d> /*wa*/) {}
160
Austin Schuhbb4aae72021-10-08 22:12:25 -0700161 void UpdateIMU(distributed_clock::time_point t,
milind-u8c72d532021-12-11 15:02:42 -0800162 std::pair<Eigen::Vector3d, Eigen::Vector3d> wa) override {
163 Integrate(t);
164 omega_ = wa.first;
165 accel_ = wa.second;
milind-ue53bf552021-12-11 14:42:00 -0800166
167 ObserveIMUUpdate(t, wa);
Austin Schuhbb4aae72021-10-08 22:12:25 -0700168 }
169
milind-ue53bf552021-12-11 14:42:00 -0800170 const Eigen::Quaternion<Scalar> &orientation() const { return orientation_; }
171
milind-ue53bf552021-12-11 14:42:00 -0800172 size_t num_errors() const { return errors_.size(); }
173 Scalar errorx(size_t i) const { return errors_[i].x(); }
174 Scalar errory(size_t i) const { return errors_[i].y(); }
175 Scalar errorz(size_t i) const { return errors_[i].z(); }
176
Austin Schuh5b379072021-12-26 16:01:04 -0800177 size_t num_perrors() const { return position_errors_.size(); }
178 Scalar errorpx(size_t i) const { return position_errors_[i].x(); }
179 Scalar errorpy(size_t i) const { return position_errors_[i].y(); }
180 Scalar errorpz(size_t i) const { return position_errors_[i].z(); }
181
Austin Schuhbb4aae72021-10-08 22:12:25 -0700182 private:
milind-ue53bf552021-12-11 14:42:00 -0800183 Eigen::Matrix<Scalar, 46, 1> Pack(Eigen::Quaternion<Scalar> q,
184 Eigen::Matrix<Scalar, 6, 1> x_hat,
185 Eigen::Matrix<Scalar, 6, 6> p) {
186 Eigen::Matrix<Scalar, 46, 1> result = Eigen::Matrix<Scalar, 46, 1>::Zero();
187 result.template block<4, 1>(0, 0) = q.coeffs();
188 result.template block<6, 1>(4, 0) = x_hat;
189 result.template block<36, 1>(10, 0) =
Jim Ostrowski977850f2022-01-22 21:04:22 -0800190 Eigen::Map<Eigen::Matrix<Scalar, 36, 1>>(p.data(), p.size());
milind-ue53bf552021-12-11 14:42:00 -0800191
192 return result;
193 }
194
195 std::tuple<Eigen::Quaternion<Scalar>, Eigen::Matrix<Scalar, 6, 1>,
Jim Ostrowski977850f2022-01-22 21:04:22 -0800196 Eigen::Matrix<Scalar, 6, 6>>
milind-ue53bf552021-12-11 14:42:00 -0800197 UnPack(Eigen::Matrix<Scalar, 46, 1> input) {
198 Eigen::Quaternion<Scalar> q(input.template block<4, 1>(0, 0));
199 Eigen::Matrix<Scalar, 6, 1> x_hat(input.template block<6, 1>(4, 0));
200 Eigen::Matrix<Scalar, 6, 6> p =
Jim Ostrowski977850f2022-01-22 21:04:22 -0800201 Eigen::Map<Eigen::Matrix<Scalar, 6, 6>>(input.data() + 10, 6, 6);
milind-ue53bf552021-12-11 14:42:00 -0800202 return std::make_tuple(q, x_hat, p);
203 }
204
Austin Schuh5b379072021-12-26 16:01:04 -0800205 Eigen::Matrix<Scalar, 46, 1> Derivative(
milind-ue53bf552021-12-11 14:42:00 -0800206 const Eigen::Matrix<Scalar, 46, 1> &input) {
207 auto [q, x_hat, p] = UnPack(input);
208
209 Eigen::Quaternion<Scalar> omega_q;
210 omega_q.w() = Scalar(0.0);
211 omega_q.vec() = 0.5 * (omega_.cast<Scalar>() - imu_bias_);
212 Eigen::Matrix<Scalar, 4, 1> q_dot = (q * omega_q).coeffs();
213
Austin Schuh5b379072021-12-26 16:01:04 -0800214 Eigen::Matrix<double, 6, 6> A = Eigen::Matrix<double, 6, 6>::Zero();
215 A(0, 3) = 1.0;
216 A(1, 4) = 1.0;
217 A(2, 5) = 1.0;
milind-ue53bf552021-12-11 14:42:00 -0800218
Austin Schuh5b379072021-12-26 16:01:04 -0800219 Eigen::Matrix<Scalar, 6, 1> x_hat_dot = A * x_hat;
220 x_hat_dot.template block<3, 1>(3, 0) =
221 orientation() * (accel_.cast<Scalar>() - accelerometer_bias_) -
222 Eigen::Vector3d(0, 0, kGravity).cast<Scalar>() * gravity_scalar_;
223
224 // Initialize the position noise to 0. If the solver is going to back-solve
225 // for the most likely starting position, let's just say that the noise is
226 // small.
227 constexpr double kPositionNoise = 0.0;
228 constexpr double kAccelerometerNoise = 2.3e-6 * 9.8;
229 constexpr double kIMUdt = 5.0e-4;
230 Eigen::Matrix<double, 6, 6> Q_dot(
231 (::Eigen::DiagonalMatrix<double, 6>().diagonal()
232 << ::std::pow(kPositionNoise, 2) / kIMUdt,
233 ::std::pow(kPositionNoise, 2) / kIMUdt,
234 ::std::pow(kPositionNoise, 2) / kIMUdt,
235 ::std::pow(kAccelerometerNoise, 2) / kIMUdt,
236 ::std::pow(kAccelerometerNoise, 2) / kIMUdt,
237 ::std::pow(kAccelerometerNoise, 2) / kIMUdt)
238 .finished()
239 .asDiagonal());
240 Eigen::Matrix<Scalar, 6, 6> p_dot = A.cast<Scalar>() * p +
241 p * A.transpose().cast<Scalar>() +
242 Q_dot.cast<Scalar>();
milind-ue53bf552021-12-11 14:42:00 -0800243
244 return Pack(Eigen::Quaternion<Scalar>(q_dot), x_hat_dot, p_dot);
245 }
246
247 virtual void ObserveIntegrated(distributed_clock::time_point /*t*/,
248 Eigen::Matrix<Scalar, 6, 1> /*x_hat*/,
Austin Schuh5b379072021-12-26 16:01:04 -0800249 Eigen::Quaternion<Scalar> /*orientation*/,
250 Eigen::Matrix<Scalar, 6, 6> /*p*/) {}
milind-ue53bf552021-12-11 14:42:00 -0800251
252 void Integrate(distributed_clock::time_point t) {
253 if (last_time_ != distributed_clock::min_time) {
254 Eigen::Matrix<Scalar, 46, 1> next = control_loops::RungeKutta(
Austin Schuh5b379072021-12-26 16:01:04 -0800255 [this](auto r) { return Derivative(r); },
milind-ue53bf552021-12-11 14:42:00 -0800256 Pack(orientation_, x_hat_, p_),
257 aos::time::DurationInSeconds(t - last_time_));
258
259 std::tie(orientation_, x_hat_, p_) = UnPack(next);
260
261 // Normalize q so it doesn't drift.
262 orientation_.normalize();
263 }
264
265 last_time_ = t;
Austin Schuh5b379072021-12-26 16:01:04 -0800266 ObserveIntegrated(t, x_hat_, orientation_, p_);
milind-ue53bf552021-12-11 14:42:00 -0800267 }
milind-u8c72d532021-12-11 15:02:42 -0800268
269 Eigen::Matrix<double, 3, 1> accel_;
270 Eigen::Matrix<double, 3, 1> omega_;
milind-ue53bf552021-12-11 14:42:00 -0800271 Eigen::Matrix<Scalar, 3, 1> imu_bias_;
milind-u8c72d532021-12-11 15:02:42 -0800272
Austin Schuh5b379072021-12-26 16:01:04 -0800273 // IMU -> world quaternion
milind-ue53bf552021-12-11 14:42:00 -0800274 Eigen::Quaternion<Scalar> orientation_;
275 Eigen::Matrix<Scalar, 6, 1> x_hat_;
276 Eigen::Matrix<Scalar, 6, 6> p_;
277 distributed_clock::time_point last_time_ = distributed_clock::min_time;
Austin Schuhbb4aae72021-10-08 22:12:25 -0700278
Austin Schuh5b379072021-12-26 16:01:04 -0800279 Eigen::Quaternion<Scalar> imu_to_camera_rotation_;
280 Eigen::Translation<Scalar, 3> imu_to_camera_translation_ =
281 Eigen::Translation3d(0, 0, 0).cast<Scalar>();
milind-ue53bf552021-12-11 14:42:00 -0800282
Austin Schuh5b379072021-12-26 16:01:04 -0800283 Eigen::Quaternion<Scalar> board_to_world_;
284 Scalar gravity_scalar_;
285 Eigen::Matrix<Scalar, 3, 1> accelerometer_bias_;
Austin Schuhbb4aae72021-10-08 22:12:25 -0700286 // States:
287 // xyz position
288 // xyz velocity
Austin Schuhbb4aae72021-10-08 22:12:25 -0700289 //
290 // Inputs
291 // xyz accel
Austin Schuhbb4aae72021-10-08 22:12:25 -0700292 //
293 // Measurement:
Austin Schuh5b379072021-12-26 16:01:04 -0800294 // xyz position from camera.
295 //
296 // Since the gyro is so good, we can just solve for the bias and initial
297 // position with the solver and see what it learns.
298
299 // Returns the angular errors for each camera sample.
300 std::vector<Eigen::Matrix<Scalar, 3, 1>> errors_;
301 std::vector<Eigen::Matrix<Scalar, 3, 1>> position_errors_;
Austin Schuhbb4aae72021-10-08 22:12:25 -0700302};
303
milind-ue53bf552021-12-11 14:42:00 -0800304// Subclass of the filter above which has plotting. This keeps debug code and
305// actual code separate.
306class PoseFilter : public CeresPoseFilter<double> {
307 public:
308 PoseFilter(Eigen::Quaternion<double> initial_orientation,
309 Eigen::Quaternion<double> imu_to_camera,
Austin Schuh5b379072021-12-26 16:01:04 -0800310 Eigen::Matrix<double, 3, 1> gyro_bias,
311 Eigen::Matrix<double, 6, 1> initial_state,
312 Eigen::Quaternion<double> board_to_world,
313 Eigen::Matrix<double, 3, 1> imu_to_camera_translation,
314 double gravity_scalar,
315 Eigen::Matrix<double, 3, 1> accelerometer_bias)
316 : CeresPoseFilter<double>(initial_orientation, imu_to_camera, gyro_bias,
317 initial_state, board_to_world,
318 imu_to_camera_translation, gravity_scalar,
319 accelerometer_bias) {}
milind-ue53bf552021-12-11 14:42:00 -0800320
321 void Plot() {
Austin Schuh5b379072021-12-26 16:01:04 -0800322 std::vector<double> rx;
323 std::vector<double> ry;
324 std::vector<double> rz;
milind-ue53bf552021-12-11 14:42:00 -0800325 std::vector<double> x;
326 std::vector<double> y;
327 std::vector<double> z;
Austin Schuh5b379072021-12-26 16:01:04 -0800328 std::vector<double> vx;
329 std::vector<double> vy;
330 std::vector<double> vz;
milind-ue53bf552021-12-11 14:42:00 -0800331 for (const Eigen::Quaternion<double> &q : orientations_) {
332 Eigen::Matrix<double, 3, 1> rotation_vector =
333 frc971::controls::ToRotationVectorFromQuaternion(q);
Austin Schuh5b379072021-12-26 16:01:04 -0800334 rx.emplace_back(rotation_vector(0, 0));
335 ry.emplace_back(rotation_vector(1, 0));
336 rz.emplace_back(rotation_vector(2, 0));
milind-ue53bf552021-12-11 14:42:00 -0800337 }
Austin Schuh5b379072021-12-26 16:01:04 -0800338 for (const Eigen::Matrix<double, 6, 1> &x_hat : x_hats_) {
339 x.emplace_back(x_hat(0));
340 y.emplace_back(x_hat(1));
341 z.emplace_back(x_hat(2));
342 vx.emplace_back(x_hat(3));
343 vy.emplace_back(x_hat(4));
344 vz.emplace_back(x_hat(5));
345 }
346
milind-ue53bf552021-12-11 14:42:00 -0800347 frc971::analysis::Plotter plotter;
348 plotter.AddFigure("position");
Austin Schuh5b379072021-12-26 16:01:04 -0800349 plotter.AddLine(times_, rx, "x_hat(0)");
350 plotter.AddLine(times_, ry, "x_hat(1)");
351 plotter.AddLine(times_, rz, "x_hat(2)");
milind-ue53bf552021-12-11 14:42:00 -0800352 plotter.AddLine(ct, cx, "Camera x");
353 plotter.AddLine(ct, cy, "Camera y");
354 plotter.AddLine(ct, cz, "Camera z");
355 plotter.AddLine(ct, cerrx, "Camera error x");
356 plotter.AddLine(ct, cerry, "Camera error y");
357 plotter.AddLine(ct, cerrz, "Camera error z");
358 plotter.Publish();
359
360 plotter.AddFigure("error");
Austin Schuh5b379072021-12-26 16:01:04 -0800361 plotter.AddLine(times_, rx, "x_hat(0)");
362 plotter.AddLine(times_, ry, "x_hat(1)");
363 plotter.AddLine(times_, rz, "x_hat(2)");
milind-ue53bf552021-12-11 14:42:00 -0800364 plotter.AddLine(ct, cerrx, "Camera error x");
365 plotter.AddLine(ct, cerry, "Camera error y");
366 plotter.AddLine(ct, cerrz, "Camera error z");
367 plotter.Publish();
368
369 plotter.AddFigure("imu");
370 plotter.AddLine(ct, world_gravity_x, "world_gravity(0)");
371 plotter.AddLine(ct, world_gravity_y, "world_gravity(1)");
372 plotter.AddLine(ct, world_gravity_z, "world_gravity(2)");
373 plotter.AddLine(imut, imu_x, "imu x");
374 plotter.AddLine(imut, imu_y, "imu y");
375 plotter.AddLine(imut, imu_z, "imu z");
Austin Schuh5b379072021-12-26 16:01:04 -0800376 plotter.AddLine(times_, rx, "rotation x");
377 plotter.AddLine(times_, ry, "rotation y");
378 plotter.AddLine(times_, rz, "rotation z");
milind-ue53bf552021-12-11 14:42:00 -0800379 plotter.Publish();
380
381 plotter.AddFigure("raw");
382 plotter.AddLine(imut, imu_x, "imu x");
383 plotter.AddLine(imut, imu_y, "imu y");
384 plotter.AddLine(imut, imu_z, "imu z");
385 plotter.AddLine(imut, imu_ratex, "omega x");
386 plotter.AddLine(imut, imu_ratey, "omega y");
387 plotter.AddLine(imut, imu_ratez, "omega z");
388 plotter.AddLine(ct, raw_cx, "Camera x");
389 plotter.AddLine(ct, raw_cy, "Camera y");
390 plotter.AddLine(ct, raw_cz, "Camera z");
391 plotter.Publish();
392
Austin Schuh5b379072021-12-26 16:01:04 -0800393 plotter.AddFigure("xyz vel");
394 plotter.AddLine(times_, x, "x");
395 plotter.AddLine(times_, y, "y");
396 plotter.AddLine(times_, z, "z");
397 plotter.AddLine(times_, vx, "vx");
398 plotter.AddLine(times_, vy, "vy");
399 plotter.AddLine(times_, vz, "vz");
400 plotter.AddLine(ct, camera_position_x, "Camera x");
401 plotter.AddLine(ct, camera_position_y, "Camera y");
402 plotter.AddLine(ct, camera_position_z, "Camera z");
403 plotter.Publish();
404
milind-ue53bf552021-12-11 14:42:00 -0800405 plotter.Spin();
406 }
407
408 void ObserveIntegrated(distributed_clock::time_point t,
409 Eigen::Matrix<double, 6, 1> x_hat,
Austin Schuh5b379072021-12-26 16:01:04 -0800410 Eigen::Quaternion<double> orientation,
411 Eigen::Matrix<double, 6, 6> p) override {
412 VLOG(1) << t << " -> " << p;
413 VLOG(1) << t << " xhat -> " << x_hat.transpose();
milind-ue53bf552021-12-11 14:42:00 -0800414 times_.emplace_back(chrono::duration<double>(t.time_since_epoch()).count());
415 x_hats_.emplace_back(x_hat);
416 orientations_.emplace_back(orientation);
417 }
418
419 void ObserveIMUUpdate(
420 distributed_clock::time_point t,
421 std::pair<Eigen::Vector3d, Eigen::Vector3d> wa) override {
422 imut.emplace_back(chrono::duration<double>(t.time_since_epoch()).count());
423 imu_ratex.emplace_back(wa.first.x());
424 imu_ratey.emplace_back(wa.first.y());
425 imu_ratez.emplace_back(wa.first.z());
426 imu_x.emplace_back(wa.second.x());
427 imu_y.emplace_back(wa.second.y());
428 imu_z.emplace_back(wa.second.z());
429
430 last_accel_ = wa.second;
431 }
432
433 void ObserveCameraUpdate(distributed_clock::time_point t,
434 Eigen::Vector3d board_to_camera_rotation,
Austin Schuh5b379072021-12-26 16:01:04 -0800435 Eigen::Quaternion<double> imu_to_world_rotation,
436 Eigen::Affine3d imu_to_world) override {
milind-ue53bf552021-12-11 14:42:00 -0800437 raw_cx.emplace_back(board_to_camera_rotation(0, 0));
438 raw_cy.emplace_back(board_to_camera_rotation(1, 0));
439 raw_cz.emplace_back(board_to_camera_rotation(2, 0));
440
441 Eigen::Matrix<double, 3, 1> rotation_vector =
Austin Schuh5b379072021-12-26 16:01:04 -0800442 frc971::controls::ToRotationVectorFromQuaternion(imu_to_world_rotation);
milind-ue53bf552021-12-11 14:42:00 -0800443 ct.emplace_back(chrono::duration<double>(t.time_since_epoch()).count());
444
445 Eigen::Matrix<double, 3, 1> cerr =
446 frc971::controls::ToRotationVectorFromQuaternion(
Austin Schuh5b379072021-12-26 16:01:04 -0800447 imu_to_world_rotation.inverse() * orientation());
milind-ue53bf552021-12-11 14:42:00 -0800448
449 cx.emplace_back(rotation_vector(0, 0));
450 cy.emplace_back(rotation_vector(1, 0));
451 cz.emplace_back(rotation_vector(2, 0));
452
453 cerrx.emplace_back(cerr(0, 0));
454 cerry.emplace_back(cerr(1, 0));
455 cerrz.emplace_back(cerr(2, 0));
456
Austin Schuh5b379072021-12-26 16:01:04 -0800457 const Eigen::Vector3d world_gravity =
458 imu_to_world_rotation * last_accel_ -
459 Eigen::Vector3d(0, 0, kGravity) * gravity_scalar();
460
461 const Eigen::Vector3d camera_position =
462 imu_to_world * Eigen::Vector3d::Zero();
milind-ue53bf552021-12-11 14:42:00 -0800463
464 world_gravity_x.emplace_back(world_gravity.x());
465 world_gravity_y.emplace_back(world_gravity.y());
466 world_gravity_z.emplace_back(world_gravity.z());
Austin Schuh5b379072021-12-26 16:01:04 -0800467
468 camera_position_x.emplace_back(camera_position.x());
469 camera_position_y.emplace_back(camera_position.y());
470 camera_position_z.emplace_back(camera_position.z());
milind-ue53bf552021-12-11 14:42:00 -0800471 }
472
473 std::vector<double> ct;
474 std::vector<double> cx;
475 std::vector<double> cy;
476 std::vector<double> cz;
477 std::vector<double> raw_cx;
478 std::vector<double> raw_cy;
479 std::vector<double> raw_cz;
480 std::vector<double> cerrx;
481 std::vector<double> cerry;
482 std::vector<double> cerrz;
483
484 std::vector<double> world_gravity_x;
485 std::vector<double> world_gravity_y;
486 std::vector<double> world_gravity_z;
487 std::vector<double> imu_x;
488 std::vector<double> imu_y;
489 std::vector<double> imu_z;
Austin Schuh5b379072021-12-26 16:01:04 -0800490 std::vector<double> camera_position_x;
491 std::vector<double> camera_position_y;
492 std::vector<double> camera_position_z;
milind-ue53bf552021-12-11 14:42:00 -0800493
494 std::vector<double> imut;
495 std::vector<double> imu_ratex;
496 std::vector<double> imu_ratey;
497 std::vector<double> imu_ratez;
498
499 std::vector<double> times_;
Jim Ostrowski977850f2022-01-22 21:04:22 -0800500 std::vector<Eigen::Matrix<double, 6, 1>> x_hats_;
501 std::vector<Eigen::Quaternion<double>> orientations_;
milind-ue53bf552021-12-11 14:42:00 -0800502
503 Eigen::Matrix<double, 3, 1> last_accel_ = Eigen::Matrix<double, 3, 1>::Zero();
504};
505
506// Adapter class from the KF above to a Ceres cost function.
507struct CostFunctor {
508 CostFunctor(CalibrationData *d) : data(d) {}
509
510 CalibrationData *data;
511
512 template <typename S>
513 bool operator()(const S *const q1, const S *const q2, const S *const v,
Austin Schuh5b379072021-12-26 16:01:04 -0800514 const S *const p, const S *const btw, const S *const itc,
515 const S *const gravity_scalar_ptr,
516 const S *const accelerometer_bias_ptr, S *residual) const {
milind-ue53bf552021-12-11 14:42:00 -0800517 Eigen::Quaternion<S> initial_orientation(q1[3], q1[0], q1[1], q1[2]);
518 Eigen::Quaternion<S> mounting_orientation(q2[3], q2[0], q2[1], q2[2]);
Austin Schuh5b379072021-12-26 16:01:04 -0800519 Eigen::Quaternion<S> board_to_world(btw[3], btw[0], btw[1], btw[2]);
520 Eigen::Matrix<S, 3, 1> gyro_bias(v[0], v[1], v[2]);
521 Eigen::Matrix<S, 6, 1> initial_state;
522 initial_state(0) = p[0];
523 initial_state(1) = p[1];
524 initial_state(2) = p[2];
525 initial_state(3) = p[3];
526 initial_state(4) = p[4];
527 initial_state(5) = p[5];
528 Eigen::Matrix<S, 3, 1> imu_to_camera_translation(itc[0], itc[1], itc[2]);
529 Eigen::Matrix<S, 3, 1> accelerometer_bias(accelerometer_bias_ptr[0],
530 accelerometer_bias_ptr[1],
531 accelerometer_bias_ptr[2]);
milind-ue53bf552021-12-11 14:42:00 -0800532
533 CeresPoseFilter<S> filter(initial_orientation, mounting_orientation,
Austin Schuh5b379072021-12-26 16:01:04 -0800534 gyro_bias, initial_state, board_to_world,
535 imu_to_camera_translation, *gravity_scalar_ptr,
536 accelerometer_bias);
milind-ue53bf552021-12-11 14:42:00 -0800537 data->ReviewData(&filter);
538
539 for (size_t i = 0; i < filter.num_errors(); ++i) {
540 residual[3 * i + 0] = filter.errorx(i);
541 residual[3 * i + 1] = filter.errory(i);
542 residual[3 * i + 2] = filter.errorz(i);
543 }
544
Austin Schuh5b379072021-12-26 16:01:04 -0800545 for (size_t i = 0; i < filter.num_perrors(); ++i) {
546 residual[3 * filter.num_errors() + 3 * i + 0] = filter.errorpx(i);
547 residual[3 * filter.num_errors() + 3 * i + 1] = filter.errorpy(i);
548 residual[3 * filter.num_errors() + 3 * i + 2] = filter.errorpz(i);
549 }
550
milind-ue53bf552021-12-11 14:42:00 -0800551 return true;
552 }
553};
554
Austin Schuhbb4aae72021-10-08 22:12:25 -0700555void Main(int argc, char **argv) {
556 CalibrationData data;
557
558 {
559 // Now, accumulate all the data into the data object.
560 aos::logger::LogReader reader(
561 aos::logger::SortParts(aos::logger::FindLogs(argc, argv)));
562
563 aos::SimulatedEventLoopFactory factory(reader.configuration());
564 reader.Register(&factory);
565
566 CHECK(aos::configuration::MultiNode(reader.configuration()));
567
568 // Find the nodes we care about.
569 const aos::Node *const roborio_node =
570 aos::configuration::GetNode(factory.configuration(), "roborio");
571
572 std::optional<uint16_t> pi_number = aos::network::ParsePiNumber(FLAGS_pi);
573 CHECK(pi_number);
574 LOG(INFO) << "Pi " << *pi_number;
575 const aos::Node *const pi_node = aos::configuration::GetNode(
576 factory.configuration(), absl::StrCat("pi", *pi_number));
577
578 LOG(INFO) << "roboRIO " << aos::FlatbufferToJson(roborio_node);
579 LOG(INFO) << "Pi " << aos::FlatbufferToJson(pi_node);
580
581 std::unique_ptr<aos::EventLoop> roborio_event_loop =
582 factory.MakeEventLoop("calibration", roborio_node);
583 std::unique_ptr<aos::EventLoop> pi_event_loop =
584 factory.MakeEventLoop("calibration", pi_node);
585
586 // Now, hook Calibration up to everything.
587 Calibration extractor(&factory, pi_event_loop.get(),
588 roborio_event_loop.get(), FLAGS_pi, &data);
589
590 factory.Run();
591
592 reader.Deregister();
593 }
594
595 LOG(INFO) << "Done with event_loop running";
596 // And now we have it, we can start processing it.
milind-u8c72d532021-12-11 15:02:42 -0800597
Austin Schuh5b379072021-12-26 16:01:04 -0800598 const Eigen::Quaternion<double> nominal_initial_orientation(
milind-ue53bf552021-12-11 14:42:00 -0800599 frc971::controls::ToQuaternionFromRotationVector(
600 Eigen::Vector3d(0.0, 0.0, M_PI)));
Austin Schuh5b379072021-12-26 16:01:04 -0800601 const Eigen::Quaternion<double> nominal_imu_to_camera(
milind-ue53bf552021-12-11 14:42:00 -0800602 Eigen::AngleAxisd(-0.5 * M_PI, Eigen::Vector3d::UnitX()));
Austin Schuh5b379072021-12-26 16:01:04 -0800603 const Eigen::Quaternion<double> nominal_board_to_world(
604 Eigen::AngleAxisd(0.5 * M_PI, Eigen::Vector3d::UnitX()));
milind-ue53bf552021-12-11 14:42:00 -0800605
Austin Schuh5b379072021-12-26 16:01:04 -0800606 Eigen::Quaternion<double> initial_orientation = nominal_initial_orientation;
607 // Eigen::Quaternion<double>::Identity();
608 Eigen::Quaternion<double> imu_to_camera = nominal_imu_to_camera;
609 // Eigen::Quaternion<double>::Identity();
610 Eigen::Quaternion<double> board_to_world = nominal_board_to_world;
611 // Eigen::Quaternion<double>::Identity();
612 Eigen::Vector3d gyro_bias = Eigen::Vector3d::Zero();
613 Eigen::Matrix<double, 6, 1> initial_state =
614 Eigen::Matrix<double, 6, 1>::Zero();
615 Eigen::Matrix<double, 3, 1> imu_to_camera_translation =
616 Eigen::Matrix<double, 3, 1>::Zero();
617
618 double gravity_scalar = 1.0;
619 Eigen::Matrix<double, 3, 1> accelerometer_bias =
620 Eigen::Matrix<double, 3, 1>::Zero();
milind-ue53bf552021-12-11 14:42:00 -0800621
milind-u8c72d532021-12-11 15:02:42 -0800622 {
milind-ue53bf552021-12-11 14:42:00 -0800623 ceres::Problem problem;
624
625 ceres::EigenQuaternionParameterization *quaternion_local_parameterization =
626 new ceres::EigenQuaternionParameterization();
627 // Set up the only cost function (also known as residual). This uses
628 // auto-differentiation to obtain the derivative (jacobian).
629
630 ceres::CostFunction *cost_function =
Austin Schuh5b379072021-12-26 16:01:04 -0800631 new ceres::AutoDiffCostFunction<CostFunctor, ceres::DYNAMIC, 4, 4, 3, 6,
632 4, 3, 1, 3>(
633 new CostFunctor(&data), data.camera_samples_size() * 6);
634 problem.AddResidualBlock(
635 cost_function, nullptr, initial_orientation.coeffs().data(),
636 imu_to_camera.coeffs().data(), gyro_bias.data(), initial_state.data(),
637 board_to_world.coeffs().data(), imu_to_camera_translation.data(),
638 &gravity_scalar, accelerometer_bias.data());
milind-ue53bf552021-12-11 14:42:00 -0800639 problem.SetParameterization(initial_orientation.coeffs().data(),
640 quaternion_local_parameterization);
641 problem.SetParameterization(imu_to_camera.coeffs().data(),
642 quaternion_local_parameterization);
Austin Schuh5b379072021-12-26 16:01:04 -0800643 problem.SetParameterization(board_to_world.coeffs().data(),
644 quaternion_local_parameterization);
milind-ue53bf552021-12-11 14:42:00 -0800645 for (int i = 0; i < 3; ++i) {
Austin Schuh5b379072021-12-26 16:01:04 -0800646 problem.SetParameterLowerBound(gyro_bias.data(), i, -0.05);
647 problem.SetParameterUpperBound(gyro_bias.data(), i, 0.05);
648 problem.SetParameterLowerBound(accelerometer_bias.data(), i, -0.05);
649 problem.SetParameterUpperBound(accelerometer_bias.data(), i, 0.05);
milind-ue53bf552021-12-11 14:42:00 -0800650 }
Austin Schuh5b379072021-12-26 16:01:04 -0800651 problem.SetParameterLowerBound(&gravity_scalar, 0, 0.95);
652 problem.SetParameterUpperBound(&gravity_scalar, 0, 1.05);
milind-ue53bf552021-12-11 14:42:00 -0800653
654 // Run the solver!
655 ceres::Solver::Options options;
656 options.minimizer_progress_to_stdout = true;
657 options.gradient_tolerance = 1e-12;
658 options.function_tolerance = 1e-16;
659 options.parameter_tolerance = 1e-12;
660 ceres::Solver::Summary summary;
661 Solve(options, &problem, &summary);
662 LOG(INFO) << summary.FullReport();
663
664 LOG(INFO) << "Nominal initial_orientation "
665 << nominal_initial_orientation.coeffs().transpose();
666 LOG(INFO) << "Nominal imu_to_camera "
667 << nominal_imu_to_camera.coeffs().transpose();
668
669 LOG(INFO) << "initial_orientation "
670 << initial_orientation.coeffs().transpose();
671 LOG(INFO) << "imu_to_camera " << imu_to_camera.coeffs().transpose();
672 LOG(INFO) << "imu_to_camera(rotation) "
673 << frc971::controls::ToRotationVectorFromQuaternion(imu_to_camera)
674 .transpose();
675 LOG(INFO) << "imu_to_camera delta "
676 << frc971::controls::ToRotationVectorFromQuaternion(
677 imu_to_camera * nominal_imu_to_camera.inverse())
678 .transpose();
Austin Schuh5b379072021-12-26 16:01:04 -0800679 LOG(INFO) << "gyro_bias " << gyro_bias.transpose();
680 LOG(INFO) << "board_to_world " << board_to_world.coeffs().transpose();
681 LOG(INFO) << "board_to_world(rotation) "
682 << frc971::controls::ToRotationVectorFromQuaternion(
683 board_to_world)
684 .transpose();
685 LOG(INFO) << "board_to_world delta "
686 << frc971::controls::ToRotationVectorFromQuaternion(
687 board_to_world * nominal_board_to_world.inverse())
688 .transpose();
689 LOG(INFO) << "imu_to_camera_translation "
690 << imu_to_camera_translation.transpose();
691 LOG(INFO) << "gravity " << kGravity * gravity_scalar;
692 LOG(INFO) << "accelerometer bias " << accelerometer_bias.transpose();
milind-ue53bf552021-12-11 14:42:00 -0800693 }
694
695 {
Austin Schuh5b379072021-12-26 16:01:04 -0800696 PoseFilter filter(initial_orientation, imu_to_camera, gyro_bias,
697 initial_state, board_to_world, imu_to_camera_translation,
698 gravity_scalar, accelerometer_bias);
milind-u8c72d532021-12-11 15:02:42 -0800699 data.ReviewData(&filter);
Austin Schuh5b379072021-12-26 16:01:04 -0800700 filter.Plot();
milind-u8c72d532021-12-11 15:02:42 -0800701 }
Austin Schuhbb4aae72021-10-08 22:12:25 -0700702}
703
704} // namespace vision
705} // namespace frc971
706
707int main(int argc, char **argv) {
708 aos::InitGoogle(&argc, &argv);
709
710 frc971::vision::Main(argc, argv);
711}