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