blob: fc15e9f235d37f8d559e0f92131c5a6f13b9533b [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 Kuszmaul29c59522022-02-12 16:44:26 -080022
23namespace frc971::controls {
24
25namespace testing {
26class LocalizerTest;
27}
28
29// Localizer implementation that makes use of a 6-axis IMU, encoder readings,
30// drivetrain voltages, and camera returns to localize the robot. Meant to
31// be run on a raspberry pi.
32//
33// This operates on the principle that the drivetrain can be in one of two
34// modes:
35// 1) A "normal" mode where it is obeying the regular drivetrain model, with
36// minimal lateral motion and no major external disturbances. This is
37// referred to as the "model" mode in the code/variable names.
38// 2) An non-holonomic mode where the robot is just flying around on a 2-D
39// plane with no meaningful constraints (referred to as an "accel" model
40// in the code, because we rely primarily on the accelerometer readings).
41//
42// In order to determine which mode to be in, we attempt to track whether the
43// two models are diverging substantially. In order to do this, we maintain a
44// 1-second long queue of "branches". A branch is generated every X iterations
45// and contains a model state and an accel state. When the branch starts, the
46// two will have identical states. For the remaining 1 second, the model state
47// will evolve purely according to the drivetrian model, and the accel state
48// will evolve purely using IMU readings.
49//
50// When the branch reaches 1 second in age, we calculate a residual associated
51// with how much the accel and model based states diverged. If they have
52// diverged substantially, that implies that the model is a poor match for
53// whatever has been happening to the robot in the past second, so if we were
54// previously relying on the model, we will override the current "actual"
55// state with the branched accel state, and then continue to update the accel
56// state based on IMU readings.
57// If we are currently in the accel state, we will continue generating branches
58// until the branches stop diverging--this will indicate that the model
59// matches the accelerometer readings again, and so we will swap back to
60// the model-based state.
61//
62// TODO:
63// * Implement paying attention to camera readings.
64// * Tune for ADIS16505/real robot.
James Kuszmaul29c59522022-02-12 16:44:26 -080065class ModelBasedLocalizer {
66 public:
Milind Upadhyayd67e9cf2022-03-13 13:56:57 -070067 static constexpr size_t kNumPis = 4;
68
James Kuszmaul29c59522022-02-12 16:44:26 -080069 static constexpr size_t kX = 0;
70 static constexpr size_t kY = 1;
71 static constexpr size_t kTheta = 2;
72
73 static constexpr size_t kVelocityX = 3;
74 static constexpr size_t kVelocityY = 4;
75 static constexpr size_t kNAccelStates = 5;
76
77 static constexpr size_t kLeftEncoder = 3;
78 static constexpr size_t kLeftVelocity = 4;
79 static constexpr size_t kLeftVoltageError = 5;
80 static constexpr size_t kRightEncoder = 6;
81 static constexpr size_t kRightVelocity = 7;
82 static constexpr size_t kRightVoltageError = 8;
83 static constexpr size_t kNModelStates = 9;
84
85 static constexpr size_t kNModelOutputs = 3;
86
87 static constexpr size_t kNAccelOuputs = 1;
88
89 static constexpr size_t kAccelX = 0;
90 static constexpr size_t kAccelY = 1;
91 static constexpr size_t kThetaRate = 2;
92 static constexpr size_t kNAccelInputs = 3;
93
94 static constexpr size_t kLeftVoltage = 0;
95 static constexpr size_t kRightVoltage = 1;
96 static constexpr size_t kNModelInputs = 2;
97
James Kuszmaul93825a02022-02-13 16:50:33 -080098 // Branching period, in cycles.
James Kuszmaul5ed29dd2022-02-13 18:32:06 -080099 // Needs 10 to even stay alive, and still at ~96% CPU.
100 // ~20 gives ~55-60% CPU.
James Kuszmaul896b4ec2022-02-26 22:56:29 -0800101 static constexpr int kBranchPeriod = 100;
James Kuszmaul93825a02022-02-13 16:50:33 -0800102
James Kuszmaul0dedb5e2022-03-05 16:02:20 -0800103 static constexpr size_t kDebugBufferSize = 10;
104
James Kuszmaul29c59522022-02-12 16:44:26 -0800105 typedef Eigen::Matrix<double, kNModelStates, 1> ModelState;
106 typedef Eigen::Matrix<double, kNAccelStates, 1> AccelState;
107 typedef Eigen::Matrix<double, kNModelInputs, 1> ModelInput;
108 typedef Eigen::Matrix<double, kNAccelInputs, 1> AccelInput;
109
110 ModelBasedLocalizer(
111 const control_loops::drivetrain::DrivetrainConfig<double> &dt_config);
112 void HandleImu(aos::monotonic_clock::time_point t,
113 const Eigen::Vector3d &gyro, const Eigen::Vector3d &accel,
James Kuszmaul5a5a7832022-03-16 23:15:08 -0700114 const std::optional<Eigen::Vector2d> encoders,
115 const Eigen::Vector2d voltage);
James Kuszmaul8c4f6592022-02-26 15:49:30 -0800116 void HandleTurret(aos::monotonic_clock::time_point sample_time,
117 double turret_position, double turret_velocity);
118 void HandleImageMatch(aos::monotonic_clock::time_point sample_time,
James Kuszmaul0dedb5e2022-03-05 16:02:20 -0800119 const y2022::vision::TargetEstimate *target,
120 int camera_index);
James Kuszmaul29c59522022-02-12 16:44:26 -0800121 void HandleReset(aos::monotonic_clock::time_point,
122 const Eigen::Vector3d &xytheta);
123
124 flatbuffers::Offset<ModelBasedStatus> PopulateStatus(
125 flatbuffers::FlatBufferBuilder *fbb);
126
127 Eigen::Vector3d xytheta() const {
128 if (using_model_) {
129 return current_state_.model_state.block<3, 1>(0, 0);
130 } else {
131 return current_state_.accel_state.block<3, 1>(0, 0);
132 }
133 }
134
James Kuszmaul10d3fd42022-02-25 21:57:36 -0800135 Eigen::Quaterniond orientation() const { return last_orientation_; }
136
James Kuszmaul29c59522022-02-12 16:44:26 -0800137 AccelState accel_state() const { return current_state_.accel_state; };
138
James Kuszmaul5ed29dd2022-02-13 18:32:06 -0800139 void set_longitudinal_offset(double offset) { long_offset_ = offset; }
James Kuszmaul20014542022-04-06 21:35:44 -0700140 void set_use_aggressive_image_corrections(bool aggressive) {
141 aggressive_corrections_ = aggressive;
142 }
James Kuszmaul5ed29dd2022-02-13 18:32:06 -0800143
James Kuszmaul0dedb5e2022-03-05 16:02:20 -0800144 void TallyRejection(const RejectionReason reason);
145
146 flatbuffers::Offset<LocalizerVisualization> PopulateVisualization(
147 flatbuffers::FlatBufferBuilder *fbb);
148
149 size_t NumQueuedImageDebugs() const { return image_debugs_.size(); }
James Kuszmaul8c4f6592022-02-26 15:49:30 -0800150
Milind Upadhyayd67e9cf2022-03-13 13:56:57 -0700151 std::array<LedOutput, kNumPis> led_outputs() const { return led_outputs_; }
152
Austin Schuh3806ffb2022-04-13 19:44:10 -0700153 int total_accepted() const { return statistics_.total_accepted; }
154
James Kuszmaul29c59522022-02-12 16:44:26 -0800155 private:
156 struct CombinedState {
James Kuszmaul8c4f6592022-02-26 15:49:30 -0800157 AccelState accel_state = AccelState::Zero();
158 ModelState model_state = ModelState::Zero();
159 aos::monotonic_clock::time_point branch_time =
160 aos::monotonic_clock::min_time;
161 double accumulated_divergence = 0.0;
162 };
163
164 // Struct to store state data needed to perform a camera correction, since
165 // camera corrections require looking back in time.
166 struct OldPosition {
167 aos::monotonic_clock::time_point sample_time =
168 aos::monotonic_clock::min_time;
169 Eigen::Vector3d xytheta = Eigen::Vector3d::Zero();
170 double turret_position = 0.0;
171 double turret_velocity = 0.0;
James Kuszmaul29c59522022-02-12 16:44:26 -0800172 };
173
174 static flatbuffers::Offset<AccelBasedState> BuildAccelState(
175 flatbuffers::FlatBufferBuilder *fbb, const AccelState &state);
176
177 static flatbuffers::Offset<ModelBasedState> BuildModelState(
178 flatbuffers::FlatBufferBuilder *fbb, const ModelState &state);
179
180 Eigen::Matrix<double, kNModelStates, kNModelStates> AModel(
181 const ModelState &state) const;
182 Eigen::Matrix<double, kNAccelStates, kNAccelStates> AAccel() const;
183 ModelState DiffModel(const ModelState &state, const ModelInput &U) const;
184 AccelState DiffAccel(const AccelState &state, const AccelInput &U) const;
185
186 ModelState UpdateModel(const ModelState &model, const ModelInput &input,
187 aos::monotonic_clock::duration dt) const;
188 AccelState UpdateAccel(const AccelState &accel, const AccelInput &input,
189 aos::monotonic_clock::duration dt) const;
190
191 AccelState AccelStateForModelState(const ModelState &state) const;
192 ModelState ModelStateForAccelState(const AccelState &state,
193 const Eigen::Vector2d &encoders,
194 const double yaw_rate) const;
195 double ModelDivergence(const CombinedState &state,
196 const AccelInput &accel_inputs,
197 const Eigen::Vector2d &filtered_accel,
198 const ModelInput &model_inputs);
James Kuszmaul5ed29dd2022-02-13 18:32:06 -0800199 void UpdateState(
200 CombinedState *state,
201 const Eigen::Matrix<double, kNModelStates, kNModelOutputs> &K,
202 const Eigen::Matrix<double, kNModelOutputs, 1> &Z,
203 const Eigen::Matrix<double, kNModelOutputs, kNModelStates> &H,
204 const AccelInput &accel_input, const ModelInput &model_input,
205 aos::monotonic_clock::duration dt);
James Kuszmaul29c59522022-02-12 16:44:26 -0800206
James Kuszmaul8c4f6592022-02-26 15:49:30 -0800207 const OldPosition GetStateForTime(aos::monotonic_clock::time_point time);
208
209 // Returns the transformation to get from the camera frame to the robot frame
210 // for the specified state.
211 const Eigen::Matrix<double, 4, 4> CameraTransform(
212 const OldPosition &state,
213 const frc971::vision::calibration::CameraCalibration *calibration,
214 std::optional<RejectionReason> *rejection_reason) const;
215
216 // Returns the robot x/y position implied by the specified camera data and
217 // estimated state from that time.
James Kuszmaul0dedb5e2022-03-05 16:02:20 -0800218 // H_field_camera is passed in so that it can be used as a debugging output.
James Kuszmaul8c4f6592022-02-26 15:49:30 -0800219 const std::optional<Eigen::Vector2d> CameraMeasuredRobotPosition(
220 const OldPosition &state, const y2022::vision::TargetEstimate *target,
James Kuszmaul0dedb5e2022-03-05 16:02:20 -0800221 std::optional<RejectionReason> *rejection_reason,
222 Eigen::Matrix<double, 4, 4> *H_field_camera_measured) const;
223
224 flatbuffers::Offset<TargetEstimateDebug> PackTargetEstimateDebug(
225 const TargetEstimateDebugT &debug, flatbuffers::FlatBufferBuilder *fbb);
226
227 flatbuffers::Offset<CumulativeStatistics> PopulateStatistics(
228 flatbuffers::FlatBufferBuilder *fbb);
James Kuszmaul8c4f6592022-02-26 15:49:30 -0800229
James Kuszmaul29c59522022-02-12 16:44:26 -0800230 const control_loops::drivetrain::DrivetrainConfig<double> dt_config_;
231 const StateFeedbackHybridPlantCoefficients<2, 2, 2, double>
232 velocity_drivetrain_coefficients_;
233 Eigen::Matrix<double, kNModelStates, kNModelStates> A_continuous_model_;
234 Eigen::Matrix<double, kNAccelStates, kNAccelStates> A_continuous_accel_;
James Kuszmaul8c4f6592022-02-26 15:49:30 -0800235 Eigen::Matrix<double, kNAccelStates, kNAccelStates> A_discrete_accel_;
James Kuszmaul29c59522022-02-12 16:44:26 -0800236 Eigen::Matrix<double, kNModelStates, kNModelInputs> B_continuous_model_;
237 Eigen::Matrix<double, kNAccelStates, kNAccelInputs> B_continuous_accel_;
238
239 Eigen::Matrix<double, kNModelStates, kNModelStates> Q_continuous_model_;
240
241 Eigen::Matrix<double, kNModelStates, kNModelStates> P_model_;
James Kuszmaul8c4f6592022-02-26 15:49:30 -0800242
243 Eigen::Matrix<double, kNAccelStates, kNAccelStates> Q_continuous_accel_;
244 Eigen::Matrix<double, kNAccelStates, kNAccelStates> Q_discrete_accel_;
245
246 Eigen::Matrix<double, kNAccelStates, kNAccelStates> P_accel_;
247
248 control_loops::drivetrain::DrivetrainUkf down_estimator_;
249
James Kuszmaul29c59522022-02-12 16:44:26 -0800250 // When we are following the model, we will, on each iteration:
251 // 1) Perform a model-based update of a single state.
252 // 2) Add a hypothetical non-model-based entry based on the current state.
253 // 3) Evict too-old non-model-based entries.
James Kuszmaul29c59522022-02-12 16:44:26 -0800254
255 // Buffer of old branches these are all created by initializing a new
256 // model-based state based on the current state, and then initializing a new
257 // accel-based state on top of that new model-based state (to eliminate the
258 // impact of any lateral motion).
259 // We then integrate up all of these states and observe how much the model and
260 // accel based states of each branch compare to one another.
James Kuszmaul93825a02022-02-13 16:50:33 -0800261 aos::RingBuffer<CombinedState, 2000 / kBranchPeriod> branches_;
262 int branch_counter_ = 0;
James Kuszmaul29c59522022-02-12 16:44:26 -0800263
James Kuszmaul8c4f6592022-02-26 15:49:30 -0800264 // Buffer of old x/y/theta positions. This is used so that we can have a
265 // reference for exactly where we thought a camera was when it took an image.
266 aos::RingBuffer<OldPosition, 500 / kBranchPeriod> old_positions_;
267
James Kuszmaul29c59522022-02-12 16:44:26 -0800268 CombinedState current_state_;
269 aos::monotonic_clock::time_point t_ = aos::monotonic_clock::min_time;
270 bool using_model_;
271
James Kuszmaul5ed29dd2022-02-13 18:32:06 -0800272 // X position of the IMU, in meters. 0 = center of robot, positive = ahead of
273 // center, negative = behind center.
274 double long_offset_ = -0.15;
275
James Kuszmaul20014542022-04-06 21:35:44 -0700276 // Whether to use more aggressive corrections on the localizer. Only do this
277 // in teleop, since it can make spline control really jumpy.
278 bool aggressive_corrections_ = false;
279
James Kuszmaul29c59522022-02-12 16:44:26 -0800280 double last_residual_ = 0.0;
281 double filtered_residual_ = 0.0;
282 Eigen::Vector2d filtered_residual_accel_ = Eigen::Vector2d::Zero();
283 Eigen::Vector3d abs_accel_ = Eigen::Vector3d::Zero();
284 double velocity_residual_ = 0.0;
285 double accel_residual_ = 0.0;
286 double theta_rate_residual_ = 0.0;
287 int hysteresis_count_ = 0;
James Kuszmaul10d3fd42022-02-25 21:57:36 -0800288 Eigen::Quaterniond last_orientation_ = Eigen::Quaterniond::Identity();
James Kuszmaul29c59522022-02-12 16:44:26 -0800289
290 int clock_resets_ = 0;
291
James Kuszmaul8c4f6592022-02-26 15:49:30 -0800292 std::optional<aos::monotonic_clock::time_point> last_turret_update_;
293 double latest_turret_position_ = 0.0;
294 double latest_turret_velocity_ = 0.0;
295
296 // Stuff to track faults.
297 static constexpr size_t kNumRejectionReasons =
298 static_cast<int>(RejectionReason::MAX) -
299 static_cast<int>(RejectionReason::MIN) + 1;
300
301 struct Statistics {
302 int total_accepted = 0;
303 int total_candidates = 0;
304 static_assert(0 == static_cast<int>(RejectionReason::MIN));
305 static_assert(
306 kNumRejectionReasons ==
307 sizeof(
308 std::invoke_result<decltype(EnumValuesRejectionReason)>::type) /
309 sizeof(RejectionReason),
310 "RejectionReason has non-contiguous error values.");
311 std::array<int, kNumRejectionReasons> rejection_counts;
312 };
313 Statistics statistics_;
314
James Kuszmaul0dedb5e2022-03-05 16:02:20 -0800315 aos::SizedArray<TargetEstimateDebugT, kDebugBufferSize> image_debugs_;
Milind Upadhyayd67e9cf2022-03-13 13:56:57 -0700316 std::array<LedOutput, kNumPis> led_outputs_;
James Kuszmaul0dedb5e2022-03-05 16:02:20 -0800317
James Kuszmaul29c59522022-02-12 16:44:26 -0800318 friend class testing::LocalizerTest;
319};
320
321class EventLoopLocalizer {
322 public:
James Kuszmaul0dedb5e2022-03-05 16:02:20 -0800323 static constexpr std::chrono::milliseconds kMinVisualizationPeriod{100};
324
James Kuszmaul29c59522022-02-12 16:44:26 -0800325 EventLoopLocalizer(
326 aos::EventLoop *event_loop,
327 const control_loops::drivetrain::DrivetrainConfig<double> &dt_config);
328
James Kuszmaul5ed29dd2022-02-13 18:32:06 -0800329 ModelBasedLocalizer *localizer() { return &model_based_; }
330
James Kuszmaul29c59522022-02-12 16:44:26 -0800331 private:
James Kuszmaul8c4f6592022-02-26 15:49:30 -0800332 std::optional<aos::monotonic_clock::duration> ClockOffset(
333 std::string_view pi);
James Kuszmaul29c59522022-02-12 16:44:26 -0800334 aos::EventLoop *event_loop_;
James Kuszmaul6d6e1302022-03-12 15:22:48 -0800335 const control_loops::drivetrain::DrivetrainConfig<double> &dt_config_;
James Kuszmaul29c59522022-02-12 16:44:26 -0800336 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 std::optional<aos::monotonic_clock::time_point> last_pico_timestamp_;
354 aos::monotonic_clock::duration pico_offset_error_;
355 // t = pico_offset_ + pico_timestamp.
356 // Note that this can drift over sufficiently long time periods!
357 std::optional<std::chrono::nanoseconds> pico_offset_;
358
James Kuszmaul5f27d8b2022-03-17 09:08:26 -0700359 ImuFailuresT imu_fault_tracker_;
360 std::optional<size_t> first_valid_data_counter_;
361 size_t total_imu_messages_received_ = 0;
362 size_t data_counter_offset_ = 0;
363 int last_data_counter_ = 0;
364
365 Eigen::Vector3d last_gyro_ = Eigen::Vector3d::Zero();
366
James Kuszmaul5ed29dd2022-02-13 18:32:06 -0800367 zeroing::UnwrapSensor left_encoder_;
368 zeroing::UnwrapSensor right_encoder_;
James Kuszmaul29c59522022-02-12 16:44:26 -0800369};
370} // namespace frc971::controls
James Kuszmaul51fa1ae2022-02-26 00:49:57 -0800371#endif // Y2022_LOCALIZER_LOCALIZER_H_