blob: a403ca85a2db9cfec5e96695685eece2df895f18 [file] [log] [blame]
James Kuszmaul51fa1ae2022-02-26 00:49:57 -08001#ifndef Y2022_LOCALIZER_LOCALIZER_H_
2#define Y2022_LOCALIZER_LOCALIZER_H_
James Kuszmaul29c59522022-02-12 16:44:26 -08003
4#include "Eigen/Dense"
5#include "Eigen/Geometry"
James Kuszmaul29c59522022-02-12 16:44:26 -08006#include "aos/containers/ring_buffer.h"
James Kuszmaul0dedb5e2022-03-05 16:02:20 -08007#include "aos/containers/sized_array.h"
James Kuszmaul8c4f6592022-02-26 15:49:30 -08008#include "aos/events/event_loop.h"
9#include "aos/network/message_bridge_server_generated.h"
James Kuszmaul29c59522022-02-12 16:44:26 -080010#include "aos/time/time.h"
James Kuszmaul29c59522022-02-12 16:44:26 -080011#include "frc971/control_loops/drivetrain/drivetrain_output_generated.h"
James Kuszmaul20014542022-04-06 21:35:44 -070012#include "frc971/input/joystick_state_generated.h"
James Kuszmaul8c4f6592022-02-26 15:49:30 -080013#include "frc971/control_loops/drivetrain/improved_down_estimator.h"
James Kuszmaul29c59522022-02-12 16:44:26 -080014#include "frc971/control_loops/drivetrain/localizer_generated.h"
James Kuszmaul9a1733a2023-02-19 16:51:47 -080015#include "frc971/control_loops/drivetrain/localization_utils.h"
James Kuszmaul29c59522022-02-12 16:44:26 -080016#include "frc971/zeroing/imu_zeroer.h"
James Kuszmaul5ed29dd2022-02-13 18:32:06 -080017#include "frc971/zeroing/wrap.h"
James Kuszmaul8c4f6592022-02-26 15:49:30 -080018#include "y2022/control_loops/superstructure/superstructure_status_generated.h"
19#include "y2022/localizer/localizer_output_generated.h"
20#include "y2022/localizer/localizer_status_generated.h"
James Kuszmaul0dedb5e2022-03-05 16:02:20 -080021#include "y2022/localizer/localizer_visualization_generated.h"
James Kuszmaul8c4f6592022-02-26 15:49:30 -080022#include "y2022/vision/target_estimate_generated.h"
James Kuszmaul9f2f53c2023-02-19 14:08:18 -080023#include "frc971/imu_reader/imu_watcher.h"
James Kuszmaul29c59522022-02-12 16:44:26 -080024
25namespace frc971::controls {
26
27namespace testing {
28class LocalizerTest;
29}
30
31// Localizer implementation that makes use of a 6-axis IMU, encoder readings,
32// drivetrain voltages, and camera returns to localize the robot. Meant to
33// be run on a raspberry pi.
34//
35// This operates on the principle that the drivetrain can be in one of two
36// modes:
37// 1) A "normal" mode where it is obeying the regular drivetrain model, with
38// minimal lateral motion and no major external disturbances. This is
39// referred to as the "model" mode in the code/variable names.
40// 2) An non-holonomic mode where the robot is just flying around on a 2-D
41// plane with no meaningful constraints (referred to as an "accel" model
42// in the code, because we rely primarily on the accelerometer readings).
43//
44// In order to determine which mode to be in, we attempt to track whether the
45// two models are diverging substantially. In order to do this, we maintain a
46// 1-second long queue of "branches". A branch is generated every X iterations
47// and contains a model state and an accel state. When the branch starts, the
48// two will have identical states. For the remaining 1 second, the model state
49// will evolve purely according to the drivetrian model, and the accel state
50// will evolve purely using IMU readings.
51//
52// When the branch reaches 1 second in age, we calculate a residual associated
53// with how much the accel and model based states diverged. If they have
54// diverged substantially, that implies that the model is a poor match for
55// whatever has been happening to the robot in the past second, so if we were
56// previously relying on the model, we will override the current "actual"
57// state with the branched accel state, and then continue to update the accel
58// state based on IMU readings.
59// If we are currently in the accel state, we will continue generating branches
60// until the branches stop diverging--this will indicate that the model
61// matches the accelerometer readings again, and so we will swap back to
62// the model-based state.
James Kuszmaul29c59522022-02-12 16:44:26 -080063class ModelBasedLocalizer {
64 public:
Milind Upadhyayd67e9cf2022-03-13 13:56:57 -070065 static constexpr size_t kNumPis = 4;
66
James Kuszmaul29c59522022-02-12 16:44:26 -080067 static constexpr size_t kX = 0;
68 static constexpr size_t kY = 1;
69 static constexpr size_t kTheta = 2;
70
71 static constexpr size_t kVelocityX = 3;
72 static constexpr size_t kVelocityY = 4;
73 static constexpr size_t kNAccelStates = 5;
74
75 static constexpr size_t kLeftEncoder = 3;
76 static constexpr size_t kLeftVelocity = 4;
77 static constexpr size_t kLeftVoltageError = 5;
78 static constexpr size_t kRightEncoder = 6;
79 static constexpr size_t kRightVelocity = 7;
80 static constexpr size_t kRightVoltageError = 8;
81 static constexpr size_t kNModelStates = 9;
82
83 static constexpr size_t kNModelOutputs = 3;
84
85 static constexpr size_t kNAccelOuputs = 1;
86
87 static constexpr size_t kAccelX = 0;
88 static constexpr size_t kAccelY = 1;
89 static constexpr size_t kThetaRate = 2;
90 static constexpr size_t kNAccelInputs = 3;
91
92 static constexpr size_t kLeftVoltage = 0;
93 static constexpr size_t kRightVoltage = 1;
94 static constexpr size_t kNModelInputs = 2;
95
James Kuszmaul93825a02022-02-13 16:50:33 -080096 // Branching period, in cycles.
James Kuszmaul5ed29dd2022-02-13 18:32:06 -080097 // Needs 10 to even stay alive, and still at ~96% CPU.
98 // ~20 gives ~55-60% CPU.
James Kuszmaul896b4ec2022-02-26 22:56:29 -080099 static constexpr int kBranchPeriod = 100;
James Kuszmaul93825a02022-02-13 16:50:33 -0800100
James Kuszmaul0dedb5e2022-03-05 16:02:20 -0800101 static constexpr size_t kDebugBufferSize = 10;
102
James Kuszmaul29c59522022-02-12 16:44:26 -0800103 typedef Eigen::Matrix<double, kNModelStates, 1> ModelState;
104 typedef Eigen::Matrix<double, kNAccelStates, 1> AccelState;
105 typedef Eigen::Matrix<double, kNModelInputs, 1> ModelInput;
106 typedef Eigen::Matrix<double, kNAccelInputs, 1> AccelInput;
107
108 ModelBasedLocalizer(
109 const control_loops::drivetrain::DrivetrainConfig<double> &dt_config);
110 void HandleImu(aos::monotonic_clock::time_point t,
111 const Eigen::Vector3d &gyro, const Eigen::Vector3d &accel,
James Kuszmaul5a5a7832022-03-16 23:15:08 -0700112 const std::optional<Eigen::Vector2d> encoders,
113 const Eigen::Vector2d voltage);
James Kuszmaul8c4f6592022-02-26 15:49:30 -0800114 void HandleTurret(aos::monotonic_clock::time_point sample_time,
115 double turret_position, double turret_velocity);
116 void HandleImageMatch(aos::monotonic_clock::time_point sample_time,
James Kuszmaul0dedb5e2022-03-05 16:02:20 -0800117 const y2022::vision::TargetEstimate *target,
118 int camera_index);
James Kuszmaul29c59522022-02-12 16:44:26 -0800119 void HandleReset(aos::monotonic_clock::time_point,
120 const Eigen::Vector3d &xytheta);
121
122 flatbuffers::Offset<ModelBasedStatus> PopulateStatus(
123 flatbuffers::FlatBufferBuilder *fbb);
124
125 Eigen::Vector3d xytheta() const {
126 if (using_model_) {
127 return current_state_.model_state.block<3, 1>(0, 0);
128 } else {
129 return current_state_.accel_state.block<3, 1>(0, 0);
130 }
131 }
132
James Kuszmaul10d3fd42022-02-25 21:57:36 -0800133 Eigen::Quaterniond orientation() const { return last_orientation_; }
134
James Kuszmaul29c59522022-02-12 16:44:26 -0800135 AccelState accel_state() const { return current_state_.accel_state; };
136
James Kuszmaul5ed29dd2022-02-13 18:32:06 -0800137 void set_longitudinal_offset(double offset) { long_offset_ = offset; }
James Kuszmaul20014542022-04-06 21:35:44 -0700138 void set_use_aggressive_image_corrections(bool aggressive) {
139 aggressive_corrections_ = aggressive;
140 }
James Kuszmaul5ed29dd2022-02-13 18:32:06 -0800141
James Kuszmaul0dedb5e2022-03-05 16:02:20 -0800142 void TallyRejection(const RejectionReason reason);
143
144 flatbuffers::Offset<LocalizerVisualization> PopulateVisualization(
145 flatbuffers::FlatBufferBuilder *fbb);
146
147 size_t NumQueuedImageDebugs() const { return image_debugs_.size(); }
James Kuszmaul8c4f6592022-02-26 15:49:30 -0800148
Milind Upadhyayd67e9cf2022-03-13 13:56:57 -0700149 std::array<LedOutput, kNumPis> led_outputs() const { return led_outputs_; }
150
Austin Schuh3806ffb2022-04-13 19:44:10 -0700151 int total_accepted() const { return statistics_.total_accepted; }
152
James Kuszmaul29c59522022-02-12 16:44:26 -0800153 private:
154 struct CombinedState {
James Kuszmaul8c4f6592022-02-26 15:49:30 -0800155 AccelState accel_state = AccelState::Zero();
156 ModelState model_state = ModelState::Zero();
157 aos::monotonic_clock::time_point branch_time =
158 aos::monotonic_clock::min_time;
159 double accumulated_divergence = 0.0;
160 };
161
162 // Struct to store state data needed to perform a camera correction, since
163 // camera corrections require looking back in time.
164 struct OldPosition {
165 aos::monotonic_clock::time_point sample_time =
166 aos::monotonic_clock::min_time;
167 Eigen::Vector3d xytheta = Eigen::Vector3d::Zero();
168 double turret_position = 0.0;
169 double turret_velocity = 0.0;
James Kuszmaul29c59522022-02-12 16:44:26 -0800170 };
171
172 static flatbuffers::Offset<AccelBasedState> BuildAccelState(
173 flatbuffers::FlatBufferBuilder *fbb, const AccelState &state);
174
175 static flatbuffers::Offset<ModelBasedState> BuildModelState(
176 flatbuffers::FlatBufferBuilder *fbb, const ModelState &state);
177
178 Eigen::Matrix<double, kNModelStates, kNModelStates> AModel(
179 const ModelState &state) const;
180 Eigen::Matrix<double, kNAccelStates, kNAccelStates> AAccel() const;
181 ModelState DiffModel(const ModelState &state, const ModelInput &U) const;
182 AccelState DiffAccel(const AccelState &state, const AccelInput &U) const;
183
184 ModelState UpdateModel(const ModelState &model, const ModelInput &input,
185 aos::monotonic_clock::duration dt) const;
186 AccelState UpdateAccel(const AccelState &accel, const AccelInput &input,
187 aos::monotonic_clock::duration dt) const;
188
189 AccelState AccelStateForModelState(const ModelState &state) const;
190 ModelState ModelStateForAccelState(const AccelState &state,
191 const Eigen::Vector2d &encoders,
192 const double yaw_rate) const;
193 double ModelDivergence(const CombinedState &state,
194 const AccelInput &accel_inputs,
195 const Eigen::Vector2d &filtered_accel,
196 const ModelInput &model_inputs);
James Kuszmaul5ed29dd2022-02-13 18:32:06 -0800197 void UpdateState(
198 CombinedState *state,
199 const Eigen::Matrix<double, kNModelStates, kNModelOutputs> &K,
200 const Eigen::Matrix<double, kNModelOutputs, 1> &Z,
201 const Eigen::Matrix<double, kNModelOutputs, kNModelStates> &H,
202 const AccelInput &accel_input, const ModelInput &model_input,
203 aos::monotonic_clock::duration dt);
James Kuszmaul29c59522022-02-12 16:44:26 -0800204
James Kuszmaul8c4f6592022-02-26 15:49:30 -0800205 const OldPosition GetStateForTime(aos::monotonic_clock::time_point time);
206
207 // Returns the transformation to get from the camera frame to the robot frame
208 // for the specified state.
209 const Eigen::Matrix<double, 4, 4> CameraTransform(
210 const OldPosition &state,
211 const frc971::vision::calibration::CameraCalibration *calibration,
212 std::optional<RejectionReason> *rejection_reason) const;
213
214 // Returns the robot x/y position implied by the specified camera data and
215 // estimated state from that time.
James Kuszmaul0dedb5e2022-03-05 16:02:20 -0800216 // H_field_camera is passed in so that it can be used as a debugging output.
James Kuszmaul8c4f6592022-02-26 15:49:30 -0800217 const std::optional<Eigen::Vector2d> CameraMeasuredRobotPosition(
218 const OldPosition &state, const y2022::vision::TargetEstimate *target,
James Kuszmaul0dedb5e2022-03-05 16:02:20 -0800219 std::optional<RejectionReason> *rejection_reason,
220 Eigen::Matrix<double, 4, 4> *H_field_camera_measured) const;
221
222 flatbuffers::Offset<TargetEstimateDebug> PackTargetEstimateDebug(
223 const TargetEstimateDebugT &debug, flatbuffers::FlatBufferBuilder *fbb);
224
225 flatbuffers::Offset<CumulativeStatistics> PopulateStatistics(
226 flatbuffers::FlatBufferBuilder *fbb);
James Kuszmaul8c4f6592022-02-26 15:49:30 -0800227
James Kuszmaul29c59522022-02-12 16:44:26 -0800228 const control_loops::drivetrain::DrivetrainConfig<double> dt_config_;
229 const StateFeedbackHybridPlantCoefficients<2, 2, 2, double>
230 velocity_drivetrain_coefficients_;
231 Eigen::Matrix<double, kNModelStates, kNModelStates> A_continuous_model_;
232 Eigen::Matrix<double, kNAccelStates, kNAccelStates> A_continuous_accel_;
James Kuszmaul8c4f6592022-02-26 15:49:30 -0800233 Eigen::Matrix<double, kNAccelStates, kNAccelStates> A_discrete_accel_;
James Kuszmaul29c59522022-02-12 16:44:26 -0800234 Eigen::Matrix<double, kNModelStates, kNModelInputs> B_continuous_model_;
235 Eigen::Matrix<double, kNAccelStates, kNAccelInputs> B_continuous_accel_;
236
237 Eigen::Matrix<double, kNModelStates, kNModelStates> Q_continuous_model_;
238
239 Eigen::Matrix<double, kNModelStates, kNModelStates> P_model_;
James Kuszmaul8c4f6592022-02-26 15:49:30 -0800240
241 Eigen::Matrix<double, kNAccelStates, kNAccelStates> Q_continuous_accel_;
242 Eigen::Matrix<double, kNAccelStates, kNAccelStates> Q_discrete_accel_;
243
244 Eigen::Matrix<double, kNAccelStates, kNAccelStates> P_accel_;
245
246 control_loops::drivetrain::DrivetrainUkf down_estimator_;
247
James Kuszmaul29c59522022-02-12 16:44:26 -0800248 // When we are following the model, we will, on each iteration:
249 // 1) Perform a model-based update of a single state.
250 // 2) Add a hypothetical non-model-based entry based on the current state.
251 // 3) Evict too-old non-model-based entries.
James Kuszmaul29c59522022-02-12 16:44:26 -0800252
253 // Buffer of old branches these are all created by initializing a new
254 // model-based state based on the current state, and then initializing a new
255 // accel-based state on top of that new model-based state (to eliminate the
256 // impact of any lateral motion).
257 // We then integrate up all of these states and observe how much the model and
258 // accel based states of each branch compare to one another.
James Kuszmaul93825a02022-02-13 16:50:33 -0800259 aos::RingBuffer<CombinedState, 2000 / kBranchPeriod> branches_;
260 int branch_counter_ = 0;
James Kuszmaul29c59522022-02-12 16:44:26 -0800261
James Kuszmaul8c4f6592022-02-26 15:49:30 -0800262 // Buffer of old x/y/theta positions. This is used so that we can have a
263 // reference for exactly where we thought a camera was when it took an image.
264 aos::RingBuffer<OldPosition, 500 / kBranchPeriod> old_positions_;
265
James Kuszmaul29c59522022-02-12 16:44:26 -0800266 CombinedState current_state_;
267 aos::monotonic_clock::time_point t_ = aos::monotonic_clock::min_time;
268 bool using_model_;
269
James Kuszmaul5ed29dd2022-02-13 18:32:06 -0800270 // X position of the IMU, in meters. 0 = center of robot, positive = ahead of
271 // center, negative = behind center.
272 double long_offset_ = -0.15;
273
James Kuszmaul20014542022-04-06 21:35:44 -0700274 // Whether to use more aggressive corrections on the localizer. Only do this
275 // in teleop, since it can make spline control really jumpy.
276 bool aggressive_corrections_ = false;
277
James Kuszmaul29c59522022-02-12 16:44:26 -0800278 double last_residual_ = 0.0;
279 double filtered_residual_ = 0.0;
280 Eigen::Vector2d filtered_residual_accel_ = Eigen::Vector2d::Zero();
281 Eigen::Vector3d abs_accel_ = Eigen::Vector3d::Zero();
282 double velocity_residual_ = 0.0;
283 double accel_residual_ = 0.0;
284 double theta_rate_residual_ = 0.0;
285 int hysteresis_count_ = 0;
James Kuszmaul10d3fd42022-02-25 21:57:36 -0800286 Eigen::Quaterniond last_orientation_ = Eigen::Quaterniond::Identity();
James Kuszmaul29c59522022-02-12 16:44:26 -0800287
288 int clock_resets_ = 0;
289
James Kuszmaul8c4f6592022-02-26 15:49:30 -0800290 std::optional<aos::monotonic_clock::time_point> last_turret_update_;
291 double latest_turret_position_ = 0.0;
292 double latest_turret_velocity_ = 0.0;
293
294 // Stuff to track faults.
295 static constexpr size_t kNumRejectionReasons =
296 static_cast<int>(RejectionReason::MAX) -
297 static_cast<int>(RejectionReason::MIN) + 1;
298
299 struct Statistics {
300 int total_accepted = 0;
301 int total_candidates = 0;
302 static_assert(0 == static_cast<int>(RejectionReason::MIN));
303 static_assert(
304 kNumRejectionReasons ==
305 sizeof(
306 std::invoke_result<decltype(EnumValuesRejectionReason)>::type) /
307 sizeof(RejectionReason),
308 "RejectionReason has non-contiguous error values.");
309 std::array<int, kNumRejectionReasons> rejection_counts;
310 };
311 Statistics statistics_;
312
James Kuszmaul0dedb5e2022-03-05 16:02:20 -0800313 aos::SizedArray<TargetEstimateDebugT, kDebugBufferSize> image_debugs_;
Milind Upadhyayd67e9cf2022-03-13 13:56:57 -0700314 std::array<LedOutput, kNumPis> led_outputs_;
James Kuszmaul0dedb5e2022-03-05 16:02:20 -0800315
James Kuszmaul29c59522022-02-12 16:44:26 -0800316 friend class testing::LocalizerTest;
317};
318
319class EventLoopLocalizer {
320 public:
James Kuszmaul0dedb5e2022-03-05 16:02:20 -0800321 static constexpr std::chrono::milliseconds kMinVisualizationPeriod{100};
322
James Kuszmaul29c59522022-02-12 16:44:26 -0800323 EventLoopLocalizer(
324 aos::EventLoop *event_loop,
325 const control_loops::drivetrain::DrivetrainConfig<double> &dt_config);
326
James Kuszmaul5ed29dd2022-02-13 18:32:06 -0800327 ModelBasedLocalizer *localizer() { return &model_based_; }
328
James Kuszmaul29c59522022-02-12 16:44:26 -0800329 private:
James Kuszmaul9f2f53c2023-02-19 14:08:18 -0800330 void HandleImu(aos::monotonic_clock::time_point sample_time_pico,
331 aos::monotonic_clock::time_point sample_time_pi,
332 std::optional<Eigen::Vector2d> encoders, Eigen::Vector3d gyro,
333 Eigen::Vector3d accel);
James Kuszmaul29c59522022-02-12 16:44:26 -0800334 aos::EventLoop *event_loop_;
335 ModelBasedLocalizer model_based_;
336 aos::Sender<LocalizerStatus> status_sender_;
337 aos::Sender<LocalizerOutput> output_sender_;
James Kuszmaul0dedb5e2022-03-05 16:02:20 -0800338 aos::Sender<LocalizerVisualization> visualization_sender_;
Milind Upadhyayd67e9cf2022-03-13 13:56:57 -0700339 std::array<aos::Fetcher<y2022::vision::TargetEstimate>,
340 ModelBasedLocalizer::kNumPis>
James Kuszmaul2b2f8772022-03-12 15:25:35 -0800341 target_estimate_fetchers_;
342 aos::Fetcher<y2022::control_loops::superstructure::Status>
343 superstructure_fetcher_;
James Kuszmaul29c59522022-02-12 16:44:26 -0800344 aos::monotonic_clock::time_point last_output_send_ =
345 aos::monotonic_clock::min_time;
James Kuszmaul0dedb5e2022-03-05 16:02:20 -0800346 aos::monotonic_clock::time_point last_visualization_send_ =
347 aos::monotonic_clock::min_time;
James Kuszmaul5ed29dd2022-02-13 18:32:06 -0800348
James Kuszmaul9f2f53c2023-02-19 14:08:18 -0800349 ImuWatcher imu_watcher_;
James Kuszmaul9a1733a2023-02-19 16:51:47 -0800350 control_loops::drivetrain::LocalizationUtils utils_;
James Kuszmaul29c59522022-02-12 16:44:26 -0800351};
352} // namespace frc971::controls
James Kuszmaul51fa1ae2022-02-26 00:49:57 -0800353#endif // Y2022_LOCALIZER_LOCALIZER_H_