blob: 5620a4d1946a5f2fcd27da82a01071e2b9789fa9 [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
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 Kuszmaul8c4f6592022-02-26 15:49:30 -0800330 std::optional<aos::monotonic_clock::duration> ClockOffset(
331 std::string_view pi);
James Kuszmaul29c59522022-02-12 16:44:26 -0800332 aos::EventLoop *event_loop_;
James Kuszmaul6d6e1302022-03-12 15:22:48 -0800333 const control_loops::drivetrain::DrivetrainConfig<double> &dt_config_;
James Kuszmaul29c59522022-02-12 16:44:26 -0800334 ModelBasedLocalizer model_based_;
335 aos::Sender<LocalizerStatus> status_sender_;
336 aos::Sender<LocalizerOutput> output_sender_;
James Kuszmaul0dedb5e2022-03-05 16:02:20 -0800337 aos::Sender<LocalizerVisualization> visualization_sender_;
James Kuszmaul29c59522022-02-12 16:44:26 -0800338 aos::Fetcher<frc971::control_loops::drivetrain::Output> output_fetcher_;
James Kuszmaul8c4f6592022-02-26 15:49:30 -0800339 aos::Fetcher<aos::message_bridge::ServerStatistics> clock_offset_fetcher_;
Milind Upadhyayd67e9cf2022-03-13 13:56:57 -0700340 std::array<aos::Fetcher<y2022::vision::TargetEstimate>,
341 ModelBasedLocalizer::kNumPis>
James Kuszmaul2b2f8772022-03-12 15:25:35 -0800342 target_estimate_fetchers_;
343 aos::Fetcher<y2022::control_loops::superstructure::Status>
344 superstructure_fetcher_;
James Kuszmaul20014542022-04-06 21:35:44 -0700345 aos::Fetcher<aos::JoystickState> joystick_state_fetcher_;
James Kuszmaul29c59522022-02-12 16:44:26 -0800346 zeroing::ImuZeroer zeroer_;
347 aos::monotonic_clock::time_point last_output_send_ =
348 aos::monotonic_clock::min_time;
James Kuszmaul0dedb5e2022-03-05 16:02:20 -0800349 aos::monotonic_clock::time_point last_visualization_send_ =
350 aos::monotonic_clock::min_time;
James Kuszmaul5ed29dd2022-02-13 18:32:06 -0800351 std::optional<aos::monotonic_clock::time_point> last_pico_timestamp_;
352 aos::monotonic_clock::duration pico_offset_error_;
353 // t = pico_offset_ + pico_timestamp.
354 // Note that this can drift over sufficiently long time periods!
355 std::optional<std::chrono::nanoseconds> pico_offset_;
356
James Kuszmaul5f27d8b2022-03-17 09:08:26 -0700357 ImuFailuresT imu_fault_tracker_;
358 std::optional<size_t> first_valid_data_counter_;
359 size_t total_imu_messages_received_ = 0;
360 size_t data_counter_offset_ = 0;
361 int last_data_counter_ = 0;
362
363 Eigen::Vector3d last_gyro_ = Eigen::Vector3d::Zero();
364
James Kuszmaul5ed29dd2022-02-13 18:32:06 -0800365 zeroing::UnwrapSensor left_encoder_;
366 zeroing::UnwrapSensor right_encoder_;
James Kuszmaul29c59522022-02-12 16:44:26 -0800367};
368} // namespace frc971::controls
James Kuszmaul51fa1ae2022-02-26 00:49:57 -0800369#endif // Y2022_LOCALIZER_LOCALIZER_H_