blob: f784f2e0fee5ae9ff5c632a95c46888607f76078 [file] [log] [blame]
James Kuszmaul2ed7b3c2019-02-09 18:26:19 -08001#ifndef FRC971_CONTROL_LOOPS_DRIVETRAIN_HYBRID_EKF_H_
2#define FRC971_CONTROL_LOOPS_DRIVETRAIN_HYBRID_EKF_H_
3
4#include <chrono>
5
James Kuszmaul651fc3f2019-05-15 21:14:25 -07006#include "Eigen/Dense"
Philipp Schrader790cb542023-07-05 21:06:52 -07007
James Kuszmaul3c5b4d32020-02-11 17:22:14 -08008#include "aos/commonmath.h"
James Kuszmaul2ed7b3c2019-02-09 18:26:19 -08009#include "aos/containers/priority_queue.h"
James Kuszmaulfedc4612019-03-10 11:24:51 -070010#include "aos/util/math.h"
James Kuszmaul2ed7b3c2019-02-09 18:26:19 -080011#include "frc971/control_loops/c2d.h"
James Kuszmaul2ed7b3c2019-02-09 18:26:19 -080012#include "frc971/control_loops/drivetrain/drivetrain_config.h"
James Kuszmaul651fc3f2019-05-15 21:14:25 -070013#include "frc971/control_loops/runge_kutta.h"
James Kuszmaul2ed7b3c2019-02-09 18:26:19 -080014
Stephan Pleinesd99b1ee2024-02-02 20:56:44 -080015namespace y2019::control_loops::testing {
James Kuszmaul1057ce82019-02-09 17:58:24 -080016class ParameterizedLocalizerTest;
Stephan Pleinesd99b1ee2024-02-02 20:56:44 -080017} // namespace y2019::control_loops::testing
James Kuszmaul1057ce82019-02-09 17:58:24 -080018
Stephan Pleinesd99b1ee2024-02-02 20:56:44 -080019namespace frc971::control_loops::drivetrain {
James Kuszmaul2ed7b3c2019-02-09 18:26:19 -080020
21namespace testing {
22class HybridEkfTest;
23}
24
25// HybridEkf is an EKF for use in robot localization. It is currently
26// coded for use with drivetrains in particular, and so the states and inputs
27// are chosen as such.
28// The "Hybrid" part of the name refers to the fact that it can take in
29// measurements with variable time-steps.
30// measurements can also have been taken in the past and we maintain a buffer
31// so that we can replay the kalman filter whenever we get an old measurement.
32// Currently, this class provides the necessary utilities for doing
33// measurement updates with an encoder/gyro as well as a more generic
34// update function that can be used for arbitrary nonlinear updates (presumably
35// a camera update).
James Kuszmaul3c5b4d32020-02-11 17:22:14 -080036//
37// Discussion of the model:
38// In the current model, we try to rely primarily on IMU measurements for
39// estimating robot state--we also need additional information (some combination
40// of output voltages, encoders, and camera data) to help eliminate the biases
41// that can accumulate due to integration of IMU data.
42// We use IMU measurements as inputs rather than measurement outputs because
43// that seemed to be easier to implement. I tried initially running with
44// the IMU as a measurement, but it seemed to blow up the complexity of the
45// model.
46//
47// On each prediction update, we take in inputs of the left/right voltages and
48// the current measured longitudinal/lateral accelerations. In the current
49// setup, the accelerometer readings will be used for estimating how the
50// evolution of the longitudinal/lateral velocities. The voltages (and voltage
51// errors) will solely be used for estimating the current rotational velocity of
52// the robot (I do this because currently I suspect that the accelerometer is a
53// much better indicator of current robot state than the voltages). We also
54// deliberately decay all of the velocity estimates towards zero to help address
55// potential accelerometer biases. We use two separate decay models:
56// -The longitudinal velocity is modelled as decaying at a constant rate (see
57// the documentation on the VelocityAccel() method)--this needs a more
58// complex model because the robot will, under normal circumstances, be
59// travelling at non-zero velocities.
60// -The lateral velocity is modelled as exponentially decaying towards zero.
61// This is simpler to model and should be reasonably valid, since we will
62// not *normally* be travelling sideways consistently (this assumption may
63// need to be revisited).
64// -The "longitudinal velocity offset" (described below) also uses an
65// exponential decay, albeit with a different time constant. A future
66// improvement may remove the decay modelling on the longitudinal velocity
67// itself and instead use that decay model on the longitudinal velocity offset.
68// This would place a bit more trust in the encoder measurements but also
69// more correctly model situations where the robot is legitimately moving at
70// a certain velocity.
71//
72// For modelling how the drivetrain encoders evolve, and to help prevent the
73// aforementioned decay functions from affecting legitimate high-velocity
74// maneuvers too much, we have a "longitudinal velocity offset" term. This term
75// models the difference between the actual longitudinal velocity of the robot
76// (estimated by the average of the left/right velocities) and the velocity
77// experienced by the wheels (which can be observed from the encoders more
78// directly). Because we model this velocity offset as decaying towards zero,
79// what this will do is allow the encoders to be a constant velocity off from
80// the accelerometer updates for short periods of time but then gradually
81// pull the "actual" longitudinal velocity offset towards that of the encoders,
82// helping to reduce constant biases.
James Kuszmaul2ed7b3c2019-02-09 18:26:19 -080083template <typename Scalar = double>
84class HybridEkf {
85 public:
86 // An enum specifying what each index in the state vector is for.
87 enum StateIdx {
James Kuszmaul3c5b4d32020-02-11 17:22:14 -080088 // Current X/Y position, in meters, of the robot.
James Kuszmaul2ed7b3c2019-02-09 18:26:19 -080089 kX = 0,
90 kY = 1,
James Kuszmaul3c5b4d32020-02-11 17:22:14 -080091 // Current heading of the robot.
James Kuszmaul2ed7b3c2019-02-09 18:26:19 -080092 kTheta = 2,
James Kuszmaul3c5b4d32020-02-11 17:22:14 -080093 // Current estimated encoder reading of the left wheels, in meters.
94 // Rezeroed once on startup.
James Kuszmaul2ed7b3c2019-02-09 18:26:19 -080095 kLeftEncoder = 3,
James Kuszmaul3c5b4d32020-02-11 17:22:14 -080096 // Current estimated actual velocity of the left side of the robot, in m/s.
James Kuszmaul2ed7b3c2019-02-09 18:26:19 -080097 kLeftVelocity = 4,
James Kuszmaul3c5b4d32020-02-11 17:22:14 -080098 // Same variables, for the right side of the robot.
James Kuszmaul2ed7b3c2019-02-09 18:26:19 -080099 kRightEncoder = 5,
100 kRightVelocity = 6,
James Kuszmaul3c5b4d32020-02-11 17:22:14 -0800101 // Estimated offset to input voltage. Used as a generic error term, Volts.
James Kuszmaul074429e2019-03-23 16:01:49 -0700102 kLeftVoltageError = 7,
James Kuszmaul651fc3f2019-05-15 21:14:25 -0700103 kRightVoltageError = 8,
James Kuszmaul3c5b4d32020-02-11 17:22:14 -0800104 // These error terms are used to estimate the difference between the actual
105 // movement of the drivetrain and that implied by the wheel odometry.
106 // Angular error effectively estimates a constant angular rate offset of the
107 // encoders relative to the actual rotation of the robot.
108 // Semi-arbitrary units (we don't bother accounting for robot radius in
109 // this).
James Kuszmaul074429e2019-03-23 16:01:49 -0700110 kAngularError = 9,
James Kuszmaul3c5b4d32020-02-11 17:22:14 -0800111 // Estimate of slip between the drivetrain wheels and the actual
112 // forwards/backwards velocity of the robot, in m/s.
113 // I.e., (left velocity + right velocity) / 2.0 = (left wheel velocity +
114 // right wheel velocity) / 2.0 + longitudinal velocity offset
115 kLongitudinalVelocityOffset = 10,
116 // Current estimate of the lateral velocity of the robot, in m/s.
117 // Positive implies the robot is moving to its left.
118 kLateralVelocity = 11,
James Kuszmaul2ed7b3c2019-02-09 18:26:19 -0800119 };
James Kuszmaul3c5b4d32020-02-11 17:22:14 -0800120 static constexpr int kNStates = 12;
121 enum InputIdx {
122 // Left/right drivetrain voltages.
123 kLeftVoltage = 0,
124 kRightVoltage = 1,
125 // Current accelerometer readings, in m/s/s, along the longitudinal and
126 // lateral axes of the robot. Should be projected onto the X/Y plane, to
127 // compensate for tilt of the robot before being passed to this filter. The
128 // HybridEkf has no knowledge of the current pitch/roll of the robot, and so
129 // can't do anything to compensate for it.
130 kLongitudinalAccel = 2,
131 kLateralAccel = 3,
132 };
James Kuszmaul2971b5a2023-01-29 15:49:32 -0800133
James Kuszmaul3c5b4d32020-02-11 17:22:14 -0800134 static constexpr int kNInputs = 4;
James Kuszmaul2ed7b3c2019-02-09 18:26:19 -0800135 // Number of previous samples to save.
Austin Schuh6e660592021-10-17 17:37:33 -0700136 static constexpr int kSaveSamples = 200;
James Kuszmaul06257f42020-05-09 15:40:09 -0700137 // Whether we should completely rerun the entire stored history of
138 // kSaveSamples on every correction. Enabling this will increase overall CPU
139 // usage substantially; however, leaving it disabled makes it so that we are
140 // less likely to notice if processing camera frames is causing delays in the
141 // drivetrain.
142 // If we are having CPU issues, we have three easy avenues to improve things:
143 // (1) Reduce kSaveSamples (e.g., if all camera frames arive within
144 // 100 ms, then we can reduce kSaveSamples to be 25 (125 ms of samples)).
145 // (2) Don't actually rely on the ability to insert corrections into the
146 // timeline.
147 // (3) Set this to false.
148 static constexpr bool kFullRewindOnEverySample = false;
James Kuszmaul2ed7b3c2019-02-09 18:26:19 -0800149 // Assume that all correction steps will have kNOutputs
150 // dimensions.
151 // TODO(james): Relax this assumption; relaxing it requires
152 // figuring out how to deal with storing variable size
153 // observation matrices, though.
154 static constexpr int kNOutputs = 3;
James Kuszmaul3c5b4d32020-02-11 17:22:14 -0800155 // Time constant to use for estimating how the longitudinal/lateral velocity
156 // offsets decay, in seconds.
James Kuszmaul5f6d1d42020-03-01 18:10:07 -0800157 static constexpr double kVelocityOffsetTimeConstant = 1.0;
James Kuszmaul3c5b4d32020-02-11 17:22:14 -0800158 static constexpr double kLateralVelocityTimeConstant = 1.0;
James Kuszmaul91aa0cf2021-02-13 13:15:06 -0800159
James Kuszmaulf3950362020-10-11 18:29:15 -0700160 // The maximum allowable timestep--we use this to check for situations where
161 // measurement updates come in too infrequently and this might cause the
162 // integrator and discretization in the prediction step to be overly
163 // aggressive.
164 static constexpr std::chrono::milliseconds kMaxTimestep{20};
James Kuszmaul2ed7b3c2019-02-09 18:26:19 -0800165 // Inputs are [left_volts, right_volts]
166 typedef Eigen::Matrix<Scalar, kNInputs, 1> Input;
167 // Outputs are either:
168 // [left_encoder, right_encoder, gyro_vel]; or [heading, distance, skew] to
169 // some target. This makes it so we don't have to figure out how we store
170 // variable-size measurement updates.
171 typedef Eigen::Matrix<Scalar, kNOutputs, 1> Output;
172 typedef Eigen::Matrix<Scalar, kNStates, kNStates> StateSquare;
James Kuszmaul3c5b4d32020-02-11 17:22:14 -0800173 // State contains the states defined by the StateIdx enum. See comments there.
James Kuszmaul2ed7b3c2019-02-09 18:26:19 -0800174 typedef Eigen::Matrix<Scalar, kNStates, 1> State;
175
James Kuszmaul2971b5a2023-01-29 15:49:32 -0800176 // The following classes exist to allow us to support doing corections in the
177 // past by rewinding the EKF, calling the appropriate H and dhdx functions,
178 // and then playing everything back. Originally, this simply used
179 // std::function's, but doing so causes us to perform dynamic memory
180 // allocation in the core of the drivetrain control loop.
181 //
182 // The ExpectedObservationFunctor class serves to provide an interface for the
183 // actual H and dH/dX that the EKF itself needs. Most implementations end up
184 // just using this; in the degenerate case, ExpectedObservationFunctor could
185 // be implemented as a class that simply stores two std::functions and calls
186 // them when H() and DHDX() are called.
187 //
188 // The ObserveDeletion() and deleted() methods exist for sanity checking--we
189 // don't rely on them to do any work, but in order to ensure that memory is
190 // being managed correctly, we have the HybridEkf call ObserveDeletion() when
191 // it no longer needs an instance of the object.
192 class ExpectedObservationFunctor {
193 public:
194 virtual ~ExpectedObservationFunctor() = default;
195 // Return the expected measurement of the system for a given state and plant
196 // input.
197 virtual Output H(const State &state, const Input &input) = 0;
198 // Return the derivative of H() with respect to the state, given the current
199 // state.
200 virtual Eigen::Matrix<Scalar, kNOutputs, kNStates> DHDX(
201 const State &state) = 0;
202 virtual void ObserveDeletion() {
203 CHECK(!deleted_);
204 deleted_ = true;
205 }
206 bool deleted() const { return deleted_; }
207
208 private:
209 bool deleted_ = false;
210 };
211
212 // The ExpectedObservationBuilder creates a new ExpectedObservationFunctor.
213 // This is used for situations where in order to know what the correction
214 // methods even are we need to know the state at some time in the past. This
215 // is only used in the y2019 code and we've generally stopped using this
216 // pattern.
217 class ExpectedObservationBuilder {
218 public:
219 virtual ~ExpectedObservationBuilder() = default;
220 // The lifetime of the returned object should last at least until
221 // ObserveDeletion() is called on said object.
222 virtual ExpectedObservationFunctor *MakeExpectedObservations(
223 const State &state, const StateSquare &P) = 0;
224 void ObserveDeletion() {
225 CHECK(!deleted_);
226 deleted_ = true;
227 }
228 bool deleted() const { return deleted_; }
229
230 private:
231 bool deleted_ = false;
232 };
233
234 // The ExpectedObservationAllocator provides a utility class which manages the
235 // memory for a single type of correction step for a given localizer.
236 // Using the knowledge that at most kSaveSamples ExpectedObservation* objects
237 // can be referenced by the HybridEkf at any given time, this keeps an
238 // internal queue that more than mirrors the HybridEkf's internal queue, using
239 // the oldest spots in the queue to construct new ExpectedObservation*'s.
240 // This can be used with T as either a ExpectedObservationBuilder or
241 // ExpectedObservationFunctor. The appropriate Correct function will then be
242 // called in place of calling HybridEkf::Correct directly. Note that unless T
243 // implements both the Builder and Functor (which is generally discouraged),
244 // only one of the Correct* functions will build.
245 template <typename T>
246 class ExpectedObservationAllocator {
247 public:
248 ExpectedObservationAllocator(HybridEkf *ekf) : ekf_(ekf) {}
249 void CorrectKnownH(const Output &z, const Input *U, T H,
250 const Eigen::Matrix<Scalar, kNOutputs, kNOutputs> &R,
251 aos::monotonic_clock::time_point t) {
252 if (functors_.full()) {
253 CHECK(functors_.begin()->functor->deleted());
254 }
255 auto pushed = functors_.PushFromBottom(Pair{t, std::move(H)});
256 if (pushed == functors_.end()) {
257 VLOG(1) << "Observation dropped off bottom of queue.";
258 return;
259 }
260 ekf_->Correct(z, U, nullptr, &pushed->functor.value(), R, t);
261 }
262 void CorrectKnownHBuilder(
263 const Output &z, const Input *U, T builder,
264 const Eigen::Matrix<Scalar, kNOutputs, kNOutputs> &R,
265 aos::monotonic_clock::time_point t) {
266 if (functors_.full()) {
267 CHECK(functors_.begin()->functor->deleted());
268 }
269 auto pushed = functors_.PushFromBottom(Pair{t, std::move(builder)});
270 if (pushed == functors_.end()) {
271 VLOG(1) << "Observation dropped off bottom of queue.";
272 return;
273 }
274 ekf_->Correct(z, U, &pushed->functor.value(), nullptr, R, t);
275 }
276
277 private:
278 struct Pair {
279 aos::monotonic_clock::time_point t;
280 std::optional<T> functor;
281 friend bool operator<(const Pair &l, const Pair &r) { return l.t < r.t; }
282 };
283
284 HybridEkf *const ekf_;
285 aos::PriorityQueue<Pair, kSaveSamples + 1, std::less<Pair>> functors_;
286 };
287
288 // A simple implementation of ExpectedObservationFunctor for an LTI correction
289 // step. Does not store any external references, so overrides
290 // ObserveDeletion() to do nothing.
291 class LinearH : public ExpectedObservationFunctor {
292 public:
293 LinearH(const Eigen::Matrix<Scalar, kNOutputs, kNStates> &H) : H_(H) {}
294 virtual ~LinearH() = default;
295 Output H(const State &state, const Input &) final { return H_ * state; }
296 Eigen::Matrix<Scalar, kNOutputs, kNStates> DHDX(const State &) final {
297 return H_;
298 }
299 void ObserveDeletion() {}
300
301 private:
302 const Eigen::Matrix<Scalar, kNOutputs, kNStates> H_;
303 };
304
James Kuszmaul2ed7b3c2019-02-09 18:26:19 -0800305 // Constructs a HybridEkf for a particular drivetrain.
306 // Currently, we use the drivetrain config for modelling constants
307 // (continuous time A and B matrices) and for the noise matrices for the
308 // encoders/gyro.
James Kuszmauld478f872020-03-16 20:54:27 -0700309 HybridEkf(const DrivetrainConfig<double> &dt_config)
James Kuszmaul2ed7b3c2019-02-09 18:26:19 -0800310 : dt_config_(dt_config),
311 velocity_drivetrain_coefficients_(
312 dt_config.make_hybrid_drivetrain_velocity_loop()
313 .plant()
314 .coefficients()) {
315 InitializeMatrices();
316 }
317
318 // Set the initial guess of the state. Can only be called once, and before
319 // any measurement updates have occured.
James Kuszmaul2ed7b3c2019-02-09 18:26:19 -0800320 void ResetInitialState(::aos::monotonic_clock::time_point t,
James Kuszmaul1057ce82019-02-09 17:58:24 -0800321 const State &state, const StateSquare &P) {
James Kuszmaul2ed7b3c2019-02-09 18:26:19 -0800322 observations_.clear();
323 X_hat_ = state;
James Kuszmaul074429e2019-03-23 16:01:49 -0700324 have_zeroed_encoders_ = true;
James Kuszmaul1057ce82019-02-09 17:58:24 -0800325 P_ = P;
James Kuszmaul06257f42020-05-09 15:40:09 -0700326 observations_.PushFromBottom({
327 t,
328 t,
329 X_hat_,
330 P_,
331 Input::Zero(),
332 Output::Zero(),
James Kuszmaul2971b5a2023-01-29 15:49:32 -0800333 nullptr,
334 &H_encoders_and_gyro_.value(),
James Kuszmaul06257f42020-05-09 15:40:09 -0700335 Eigen::Matrix<Scalar, kNOutputs, kNOutputs>::Identity(),
336 StateSquare::Identity(),
337 StateSquare::Zero(),
338 std::chrono::seconds(0),
339 State::Zero(),
340 });
James Kuszmaul2ed7b3c2019-02-09 18:26:19 -0800341 }
342
343 // Correct with:
344 // A measurement z at time t with z = h(X_hat, U) + v where v has noise
345 // covariance R.
346 // Input U is applied from the previous timestep until time t.
347 // If t is later than any previous measurements, then U must be provided.
348 // If the measurement falls between two previous measurements, then U
349 // can be provided or not; if U is not provided, then it is filled in based
350 // on an assumption that the voltage was held constant between the time steps.
351 // TODO(james): Is it necessary to explicitly to provide a version with H as a
352 // matrix for linear cases?
James Kuszmaul2971b5a2023-01-29 15:49:32 -0800353 void Correct(const Output &z, const Input *U,
354 ExpectedObservationBuilder *observation_builder,
355 ExpectedObservationFunctor *expected_observations,
356 const Eigen::Matrix<Scalar, kNOutputs, kNOutputs> &R,
357 aos::monotonic_clock::time_point t);
James Kuszmaul2ed7b3c2019-02-09 18:26:19 -0800358
359 // A utility function for specifically updating with encoder and gyro
360 // measurements.
361 void UpdateEncodersAndGyro(const Scalar left_encoder,
362 const Scalar right_encoder, const Scalar gyro_rate,
James Kuszmaul3c5b4d32020-02-11 17:22:14 -0800363 const Eigen::Matrix<Scalar, 2, 1> &voltage,
364 const Eigen::Matrix<Scalar, 3, 1> &accel,
365 aos::monotonic_clock::time_point t) {
366 Input U;
367 U.template block<2, 1>(0, 0) = voltage;
368 U.template block<2, 1>(kLongitudinalAccel, 0) =
369 accel.template block<2, 1>(0, 0);
370 RawUpdateEncodersAndGyro(left_encoder, right_encoder, gyro_rate, U, t);
371 }
372 // Version of UpdateEncodersAndGyro that takes a input matrix rather than
373 // taking in a voltage/acceleration separately.
374 void RawUpdateEncodersAndGyro(const Scalar left_encoder,
375 const Scalar right_encoder,
376 const Scalar gyro_rate, const Input &U,
377 aos::monotonic_clock::time_point t) {
James Kuszmaul074429e2019-03-23 16:01:49 -0700378 // Because the check below for have_zeroed_encoders_ will add an
379 // Observation, do a check here to ensure that initialization has been
380 // performed and so there is at least one observation.
James Kuszmaul3c5b4d32020-02-11 17:22:14 -0800381 CHECK(!observations_.empty());
James Kuszmaul074429e2019-03-23 16:01:49 -0700382 if (!have_zeroed_encoders_) {
383 // This logic handles ensuring that on the first encoder reading, we
384 // update the internal state for the encoders to match the reading.
385 // Otherwise, if we restart the drivetrain without restarting
386 // wpilib_interface, then we can get some obnoxious initial corrections
387 // that mess up the localization.
388 State newstate = X_hat_;
James Kuszmaul3c5b4d32020-02-11 17:22:14 -0800389 newstate(kLeftEncoder) = left_encoder;
390 newstate(kRightEncoder) = right_encoder;
391 newstate(kLeftVoltageError) = 0.0;
392 newstate(kRightVoltageError) = 0.0;
393 newstate(kAngularError) = 0.0;
394 newstate(kLongitudinalVelocityOffset) = 0.0;
395 newstate(kLateralVelocity) = 0.0;
James Kuszmaul074429e2019-03-23 16:01:49 -0700396 ResetInitialState(t, newstate, P_);
397 // We need to set have_zeroed_encoders_ after ResetInitialPosition because
398 // the reset clears have_zeroed_encoders_...
399 have_zeroed_encoders_ = true;
400 }
James Kuszmaul3c5b4d32020-02-11 17:22:14 -0800401
James Kuszmaul2ed7b3c2019-02-09 18:26:19 -0800402 Output z(left_encoder, right_encoder, gyro_rate);
James Kuszmaul3c5b4d32020-02-11 17:22:14 -0800403
James Kuszmaul2ed7b3c2019-02-09 18:26:19 -0800404 Eigen::Matrix<Scalar, kNOutputs, kNOutputs> R;
405 R.setZero();
406 R.diagonal() << encoder_noise_, encoder_noise_, gyro_noise_;
James Kuszmaul2971b5a2023-01-29 15:49:32 -0800407 CHECK(H_encoders_and_gyro_.has_value());
408 Correct(z, &U, nullptr, &H_encoders_and_gyro_.value(), R, t);
James Kuszmaul2ed7b3c2019-02-09 18:26:19 -0800409 }
410
411 // Sundry accessor:
412 State X_hat() const { return X_hat_; }
James Kuszmaul3c5b4d32020-02-11 17:22:14 -0800413 Scalar X_hat(long i) const { return X_hat_(i); }
James Kuszmaul2ed7b3c2019-02-09 18:26:19 -0800414 StateSquare P() const { return P_; }
James Kuszmaul3c5b4d32020-02-11 17:22:14 -0800415 aos::monotonic_clock::time_point latest_t() const {
James Kuszmaul2ed7b3c2019-02-09 18:26:19 -0800416 return observations_.top().t;
417 }
418
James Kuszmaul3c5b4d32020-02-11 17:22:14 -0800419 static Scalar CalcLongitudinalVelocity(const State &X) {
420 return (X(kLeftVelocity) + X(kRightVelocity)) / 2.0;
421 }
422
423 Scalar CalcYawRate(const State &X) const {
424 return (X(kRightVelocity) - X(kLeftVelocity)) / 2.0 /
425 dt_config_.robot_radius;
426 }
427
James Kuszmaul06257f42020-05-09 15:40:09 -0700428 // Returns the last state before the specified time.
429 // Returns nullopt if time is older than the oldest measurement.
430 std::optional<State> LastStateBeforeTime(
431 aos::monotonic_clock::time_point time) {
432 if (observations_.empty() || observations_.begin()->t > time) {
433 return std::nullopt;
434 }
435 for (const auto &observation : observations_) {
436 if (observation.t > time) {
437 // Note that observation.X_hat actually references the _previous_ X_hat.
438 return observation.X_hat;
439 }
440 }
441 return X_hat();
442 }
James Kuszmaulba59dc92022-03-12 10:46:54 -0800443 std::optional<State> OldestState() {
444 if (observations_.empty()) {
445 return std::nullopt;
446 }
447 return observations_.begin()->X_hat;
448 }
James Kuszmaul06257f42020-05-09 15:40:09 -0700449
450 // Returns the most recent input vector.
451 Input MostRecentInput() {
452 CHECK(!observations_.empty());
453 Input U = observations_.top().U;
454 return U;
455 }
456
James Kuszmaul91aa0cf2021-02-13 13:15:06 -0800457 void set_ignore_accel(bool ignore_accel) { ignore_accel_ = ignore_accel; }
458
James Kuszmaul2ed7b3c2019-02-09 18:26:19 -0800459 private:
460 struct Observation {
James Kuszmaul2971b5a2023-01-29 15:49:32 -0800461 Observation(aos::monotonic_clock::time_point t,
462 aos::monotonic_clock::time_point prev_t, State X_hat,
463 StateSquare P, Input U, Output z,
464 ExpectedObservationBuilder *make_h,
465 ExpectedObservationFunctor *h,
466 Eigen::Matrix<Scalar, kNOutputs, kNOutputs> R, StateSquare A_d,
467 StateSquare Q_d,
468 aos::monotonic_clock::duration discretization_time,
469 State predict_update)
470 : t(t),
471 prev_t(prev_t),
472 X_hat(X_hat),
473 P(P),
474 U(U),
475 z(z),
476 make_h(make_h),
477 h(h),
478 R(R),
479 A_d(A_d),
480 Q_d(Q_d),
481 discretization_time(discretization_time),
482 predict_update(predict_update) {}
483 Observation(const Observation &) = delete;
484 Observation &operator=(const Observation &) = delete;
485 // Move-construct an observation by copying over the contents of the struct
486 // and then clearing the old Observation's pointers so that it doesn't try
487 // to clean things up.
488 Observation(Observation &&o)
489 : Observation(o.t, o.prev_t, o.X_hat, o.P, o.U, o.z, o.make_h, o.h, o.R,
490 o.A_d, o.Q_d, o.discretization_time, o.predict_update) {
491 o.make_h = nullptr;
492 o.h = nullptr;
493 }
494 Observation &operator=(Observation &&observation) = delete;
495 ~Observation() {
496 // Observe h being deleted first, since make_h may own its memory.
497 // Shouldn't actually matter, though.
498 if (h != nullptr) {
499 h->ObserveDeletion();
500 }
501 if (make_h != nullptr) {
502 make_h->ObserveDeletion();
503 }
504 }
James Kuszmaul2ed7b3c2019-02-09 18:26:19 -0800505 // Time when the observation was taken.
506 aos::monotonic_clock::time_point t;
507 // Time that the previous observation was taken:
508 aos::monotonic_clock::time_point prev_t;
509 // Estimate of state at previous observation time t, after accounting for
510 // the previous observation.
511 State X_hat;
512 // Noise matrix corresponding to X_hat_.
513 StateSquare P;
514 // The input applied from previous observation until time t.
515 Input U;
516 // Measurement taken at that time.
517 Output z;
518 // A function to create h and dhdx from a given position/covariance
519 // estimate. This is used by the camera to make it so that we only have to
520 // match targets once.
521 // Only called if h and dhdx are empty.
James Kuszmaul2971b5a2023-01-29 15:49:32 -0800522 ExpectedObservationBuilder *make_h = nullptr;
James Kuszmaul2ed7b3c2019-02-09 18:26:19 -0800523 // A function to calculate the expected output at a given state/input.
524 // TODO(james): For encoders/gyro, it is linear and the function call may
525 // be expensive. Potential source of optimization.
James Kuszmaul2971b5a2023-01-29 15:49:32 -0800526 ExpectedObservationFunctor *h = nullptr;
James Kuszmaul2ed7b3c2019-02-09 18:26:19 -0800527 // The measurement noise matrix.
528 Eigen::Matrix<Scalar, kNOutputs, kNOutputs> R;
529
James Kuszmaul06257f42020-05-09 15:40:09 -0700530 // Discretized A and Q to use on this update step. These will only be
531 // recalculated if the timestep changes.
532 StateSquare A_d;
533 StateSquare Q_d;
534 aos::monotonic_clock::duration discretization_time;
535
536 // A cached value indicating how much we change X_hat in the prediction step
537 // of this Observation.
538 State predict_update;
539
James Kuszmaul2ed7b3c2019-02-09 18:26:19 -0800540 // In order to sort the observations in the PriorityQueue object, we
541 // need a comparison function.
James Kuszmaul651fc3f2019-05-15 21:14:25 -0700542 friend bool operator<(const Observation &l, const Observation &r) {
James Kuszmaul2ed7b3c2019-02-09 18:26:19 -0800543 return l.t < r.t;
544 }
545 };
546
547 void InitializeMatrices();
548
James Kuszmaul3c5b4d32020-02-11 17:22:14 -0800549 // These constants and functions define how the longitudinal velocity
550 // (the average of the left and right velocities) decays. We model it as
551 // decaying at a constant rate, except very near zero where the decay rate is
552 // exponential (this is more numerically stable than just using a constant
553 // rate the whole time). We use this model rather than a simpler exponential
554 // decay because an exponential decay will result in the robot's velocity
555 // estimate consistently being far too low when at high velocities, and since
556 // the acceleromater-based estimate of the velocity will only drift at a
557 // relatively slow rate and doesn't get worse at higher velocities, we can
558 // safely decay pretty slowly.
559 static constexpr double kMaxVelocityAccel = 0.005;
560 static constexpr double kMaxVelocityGain = 1.0;
561 static Scalar VelocityAccel(Scalar velocity) {
562 return -std::clamp(kMaxVelocityGain * velocity, -kMaxVelocityAccel,
563 kMaxVelocityAccel);
564 }
565
566 static Scalar VelocityAccelDiff(Scalar velocity) {
567 return (std::abs(kMaxVelocityGain * velocity) > kMaxVelocityAccel)
568 ? 0.0
569 : -kMaxVelocityGain;
570 }
571
572 // Returns the "A" matrix for a given state. See DiffEq for discussion of
573 // ignore_accel.
James Kuszmaul91aa0cf2021-02-13 13:15:06 -0800574 StateSquare AForState(const State &X, bool ignore_accel) const {
James Kuszmaul3c5b4d32020-02-11 17:22:14 -0800575 // Calculate the A matrix for a given state. Note that A = partial Xdot /
576 // partial X. This is distinct from saying that Xdot = A * X. This is
577 // particularly relevant for the (kX, kTheta) members which otherwise seem
578 // odd.
James Kuszmaul2ed7b3c2019-02-09 18:26:19 -0800579 StateSquare A_continuous = A_continuous_;
James Kuszmaul3c5b4d32020-02-11 17:22:14 -0800580 const Scalar theta = X(kTheta);
581 const Scalar stheta = std::sin(theta);
582 const Scalar ctheta = std::cos(theta);
583 const Scalar lng_vel = CalcLongitudinalVelocity(X);
584 const Scalar lat_vel = X(kLateralVelocity);
585 const Scalar diameter = 2.0 * dt_config_.robot_radius;
586 const Scalar yaw_rate = CalcYawRate(X);
James Kuszmaul2ed7b3c2019-02-09 18:26:19 -0800587 // X and Y derivatives
Austin Schuhd749d932020-12-30 21:38:40 -0800588 A_continuous(kX, kTheta) = -stheta * lng_vel - ctheta * lat_vel;
James Kuszmaul2ed7b3c2019-02-09 18:26:19 -0800589 A_continuous(kX, kLeftVelocity) = ctheta / 2.0;
590 A_continuous(kX, kRightVelocity) = ctheta / 2.0;
James Kuszmaul3c5b4d32020-02-11 17:22:14 -0800591 A_continuous(kX, kLateralVelocity) = -stheta;
592 A_continuous(kY, kTheta) = ctheta * lng_vel - stheta * lat_vel;
James Kuszmaul2ed7b3c2019-02-09 18:26:19 -0800593 A_continuous(kY, kLeftVelocity) = stheta / 2.0;
594 A_continuous(kY, kRightVelocity) = stheta / 2.0;
James Kuszmaul3c5b4d32020-02-11 17:22:14 -0800595 A_continuous(kY, kLateralVelocity) = ctheta;
596
597 if (!ignore_accel) {
598 const Eigen::Matrix<Scalar, 1, kNStates> lng_vel_row =
599 (A_continuous.row(kLeftVelocity) + A_continuous.row(kRightVelocity)) /
600 2.0;
601 A_continuous.row(kLeftVelocity) -= lng_vel_row;
602 A_continuous.row(kRightVelocity) -= lng_vel_row;
603 // Terms to account for centripetal accelerations.
604 // lateral centripetal accel = -yaw_rate * lng_vel
605 A_continuous(kLateralVelocity, kLeftVelocity) +=
606 X(kLeftVelocity) / diameter;
607 A_continuous(kLateralVelocity, kRightVelocity) +=
608 -X(kRightVelocity) / diameter;
609 A_continuous(kRightVelocity, kLateralVelocity) += yaw_rate;
610 A_continuous(kLeftVelocity, kLateralVelocity) += yaw_rate;
611 const Scalar dlng_accel_dwheel_vel = X(kLateralVelocity) / diameter;
612 A_continuous(kRightVelocity, kRightVelocity) += dlng_accel_dwheel_vel;
613 A_continuous(kLeftVelocity, kRightVelocity) += dlng_accel_dwheel_vel;
614 A_continuous(kRightVelocity, kLeftVelocity) += -dlng_accel_dwheel_vel;
615 A_continuous(kLeftVelocity, kLeftVelocity) += -dlng_accel_dwheel_vel;
616
617 A_continuous(kRightVelocity, kRightVelocity) +=
618 VelocityAccelDiff(lng_vel) / 2.0;
619 A_continuous(kRightVelocity, kLeftVelocity) +=
620 VelocityAccelDiff(lng_vel) / 2.0;
621 A_continuous(kLeftVelocity, kRightVelocity) +=
622 VelocityAccelDiff(lng_vel) / 2.0;
623 A_continuous(kLeftVelocity, kLeftVelocity) +=
624 VelocityAccelDiff(lng_vel) / 2.0;
625 }
James Kuszmaul2ed7b3c2019-02-09 18:26:19 -0800626 return A_continuous;
627 }
628
James Kuszmaul3c5b4d32020-02-11 17:22:14 -0800629 // Returns dX / dt given X and U. If ignore_accel is set, then we ignore the
630 // accelerometer-based components of U (this is solely used in testing).
James Kuszmaul91aa0cf2021-02-13 13:15:06 -0800631 State DiffEq(const State &X, const Input &U, bool ignore_accel) const {
James Kuszmaul2ed7b3c2019-02-09 18:26:19 -0800632 State Xdot = A_continuous_ * X + B_continuous_ * U;
633 // And then we need to add on the terms for the x/y change:
James Kuszmaul3c5b4d32020-02-11 17:22:14 -0800634 const Scalar theta = X(kTheta);
635 const Scalar lng_vel = CalcLongitudinalVelocity(X);
636 const Scalar lat_vel = X(kLateralVelocity);
637 const Scalar stheta = std::sin(theta);
638 const Scalar ctheta = std::cos(theta);
639 Xdot(kX) = ctheta * lng_vel - stheta * lat_vel;
640 Xdot(kY) = stheta * lng_vel + ctheta * lat_vel;
641
642 const Scalar yaw_rate = CalcYawRate(X);
643 const Scalar expected_lat_accel = lng_vel * yaw_rate;
644 const Scalar expected_lng_accel =
645 CalcLongitudinalVelocity(Xdot) - yaw_rate * lat_vel;
Austin Schuhd749d932020-12-30 21:38:40 -0800646 const Scalar lng_accel_offset = U(kLongitudinalAccel) - expected_lng_accel;
James Kuszmaul3c5b4d32020-02-11 17:22:14 -0800647 constexpr double kAccelWeight = 1.0;
648 if (!ignore_accel) {
649 Xdot(kLeftVelocity) += kAccelWeight * lng_accel_offset;
650 Xdot(kRightVelocity) += kAccelWeight * lng_accel_offset;
651 Xdot(kLateralVelocity) += U(kLateralAccel) - expected_lat_accel;
652
653 Xdot(kRightVelocity) += VelocityAccel(lng_vel);
654 Xdot(kLeftVelocity) += VelocityAccel(lng_vel);
655 }
James Kuszmaul2ed7b3c2019-02-09 18:26:19 -0800656 return Xdot;
657 }
658
James Kuszmaul06257f42020-05-09 15:40:09 -0700659 void PredictImpl(Observation *obs, std::chrono::nanoseconds dt, State *state,
James Kuszmaul2ed7b3c2019-02-09 18:26:19 -0800660 StateSquare *P) {
James Kuszmaul06257f42020-05-09 15:40:09 -0700661 // Only recalculate the discretization if the timestep has changed.
662 // Technically, this isn't quite correct, since the discretization will
663 // change depending on the current state. However, the slight loss of
664 // precision seems acceptable for the sake of significantly reducing CPU
665 // usage.
666 if (obs->discretization_time != dt) {
667 // TODO(james): By far the biggest CPU sink in the localization appears to
668 // be this discretization--it's possible the spline code spikes higher,
669 // but it doesn't create anywhere near the same sustained load. There
670 // are a few potential options for optimizing this code, but none of
671 // them are entirely trivial, e.g. we could:
672 // -Reduce the number of states (this function grows at O(kNStates^3))
673 // -Adjust the discretization function itself (there're a few things we
674 // can tune there).
675 // -Try to come up with some sort of lookup table or other way of
676 // pre-calculating A_d and Q_d.
677 // I also have to figure out how much we care about the precision of
678 // some of these values--I don't think we care much, but we probably
679 // do want to maintain some of the structure of the matrices.
James Kuszmaul91aa0cf2021-02-13 13:15:06 -0800680 const StateSquare A_c = AForState(*state, ignore_accel_);
James Kuszmaul06257f42020-05-09 15:40:09 -0700681 controls::DiscretizeQAFast(Q_continuous_, A_c, dt, &obs->Q_d, &obs->A_d);
682 obs->discretization_time = dt;
James Kuszmaul2ed7b3c2019-02-09 18:26:19 -0800683
James Kuszmaul06257f42020-05-09 15:40:09 -0700684 obs->predict_update =
685 RungeKuttaU(
James Kuszmaul91aa0cf2021-02-13 13:15:06 -0800686 [this](const State &X, const Input &U) {
687 return DiffEq(X, U, ignore_accel_);
688 },
James Kuszmaul06257f42020-05-09 15:40:09 -0700689 *state, obs->U, aos::time::DurationInSeconds(dt)) -
690 *state;
691 }
James Kuszmaulb2a2f352019-03-02 16:59:34 -0800692
James Kuszmaul06257f42020-05-09 15:40:09 -0700693 *state += obs->predict_update;
694
695 StateSquare Ptemp = obs->A_d * *P * obs->A_d.transpose() + obs->Q_d;
James Kuszmaulb2a2f352019-03-02 16:59:34 -0800696 *P = Ptemp;
James Kuszmaul2ed7b3c2019-02-09 18:26:19 -0800697 }
698
James Kuszmaul06257f42020-05-09 15:40:09 -0700699 void CorrectImpl(Observation *obs, State *state, StateSquare *P) {
James Kuszmaul2971b5a2023-01-29 15:49:32 -0800700 const Eigen::Matrix<Scalar, kNOutputs, kNStates> H = obs->h->DHDX(*state);
James Kuszmaul06257f42020-05-09 15:40:09 -0700701 // Note: Technically, this does calculate P * H.transpose() twice. However,
702 // when I was mucking around with some things, I found that in practice
703 // putting everything into one expression and letting Eigen optimize it
704 // directly actually improved performance relative to precalculating P *
705 // H.transpose().
706 const Eigen::Matrix<Scalar, kNStates, kNOutputs> K =
707 *P * H.transpose() * (H * *P * H.transpose() + obs->R).inverse();
708 const StateSquare Ptemp = (StateSquare::Identity() - K * H) * *P;
James Kuszmaulb2a2f352019-03-02 16:59:34 -0800709 *P = Ptemp;
James Kuszmaul2971b5a2023-01-29 15:49:32 -0800710 *state += K * (obs->z - obs->h->H(*state, obs->U));
James Kuszmaul2ed7b3c2019-02-09 18:26:19 -0800711 }
712
713 void ProcessObservation(Observation *obs, const std::chrono::nanoseconds dt,
714 State *state, StateSquare *P) {
715 *state = obs->X_hat;
716 *P = obs->P;
James Kuszmaulf3950362020-10-11 18:29:15 -0700717 if (dt.count() != 0 && dt < kMaxTimestep) {
James Kuszmaul06257f42020-05-09 15:40:09 -0700718 PredictImpl(obs, dt, state, P);
James Kuszmaul2ed7b3c2019-02-09 18:26:19 -0800719 }
James Kuszmaul2971b5a2023-01-29 15:49:32 -0800720 if (obs->h == nullptr) {
721 CHECK(obs->make_h != nullptr);
722 obs->h = CHECK_NOTNULL(obs->make_h->MakeExpectedObservations(*state, *P));
James Kuszmaul2ed7b3c2019-02-09 18:26:19 -0800723 }
James Kuszmaul06257f42020-05-09 15:40:09 -0700724 CorrectImpl(obs, state, P);
James Kuszmaul2ed7b3c2019-02-09 18:26:19 -0800725 }
726
James Kuszmauld478f872020-03-16 20:54:27 -0700727 DrivetrainConfig<double> dt_config_;
James Kuszmaul2ed7b3c2019-02-09 18:26:19 -0800728 State X_hat_;
James Kuszmauld478f872020-03-16 20:54:27 -0700729 StateFeedbackHybridPlantCoefficients<2, 2, 2, double>
James Kuszmaul2ed7b3c2019-02-09 18:26:19 -0800730 velocity_drivetrain_coefficients_;
731 StateSquare A_continuous_;
732 StateSquare Q_continuous_;
733 StateSquare P_;
James Kuszmaul2971b5a2023-01-29 15:49:32 -0800734 std::optional<LinearH> H_encoders_and_gyro_;
James Kuszmaul2ed7b3c2019-02-09 18:26:19 -0800735 Scalar encoder_noise_, gyro_noise_;
736 Eigen::Matrix<Scalar, kNStates, kNInputs> B_continuous_;
737
James Kuszmaul074429e2019-03-23 16:01:49 -0700738 bool have_zeroed_encoders_ = false;
739
James Kuszmaul91aa0cf2021-02-13 13:15:06 -0800740 // Whether to pay attention to accelerometer readings to compensate for wheel
741 // slip.
742 bool ignore_accel_ = false;
743
James Kuszmaul3c5b4d32020-02-11 17:22:14 -0800744 aos::PriorityQueue<Observation, kSaveSamples, std::less<Observation>>
James Kuszmaul2ed7b3c2019-02-09 18:26:19 -0800745 observations_;
746
747 friend class testing::HybridEkfTest;
James Kuszmaul3c5b4d32020-02-11 17:22:14 -0800748 friend class y2019::control_loops::testing::ParameterizedLocalizerTest;
James Kuszmaul2ed7b3c2019-02-09 18:26:19 -0800749}; // class HybridEkf
750
751template <typename Scalar>
752void HybridEkf<Scalar>::Correct(
753 const Output &z, const Input *U,
James Kuszmaul2971b5a2023-01-29 15:49:32 -0800754 ExpectedObservationBuilder *observation_builder,
755 ExpectedObservationFunctor *expected_observations,
Austin Schuhd749d932020-12-30 21:38:40 -0800756 const Eigen::Matrix<Scalar, kNOutputs, kNOutputs> &R,
James Kuszmaul2ed7b3c2019-02-09 18:26:19 -0800757 aos::monotonic_clock::time_point t) {
James Kuszmaul3c5b4d32020-02-11 17:22:14 -0800758 CHECK(!observations_.empty());
James Kuszmaul2ed7b3c2019-02-09 18:26:19 -0800759 if (!observations_.full() && t < observations_.begin()->t) {
James Kuszmaul3c5b4d32020-02-11 17:22:14 -0800760 LOG(ERROR) << "Dropped an observation that was received before we "
761 "initialized.\n";
James Kuszmaul2ed7b3c2019-02-09 18:26:19 -0800762 return;
763 }
James Kuszmaul06257f42020-05-09 15:40:09 -0700764 auto cur_it = observations_.PushFromBottom(
James Kuszmaul2971b5a2023-01-29 15:49:32 -0800765 {t, t, State::Zero(), StateSquare::Zero(), Input::Zero(), z,
766 observation_builder, expected_observations, R, StateSquare::Identity(),
767 StateSquare::Zero(), std::chrono::seconds(0), State::Zero()});
James Kuszmaul2ed7b3c2019-02-09 18:26:19 -0800768 if (cur_it == observations_.end()) {
James Kuszmaul3c5b4d32020-02-11 17:22:14 -0800769 VLOG(1) << "Camera dropped off of end with time of "
770 << aos::time::DurationInSeconds(t.time_since_epoch())
771 << "s; earliest observation in "
772 "queue has time of "
773 << aos::time::DurationInSeconds(
774 observations_.begin()->t.time_since_epoch())
775 << "s.\n";
James Kuszmaul2ed7b3c2019-02-09 18:26:19 -0800776 return;
777 }
James Kuszmaul2ed7b3c2019-02-09 18:26:19 -0800778 // Now we populate any state information that depends on where the
779 // observation was inserted into the queue. X_hat and P must be populated
780 // from the values present in the observation *following* this one in
781 // the queue (note that the X_hat and P that we store in each observation
782 // is the values that they held after accounting for the previous
783 // measurement and before accounting for the time between the previous and
784 // current measurement). If we appended to the end of the queue, then
785 // we need to pull from X_hat_ and P_ specifically.
786 // Furthermore, for U:
787 // -If the observation was inserted at the end, then the user must've
788 // provided U and we use it.
789 // -Otherwise, only grab U if necessary.
790 auto next_it = cur_it;
791 ++next_it;
792 if (next_it == observations_.end()) {
793 cur_it->X_hat = X_hat_;
794 cur_it->P = P_;
795 // Note that if next_it == observations_.end(), then because we already
796 // checked for !observations_.empty(), we are guaranteed to have
797 // valid prev_it.
798 auto prev_it = cur_it;
799 --prev_it;
800 cur_it->prev_t = prev_it->t;
801 // TODO(james): Figure out a saner way of handling this.
James Kuszmaul3c5b4d32020-02-11 17:22:14 -0800802 CHECK(U != nullptr);
James Kuszmaul2ed7b3c2019-02-09 18:26:19 -0800803 cur_it->U = *U;
804 } else {
805 cur_it->X_hat = next_it->X_hat;
806 cur_it->P = next_it->P;
807 cur_it->prev_t = next_it->prev_t;
808 next_it->prev_t = cur_it->t;
809 cur_it->U = (U == nullptr) ? next_it->U : *U;
810 }
James Kuszmaul06257f42020-05-09 15:40:09 -0700811
812 if (kFullRewindOnEverySample) {
813 next_it = observations_.begin();
814 cur_it = next_it++;
815 }
816
James Kuszmaul2ed7b3c2019-02-09 18:26:19 -0800817 // Now we need to rerun the predict step from the previous to the new
818 // observation as well as every following correct/predict up to the current
819 // time.
820 while (true) {
821 // We use X_hat_ and P_ to store the intermediate states, and then
822 // once we reach the end they will all be up-to-date.
823 ProcessObservation(&*cur_it, cur_it->t - cur_it->prev_t, &X_hat_, &P_);
James Kuszmaul891f4f12020-10-31 17:13:23 -0700824 // TOOD(james): Note that this can be triggered when there are extremely
825 // small values in P_. This is particularly likely if Scalar is just float
826 // and we are performing zero-time updates where the predict step never
827 // runs.
James Kuszmaul3c5b4d32020-02-11 17:22:14 -0800828 CHECK(X_hat_.allFinite());
James Kuszmaul2ed7b3c2019-02-09 18:26:19 -0800829 if (next_it != observations_.end()) {
830 next_it->X_hat = X_hat_;
831 next_it->P = P_;
832 } else {
833 break;
834 }
835 ++cur_it;
836 ++next_it;
837 }
838}
839
840template <typename Scalar>
841void HybridEkf<Scalar>::InitializeMatrices() {
842 A_continuous_.setZero();
843 const Scalar diameter = 2.0 * dt_config_.robot_radius;
844 // Theta derivative
845 A_continuous_(kTheta, kLeftVelocity) = -1.0 / diameter;
846 A_continuous_(kTheta, kRightVelocity) = 1.0 / diameter;
847
848 // Encoder derivatives
849 A_continuous_(kLeftEncoder, kLeftVelocity) = 1.0;
James Kuszmaul074429e2019-03-23 16:01:49 -0700850 A_continuous_(kLeftEncoder, kAngularError) = 1.0;
James Kuszmaul3c5b4d32020-02-11 17:22:14 -0800851 A_continuous_(kLeftEncoder, kLongitudinalVelocityOffset) = -1.0;
James Kuszmaul2ed7b3c2019-02-09 18:26:19 -0800852 A_continuous_(kRightEncoder, kRightVelocity) = 1.0;
James Kuszmaul074429e2019-03-23 16:01:49 -0700853 A_continuous_(kRightEncoder, kAngularError) = -1.0;
James Kuszmaul3c5b4d32020-02-11 17:22:14 -0800854 A_continuous_(kRightEncoder, kLongitudinalVelocityOffset) = -1.0;
James Kuszmaul2ed7b3c2019-02-09 18:26:19 -0800855
856 // Pull velocity derivatives from velocity matrices.
857 // Note that this looks really awkward (doesn't use
858 // Eigen blocks) because someone decided that the full
James Kuszmaulbcd96fc2020-10-12 20:29:32 -0700859 // drivetrain Kalman Filter should have a weird convention.
James Kuszmaul2ed7b3c2019-02-09 18:26:19 -0800860 // TODO(james): Support shifting drivetrains with changing A_continuous
861 const auto &vel_coefs = velocity_drivetrain_coefficients_;
862 A_continuous_(kLeftVelocity, kLeftVelocity) = vel_coefs.A_continuous(0, 0);
863 A_continuous_(kLeftVelocity, kRightVelocity) = vel_coefs.A_continuous(0, 1);
864 A_continuous_(kRightVelocity, kLeftVelocity) = vel_coefs.A_continuous(1, 0);
865 A_continuous_(kRightVelocity, kRightVelocity) = vel_coefs.A_continuous(1, 1);
866
James Kuszmaul3c5b4d32020-02-11 17:22:14 -0800867 A_continuous_(kLongitudinalVelocityOffset, kLongitudinalVelocityOffset) =
868 -1.0 / kVelocityOffsetTimeConstant;
869 A_continuous_(kLateralVelocity, kLateralVelocity) =
870 -1.0 / kLateralVelocityTimeConstant;
871
James Kuszmaul3c5b4d32020-02-11 17:22:14 -0800872 // TODO(james): Decide what to do about these terms. They don't really matter
873 // too much when we have accelerometer readings available.
James Kuszmaul2ed7b3c2019-02-09 18:26:19 -0800874 B_continuous_.setZero();
James Kuszmaul3c5b4d32020-02-11 17:22:14 -0800875 B_continuous_.template block<1, 2>(kLeftVelocity, kLeftVoltage) =
James Kuszmauld478f872020-03-16 20:54:27 -0700876 vel_coefs.B_continuous.row(0).template cast<Scalar>();
James Kuszmaul3c5b4d32020-02-11 17:22:14 -0800877 B_continuous_.template block<1, 2>(kRightVelocity, kLeftVoltage) =
James Kuszmauld478f872020-03-16 20:54:27 -0700878 vel_coefs.B_continuous.row(1).template cast<Scalar>();
James Kuszmaul3c5b4d32020-02-11 17:22:14 -0800879 A_continuous_.template block<kNStates, 2>(0, kLeftVoltageError) =
880 B_continuous_.template block<kNStates, 2>(0, kLeftVoltage);
James Kuszmaul2ed7b3c2019-02-09 18:26:19 -0800881
882 Q_continuous_.setZero();
883 // TODO(james): Improve estimates of process noise--e.g., X/Y noise can
James Kuszmaul1057ce82019-02-09 17:58:24 -0800884 // probably be reduced when we are stopped because you rarely jump randomly.
885 // Or maybe it's more appropriate to scale wheelspeed noise with wheelspeed,
886 // since the wheels aren't likely to slip much stopped.
James Kuszmaula5632fe2019-03-23 20:28:33 -0700887 Q_continuous_(kX, kX) = 0.002;
888 Q_continuous_(kY, kY) = 0.002;
James Kuszmaul7f1a4082019-04-14 10:50:44 -0700889 Q_continuous_(kTheta, kTheta) = 0.0001;
James Kuszmaul3c5b4d32020-02-11 17:22:14 -0800890 Q_continuous_(kLeftEncoder, kLeftEncoder) = std::pow(0.15, 2.0);
891 Q_continuous_(kRightEncoder, kRightEncoder) = std::pow(0.15, 2.0);
892 Q_continuous_(kLeftVelocity, kLeftVelocity) = std::pow(0.5, 2.0);
893 Q_continuous_(kRightVelocity, kRightVelocity) = std::pow(0.5, 2.0);
894 Q_continuous_(kLeftVoltageError, kLeftVoltageError) = std::pow(10.0, 2.0);
895 Q_continuous_(kRightVoltageError, kRightVoltageError) = std::pow(10.0, 2.0);
896 Q_continuous_(kAngularError, kAngularError) = std::pow(2.0, 2.0);
897 // This noise value largely governs whether we will trust the encoders or
898 // accelerometer more for estimating the robot position.
James Kuszmaul5398fae2020-02-17 16:44:03 -0800899 // Note that this also affects how we interpret camera measurements,
900 // particularly when using a heading/distance/skew measurement--if the
901 // noise on these numbers is particularly high, then we can end up with weird
902 // dynamics where a camera update both shifts our X/Y position and adjusts our
903 // velocity estimates substantially, causing the camera updates to create
Austin Schuhd749d932020-12-30 21:38:40 -0800904 // "momentum" and if we don't trust the encoders enough, then we have no way
905 // of determining that the velocity updates are bogus. This also interacts
906 // with kVelocityOffsetTimeConstant.
James Kuszmaul3c5b4d32020-02-11 17:22:14 -0800907 Q_continuous_(kLongitudinalVelocityOffset, kLongitudinalVelocityOffset) =
908 std::pow(1.1, 2.0);
909 Q_continuous_(kLateralVelocity, kLateralVelocity) = std::pow(0.1, 2.0);
James Kuszmaul2ed7b3c2019-02-09 18:26:19 -0800910
James Kuszmaul2971b5a2023-01-29 15:49:32 -0800911 {
912 Eigen::Matrix<Scalar, kNOutputs, kNStates> H_encoders_and_gyro;
913 H_encoders_and_gyro.setZero();
914 // Encoders are stored directly in the state matrix, so are a minor
915 // transform away.
916 H_encoders_and_gyro(0, kLeftEncoder) = 1.0;
917 H_encoders_and_gyro(1, kRightEncoder) = 1.0;
918 // Gyro rate is just the difference between right/left side speeds:
919 H_encoders_and_gyro(2, kLeftVelocity) = -1.0 / diameter;
920 H_encoders_and_gyro(2, kRightVelocity) = 1.0 / diameter;
921 H_encoders_and_gyro_.emplace(H_encoders_and_gyro);
922 }
James Kuszmaul2ed7b3c2019-02-09 18:26:19 -0800923
James Kuszmaul3c5b4d32020-02-11 17:22:14 -0800924 encoder_noise_ = 5e-9;
925 gyro_noise_ = 1e-13;
Austin Schuh9fe68f72019-08-10 19:32:03 -0700926
927 X_hat_.setZero();
928 P_.setZero();
James Kuszmaul2ed7b3c2019-02-09 18:26:19 -0800929}
930
Stephan Pleinesd99b1ee2024-02-02 20:56:44 -0800931} // namespace frc971::control_loops::drivetrain
James Kuszmaul2ed7b3c2019-02-09 18:26:19 -0800932
933#endif // FRC971_CONTROL_LOOPS_DRIVETRAIN_HYBRID_EKF_H_