blob: 917f1319b6c9a95f0ea8169d6ed6871289b77845 [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"
15#include "frc971/zeroing/imu_zeroer.h"
James Kuszmaul5ed29dd2022-02-13 18:32:06 -080016#include "frc971/zeroing/wrap.h"
James Kuszmaul8c4f6592022-02-26 15:49:30 -080017#include "y2022/control_loops/superstructure/superstructure_status_generated.h"
18#include "y2022/localizer/localizer_output_generated.h"
19#include "y2022/localizer/localizer_status_generated.h"
James Kuszmaul0dedb5e2022-03-05 16:02:20 -080020#include "y2022/localizer/localizer_visualization_generated.h"
James Kuszmaul8c4f6592022-02-26 15:49:30 -080021#include "y2022/vision/target_estimate_generated.h"
James Kuszmaul9f2f53c2023-02-19 14:08:18 -080022#include "frc971/imu_reader/imu_watcher.h"
James Kuszmaul29c59522022-02-12 16:44:26 -080023
24namespace frc971::controls {
25
26namespace testing {
27class LocalizerTest;
28}
29
30// Localizer implementation that makes use of a 6-axis IMU, encoder readings,
31// drivetrain voltages, and camera returns to localize the robot. Meant to
32// be run on a raspberry pi.
33//
34// This operates on the principle that the drivetrain can be in one of two
35// modes:
36// 1) A "normal" mode where it is obeying the regular drivetrain model, with
37// minimal lateral motion and no major external disturbances. This is
38// referred to as the "model" mode in the code/variable names.
39// 2) An non-holonomic mode where the robot is just flying around on a 2-D
40// plane with no meaningful constraints (referred to as an "accel" model
41// in the code, because we rely primarily on the accelerometer readings).
42//
43// In order to determine which mode to be in, we attempt to track whether the
44// two models are diverging substantially. In order to do this, we maintain a
45// 1-second long queue of "branches". A branch is generated every X iterations
46// and contains a model state and an accel state. When the branch starts, the
47// two will have identical states. For the remaining 1 second, the model state
48// will evolve purely according to the drivetrian model, and the accel state
49// will evolve purely using IMU readings.
50//
51// When the branch reaches 1 second in age, we calculate a residual associated
52// with how much the accel and model based states diverged. If they have
53// diverged substantially, that implies that the model is a poor match for
54// whatever has been happening to the robot in the past second, so if we were
55// previously relying on the model, we will override the current "actual"
56// state with the branched accel state, and then continue to update the accel
57// state based on IMU readings.
58// If we are currently in the accel state, we will continue generating branches
59// until the branches stop diverging--this will indicate that the model
60// matches the accelerometer readings again, and so we will swap back to
61// the model-based state.
James Kuszmaul29c59522022-02-12 16:44:26 -080062class ModelBasedLocalizer {
63 public:
Milind Upadhyayd67e9cf2022-03-13 13:56:57 -070064 static constexpr size_t kNumPis = 4;
65
James Kuszmaul29c59522022-02-12 16:44:26 -080066 static constexpr size_t kX = 0;
67 static constexpr size_t kY = 1;
68 static constexpr size_t kTheta = 2;
69
70 static constexpr size_t kVelocityX = 3;
71 static constexpr size_t kVelocityY = 4;
72 static constexpr size_t kNAccelStates = 5;
73
74 static constexpr size_t kLeftEncoder = 3;
75 static constexpr size_t kLeftVelocity = 4;
76 static constexpr size_t kLeftVoltageError = 5;
77 static constexpr size_t kRightEncoder = 6;
78 static constexpr size_t kRightVelocity = 7;
79 static constexpr size_t kRightVoltageError = 8;
80 static constexpr size_t kNModelStates = 9;
81
82 static constexpr size_t kNModelOutputs = 3;
83
84 static constexpr size_t kNAccelOuputs = 1;
85
86 static constexpr size_t kAccelX = 0;
87 static constexpr size_t kAccelY = 1;
88 static constexpr size_t kThetaRate = 2;
89 static constexpr size_t kNAccelInputs = 3;
90
91 static constexpr size_t kLeftVoltage = 0;
92 static constexpr size_t kRightVoltage = 1;
93 static constexpr size_t kNModelInputs = 2;
94
James Kuszmaul93825a02022-02-13 16:50:33 -080095 // Branching period, in cycles.
James Kuszmaul5ed29dd2022-02-13 18:32:06 -080096 // Needs 10 to even stay alive, and still at ~96% CPU.
97 // ~20 gives ~55-60% CPU.
James Kuszmaul896b4ec2022-02-26 22:56:29 -080098 static constexpr int kBranchPeriod = 100;
James Kuszmaul93825a02022-02-13 16:50:33 -080099
James Kuszmaul0dedb5e2022-03-05 16:02:20 -0800100 static constexpr size_t kDebugBufferSize = 10;
101
James Kuszmaul29c59522022-02-12 16:44:26 -0800102 typedef Eigen::Matrix<double, kNModelStates, 1> ModelState;
103 typedef Eigen::Matrix<double, kNAccelStates, 1> AccelState;
104 typedef Eigen::Matrix<double, kNModelInputs, 1> ModelInput;
105 typedef Eigen::Matrix<double, kNAccelInputs, 1> AccelInput;
106
107 ModelBasedLocalizer(
108 const control_loops::drivetrain::DrivetrainConfig<double> &dt_config);
109 void HandleImu(aos::monotonic_clock::time_point t,
110 const Eigen::Vector3d &gyro, const Eigen::Vector3d &accel,
James Kuszmaul5a5a7832022-03-16 23:15:08 -0700111 const std::optional<Eigen::Vector2d> encoders,
112 const Eigen::Vector2d voltage);
James Kuszmaul8c4f6592022-02-26 15:49:30 -0800113 void HandleTurret(aos::monotonic_clock::time_point sample_time,
114 double turret_position, double turret_velocity);
115 void HandleImageMatch(aos::monotonic_clock::time_point sample_time,
James Kuszmaul0dedb5e2022-03-05 16:02:20 -0800116 const y2022::vision::TargetEstimate *target,
117 int camera_index);
James Kuszmaul29c59522022-02-12 16:44:26 -0800118 void HandleReset(aos::monotonic_clock::time_point,
119 const Eigen::Vector3d &xytheta);
120
121 flatbuffers::Offset<ModelBasedStatus> PopulateStatus(
122 flatbuffers::FlatBufferBuilder *fbb);
123
124 Eigen::Vector3d xytheta() const {
125 if (using_model_) {
126 return current_state_.model_state.block<3, 1>(0, 0);
127 } else {
128 return current_state_.accel_state.block<3, 1>(0, 0);
129 }
130 }
131
James Kuszmaul10d3fd42022-02-25 21:57:36 -0800132 Eigen::Quaterniond orientation() const { return last_orientation_; }
133
James Kuszmaul29c59522022-02-12 16:44:26 -0800134 AccelState accel_state() const { return current_state_.accel_state; };
135
James Kuszmaul5ed29dd2022-02-13 18:32:06 -0800136 void set_longitudinal_offset(double offset) { long_offset_ = offset; }
James Kuszmaul20014542022-04-06 21:35:44 -0700137 void set_use_aggressive_image_corrections(bool aggressive) {
138 aggressive_corrections_ = aggressive;
139 }
James Kuszmaul5ed29dd2022-02-13 18:32:06 -0800140
James Kuszmaul0dedb5e2022-03-05 16:02:20 -0800141 void TallyRejection(const RejectionReason reason);
142
143 flatbuffers::Offset<LocalizerVisualization> PopulateVisualization(
144 flatbuffers::FlatBufferBuilder *fbb);
145
146 size_t NumQueuedImageDebugs() const { return image_debugs_.size(); }
James Kuszmaul8c4f6592022-02-26 15:49:30 -0800147
Milind Upadhyayd67e9cf2022-03-13 13:56:57 -0700148 std::array<LedOutput, kNumPis> led_outputs() const { return led_outputs_; }
149
Austin Schuh3806ffb2022-04-13 19:44:10 -0700150 int total_accepted() const { return statistics_.total_accepted; }
151
James Kuszmaul29c59522022-02-12 16:44:26 -0800152 private:
153 struct CombinedState {
James Kuszmaul8c4f6592022-02-26 15:49:30 -0800154 AccelState accel_state = AccelState::Zero();
155 ModelState model_state = ModelState::Zero();
156 aos::monotonic_clock::time_point branch_time =
157 aos::monotonic_clock::min_time;
158 double accumulated_divergence = 0.0;
159 };
160
161 // Struct to store state data needed to perform a camera correction, since
162 // camera corrections require looking back in time.
163 struct OldPosition {
164 aos::monotonic_clock::time_point sample_time =
165 aos::monotonic_clock::min_time;
166 Eigen::Vector3d xytheta = Eigen::Vector3d::Zero();
167 double turret_position = 0.0;
168 double turret_velocity = 0.0;
James Kuszmaul29c59522022-02-12 16:44:26 -0800169 };
170
171 static flatbuffers::Offset<AccelBasedState> BuildAccelState(
172 flatbuffers::FlatBufferBuilder *fbb, const AccelState &state);
173
174 static flatbuffers::Offset<ModelBasedState> BuildModelState(
175 flatbuffers::FlatBufferBuilder *fbb, const ModelState &state);
176
177 Eigen::Matrix<double, kNModelStates, kNModelStates> AModel(
178 const ModelState &state) const;
179 Eigen::Matrix<double, kNAccelStates, kNAccelStates> AAccel() const;
180 ModelState DiffModel(const ModelState &state, const ModelInput &U) const;
181 AccelState DiffAccel(const AccelState &state, const AccelInput &U) const;
182
183 ModelState UpdateModel(const ModelState &model, const ModelInput &input,
184 aos::monotonic_clock::duration dt) const;
185 AccelState UpdateAccel(const AccelState &accel, const AccelInput &input,
186 aos::monotonic_clock::duration dt) const;
187
188 AccelState AccelStateForModelState(const ModelState &state) const;
189 ModelState ModelStateForAccelState(const AccelState &state,
190 const Eigen::Vector2d &encoders,
191 const double yaw_rate) const;
192 double ModelDivergence(const CombinedState &state,
193 const AccelInput &accel_inputs,
194 const Eigen::Vector2d &filtered_accel,
195 const ModelInput &model_inputs);
James Kuszmaul5ed29dd2022-02-13 18:32:06 -0800196 void UpdateState(
197 CombinedState *state,
198 const Eigen::Matrix<double, kNModelStates, kNModelOutputs> &K,
199 const Eigen::Matrix<double, kNModelOutputs, 1> &Z,
200 const Eigen::Matrix<double, kNModelOutputs, kNModelStates> &H,
201 const AccelInput &accel_input, const ModelInput &model_input,
202 aos::monotonic_clock::duration dt);
James Kuszmaul29c59522022-02-12 16:44:26 -0800203
James Kuszmaul8c4f6592022-02-26 15:49:30 -0800204 const OldPosition GetStateForTime(aos::monotonic_clock::time_point time);
205
206 // Returns the transformation to get from the camera frame to the robot frame
207 // for the specified state.
208 const Eigen::Matrix<double, 4, 4> CameraTransform(
209 const OldPosition &state,
210 const frc971::vision::calibration::CameraCalibration *calibration,
211 std::optional<RejectionReason> *rejection_reason) const;
212
213 // Returns the robot x/y position implied by the specified camera data and
214 // estimated state from that time.
James Kuszmaul0dedb5e2022-03-05 16:02:20 -0800215 // H_field_camera is passed in so that it can be used as a debugging output.
James Kuszmaul8c4f6592022-02-26 15:49:30 -0800216 const std::optional<Eigen::Vector2d> CameraMeasuredRobotPosition(
217 const OldPosition &state, const y2022::vision::TargetEstimate *target,
James Kuszmaul0dedb5e2022-03-05 16:02:20 -0800218 std::optional<RejectionReason> *rejection_reason,
219 Eigen::Matrix<double, 4, 4> *H_field_camera_measured) const;
220
221 flatbuffers::Offset<TargetEstimateDebug> PackTargetEstimateDebug(
222 const TargetEstimateDebugT &debug, flatbuffers::FlatBufferBuilder *fbb);
223
224 flatbuffers::Offset<CumulativeStatistics> PopulateStatistics(
225 flatbuffers::FlatBufferBuilder *fbb);
James Kuszmaul8c4f6592022-02-26 15:49:30 -0800226
James Kuszmaul29c59522022-02-12 16:44:26 -0800227 const control_loops::drivetrain::DrivetrainConfig<double> dt_config_;
228 const StateFeedbackHybridPlantCoefficients<2, 2, 2, double>
229 velocity_drivetrain_coefficients_;
230 Eigen::Matrix<double, kNModelStates, kNModelStates> A_continuous_model_;
231 Eigen::Matrix<double, kNAccelStates, kNAccelStates> A_continuous_accel_;
James Kuszmaul8c4f6592022-02-26 15:49:30 -0800232 Eigen::Matrix<double, kNAccelStates, kNAccelStates> A_discrete_accel_;
James Kuszmaul29c59522022-02-12 16:44:26 -0800233 Eigen::Matrix<double, kNModelStates, kNModelInputs> B_continuous_model_;
234 Eigen::Matrix<double, kNAccelStates, kNAccelInputs> B_continuous_accel_;
235
236 Eigen::Matrix<double, kNModelStates, kNModelStates> Q_continuous_model_;
237
238 Eigen::Matrix<double, kNModelStates, kNModelStates> P_model_;
James Kuszmaul8c4f6592022-02-26 15:49:30 -0800239
240 Eigen::Matrix<double, kNAccelStates, kNAccelStates> Q_continuous_accel_;
241 Eigen::Matrix<double, kNAccelStates, kNAccelStates> Q_discrete_accel_;
242
243 Eigen::Matrix<double, kNAccelStates, kNAccelStates> P_accel_;
244
245 control_loops::drivetrain::DrivetrainUkf down_estimator_;
246
James Kuszmaul29c59522022-02-12 16:44:26 -0800247 // When we are following the model, we will, on each iteration:
248 // 1) Perform a model-based update of a single state.
249 // 2) Add a hypothetical non-model-based entry based on the current state.
250 // 3) Evict too-old non-model-based entries.
James Kuszmaul29c59522022-02-12 16:44:26 -0800251
252 // Buffer of old branches these are all created by initializing a new
253 // model-based state based on the current state, and then initializing a new
254 // accel-based state on top of that new model-based state (to eliminate the
255 // impact of any lateral motion).
256 // We then integrate up all of these states and observe how much the model and
257 // accel based states of each branch compare to one another.
James Kuszmaul93825a02022-02-13 16:50:33 -0800258 aos::RingBuffer<CombinedState, 2000 / kBranchPeriod> branches_;
259 int branch_counter_ = 0;
James Kuszmaul29c59522022-02-12 16:44:26 -0800260
James Kuszmaul8c4f6592022-02-26 15:49:30 -0800261 // Buffer of old x/y/theta positions. This is used so that we can have a
262 // reference for exactly where we thought a camera was when it took an image.
263 aos::RingBuffer<OldPosition, 500 / kBranchPeriod> old_positions_;
264
James Kuszmaul29c59522022-02-12 16:44:26 -0800265 CombinedState current_state_;
266 aos::monotonic_clock::time_point t_ = aos::monotonic_clock::min_time;
267 bool using_model_;
268
James Kuszmaul5ed29dd2022-02-13 18:32:06 -0800269 // X position of the IMU, in meters. 0 = center of robot, positive = ahead of
270 // center, negative = behind center.
271 double long_offset_ = -0.15;
272
James Kuszmaul20014542022-04-06 21:35:44 -0700273 // Whether to use more aggressive corrections on the localizer. Only do this
274 // in teleop, since it can make spline control really jumpy.
275 bool aggressive_corrections_ = false;
276
James Kuszmaul29c59522022-02-12 16:44:26 -0800277 double last_residual_ = 0.0;
278 double filtered_residual_ = 0.0;
279 Eigen::Vector2d filtered_residual_accel_ = Eigen::Vector2d::Zero();
280 Eigen::Vector3d abs_accel_ = Eigen::Vector3d::Zero();
281 double velocity_residual_ = 0.0;
282 double accel_residual_ = 0.0;
283 double theta_rate_residual_ = 0.0;
284 int hysteresis_count_ = 0;
James Kuszmaul10d3fd42022-02-25 21:57:36 -0800285 Eigen::Quaterniond last_orientation_ = Eigen::Quaterniond::Identity();
James Kuszmaul29c59522022-02-12 16:44:26 -0800286
287 int clock_resets_ = 0;
288
James Kuszmaul8c4f6592022-02-26 15:49:30 -0800289 std::optional<aos::monotonic_clock::time_point> last_turret_update_;
290 double latest_turret_position_ = 0.0;
291 double latest_turret_velocity_ = 0.0;
292
293 // Stuff to track faults.
294 static constexpr size_t kNumRejectionReasons =
295 static_cast<int>(RejectionReason::MAX) -
296 static_cast<int>(RejectionReason::MIN) + 1;
297
298 struct Statistics {
299 int total_accepted = 0;
300 int total_candidates = 0;
301 static_assert(0 == static_cast<int>(RejectionReason::MIN));
302 static_assert(
303 kNumRejectionReasons ==
304 sizeof(
305 std::invoke_result<decltype(EnumValuesRejectionReason)>::type) /
306 sizeof(RejectionReason),
307 "RejectionReason has non-contiguous error values.");
308 std::array<int, kNumRejectionReasons> rejection_counts;
309 };
310 Statistics statistics_;
311
James Kuszmaul0dedb5e2022-03-05 16:02:20 -0800312 aos::SizedArray<TargetEstimateDebugT, kDebugBufferSize> image_debugs_;
Milind Upadhyayd67e9cf2022-03-13 13:56:57 -0700313 std::array<LedOutput, kNumPis> led_outputs_;
James Kuszmaul0dedb5e2022-03-05 16:02:20 -0800314
James Kuszmaul29c59522022-02-12 16:44:26 -0800315 friend class testing::LocalizerTest;
316};
317
318class EventLoopLocalizer {
319 public:
James Kuszmaul0dedb5e2022-03-05 16:02:20 -0800320 static constexpr std::chrono::milliseconds kMinVisualizationPeriod{100};
321
James Kuszmaul29c59522022-02-12 16:44:26 -0800322 EventLoopLocalizer(
323 aos::EventLoop *event_loop,
324 const control_loops::drivetrain::DrivetrainConfig<double> &dt_config);
325
James Kuszmaul5ed29dd2022-02-13 18:32:06 -0800326 ModelBasedLocalizer *localizer() { return &model_based_; }
327
James Kuszmaul29c59522022-02-12 16:44:26 -0800328 private:
James Kuszmaul8c4f6592022-02-26 15:49:30 -0800329 std::optional<aos::monotonic_clock::duration> ClockOffset(
330 std::string_view pi);
James Kuszmaul9f2f53c2023-02-19 14:08:18 -0800331 void HandleImu(aos::monotonic_clock::time_point sample_time_pico,
332 aos::monotonic_clock::time_point sample_time_pi,
333 std::optional<Eigen::Vector2d> encoders, Eigen::Vector3d gyro,
334 Eigen::Vector3d accel);
James Kuszmaul29c59522022-02-12 16:44:26 -0800335 aos::EventLoop *event_loop_;
336 ModelBasedLocalizer model_based_;
337 aos::Sender<LocalizerStatus> status_sender_;
338 aos::Sender<LocalizerOutput> output_sender_;
James Kuszmaul0dedb5e2022-03-05 16:02:20 -0800339 aos::Sender<LocalizerVisualization> visualization_sender_;
James Kuszmaul29c59522022-02-12 16:44:26 -0800340 aos::Fetcher<frc971::control_loops::drivetrain::Output> output_fetcher_;
James Kuszmaul8c4f6592022-02-26 15:49:30 -0800341 aos::Fetcher<aos::message_bridge::ServerStatistics> clock_offset_fetcher_;
Milind Upadhyayd67e9cf2022-03-13 13:56:57 -0700342 std::array<aos::Fetcher<y2022::vision::TargetEstimate>,
343 ModelBasedLocalizer::kNumPis>
James Kuszmaul2b2f8772022-03-12 15:25:35 -0800344 target_estimate_fetchers_;
345 aos::Fetcher<y2022::control_loops::superstructure::Status>
346 superstructure_fetcher_;
James Kuszmaul20014542022-04-06 21:35:44 -0700347 aos::Fetcher<aos::JoystickState> joystick_state_fetcher_;
James Kuszmaul29c59522022-02-12 16:44:26 -0800348 zeroing::ImuZeroer zeroer_;
349 aos::monotonic_clock::time_point last_output_send_ =
350 aos::monotonic_clock::min_time;
James Kuszmaul0dedb5e2022-03-05 16:02:20 -0800351 aos::monotonic_clock::time_point last_visualization_send_ =
352 aos::monotonic_clock::min_time;
James Kuszmaul5ed29dd2022-02-13 18:32:06 -0800353
James Kuszmaul9f2f53c2023-02-19 14:08:18 -0800354 ImuWatcher imu_watcher_;
James Kuszmaul29c59522022-02-12 16:44:26 -0800355};
356} // namespace frc971::controls
James Kuszmaul51fa1ae2022-02-26 00:49:57 -0800357#endif // Y2022_LOCALIZER_LOCALIZER_H_