blob: f2cb50eea7420685c98f568b25959247ea9cc296 [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 Kuszmaul8c4f6592022-02-26 15:49:30 -080012#include "frc971/control_loops/drivetrain/improved_down_estimator.h"
James Kuszmaul29c59522022-02-12 16:44:26 -080013#include "frc971/control_loops/drivetrain/localizer_generated.h"
14#include "frc971/zeroing/imu_zeroer.h"
James Kuszmaul5ed29dd2022-02-13 18:32:06 -080015#include "frc971/zeroing/wrap.h"
James Kuszmaul8c4f6592022-02-26 15:49:30 -080016#include "y2022/control_loops/superstructure/superstructure_status_generated.h"
17#include "y2022/localizer/localizer_output_generated.h"
18#include "y2022/localizer/localizer_status_generated.h"
James Kuszmaul0dedb5e2022-03-05 16:02:20 -080019#include "y2022/localizer/localizer_visualization_generated.h"
James Kuszmaul8c4f6592022-02-26 15:49:30 -080020#include "y2022/vision/target_estimate_generated.h"
James Kuszmaul29c59522022-02-12 16:44:26 -080021
22namespace frc971::controls {
23
24namespace testing {
25class LocalizerTest;
26}
27
28// Localizer implementation that makes use of a 6-axis IMU, encoder readings,
29// drivetrain voltages, and camera returns to localize the robot. Meant to
30// be run on a raspberry pi.
31//
32// This operates on the principle that the drivetrain can be in one of two
33// modes:
34// 1) A "normal" mode where it is obeying the regular drivetrain model, with
35// minimal lateral motion and no major external disturbances. This is
36// referred to as the "model" mode in the code/variable names.
37// 2) An non-holonomic mode where the robot is just flying around on a 2-D
38// plane with no meaningful constraints (referred to as an "accel" model
39// in the code, because we rely primarily on the accelerometer readings).
40//
41// In order to determine which mode to be in, we attempt to track whether the
42// two models are diverging substantially. In order to do this, we maintain a
43// 1-second long queue of "branches". A branch is generated every X iterations
44// and contains a model state and an accel state. When the branch starts, the
45// two will have identical states. For the remaining 1 second, the model state
46// will evolve purely according to the drivetrian model, and the accel state
47// will evolve purely using IMU readings.
48//
49// When the branch reaches 1 second in age, we calculate a residual associated
50// with how much the accel and model based states diverged. If they have
51// diverged substantially, that implies that the model is a poor match for
52// whatever has been happening to the robot in the past second, so if we were
53// previously relying on the model, we will override the current "actual"
54// state with the branched accel state, and then continue to update the accel
55// state based on IMU readings.
56// If we are currently in the accel state, we will continue generating branches
57// until the branches stop diverging--this will indicate that the model
58// matches the accelerometer readings again, and so we will swap back to
59// the model-based state.
60//
61// TODO:
62// * Implement paying attention to camera readings.
63// * Tune for ADIS16505/real robot.
James Kuszmaul29c59522022-02-12 16:44:26 -080064class ModelBasedLocalizer {
65 public:
Milind Upadhyayd67e9cf2022-03-13 13:56:57 -070066 static constexpr size_t kNumPis = 4;
67
James Kuszmaul29c59522022-02-12 16:44:26 -080068 static constexpr size_t kX = 0;
69 static constexpr size_t kY = 1;
70 static constexpr size_t kTheta = 2;
71
72 static constexpr size_t kVelocityX = 3;
73 static constexpr size_t kVelocityY = 4;
74 static constexpr size_t kNAccelStates = 5;
75
76 static constexpr size_t kLeftEncoder = 3;
77 static constexpr size_t kLeftVelocity = 4;
78 static constexpr size_t kLeftVoltageError = 5;
79 static constexpr size_t kRightEncoder = 6;
80 static constexpr size_t kRightVelocity = 7;
81 static constexpr size_t kRightVoltageError = 8;
82 static constexpr size_t kNModelStates = 9;
83
84 static constexpr size_t kNModelOutputs = 3;
85
86 static constexpr size_t kNAccelOuputs = 1;
87
88 static constexpr size_t kAccelX = 0;
89 static constexpr size_t kAccelY = 1;
90 static constexpr size_t kThetaRate = 2;
91 static constexpr size_t kNAccelInputs = 3;
92
93 static constexpr size_t kLeftVoltage = 0;
94 static constexpr size_t kRightVoltage = 1;
95 static constexpr size_t kNModelInputs = 2;
96
James Kuszmaul93825a02022-02-13 16:50:33 -080097 // Branching period, in cycles.
James Kuszmaul5ed29dd2022-02-13 18:32:06 -080098 // Needs 10 to even stay alive, and still at ~96% CPU.
99 // ~20 gives ~55-60% CPU.
James Kuszmaul896b4ec2022-02-26 22:56:29 -0800100 static constexpr int kBranchPeriod = 100;
James Kuszmaul93825a02022-02-13 16:50:33 -0800101
James Kuszmaul0dedb5e2022-03-05 16:02:20 -0800102 static constexpr size_t kDebugBufferSize = 10;
103
James Kuszmaul29c59522022-02-12 16:44:26 -0800104 typedef Eigen::Matrix<double, kNModelStates, 1> ModelState;
105 typedef Eigen::Matrix<double, kNAccelStates, 1> AccelState;
106 typedef Eigen::Matrix<double, kNModelInputs, 1> ModelInput;
107 typedef Eigen::Matrix<double, kNAccelInputs, 1> AccelInput;
108
109 ModelBasedLocalizer(
110 const control_loops::drivetrain::DrivetrainConfig<double> &dt_config);
111 void HandleImu(aos::monotonic_clock::time_point t,
112 const Eigen::Vector3d &gyro, const Eigen::Vector3d &accel,
James Kuszmaul5a5a7832022-03-16 23:15:08 -0700113 const std::optional<Eigen::Vector2d> encoders,
114 const Eigen::Vector2d voltage);
James Kuszmaul8c4f6592022-02-26 15:49:30 -0800115 void HandleTurret(aos::monotonic_clock::time_point sample_time,
116 double turret_position, double turret_velocity);
117 void HandleImageMatch(aos::monotonic_clock::time_point sample_time,
James Kuszmaul0dedb5e2022-03-05 16:02:20 -0800118 const y2022::vision::TargetEstimate *target,
119 int camera_index);
James Kuszmaul29c59522022-02-12 16:44:26 -0800120 void HandleReset(aos::monotonic_clock::time_point,
121 const Eigen::Vector3d &xytheta);
122
123 flatbuffers::Offset<ModelBasedStatus> PopulateStatus(
124 flatbuffers::FlatBufferBuilder *fbb);
125
126 Eigen::Vector3d xytheta() const {
127 if (using_model_) {
128 return current_state_.model_state.block<3, 1>(0, 0);
129 } else {
130 return current_state_.accel_state.block<3, 1>(0, 0);
131 }
132 }
133
James Kuszmaul10d3fd42022-02-25 21:57:36 -0800134 Eigen::Quaterniond orientation() const { return last_orientation_; }
135
James Kuszmaul29c59522022-02-12 16:44:26 -0800136 AccelState accel_state() const { return current_state_.accel_state; };
137
James Kuszmaul5ed29dd2022-02-13 18:32:06 -0800138 void set_longitudinal_offset(double offset) { long_offset_ = offset; }
139
James Kuszmaul0dedb5e2022-03-05 16:02:20 -0800140 void TallyRejection(const RejectionReason reason);
141
142 flatbuffers::Offset<LocalizerVisualization> PopulateVisualization(
143 flatbuffers::FlatBufferBuilder *fbb);
144
145 size_t NumQueuedImageDebugs() const { return image_debugs_.size(); }
James Kuszmaul8c4f6592022-02-26 15:49:30 -0800146
Milind Upadhyayd67e9cf2022-03-13 13:56:57 -0700147 std::array<LedOutput, kNumPis> led_outputs() const { return led_outputs_; }
148
James Kuszmaul29c59522022-02-12 16:44:26 -0800149 private:
150 struct CombinedState {
James Kuszmaul8c4f6592022-02-26 15:49:30 -0800151 AccelState accel_state = AccelState::Zero();
152 ModelState model_state = ModelState::Zero();
153 aos::monotonic_clock::time_point branch_time =
154 aos::monotonic_clock::min_time;
155 double accumulated_divergence = 0.0;
156 };
157
158 // Struct to store state data needed to perform a camera correction, since
159 // camera corrections require looking back in time.
160 struct OldPosition {
161 aos::monotonic_clock::time_point sample_time =
162 aos::monotonic_clock::min_time;
163 Eigen::Vector3d xytheta = Eigen::Vector3d::Zero();
164 double turret_position = 0.0;
165 double turret_velocity = 0.0;
James Kuszmaul29c59522022-02-12 16:44:26 -0800166 };
167
168 static flatbuffers::Offset<AccelBasedState> BuildAccelState(
169 flatbuffers::FlatBufferBuilder *fbb, const AccelState &state);
170
171 static flatbuffers::Offset<ModelBasedState> BuildModelState(
172 flatbuffers::FlatBufferBuilder *fbb, const ModelState &state);
173
174 Eigen::Matrix<double, kNModelStates, kNModelStates> AModel(
175 const ModelState &state) const;
176 Eigen::Matrix<double, kNAccelStates, kNAccelStates> AAccel() const;
177 ModelState DiffModel(const ModelState &state, const ModelInput &U) const;
178 AccelState DiffAccel(const AccelState &state, const AccelInput &U) const;
179
180 ModelState UpdateModel(const ModelState &model, const ModelInput &input,
181 aos::monotonic_clock::duration dt) const;
182 AccelState UpdateAccel(const AccelState &accel, const AccelInput &input,
183 aos::monotonic_clock::duration dt) const;
184
185 AccelState AccelStateForModelState(const ModelState &state) const;
186 ModelState ModelStateForAccelState(const AccelState &state,
187 const Eigen::Vector2d &encoders,
188 const double yaw_rate) const;
189 double ModelDivergence(const CombinedState &state,
190 const AccelInput &accel_inputs,
191 const Eigen::Vector2d &filtered_accel,
192 const ModelInput &model_inputs);
James Kuszmaul5ed29dd2022-02-13 18:32:06 -0800193 void UpdateState(
194 CombinedState *state,
195 const Eigen::Matrix<double, kNModelStates, kNModelOutputs> &K,
196 const Eigen::Matrix<double, kNModelOutputs, 1> &Z,
197 const Eigen::Matrix<double, kNModelOutputs, kNModelStates> &H,
198 const AccelInput &accel_input, const ModelInput &model_input,
199 aos::monotonic_clock::duration dt);
James Kuszmaul29c59522022-02-12 16:44:26 -0800200
James Kuszmaul8c4f6592022-02-26 15:49:30 -0800201 const OldPosition GetStateForTime(aos::monotonic_clock::time_point time);
202
203 // Returns the transformation to get from the camera frame to the robot frame
204 // for the specified state.
205 const Eigen::Matrix<double, 4, 4> CameraTransform(
206 const OldPosition &state,
207 const frc971::vision::calibration::CameraCalibration *calibration,
208 std::optional<RejectionReason> *rejection_reason) const;
209
210 // Returns the robot x/y position implied by the specified camera data and
211 // estimated state from that time.
James Kuszmaul0dedb5e2022-03-05 16:02:20 -0800212 // H_field_camera is passed in so that it can be used as a debugging output.
James Kuszmaul8c4f6592022-02-26 15:49:30 -0800213 const std::optional<Eigen::Vector2d> CameraMeasuredRobotPosition(
214 const OldPosition &state, const y2022::vision::TargetEstimate *target,
James Kuszmaul0dedb5e2022-03-05 16:02:20 -0800215 std::optional<RejectionReason> *rejection_reason,
216 Eigen::Matrix<double, 4, 4> *H_field_camera_measured) const;
217
218 flatbuffers::Offset<TargetEstimateDebug> PackTargetEstimateDebug(
219 const TargetEstimateDebugT &debug, flatbuffers::FlatBufferBuilder *fbb);
220
221 flatbuffers::Offset<CumulativeStatistics> PopulateStatistics(
222 flatbuffers::FlatBufferBuilder *fbb);
James Kuszmaul8c4f6592022-02-26 15:49:30 -0800223
James Kuszmaul29c59522022-02-12 16:44:26 -0800224 const control_loops::drivetrain::DrivetrainConfig<double> dt_config_;
225 const StateFeedbackHybridPlantCoefficients<2, 2, 2, double>
226 velocity_drivetrain_coefficients_;
227 Eigen::Matrix<double, kNModelStates, kNModelStates> A_continuous_model_;
228 Eigen::Matrix<double, kNAccelStates, kNAccelStates> A_continuous_accel_;
James Kuszmaul8c4f6592022-02-26 15:49:30 -0800229 Eigen::Matrix<double, kNAccelStates, kNAccelStates> A_discrete_accel_;
James Kuszmaul29c59522022-02-12 16:44:26 -0800230 Eigen::Matrix<double, kNModelStates, kNModelInputs> B_continuous_model_;
231 Eigen::Matrix<double, kNAccelStates, kNAccelInputs> B_continuous_accel_;
232
233 Eigen::Matrix<double, kNModelStates, kNModelStates> Q_continuous_model_;
234
235 Eigen::Matrix<double, kNModelStates, kNModelStates> P_model_;
James Kuszmaul8c4f6592022-02-26 15:49:30 -0800236
237 Eigen::Matrix<double, kNAccelStates, kNAccelStates> Q_continuous_accel_;
238 Eigen::Matrix<double, kNAccelStates, kNAccelStates> Q_discrete_accel_;
239
240 Eigen::Matrix<double, kNAccelStates, kNAccelStates> P_accel_;
241
242 control_loops::drivetrain::DrivetrainUkf down_estimator_;
243
James Kuszmaul29c59522022-02-12 16:44:26 -0800244 // When we are following the model, we will, on each iteration:
245 // 1) Perform a model-based update of a single state.
246 // 2) Add a hypothetical non-model-based entry based on the current state.
247 // 3) Evict too-old non-model-based entries.
James Kuszmaul29c59522022-02-12 16:44:26 -0800248
249 // Buffer of old branches these are all created by initializing a new
250 // model-based state based on the current state, and then initializing a new
251 // accel-based state on top of that new model-based state (to eliminate the
252 // impact of any lateral motion).
253 // We then integrate up all of these states and observe how much the model and
254 // accel based states of each branch compare to one another.
James Kuszmaul93825a02022-02-13 16:50:33 -0800255 aos::RingBuffer<CombinedState, 2000 / kBranchPeriod> branches_;
256 int branch_counter_ = 0;
James Kuszmaul29c59522022-02-12 16:44:26 -0800257
James Kuszmaul8c4f6592022-02-26 15:49:30 -0800258 // Buffer of old x/y/theta positions. This is used so that we can have a
259 // reference for exactly where we thought a camera was when it took an image.
260 aos::RingBuffer<OldPosition, 500 / kBranchPeriod> old_positions_;
261
James Kuszmaul29c59522022-02-12 16:44:26 -0800262 CombinedState current_state_;
263 aos::monotonic_clock::time_point t_ = aos::monotonic_clock::min_time;
264 bool using_model_;
265
James Kuszmaul5ed29dd2022-02-13 18:32:06 -0800266 // X position of the IMU, in meters. 0 = center of robot, positive = ahead of
267 // center, negative = behind center.
268 double long_offset_ = -0.15;
269
James Kuszmaul29c59522022-02-12 16:44:26 -0800270 double last_residual_ = 0.0;
271 double filtered_residual_ = 0.0;
272 Eigen::Vector2d filtered_residual_accel_ = Eigen::Vector2d::Zero();
273 Eigen::Vector3d abs_accel_ = Eigen::Vector3d::Zero();
274 double velocity_residual_ = 0.0;
275 double accel_residual_ = 0.0;
276 double theta_rate_residual_ = 0.0;
277 int hysteresis_count_ = 0;
James Kuszmaul10d3fd42022-02-25 21:57:36 -0800278 Eigen::Quaterniond last_orientation_ = Eigen::Quaterniond::Identity();
James Kuszmaul29c59522022-02-12 16:44:26 -0800279
280 int clock_resets_ = 0;
281
James Kuszmaul8c4f6592022-02-26 15:49:30 -0800282 std::optional<aos::monotonic_clock::time_point> last_turret_update_;
283 double latest_turret_position_ = 0.0;
284 double latest_turret_velocity_ = 0.0;
285
286 // Stuff to track faults.
287 static constexpr size_t kNumRejectionReasons =
288 static_cast<int>(RejectionReason::MAX) -
289 static_cast<int>(RejectionReason::MIN) + 1;
290
291 struct Statistics {
292 int total_accepted = 0;
293 int total_candidates = 0;
294 static_assert(0 == static_cast<int>(RejectionReason::MIN));
295 static_assert(
296 kNumRejectionReasons ==
297 sizeof(
298 std::invoke_result<decltype(EnumValuesRejectionReason)>::type) /
299 sizeof(RejectionReason),
300 "RejectionReason has non-contiguous error values.");
301 std::array<int, kNumRejectionReasons> rejection_counts;
302 };
303 Statistics statistics_;
304
James Kuszmaul0dedb5e2022-03-05 16:02:20 -0800305 aos::SizedArray<TargetEstimateDebugT, kDebugBufferSize> image_debugs_;
Milind Upadhyayd67e9cf2022-03-13 13:56:57 -0700306 std::array<LedOutput, kNumPis> led_outputs_;
James Kuszmaul0dedb5e2022-03-05 16:02:20 -0800307
James Kuszmaul29c59522022-02-12 16:44:26 -0800308 friend class testing::LocalizerTest;
309};
310
311class EventLoopLocalizer {
312 public:
James Kuszmaul0dedb5e2022-03-05 16:02:20 -0800313 static constexpr std::chrono::milliseconds kMinVisualizationPeriod{100};
314
James Kuszmaul29c59522022-02-12 16:44:26 -0800315 EventLoopLocalizer(
316 aos::EventLoop *event_loop,
317 const control_loops::drivetrain::DrivetrainConfig<double> &dt_config);
318
James Kuszmaul5ed29dd2022-02-13 18:32:06 -0800319 ModelBasedLocalizer *localizer() { return &model_based_; }
320
James Kuszmaul29c59522022-02-12 16:44:26 -0800321 private:
James Kuszmaul8c4f6592022-02-26 15:49:30 -0800322 std::optional<aos::monotonic_clock::duration> ClockOffset(
323 std::string_view pi);
James Kuszmaul29c59522022-02-12 16:44:26 -0800324 aos::EventLoop *event_loop_;
James Kuszmaul6d6e1302022-03-12 15:22:48 -0800325 const control_loops::drivetrain::DrivetrainConfig<double> &dt_config_;
James Kuszmaul29c59522022-02-12 16:44:26 -0800326 ModelBasedLocalizer model_based_;
327 aos::Sender<LocalizerStatus> status_sender_;
328 aos::Sender<LocalizerOutput> output_sender_;
James Kuszmaul0dedb5e2022-03-05 16:02:20 -0800329 aos::Sender<LocalizerVisualization> visualization_sender_;
James Kuszmaul29c59522022-02-12 16:44:26 -0800330 aos::Fetcher<frc971::control_loops::drivetrain::Output> output_fetcher_;
James Kuszmaul8c4f6592022-02-26 15:49:30 -0800331 aos::Fetcher<aos::message_bridge::ServerStatistics> clock_offset_fetcher_;
Milind Upadhyayd67e9cf2022-03-13 13:56:57 -0700332 std::array<aos::Fetcher<y2022::vision::TargetEstimate>,
333 ModelBasedLocalizer::kNumPis>
James Kuszmaul2b2f8772022-03-12 15:25:35 -0800334 target_estimate_fetchers_;
335 aos::Fetcher<y2022::control_loops::superstructure::Status>
336 superstructure_fetcher_;
James Kuszmaul29c59522022-02-12 16:44:26 -0800337 zeroing::ImuZeroer zeroer_;
338 aos::monotonic_clock::time_point last_output_send_ =
339 aos::monotonic_clock::min_time;
James Kuszmaul0dedb5e2022-03-05 16:02:20 -0800340 aos::monotonic_clock::time_point last_visualization_send_ =
341 aos::monotonic_clock::min_time;
James Kuszmaul5ed29dd2022-02-13 18:32:06 -0800342 std::optional<aos::monotonic_clock::time_point> last_pico_timestamp_;
343 aos::monotonic_clock::duration pico_offset_error_;
344 // t = pico_offset_ + pico_timestamp.
345 // Note that this can drift over sufficiently long time periods!
346 std::optional<std::chrono::nanoseconds> pico_offset_;
347
348 zeroing::UnwrapSensor left_encoder_;
349 zeroing::UnwrapSensor right_encoder_;
James Kuszmaul29c59522022-02-12 16:44:26 -0800350};
351} // namespace frc971::controls
James Kuszmaul51fa1ae2022-02-26 00:49:57 -0800352#endif // Y2022_LOCALIZER_LOCALIZER_H_