blob: 89b2182954ee038b2e4c94232c3929f6ec6b23e8 [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"
James Kuszmaul3c5b4d32020-02-11 17:22:14 -08007#include "aos/commonmath.h"
James Kuszmaul2ed7b3c2019-02-09 18:26:19 -08008#include "aos/containers/priority_queue.h"
James Kuszmaulfedc4612019-03-10 11:24:51 -07009#include "aos/util/math.h"
James Kuszmaul2ed7b3c2019-02-09 18:26:19 -080010#include "frc971/control_loops/c2d.h"
James Kuszmaul2ed7b3c2019-02-09 18:26:19 -080011#include "frc971/control_loops/drivetrain/drivetrain_config.h"
James Kuszmaul651fc3f2019-05-15 21:14:25 -070012#include "frc971/control_loops/runge_kutta.h"
James Kuszmaul2ed7b3c2019-02-09 18:26:19 -080013
James Kuszmaul1057ce82019-02-09 17:58:24 -080014namespace y2019 {
15namespace control_loops {
16namespace testing {
17class ParameterizedLocalizerTest;
18} // namespace testing
19} // namespace control_loops
20} // namespace y2019
21
James Kuszmaul2ed7b3c2019-02-09 18:26:19 -080022namespace frc971 {
23namespace control_loops {
24namespace drivetrain {
25
26namespace testing {
27class HybridEkfTest;
28}
29
30// HybridEkf is an EKF for use in robot localization. It is currently
31// coded for use with drivetrains in particular, and so the states and inputs
32// are chosen as such.
33// The "Hybrid" part of the name refers to the fact that it can take in
34// measurements with variable time-steps.
35// measurements can also have been taken in the past and we maintain a buffer
36// so that we can replay the kalman filter whenever we get an old measurement.
37// Currently, this class provides the necessary utilities for doing
38// measurement updates with an encoder/gyro as well as a more generic
39// update function that can be used for arbitrary nonlinear updates (presumably
40// a camera update).
James Kuszmaul3c5b4d32020-02-11 17:22:14 -080041//
42// Discussion of the model:
43// In the current model, we try to rely primarily on IMU measurements for
44// estimating robot state--we also need additional information (some combination
45// of output voltages, encoders, and camera data) to help eliminate the biases
46// that can accumulate due to integration of IMU data.
47// We use IMU measurements as inputs rather than measurement outputs because
48// that seemed to be easier to implement. I tried initially running with
49// the IMU as a measurement, but it seemed to blow up the complexity of the
50// model.
51//
52// On each prediction update, we take in inputs of the left/right voltages and
53// the current measured longitudinal/lateral accelerations. In the current
54// setup, the accelerometer readings will be used for estimating how the
55// evolution of the longitudinal/lateral velocities. The voltages (and voltage
56// errors) will solely be used for estimating the current rotational velocity of
57// the robot (I do this because currently I suspect that the accelerometer is a
58// much better indicator of current robot state than the voltages). We also
59// deliberately decay all of the velocity estimates towards zero to help address
60// potential accelerometer biases. We use two separate decay models:
61// -The longitudinal velocity is modelled as decaying at a constant rate (see
62// the documentation on the VelocityAccel() method)--this needs a more
63// complex model because the robot will, under normal circumstances, be
64// travelling at non-zero velocities.
65// -The lateral velocity is modelled as exponentially decaying towards zero.
66// This is simpler to model and should be reasonably valid, since we will
67// not *normally* be travelling sideways consistently (this assumption may
68// need to be revisited).
69// -The "longitudinal velocity offset" (described below) also uses an
70// exponential decay, albeit with a different time constant. A future
71// improvement may remove the decay modelling on the longitudinal velocity
72// itself and instead use that decay model on the longitudinal velocity offset.
73// This would place a bit more trust in the encoder measurements but also
74// more correctly model situations where the robot is legitimately moving at
75// a certain velocity.
76//
77// For modelling how the drivetrain encoders evolve, and to help prevent the
78// aforementioned decay functions from affecting legitimate high-velocity
79// maneuvers too much, we have a "longitudinal velocity offset" term. This term
80// models the difference between the actual longitudinal velocity of the robot
81// (estimated by the average of the left/right velocities) and the velocity
82// experienced by the wheels (which can be observed from the encoders more
83// directly). Because we model this velocity offset as decaying towards zero,
84// what this will do is allow the encoders to be a constant velocity off from
85// the accelerometer updates for short periods of time but then gradually
86// pull the "actual" longitudinal velocity offset towards that of the encoders,
87// helping to reduce constant biases.
James Kuszmaul2ed7b3c2019-02-09 18:26:19 -080088template <typename Scalar = double>
89class HybridEkf {
90 public:
91 // An enum specifying what each index in the state vector is for.
92 enum StateIdx {
James Kuszmaul3c5b4d32020-02-11 17:22:14 -080093 // Current X/Y position, in meters, of the robot.
James Kuszmaul2ed7b3c2019-02-09 18:26:19 -080094 kX = 0,
95 kY = 1,
James Kuszmaul3c5b4d32020-02-11 17:22:14 -080096 // Current heading of the robot.
James Kuszmaul2ed7b3c2019-02-09 18:26:19 -080097 kTheta = 2,
James Kuszmaul3c5b4d32020-02-11 17:22:14 -080098 // Current estimated encoder reading of the left wheels, in meters.
99 // Rezeroed once on startup.
James Kuszmaul2ed7b3c2019-02-09 18:26:19 -0800100 kLeftEncoder = 3,
James Kuszmaul3c5b4d32020-02-11 17:22:14 -0800101 // Current estimated actual velocity of the left side of the robot, in m/s.
James Kuszmaul2ed7b3c2019-02-09 18:26:19 -0800102 kLeftVelocity = 4,
James Kuszmaul3c5b4d32020-02-11 17:22:14 -0800103 // Same variables, for the right side of the robot.
James Kuszmaul2ed7b3c2019-02-09 18:26:19 -0800104 kRightEncoder = 5,
105 kRightVelocity = 6,
James Kuszmaul3c5b4d32020-02-11 17:22:14 -0800106 // Estimated offset to input voltage. Used as a generic error term, Volts.
James Kuszmaul074429e2019-03-23 16:01:49 -0700107 kLeftVoltageError = 7,
James Kuszmaul651fc3f2019-05-15 21:14:25 -0700108 kRightVoltageError = 8,
James Kuszmaul3c5b4d32020-02-11 17:22:14 -0800109 // These error terms are used to estimate the difference between the actual
110 // movement of the drivetrain and that implied by the wheel odometry.
111 // Angular error effectively estimates a constant angular rate offset of the
112 // encoders relative to the actual rotation of the robot.
113 // Semi-arbitrary units (we don't bother accounting for robot radius in
114 // this).
James Kuszmaul074429e2019-03-23 16:01:49 -0700115 kAngularError = 9,
James Kuszmaul3c5b4d32020-02-11 17:22:14 -0800116 // Estimate of slip between the drivetrain wheels and the actual
117 // forwards/backwards velocity of the robot, in m/s.
118 // I.e., (left velocity + right velocity) / 2.0 = (left wheel velocity +
119 // right wheel velocity) / 2.0 + longitudinal velocity offset
120 kLongitudinalVelocityOffset = 10,
121 // Current estimate of the lateral velocity of the robot, in m/s.
122 // Positive implies the robot is moving to its left.
123 kLateralVelocity = 11,
James Kuszmaul2ed7b3c2019-02-09 18:26:19 -0800124 };
James Kuszmaul3c5b4d32020-02-11 17:22:14 -0800125 static constexpr int kNStates = 12;
126 enum InputIdx {
127 // Left/right drivetrain voltages.
128 kLeftVoltage = 0,
129 kRightVoltage = 1,
130 // Current accelerometer readings, in m/s/s, along the longitudinal and
131 // lateral axes of the robot. Should be projected onto the X/Y plane, to
132 // compensate for tilt of the robot before being passed to this filter. The
133 // HybridEkf has no knowledge of the current pitch/roll of the robot, and so
134 // can't do anything to compensate for it.
135 kLongitudinalAccel = 2,
136 kLateralAccel = 3,
137 };
James Kuszmaul2971b5a2023-01-29 15:49:32 -0800138
James Kuszmaul3c5b4d32020-02-11 17:22:14 -0800139 static constexpr int kNInputs = 4;
James Kuszmaul2ed7b3c2019-02-09 18:26:19 -0800140 // Number of previous samples to save.
Austin Schuh6e660592021-10-17 17:37:33 -0700141 static constexpr int kSaveSamples = 200;
James Kuszmaul06257f42020-05-09 15:40:09 -0700142 // Whether we should completely rerun the entire stored history of
143 // kSaveSamples on every correction. Enabling this will increase overall CPU
144 // usage substantially; however, leaving it disabled makes it so that we are
145 // less likely to notice if processing camera frames is causing delays in the
146 // drivetrain.
147 // If we are having CPU issues, we have three easy avenues to improve things:
148 // (1) Reduce kSaveSamples (e.g., if all camera frames arive within
149 // 100 ms, then we can reduce kSaveSamples to be 25 (125 ms of samples)).
150 // (2) Don't actually rely on the ability to insert corrections into the
151 // timeline.
152 // (3) Set this to false.
153 static constexpr bool kFullRewindOnEverySample = false;
James Kuszmaul2ed7b3c2019-02-09 18:26:19 -0800154 // Assume that all correction steps will have kNOutputs
155 // dimensions.
156 // TODO(james): Relax this assumption; relaxing it requires
157 // figuring out how to deal with storing variable size
158 // observation matrices, though.
159 static constexpr int kNOutputs = 3;
James Kuszmaul3c5b4d32020-02-11 17:22:14 -0800160 // Time constant to use for estimating how the longitudinal/lateral velocity
161 // offsets decay, in seconds.
James Kuszmaul5f6d1d42020-03-01 18:10:07 -0800162 static constexpr double kVelocityOffsetTimeConstant = 1.0;
James Kuszmaul3c5b4d32020-02-11 17:22:14 -0800163 static constexpr double kLateralVelocityTimeConstant = 1.0;
James Kuszmaul91aa0cf2021-02-13 13:15:06 -0800164
James Kuszmaulf3950362020-10-11 18:29:15 -0700165 // The maximum allowable timestep--we use this to check for situations where
166 // measurement updates come in too infrequently and this might cause the
167 // integrator and discretization in the prediction step to be overly
168 // aggressive.
169 static constexpr std::chrono::milliseconds kMaxTimestep{20};
James Kuszmaul2ed7b3c2019-02-09 18:26:19 -0800170 // Inputs are [left_volts, right_volts]
171 typedef Eigen::Matrix<Scalar, kNInputs, 1> Input;
172 // Outputs are either:
173 // [left_encoder, right_encoder, gyro_vel]; or [heading, distance, skew] to
174 // some target. This makes it so we don't have to figure out how we store
175 // variable-size measurement updates.
176 typedef Eigen::Matrix<Scalar, kNOutputs, 1> Output;
177 typedef Eigen::Matrix<Scalar, kNStates, kNStates> StateSquare;
James Kuszmaul3c5b4d32020-02-11 17:22:14 -0800178 // State contains the states defined by the StateIdx enum. See comments there.
James Kuszmaul2ed7b3c2019-02-09 18:26:19 -0800179 typedef Eigen::Matrix<Scalar, kNStates, 1> State;
180
James Kuszmaul2971b5a2023-01-29 15:49:32 -0800181 // The following classes exist to allow us to support doing corections in the
182 // past by rewinding the EKF, calling the appropriate H and dhdx functions,
183 // and then playing everything back. Originally, this simply used
184 // std::function's, but doing so causes us to perform dynamic memory
185 // allocation in the core of the drivetrain control loop.
186 //
187 // The ExpectedObservationFunctor class serves to provide an interface for the
188 // actual H and dH/dX that the EKF itself needs. Most implementations end up
189 // just using this; in the degenerate case, ExpectedObservationFunctor could
190 // be implemented as a class that simply stores two std::functions and calls
191 // them when H() and DHDX() are called.
192 //
193 // The ObserveDeletion() and deleted() methods exist for sanity checking--we
194 // don't rely on them to do any work, but in order to ensure that memory is
195 // being managed correctly, we have the HybridEkf call ObserveDeletion() when
196 // it no longer needs an instance of the object.
197 class ExpectedObservationFunctor {
198 public:
199 virtual ~ExpectedObservationFunctor() = default;
200 // Return the expected measurement of the system for a given state and plant
201 // input.
202 virtual Output H(const State &state, const Input &input) = 0;
203 // Return the derivative of H() with respect to the state, given the current
204 // state.
205 virtual Eigen::Matrix<Scalar, kNOutputs, kNStates> DHDX(
206 const State &state) = 0;
207 virtual void ObserveDeletion() {
208 CHECK(!deleted_);
209 deleted_ = true;
210 }
211 bool deleted() const { return deleted_; }
212
213 private:
214 bool deleted_ = false;
215 };
216
217 // The ExpectedObservationBuilder creates a new ExpectedObservationFunctor.
218 // This is used for situations where in order to know what the correction
219 // methods even are we need to know the state at some time in the past. This
220 // is only used in the y2019 code and we've generally stopped using this
221 // pattern.
222 class ExpectedObservationBuilder {
223 public:
224 virtual ~ExpectedObservationBuilder() = default;
225 // The lifetime of the returned object should last at least until
226 // ObserveDeletion() is called on said object.
227 virtual ExpectedObservationFunctor *MakeExpectedObservations(
228 const State &state, const StateSquare &P) = 0;
229 void ObserveDeletion() {
230 CHECK(!deleted_);
231 deleted_ = true;
232 }
233 bool deleted() const { return deleted_; }
234
235 private:
236 bool deleted_ = false;
237 };
238
239 // The ExpectedObservationAllocator provides a utility class which manages the
240 // memory for a single type of correction step for a given localizer.
241 // Using the knowledge that at most kSaveSamples ExpectedObservation* objects
242 // can be referenced by the HybridEkf at any given time, this keeps an
243 // internal queue that more than mirrors the HybridEkf's internal queue, using
244 // the oldest spots in the queue to construct new ExpectedObservation*'s.
245 // This can be used with T as either a ExpectedObservationBuilder or
246 // ExpectedObservationFunctor. The appropriate Correct function will then be
247 // called in place of calling HybridEkf::Correct directly. Note that unless T
248 // implements both the Builder and Functor (which is generally discouraged),
249 // only one of the Correct* functions will build.
250 template <typename T>
251 class ExpectedObservationAllocator {
252 public:
253 ExpectedObservationAllocator(HybridEkf *ekf) : ekf_(ekf) {}
254 void CorrectKnownH(const Output &z, const Input *U, T H,
255 const Eigen::Matrix<Scalar, kNOutputs, kNOutputs> &R,
256 aos::monotonic_clock::time_point t) {
257 if (functors_.full()) {
258 CHECK(functors_.begin()->functor->deleted());
259 }
260 auto pushed = functors_.PushFromBottom(Pair{t, std::move(H)});
261 if (pushed == functors_.end()) {
262 VLOG(1) << "Observation dropped off bottom of queue.";
263 return;
264 }
265 ekf_->Correct(z, U, nullptr, &pushed->functor.value(), R, t);
266 }
267 void CorrectKnownHBuilder(
268 const Output &z, const Input *U, T builder,
269 const Eigen::Matrix<Scalar, kNOutputs, kNOutputs> &R,
270 aos::monotonic_clock::time_point t) {
271 if (functors_.full()) {
272 CHECK(functors_.begin()->functor->deleted());
273 }
274 auto pushed = functors_.PushFromBottom(Pair{t, std::move(builder)});
275 if (pushed == functors_.end()) {
276 VLOG(1) << "Observation dropped off bottom of queue.";
277 return;
278 }
279 ekf_->Correct(z, U, &pushed->functor.value(), nullptr, R, t);
280 }
281
282 private:
283 struct Pair {
284 aos::monotonic_clock::time_point t;
285 std::optional<T> functor;
286 friend bool operator<(const Pair &l, const Pair &r) { return l.t < r.t; }
287 };
288
289 HybridEkf *const ekf_;
290 aos::PriorityQueue<Pair, kSaveSamples + 1, std::less<Pair>> functors_;
291 };
292
293 // A simple implementation of ExpectedObservationFunctor for an LTI correction
294 // step. Does not store any external references, so overrides
295 // ObserveDeletion() to do nothing.
296 class LinearH : public ExpectedObservationFunctor {
297 public:
298 LinearH(const Eigen::Matrix<Scalar, kNOutputs, kNStates> &H) : H_(H) {}
299 virtual ~LinearH() = default;
300 Output H(const State &state, const Input &) final { return H_ * state; }
301 Eigen::Matrix<Scalar, kNOutputs, kNStates> DHDX(const State &) final {
302 return H_;
303 }
304 void ObserveDeletion() {}
305
306 private:
307 const Eigen::Matrix<Scalar, kNOutputs, kNStates> H_;
308 };
309
James Kuszmaul2ed7b3c2019-02-09 18:26:19 -0800310 // Constructs a HybridEkf for a particular drivetrain.
311 // Currently, we use the drivetrain config for modelling constants
312 // (continuous time A and B matrices) and for the noise matrices for the
313 // encoders/gyro.
James Kuszmauld478f872020-03-16 20:54:27 -0700314 HybridEkf(const DrivetrainConfig<double> &dt_config)
James Kuszmaul2ed7b3c2019-02-09 18:26:19 -0800315 : dt_config_(dt_config),
316 velocity_drivetrain_coefficients_(
317 dt_config.make_hybrid_drivetrain_velocity_loop()
318 .plant()
319 .coefficients()) {
320 InitializeMatrices();
321 }
322
323 // Set the initial guess of the state. Can only be called once, and before
324 // any measurement updates have occured.
325 // TODO(james): We may want to actually re-initialize and reset things on
326 // the field. Create some sort of Reset() function.
327 void ResetInitialState(::aos::monotonic_clock::time_point t,
James Kuszmaul1057ce82019-02-09 17:58:24 -0800328 const State &state, const StateSquare &P) {
James Kuszmaul2ed7b3c2019-02-09 18:26:19 -0800329 observations_.clear();
330 X_hat_ = state;
James Kuszmaul074429e2019-03-23 16:01:49 -0700331 have_zeroed_encoders_ = true;
James Kuszmaul1057ce82019-02-09 17:58:24 -0800332 P_ = P;
James Kuszmaul06257f42020-05-09 15:40:09 -0700333 observations_.PushFromBottom({
334 t,
335 t,
336 X_hat_,
337 P_,
338 Input::Zero(),
339 Output::Zero(),
James Kuszmaul2971b5a2023-01-29 15:49:32 -0800340 nullptr,
341 &H_encoders_and_gyro_.value(),
James Kuszmaul06257f42020-05-09 15:40:09 -0700342 Eigen::Matrix<Scalar, kNOutputs, kNOutputs>::Identity(),
343 StateSquare::Identity(),
344 StateSquare::Zero(),
345 std::chrono::seconds(0),
346 State::Zero(),
347 });
James Kuszmaul2ed7b3c2019-02-09 18:26:19 -0800348 }
349
350 // Correct with:
351 // A measurement z at time t with z = h(X_hat, U) + v where v has noise
352 // covariance R.
353 // Input U is applied from the previous timestep until time t.
354 // If t is later than any previous measurements, then U must be provided.
355 // If the measurement falls between two previous measurements, then U
356 // can be provided or not; if U is not provided, then it is filled in based
357 // on an assumption that the voltage was held constant between the time steps.
358 // TODO(james): Is it necessary to explicitly to provide a version with H as a
359 // matrix for linear cases?
James Kuszmaul2971b5a2023-01-29 15:49:32 -0800360 void Correct(const Output &z, const Input *U,
361 ExpectedObservationBuilder *observation_builder,
362 ExpectedObservationFunctor *expected_observations,
363 const Eigen::Matrix<Scalar, kNOutputs, kNOutputs> &R,
364 aos::monotonic_clock::time_point t);
James Kuszmaul2ed7b3c2019-02-09 18:26:19 -0800365
366 // A utility function for specifically updating with encoder and gyro
367 // measurements.
368 void UpdateEncodersAndGyro(const Scalar left_encoder,
369 const Scalar right_encoder, const Scalar gyro_rate,
James Kuszmaul3c5b4d32020-02-11 17:22:14 -0800370 const Eigen::Matrix<Scalar, 2, 1> &voltage,
371 const Eigen::Matrix<Scalar, 3, 1> &accel,
372 aos::monotonic_clock::time_point t) {
373 Input U;
374 U.template block<2, 1>(0, 0) = voltage;
375 U.template block<2, 1>(kLongitudinalAccel, 0) =
376 accel.template block<2, 1>(0, 0);
377 RawUpdateEncodersAndGyro(left_encoder, right_encoder, gyro_rate, U, t);
378 }
379 // Version of UpdateEncodersAndGyro that takes a input matrix rather than
380 // taking in a voltage/acceleration separately.
381 void RawUpdateEncodersAndGyro(const Scalar left_encoder,
382 const Scalar right_encoder,
383 const Scalar gyro_rate, const Input &U,
384 aos::monotonic_clock::time_point t) {
James Kuszmaul074429e2019-03-23 16:01:49 -0700385 // Because the check below for have_zeroed_encoders_ will add an
386 // Observation, do a check here to ensure that initialization has been
387 // performed and so there is at least one observation.
James Kuszmaul3c5b4d32020-02-11 17:22:14 -0800388 CHECK(!observations_.empty());
James Kuszmaul074429e2019-03-23 16:01:49 -0700389 if (!have_zeroed_encoders_) {
390 // This logic handles ensuring that on the first encoder reading, we
391 // update the internal state for the encoders to match the reading.
392 // Otherwise, if we restart the drivetrain without restarting
393 // wpilib_interface, then we can get some obnoxious initial corrections
394 // that mess up the localization.
395 State newstate = X_hat_;
James Kuszmaul3c5b4d32020-02-11 17:22:14 -0800396 newstate(kLeftEncoder) = left_encoder;
397 newstate(kRightEncoder) = right_encoder;
398 newstate(kLeftVoltageError) = 0.0;
399 newstate(kRightVoltageError) = 0.0;
400 newstate(kAngularError) = 0.0;
401 newstate(kLongitudinalVelocityOffset) = 0.0;
402 newstate(kLateralVelocity) = 0.0;
James Kuszmaul074429e2019-03-23 16:01:49 -0700403 ResetInitialState(t, newstate, P_);
404 // We need to set have_zeroed_encoders_ after ResetInitialPosition because
405 // the reset clears have_zeroed_encoders_...
406 have_zeroed_encoders_ = true;
407 }
James Kuszmaul3c5b4d32020-02-11 17:22:14 -0800408
James Kuszmaul2ed7b3c2019-02-09 18:26:19 -0800409 Output z(left_encoder, right_encoder, gyro_rate);
James Kuszmaul3c5b4d32020-02-11 17:22:14 -0800410
James Kuszmaul2ed7b3c2019-02-09 18:26:19 -0800411 Eigen::Matrix<Scalar, kNOutputs, kNOutputs> R;
412 R.setZero();
413 R.diagonal() << encoder_noise_, encoder_noise_, gyro_noise_;
James Kuszmaul2971b5a2023-01-29 15:49:32 -0800414 CHECK(H_encoders_and_gyro_.has_value());
415 Correct(z, &U, nullptr, &H_encoders_and_gyro_.value(), R, t);
James Kuszmaul2ed7b3c2019-02-09 18:26:19 -0800416 }
417
418 // Sundry accessor:
419 State X_hat() const { return X_hat_; }
James Kuszmaul3c5b4d32020-02-11 17:22:14 -0800420 Scalar X_hat(long i) const { return X_hat_(i); }
James Kuszmaul2ed7b3c2019-02-09 18:26:19 -0800421 StateSquare P() const { return P_; }
James Kuszmaul3c5b4d32020-02-11 17:22:14 -0800422 aos::monotonic_clock::time_point latest_t() const {
James Kuszmaul2ed7b3c2019-02-09 18:26:19 -0800423 return observations_.top().t;
424 }
425
James Kuszmaul3c5b4d32020-02-11 17:22:14 -0800426 static Scalar CalcLongitudinalVelocity(const State &X) {
427 return (X(kLeftVelocity) + X(kRightVelocity)) / 2.0;
428 }
429
430 Scalar CalcYawRate(const State &X) const {
431 return (X(kRightVelocity) - X(kLeftVelocity)) / 2.0 /
432 dt_config_.robot_radius;
433 }
434
James Kuszmaul06257f42020-05-09 15:40:09 -0700435 // Returns the last state before the specified time.
436 // Returns nullopt if time is older than the oldest measurement.
437 std::optional<State> LastStateBeforeTime(
438 aos::monotonic_clock::time_point time) {
439 if (observations_.empty() || observations_.begin()->t > time) {
440 return std::nullopt;
441 }
442 for (const auto &observation : observations_) {
443 if (observation.t > time) {
444 // Note that observation.X_hat actually references the _previous_ X_hat.
445 return observation.X_hat;
446 }
447 }
448 return X_hat();
449 }
James Kuszmaulba59dc92022-03-12 10:46:54 -0800450 std::optional<State> OldestState() {
451 if (observations_.empty()) {
452 return std::nullopt;
453 }
454 return observations_.begin()->X_hat;
455 }
James Kuszmaul06257f42020-05-09 15:40:09 -0700456
457 // Returns the most recent input vector.
458 Input MostRecentInput() {
459 CHECK(!observations_.empty());
460 Input U = observations_.top().U;
461 return U;
462 }
463
James Kuszmaul91aa0cf2021-02-13 13:15:06 -0800464 void set_ignore_accel(bool ignore_accel) { ignore_accel_ = ignore_accel; }
465
James Kuszmaul2ed7b3c2019-02-09 18:26:19 -0800466 private:
467 struct Observation {
James Kuszmaul2971b5a2023-01-29 15:49:32 -0800468 Observation(aos::monotonic_clock::time_point t,
469 aos::monotonic_clock::time_point prev_t, State X_hat,
470 StateSquare P, Input U, Output z,
471 ExpectedObservationBuilder *make_h,
472 ExpectedObservationFunctor *h,
473 Eigen::Matrix<Scalar, kNOutputs, kNOutputs> R, StateSquare A_d,
474 StateSquare Q_d,
475 aos::monotonic_clock::duration discretization_time,
476 State predict_update)
477 : t(t),
478 prev_t(prev_t),
479 X_hat(X_hat),
480 P(P),
481 U(U),
482 z(z),
483 make_h(make_h),
484 h(h),
485 R(R),
486 A_d(A_d),
487 Q_d(Q_d),
488 discretization_time(discretization_time),
489 predict_update(predict_update) {}
490 Observation(const Observation &) = delete;
491 Observation &operator=(const Observation &) = delete;
492 // Move-construct an observation by copying over the contents of the struct
493 // and then clearing the old Observation's pointers so that it doesn't try
494 // to clean things up.
495 Observation(Observation &&o)
496 : Observation(o.t, o.prev_t, o.X_hat, o.P, o.U, o.z, o.make_h, o.h, o.R,
497 o.A_d, o.Q_d, o.discretization_time, o.predict_update) {
498 o.make_h = nullptr;
499 o.h = nullptr;
500 }
501 Observation &operator=(Observation &&observation) = delete;
502 ~Observation() {
503 // Observe h being deleted first, since make_h may own its memory.
504 // Shouldn't actually matter, though.
505 if (h != nullptr) {
506 h->ObserveDeletion();
507 }
508 if (make_h != nullptr) {
509 make_h->ObserveDeletion();
510 }
511 }
James Kuszmaul2ed7b3c2019-02-09 18:26:19 -0800512 // Time when the observation was taken.
513 aos::monotonic_clock::time_point t;
514 // Time that the previous observation was taken:
515 aos::monotonic_clock::time_point prev_t;
516 // Estimate of state at previous observation time t, after accounting for
517 // the previous observation.
518 State X_hat;
519 // Noise matrix corresponding to X_hat_.
520 StateSquare P;
521 // The input applied from previous observation until time t.
522 Input U;
523 // Measurement taken at that time.
524 Output z;
525 // A function to create h and dhdx from a given position/covariance
526 // estimate. This is used by the camera to make it so that we only have to
527 // match targets once.
528 // Only called if h and dhdx are empty.
James Kuszmaul2971b5a2023-01-29 15:49:32 -0800529 ExpectedObservationBuilder *make_h = nullptr;
James Kuszmaul2ed7b3c2019-02-09 18:26:19 -0800530 // A function to calculate the expected output at a given state/input.
531 // TODO(james): For encoders/gyro, it is linear and the function call may
532 // be expensive. Potential source of optimization.
James Kuszmaul2971b5a2023-01-29 15:49:32 -0800533 ExpectedObservationFunctor *h = nullptr;
James Kuszmaul2ed7b3c2019-02-09 18:26:19 -0800534 // The measurement noise matrix.
535 Eigen::Matrix<Scalar, kNOutputs, kNOutputs> R;
536
James Kuszmaul06257f42020-05-09 15:40:09 -0700537 // Discretized A and Q to use on this update step. These will only be
538 // recalculated if the timestep changes.
539 StateSquare A_d;
540 StateSquare Q_d;
541 aos::monotonic_clock::duration discretization_time;
542
543 // A cached value indicating how much we change X_hat in the prediction step
544 // of this Observation.
545 State predict_update;
546
James Kuszmaul2ed7b3c2019-02-09 18:26:19 -0800547 // In order to sort the observations in the PriorityQueue object, we
548 // need a comparison function.
James Kuszmaul651fc3f2019-05-15 21:14:25 -0700549 friend bool operator<(const Observation &l, const Observation &r) {
James Kuszmaul2ed7b3c2019-02-09 18:26:19 -0800550 return l.t < r.t;
551 }
552 };
553
554 void InitializeMatrices();
555
James Kuszmaul3c5b4d32020-02-11 17:22:14 -0800556 // These constants and functions define how the longitudinal velocity
557 // (the average of the left and right velocities) decays. We model it as
558 // decaying at a constant rate, except very near zero where the decay rate is
559 // exponential (this is more numerically stable than just using a constant
560 // rate the whole time). We use this model rather than a simpler exponential
561 // decay because an exponential decay will result in the robot's velocity
562 // estimate consistently being far too low when at high velocities, and since
563 // the acceleromater-based estimate of the velocity will only drift at a
564 // relatively slow rate and doesn't get worse at higher velocities, we can
565 // safely decay pretty slowly.
566 static constexpr double kMaxVelocityAccel = 0.005;
567 static constexpr double kMaxVelocityGain = 1.0;
568 static Scalar VelocityAccel(Scalar velocity) {
569 return -std::clamp(kMaxVelocityGain * velocity, -kMaxVelocityAccel,
570 kMaxVelocityAccel);
571 }
572
573 static Scalar VelocityAccelDiff(Scalar velocity) {
574 return (std::abs(kMaxVelocityGain * velocity) > kMaxVelocityAccel)
575 ? 0.0
576 : -kMaxVelocityGain;
577 }
578
579 // Returns the "A" matrix for a given state. See DiffEq for discussion of
580 // ignore_accel.
James Kuszmaul91aa0cf2021-02-13 13:15:06 -0800581 StateSquare AForState(const State &X, bool ignore_accel) const {
James Kuszmaul3c5b4d32020-02-11 17:22:14 -0800582 // Calculate the A matrix for a given state. Note that A = partial Xdot /
583 // partial X. This is distinct from saying that Xdot = A * X. This is
584 // particularly relevant for the (kX, kTheta) members which otherwise seem
585 // odd.
James Kuszmaul2ed7b3c2019-02-09 18:26:19 -0800586 StateSquare A_continuous = A_continuous_;
James Kuszmaul3c5b4d32020-02-11 17:22:14 -0800587 const Scalar theta = X(kTheta);
588 const Scalar stheta = std::sin(theta);
589 const Scalar ctheta = std::cos(theta);
590 const Scalar lng_vel = CalcLongitudinalVelocity(X);
591 const Scalar lat_vel = X(kLateralVelocity);
592 const Scalar diameter = 2.0 * dt_config_.robot_radius;
593 const Scalar yaw_rate = CalcYawRate(X);
James Kuszmaul2ed7b3c2019-02-09 18:26:19 -0800594 // X and Y derivatives
Austin Schuhd749d932020-12-30 21:38:40 -0800595 A_continuous(kX, kTheta) = -stheta * lng_vel - ctheta * lat_vel;
James Kuszmaul2ed7b3c2019-02-09 18:26:19 -0800596 A_continuous(kX, kLeftVelocity) = ctheta / 2.0;
597 A_continuous(kX, kRightVelocity) = ctheta / 2.0;
James Kuszmaul3c5b4d32020-02-11 17:22:14 -0800598 A_continuous(kX, kLateralVelocity) = -stheta;
599 A_continuous(kY, kTheta) = ctheta * lng_vel - stheta * lat_vel;
James Kuszmaul2ed7b3c2019-02-09 18:26:19 -0800600 A_continuous(kY, kLeftVelocity) = stheta / 2.0;
601 A_continuous(kY, kRightVelocity) = stheta / 2.0;
James Kuszmaul3c5b4d32020-02-11 17:22:14 -0800602 A_continuous(kY, kLateralVelocity) = ctheta;
603
604 if (!ignore_accel) {
605 const Eigen::Matrix<Scalar, 1, kNStates> lng_vel_row =
606 (A_continuous.row(kLeftVelocity) + A_continuous.row(kRightVelocity)) /
607 2.0;
608 A_continuous.row(kLeftVelocity) -= lng_vel_row;
609 A_continuous.row(kRightVelocity) -= lng_vel_row;
610 // Terms to account for centripetal accelerations.
611 // lateral centripetal accel = -yaw_rate * lng_vel
612 A_continuous(kLateralVelocity, kLeftVelocity) +=
613 X(kLeftVelocity) / diameter;
614 A_continuous(kLateralVelocity, kRightVelocity) +=
615 -X(kRightVelocity) / diameter;
616 A_continuous(kRightVelocity, kLateralVelocity) += yaw_rate;
617 A_continuous(kLeftVelocity, kLateralVelocity) += yaw_rate;
618 const Scalar dlng_accel_dwheel_vel = X(kLateralVelocity) / diameter;
619 A_continuous(kRightVelocity, kRightVelocity) += dlng_accel_dwheel_vel;
620 A_continuous(kLeftVelocity, kRightVelocity) += dlng_accel_dwheel_vel;
621 A_continuous(kRightVelocity, kLeftVelocity) += -dlng_accel_dwheel_vel;
622 A_continuous(kLeftVelocity, kLeftVelocity) += -dlng_accel_dwheel_vel;
623
624 A_continuous(kRightVelocity, kRightVelocity) +=
625 VelocityAccelDiff(lng_vel) / 2.0;
626 A_continuous(kRightVelocity, kLeftVelocity) +=
627 VelocityAccelDiff(lng_vel) / 2.0;
628 A_continuous(kLeftVelocity, kRightVelocity) +=
629 VelocityAccelDiff(lng_vel) / 2.0;
630 A_continuous(kLeftVelocity, kLeftVelocity) +=
631 VelocityAccelDiff(lng_vel) / 2.0;
632 }
James Kuszmaul2ed7b3c2019-02-09 18:26:19 -0800633 return A_continuous;
634 }
635
James Kuszmaul3c5b4d32020-02-11 17:22:14 -0800636 // Returns dX / dt given X and U. If ignore_accel is set, then we ignore the
637 // accelerometer-based components of U (this is solely used in testing).
James Kuszmaul91aa0cf2021-02-13 13:15:06 -0800638 State DiffEq(const State &X, const Input &U, bool ignore_accel) const {
James Kuszmaul2ed7b3c2019-02-09 18:26:19 -0800639 State Xdot = A_continuous_ * X + B_continuous_ * U;
640 // And then we need to add on the terms for the x/y change:
James Kuszmaul3c5b4d32020-02-11 17:22:14 -0800641 const Scalar theta = X(kTheta);
642 const Scalar lng_vel = CalcLongitudinalVelocity(X);
643 const Scalar lat_vel = X(kLateralVelocity);
644 const Scalar stheta = std::sin(theta);
645 const Scalar ctheta = std::cos(theta);
646 Xdot(kX) = ctheta * lng_vel - stheta * lat_vel;
647 Xdot(kY) = stheta * lng_vel + ctheta * lat_vel;
648
649 const Scalar yaw_rate = CalcYawRate(X);
650 const Scalar expected_lat_accel = lng_vel * yaw_rate;
651 const Scalar expected_lng_accel =
652 CalcLongitudinalVelocity(Xdot) - yaw_rate * lat_vel;
Austin Schuhd749d932020-12-30 21:38:40 -0800653 const Scalar lng_accel_offset = U(kLongitudinalAccel) - expected_lng_accel;
James Kuszmaul3c5b4d32020-02-11 17:22:14 -0800654 constexpr double kAccelWeight = 1.0;
655 if (!ignore_accel) {
656 Xdot(kLeftVelocity) += kAccelWeight * lng_accel_offset;
657 Xdot(kRightVelocity) += kAccelWeight * lng_accel_offset;
658 Xdot(kLateralVelocity) += U(kLateralAccel) - expected_lat_accel;
659
660 Xdot(kRightVelocity) += VelocityAccel(lng_vel);
661 Xdot(kLeftVelocity) += VelocityAccel(lng_vel);
662 }
James Kuszmaul2ed7b3c2019-02-09 18:26:19 -0800663 return Xdot;
664 }
665
James Kuszmaul06257f42020-05-09 15:40:09 -0700666 void PredictImpl(Observation *obs, std::chrono::nanoseconds dt, State *state,
James Kuszmaul2ed7b3c2019-02-09 18:26:19 -0800667 StateSquare *P) {
James Kuszmaul06257f42020-05-09 15:40:09 -0700668 // Only recalculate the discretization if the timestep has changed.
669 // Technically, this isn't quite correct, since the discretization will
670 // change depending on the current state. However, the slight loss of
671 // precision seems acceptable for the sake of significantly reducing CPU
672 // usage.
673 if (obs->discretization_time != dt) {
674 // TODO(james): By far the biggest CPU sink in the localization appears to
675 // be this discretization--it's possible the spline code spikes higher,
676 // but it doesn't create anywhere near the same sustained load. There
677 // are a few potential options for optimizing this code, but none of
678 // them are entirely trivial, e.g. we could:
679 // -Reduce the number of states (this function grows at O(kNStates^3))
680 // -Adjust the discretization function itself (there're a few things we
681 // can tune there).
682 // -Try to come up with some sort of lookup table or other way of
683 // pre-calculating A_d and Q_d.
684 // I also have to figure out how much we care about the precision of
685 // some of these values--I don't think we care much, but we probably
686 // do want to maintain some of the structure of the matrices.
James Kuszmaul91aa0cf2021-02-13 13:15:06 -0800687 const StateSquare A_c = AForState(*state, ignore_accel_);
James Kuszmaul06257f42020-05-09 15:40:09 -0700688 controls::DiscretizeQAFast(Q_continuous_, A_c, dt, &obs->Q_d, &obs->A_d);
689 obs->discretization_time = dt;
James Kuszmaul2ed7b3c2019-02-09 18:26:19 -0800690
James Kuszmaul06257f42020-05-09 15:40:09 -0700691 obs->predict_update =
692 RungeKuttaU(
James Kuszmaul91aa0cf2021-02-13 13:15:06 -0800693 [this](const State &X, const Input &U) {
694 return DiffEq(X, U, ignore_accel_);
695 },
James Kuszmaul06257f42020-05-09 15:40:09 -0700696 *state, obs->U, aos::time::DurationInSeconds(dt)) -
697 *state;
698 }
James Kuszmaulb2a2f352019-03-02 16:59:34 -0800699
James Kuszmaul06257f42020-05-09 15:40:09 -0700700 *state += obs->predict_update;
701
702 StateSquare Ptemp = obs->A_d * *P * obs->A_d.transpose() + obs->Q_d;
James Kuszmaulb2a2f352019-03-02 16:59:34 -0800703 *P = Ptemp;
James Kuszmaul2ed7b3c2019-02-09 18:26:19 -0800704 }
705
James Kuszmaul06257f42020-05-09 15:40:09 -0700706 void CorrectImpl(Observation *obs, State *state, StateSquare *P) {
James Kuszmaul2971b5a2023-01-29 15:49:32 -0800707 const Eigen::Matrix<Scalar, kNOutputs, kNStates> H = obs->h->DHDX(*state);
James Kuszmaul06257f42020-05-09 15:40:09 -0700708 // Note: Technically, this does calculate P * H.transpose() twice. However,
709 // when I was mucking around with some things, I found that in practice
710 // putting everything into one expression and letting Eigen optimize it
711 // directly actually improved performance relative to precalculating P *
712 // H.transpose().
713 const Eigen::Matrix<Scalar, kNStates, kNOutputs> K =
714 *P * H.transpose() * (H * *P * H.transpose() + obs->R).inverse();
715 const StateSquare Ptemp = (StateSquare::Identity() - K * H) * *P;
James Kuszmaulb2a2f352019-03-02 16:59:34 -0800716 *P = Ptemp;
James Kuszmaul2971b5a2023-01-29 15:49:32 -0800717 *state += K * (obs->z - obs->h->H(*state, obs->U));
James Kuszmaul2ed7b3c2019-02-09 18:26:19 -0800718 }
719
720 void ProcessObservation(Observation *obs, const std::chrono::nanoseconds dt,
721 State *state, StateSquare *P) {
722 *state = obs->X_hat;
723 *P = obs->P;
James Kuszmaulf3950362020-10-11 18:29:15 -0700724 if (dt.count() != 0 && dt < kMaxTimestep) {
James Kuszmaul06257f42020-05-09 15:40:09 -0700725 PredictImpl(obs, dt, state, P);
James Kuszmaul2ed7b3c2019-02-09 18:26:19 -0800726 }
James Kuszmaul2971b5a2023-01-29 15:49:32 -0800727 if (obs->h == nullptr) {
728 CHECK(obs->make_h != nullptr);
729 obs->h = CHECK_NOTNULL(obs->make_h->MakeExpectedObservations(*state, *P));
James Kuszmaul2ed7b3c2019-02-09 18:26:19 -0800730 }
James Kuszmaul06257f42020-05-09 15:40:09 -0700731 CorrectImpl(obs, state, P);
James Kuszmaul2ed7b3c2019-02-09 18:26:19 -0800732 }
733
James Kuszmauld478f872020-03-16 20:54:27 -0700734 DrivetrainConfig<double> dt_config_;
James Kuszmaul2ed7b3c2019-02-09 18:26:19 -0800735 State X_hat_;
James Kuszmauld478f872020-03-16 20:54:27 -0700736 StateFeedbackHybridPlantCoefficients<2, 2, 2, double>
James Kuszmaul2ed7b3c2019-02-09 18:26:19 -0800737 velocity_drivetrain_coefficients_;
738 StateSquare A_continuous_;
739 StateSquare Q_continuous_;
740 StateSquare P_;
James Kuszmaul2971b5a2023-01-29 15:49:32 -0800741 std::optional<LinearH> H_encoders_and_gyro_;
James Kuszmaul2ed7b3c2019-02-09 18:26:19 -0800742 Scalar encoder_noise_, gyro_noise_;
743 Eigen::Matrix<Scalar, kNStates, kNInputs> B_continuous_;
744
James Kuszmaul074429e2019-03-23 16:01:49 -0700745 bool have_zeroed_encoders_ = false;
746
James Kuszmaul91aa0cf2021-02-13 13:15:06 -0800747 // Whether to pay attention to accelerometer readings to compensate for wheel
748 // slip.
749 bool ignore_accel_ = false;
750
James Kuszmaul3c5b4d32020-02-11 17:22:14 -0800751 aos::PriorityQueue<Observation, kSaveSamples, std::less<Observation>>
James Kuszmaul2ed7b3c2019-02-09 18:26:19 -0800752 observations_;
753
754 friend class testing::HybridEkfTest;
James Kuszmaul3c5b4d32020-02-11 17:22:14 -0800755 friend class y2019::control_loops::testing::ParameterizedLocalizerTest;
James Kuszmaul2ed7b3c2019-02-09 18:26:19 -0800756}; // class HybridEkf
757
758template <typename Scalar>
759void HybridEkf<Scalar>::Correct(
760 const Output &z, const Input *U,
James Kuszmaul2971b5a2023-01-29 15:49:32 -0800761 ExpectedObservationBuilder *observation_builder,
762 ExpectedObservationFunctor *expected_observations,
Austin Schuhd749d932020-12-30 21:38:40 -0800763 const Eigen::Matrix<Scalar, kNOutputs, kNOutputs> &R,
James Kuszmaul2ed7b3c2019-02-09 18:26:19 -0800764 aos::monotonic_clock::time_point t) {
James Kuszmaul3c5b4d32020-02-11 17:22:14 -0800765 CHECK(!observations_.empty());
James Kuszmaul2ed7b3c2019-02-09 18:26:19 -0800766 if (!observations_.full() && t < observations_.begin()->t) {
James Kuszmaul3c5b4d32020-02-11 17:22:14 -0800767 LOG(ERROR) << "Dropped an observation that was received before we "
768 "initialized.\n";
James Kuszmaul2ed7b3c2019-02-09 18:26:19 -0800769 return;
770 }
James Kuszmaul06257f42020-05-09 15:40:09 -0700771 auto cur_it = observations_.PushFromBottom(
James Kuszmaul2971b5a2023-01-29 15:49:32 -0800772 {t, t, State::Zero(), StateSquare::Zero(), Input::Zero(), z,
773 observation_builder, expected_observations, R, StateSquare::Identity(),
774 StateSquare::Zero(), std::chrono::seconds(0), State::Zero()});
James Kuszmaul2ed7b3c2019-02-09 18:26:19 -0800775 if (cur_it == observations_.end()) {
James Kuszmaul3c5b4d32020-02-11 17:22:14 -0800776 VLOG(1) << "Camera dropped off of end with time of "
777 << aos::time::DurationInSeconds(t.time_since_epoch())
778 << "s; earliest observation in "
779 "queue has time of "
780 << aos::time::DurationInSeconds(
781 observations_.begin()->t.time_since_epoch())
782 << "s.\n";
James Kuszmaul2ed7b3c2019-02-09 18:26:19 -0800783 return;
784 }
James Kuszmaul2ed7b3c2019-02-09 18:26:19 -0800785 // Now we populate any state information that depends on where the
786 // observation was inserted into the queue. X_hat and P must be populated
787 // from the values present in the observation *following* this one in
788 // the queue (note that the X_hat and P that we store in each observation
789 // is the values that they held after accounting for the previous
790 // measurement and before accounting for the time between the previous and
791 // current measurement). If we appended to the end of the queue, then
792 // we need to pull from X_hat_ and P_ specifically.
793 // Furthermore, for U:
794 // -If the observation was inserted at the end, then the user must've
795 // provided U and we use it.
796 // -Otherwise, only grab U if necessary.
797 auto next_it = cur_it;
798 ++next_it;
799 if (next_it == observations_.end()) {
800 cur_it->X_hat = X_hat_;
801 cur_it->P = P_;
802 // Note that if next_it == observations_.end(), then because we already
803 // checked for !observations_.empty(), we are guaranteed to have
804 // valid prev_it.
805 auto prev_it = cur_it;
806 --prev_it;
807 cur_it->prev_t = prev_it->t;
808 // TODO(james): Figure out a saner way of handling this.
James Kuszmaul3c5b4d32020-02-11 17:22:14 -0800809 CHECK(U != nullptr);
James Kuszmaul2ed7b3c2019-02-09 18:26:19 -0800810 cur_it->U = *U;
811 } else {
812 cur_it->X_hat = next_it->X_hat;
813 cur_it->P = next_it->P;
814 cur_it->prev_t = next_it->prev_t;
815 next_it->prev_t = cur_it->t;
816 cur_it->U = (U == nullptr) ? next_it->U : *U;
817 }
James Kuszmaul06257f42020-05-09 15:40:09 -0700818
819 if (kFullRewindOnEverySample) {
820 next_it = observations_.begin();
821 cur_it = next_it++;
822 }
823
James Kuszmaul2ed7b3c2019-02-09 18:26:19 -0800824 // Now we need to rerun the predict step from the previous to the new
825 // observation as well as every following correct/predict up to the current
826 // time.
827 while (true) {
828 // We use X_hat_ and P_ to store the intermediate states, and then
829 // once we reach the end they will all be up-to-date.
830 ProcessObservation(&*cur_it, cur_it->t - cur_it->prev_t, &X_hat_, &P_);
James Kuszmaul891f4f12020-10-31 17:13:23 -0700831 // TOOD(james): Note that this can be triggered when there are extremely
832 // small values in P_. This is particularly likely if Scalar is just float
833 // and we are performing zero-time updates where the predict step never
834 // runs.
James Kuszmaul3c5b4d32020-02-11 17:22:14 -0800835 CHECK(X_hat_.allFinite());
James Kuszmaul2ed7b3c2019-02-09 18:26:19 -0800836 if (next_it != observations_.end()) {
837 next_it->X_hat = X_hat_;
838 next_it->P = P_;
839 } else {
840 break;
841 }
842 ++cur_it;
843 ++next_it;
844 }
845}
846
847template <typename Scalar>
848void HybridEkf<Scalar>::InitializeMatrices() {
849 A_continuous_.setZero();
850 const Scalar diameter = 2.0 * dt_config_.robot_radius;
851 // Theta derivative
852 A_continuous_(kTheta, kLeftVelocity) = -1.0 / diameter;
853 A_continuous_(kTheta, kRightVelocity) = 1.0 / diameter;
854
855 // Encoder derivatives
856 A_continuous_(kLeftEncoder, kLeftVelocity) = 1.0;
James Kuszmaul074429e2019-03-23 16:01:49 -0700857 A_continuous_(kLeftEncoder, kAngularError) = 1.0;
James Kuszmaul3c5b4d32020-02-11 17:22:14 -0800858 A_continuous_(kLeftEncoder, kLongitudinalVelocityOffset) = -1.0;
James Kuszmaul2ed7b3c2019-02-09 18:26:19 -0800859 A_continuous_(kRightEncoder, kRightVelocity) = 1.0;
James Kuszmaul074429e2019-03-23 16:01:49 -0700860 A_continuous_(kRightEncoder, kAngularError) = -1.0;
James Kuszmaul3c5b4d32020-02-11 17:22:14 -0800861 A_continuous_(kRightEncoder, kLongitudinalVelocityOffset) = -1.0;
James Kuszmaul2ed7b3c2019-02-09 18:26:19 -0800862
863 // Pull velocity derivatives from velocity matrices.
864 // Note that this looks really awkward (doesn't use
865 // Eigen blocks) because someone decided that the full
James Kuszmaulbcd96fc2020-10-12 20:29:32 -0700866 // drivetrain Kalman Filter should have a weird convention.
James Kuszmaul2ed7b3c2019-02-09 18:26:19 -0800867 // TODO(james): Support shifting drivetrains with changing A_continuous
868 const auto &vel_coefs = velocity_drivetrain_coefficients_;
869 A_continuous_(kLeftVelocity, kLeftVelocity) = vel_coefs.A_continuous(0, 0);
870 A_continuous_(kLeftVelocity, kRightVelocity) = vel_coefs.A_continuous(0, 1);
871 A_continuous_(kRightVelocity, kLeftVelocity) = vel_coefs.A_continuous(1, 0);
872 A_continuous_(kRightVelocity, kRightVelocity) = vel_coefs.A_continuous(1, 1);
873
James Kuszmaul3c5b4d32020-02-11 17:22:14 -0800874 A_continuous_(kLongitudinalVelocityOffset, kLongitudinalVelocityOffset) =
875 -1.0 / kVelocityOffsetTimeConstant;
876 A_continuous_(kLateralVelocity, kLateralVelocity) =
877 -1.0 / kLateralVelocityTimeConstant;
878
James Kuszmaul3c5b4d32020-02-11 17:22:14 -0800879 // TODO(james): Decide what to do about these terms. They don't really matter
880 // too much when we have accelerometer readings available.
James Kuszmaul2ed7b3c2019-02-09 18:26:19 -0800881 B_continuous_.setZero();
James Kuszmaul3c5b4d32020-02-11 17:22:14 -0800882 B_continuous_.template block<1, 2>(kLeftVelocity, kLeftVoltage) =
James Kuszmauld478f872020-03-16 20:54:27 -0700883 vel_coefs.B_continuous.row(0).template cast<Scalar>();
James Kuszmaul3c5b4d32020-02-11 17:22:14 -0800884 B_continuous_.template block<1, 2>(kRightVelocity, kLeftVoltage) =
James Kuszmauld478f872020-03-16 20:54:27 -0700885 vel_coefs.B_continuous.row(1).template cast<Scalar>();
James Kuszmaul3c5b4d32020-02-11 17:22:14 -0800886 A_continuous_.template block<kNStates, 2>(0, kLeftVoltageError) =
887 B_continuous_.template block<kNStates, 2>(0, kLeftVoltage);
James Kuszmaul2ed7b3c2019-02-09 18:26:19 -0800888
889 Q_continuous_.setZero();
890 // TODO(james): Improve estimates of process noise--e.g., X/Y noise can
James Kuszmaul1057ce82019-02-09 17:58:24 -0800891 // probably be reduced when we are stopped because you rarely jump randomly.
892 // Or maybe it's more appropriate to scale wheelspeed noise with wheelspeed,
893 // since the wheels aren't likely to slip much stopped.
James Kuszmaula5632fe2019-03-23 20:28:33 -0700894 Q_continuous_(kX, kX) = 0.002;
895 Q_continuous_(kY, kY) = 0.002;
James Kuszmaul7f1a4082019-04-14 10:50:44 -0700896 Q_continuous_(kTheta, kTheta) = 0.0001;
James Kuszmaul3c5b4d32020-02-11 17:22:14 -0800897 Q_continuous_(kLeftEncoder, kLeftEncoder) = std::pow(0.15, 2.0);
898 Q_continuous_(kRightEncoder, kRightEncoder) = std::pow(0.15, 2.0);
899 Q_continuous_(kLeftVelocity, kLeftVelocity) = std::pow(0.5, 2.0);
900 Q_continuous_(kRightVelocity, kRightVelocity) = std::pow(0.5, 2.0);
901 Q_continuous_(kLeftVoltageError, kLeftVoltageError) = std::pow(10.0, 2.0);
902 Q_continuous_(kRightVoltageError, kRightVoltageError) = std::pow(10.0, 2.0);
903 Q_continuous_(kAngularError, kAngularError) = std::pow(2.0, 2.0);
904 // This noise value largely governs whether we will trust the encoders or
905 // accelerometer more for estimating the robot position.
James Kuszmaul5398fae2020-02-17 16:44:03 -0800906 // Note that this also affects how we interpret camera measurements,
907 // particularly when using a heading/distance/skew measurement--if the
908 // noise on these numbers is particularly high, then we can end up with weird
909 // dynamics where a camera update both shifts our X/Y position and adjusts our
910 // velocity estimates substantially, causing the camera updates to create
Austin Schuhd749d932020-12-30 21:38:40 -0800911 // "momentum" and if we don't trust the encoders enough, then we have no way
912 // of determining that the velocity updates are bogus. This also interacts
913 // with kVelocityOffsetTimeConstant.
James Kuszmaul3c5b4d32020-02-11 17:22:14 -0800914 Q_continuous_(kLongitudinalVelocityOffset, kLongitudinalVelocityOffset) =
915 std::pow(1.1, 2.0);
916 Q_continuous_(kLateralVelocity, kLateralVelocity) = std::pow(0.1, 2.0);
James Kuszmaul2ed7b3c2019-02-09 18:26:19 -0800917
James Kuszmaul2971b5a2023-01-29 15:49:32 -0800918 {
919 Eigen::Matrix<Scalar, kNOutputs, kNStates> H_encoders_and_gyro;
920 H_encoders_and_gyro.setZero();
921 // Encoders are stored directly in the state matrix, so are a minor
922 // transform away.
923 H_encoders_and_gyro(0, kLeftEncoder) = 1.0;
924 H_encoders_and_gyro(1, kRightEncoder) = 1.0;
925 // Gyro rate is just the difference between right/left side speeds:
926 H_encoders_and_gyro(2, kLeftVelocity) = -1.0 / diameter;
927 H_encoders_and_gyro(2, kRightVelocity) = 1.0 / diameter;
928 H_encoders_and_gyro_.emplace(H_encoders_and_gyro);
929 }
James Kuszmaul2ed7b3c2019-02-09 18:26:19 -0800930
James Kuszmaul3c5b4d32020-02-11 17:22:14 -0800931 encoder_noise_ = 5e-9;
932 gyro_noise_ = 1e-13;
Austin Schuh9fe68f72019-08-10 19:32:03 -0700933
934 X_hat_.setZero();
935 P_.setZero();
James Kuszmaul2ed7b3c2019-02-09 18:26:19 -0800936}
937
938} // namespace drivetrain
939} // namespace control_loops
940} // namespace frc971
941
942#endif // FRC971_CONTROL_LOOPS_DRIVETRAIN_HYBRID_EKF_H_