blob: c19bf053ee6ef318b99b741f84d7ad95aeba01e4 [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:
66 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,
111 const Eigen::Vector2d encoders, const Eigen::Vector2d voltage);
James Kuszmaul8c4f6592022-02-26 15:49:30 -0800112 void HandleTurret(aos::monotonic_clock::time_point sample_time,
113 double turret_position, double turret_velocity);
114 void HandleImageMatch(aos::monotonic_clock::time_point sample_time,
James Kuszmaul0dedb5e2022-03-05 16:02:20 -0800115 const y2022::vision::TargetEstimate *target,
116 int camera_index);
James Kuszmaul29c59522022-02-12 16:44:26 -0800117 void HandleReset(aos::monotonic_clock::time_point,
118 const Eigen::Vector3d &xytheta);
119
120 flatbuffers::Offset<ModelBasedStatus> PopulateStatus(
121 flatbuffers::FlatBufferBuilder *fbb);
122
123 Eigen::Vector3d xytheta() const {
124 if (using_model_) {
125 return current_state_.model_state.block<3, 1>(0, 0);
126 } else {
127 return current_state_.accel_state.block<3, 1>(0, 0);
128 }
129 }
130
James Kuszmaul10d3fd42022-02-25 21:57:36 -0800131 Eigen::Quaterniond orientation() const { return last_orientation_; }
132
James Kuszmaul29c59522022-02-12 16:44:26 -0800133 AccelState accel_state() const { return current_state_.accel_state; };
134
James Kuszmaul5ed29dd2022-02-13 18:32:06 -0800135 void set_longitudinal_offset(double offset) { long_offset_ = offset; }
136
James Kuszmaul0dedb5e2022-03-05 16:02:20 -0800137 void TallyRejection(const RejectionReason reason);
138
139 flatbuffers::Offset<LocalizerVisualization> PopulateVisualization(
140 flatbuffers::FlatBufferBuilder *fbb);
141
142 size_t NumQueuedImageDebugs() const { return image_debugs_.size(); }
James Kuszmaul8c4f6592022-02-26 15:49:30 -0800143
James Kuszmaul29c59522022-02-12 16:44:26 -0800144 private:
145 struct CombinedState {
James Kuszmaul8c4f6592022-02-26 15:49:30 -0800146 AccelState accel_state = AccelState::Zero();
147 ModelState model_state = ModelState::Zero();
148 aos::monotonic_clock::time_point branch_time =
149 aos::monotonic_clock::min_time;
150 double accumulated_divergence = 0.0;
151 };
152
153 // Struct to store state data needed to perform a camera correction, since
154 // camera corrections require looking back in time.
155 struct OldPosition {
156 aos::monotonic_clock::time_point sample_time =
157 aos::monotonic_clock::min_time;
158 Eigen::Vector3d xytheta = Eigen::Vector3d::Zero();
159 double turret_position = 0.0;
160 double turret_velocity = 0.0;
James Kuszmaul29c59522022-02-12 16:44:26 -0800161 };
162
163 static flatbuffers::Offset<AccelBasedState> BuildAccelState(
164 flatbuffers::FlatBufferBuilder *fbb, const AccelState &state);
165
166 static flatbuffers::Offset<ModelBasedState> BuildModelState(
167 flatbuffers::FlatBufferBuilder *fbb, const ModelState &state);
168
169 Eigen::Matrix<double, kNModelStates, kNModelStates> AModel(
170 const ModelState &state) const;
171 Eigen::Matrix<double, kNAccelStates, kNAccelStates> AAccel() const;
172 ModelState DiffModel(const ModelState &state, const ModelInput &U) const;
173 AccelState DiffAccel(const AccelState &state, const AccelInput &U) const;
174
175 ModelState UpdateModel(const ModelState &model, const ModelInput &input,
176 aos::monotonic_clock::duration dt) const;
177 AccelState UpdateAccel(const AccelState &accel, const AccelInput &input,
178 aos::monotonic_clock::duration dt) const;
179
180 AccelState AccelStateForModelState(const ModelState &state) const;
181 ModelState ModelStateForAccelState(const AccelState &state,
182 const Eigen::Vector2d &encoders,
183 const double yaw_rate) const;
184 double ModelDivergence(const CombinedState &state,
185 const AccelInput &accel_inputs,
186 const Eigen::Vector2d &filtered_accel,
187 const ModelInput &model_inputs);
James Kuszmaul5ed29dd2022-02-13 18:32:06 -0800188 void UpdateState(
189 CombinedState *state,
190 const Eigen::Matrix<double, kNModelStates, kNModelOutputs> &K,
191 const Eigen::Matrix<double, kNModelOutputs, 1> &Z,
192 const Eigen::Matrix<double, kNModelOutputs, kNModelStates> &H,
193 const AccelInput &accel_input, const ModelInput &model_input,
194 aos::monotonic_clock::duration dt);
James Kuszmaul29c59522022-02-12 16:44:26 -0800195
James Kuszmaul8c4f6592022-02-26 15:49:30 -0800196 const OldPosition GetStateForTime(aos::monotonic_clock::time_point time);
197
198 // Returns the transformation to get from the camera frame to the robot frame
199 // for the specified state.
200 const Eigen::Matrix<double, 4, 4> CameraTransform(
201 const OldPosition &state,
202 const frc971::vision::calibration::CameraCalibration *calibration,
203 std::optional<RejectionReason> *rejection_reason) const;
204
205 // Returns the robot x/y position implied by the specified camera data and
206 // estimated state from that time.
James Kuszmaul0dedb5e2022-03-05 16:02:20 -0800207 // H_field_camera is passed in so that it can be used as a debugging output.
James Kuszmaul8c4f6592022-02-26 15:49:30 -0800208 const std::optional<Eigen::Vector2d> CameraMeasuredRobotPosition(
209 const OldPosition &state, const y2022::vision::TargetEstimate *target,
James Kuszmaul0dedb5e2022-03-05 16:02:20 -0800210 std::optional<RejectionReason> *rejection_reason,
211 Eigen::Matrix<double, 4, 4> *H_field_camera_measured) const;
212
213 flatbuffers::Offset<TargetEstimateDebug> PackTargetEstimateDebug(
214 const TargetEstimateDebugT &debug, flatbuffers::FlatBufferBuilder *fbb);
215
216 flatbuffers::Offset<CumulativeStatistics> PopulateStatistics(
217 flatbuffers::FlatBufferBuilder *fbb);
James Kuszmaul8c4f6592022-02-26 15:49:30 -0800218
James Kuszmaul29c59522022-02-12 16:44:26 -0800219 const control_loops::drivetrain::DrivetrainConfig<double> dt_config_;
220 const StateFeedbackHybridPlantCoefficients<2, 2, 2, double>
221 velocity_drivetrain_coefficients_;
222 Eigen::Matrix<double, kNModelStates, kNModelStates> A_continuous_model_;
223 Eigen::Matrix<double, kNAccelStates, kNAccelStates> A_continuous_accel_;
James Kuszmaul8c4f6592022-02-26 15:49:30 -0800224 Eigen::Matrix<double, kNAccelStates, kNAccelStates> A_discrete_accel_;
James Kuszmaul29c59522022-02-12 16:44:26 -0800225 Eigen::Matrix<double, kNModelStates, kNModelInputs> B_continuous_model_;
226 Eigen::Matrix<double, kNAccelStates, kNAccelInputs> B_continuous_accel_;
227
228 Eigen::Matrix<double, kNModelStates, kNModelStates> Q_continuous_model_;
229
230 Eigen::Matrix<double, kNModelStates, kNModelStates> P_model_;
James Kuszmaul8c4f6592022-02-26 15:49:30 -0800231
232 Eigen::Matrix<double, kNAccelStates, kNAccelStates> Q_continuous_accel_;
233 Eigen::Matrix<double, kNAccelStates, kNAccelStates> Q_discrete_accel_;
234
235 Eigen::Matrix<double, kNAccelStates, kNAccelStates> P_accel_;
236
237 control_loops::drivetrain::DrivetrainUkf down_estimator_;
238
James Kuszmaul29c59522022-02-12 16:44:26 -0800239 // When we are following the model, we will, on each iteration:
240 // 1) Perform a model-based update of a single state.
241 // 2) Add a hypothetical non-model-based entry based on the current state.
242 // 3) Evict too-old non-model-based entries.
James Kuszmaul29c59522022-02-12 16:44:26 -0800243
244 // Buffer of old branches these are all created by initializing a new
245 // model-based state based on the current state, and then initializing a new
246 // accel-based state on top of that new model-based state (to eliminate the
247 // impact of any lateral motion).
248 // We then integrate up all of these states and observe how much the model and
249 // accel based states of each branch compare to one another.
James Kuszmaul93825a02022-02-13 16:50:33 -0800250 aos::RingBuffer<CombinedState, 2000 / kBranchPeriod> branches_;
251 int branch_counter_ = 0;
James Kuszmaul29c59522022-02-12 16:44:26 -0800252
James Kuszmaul8c4f6592022-02-26 15:49:30 -0800253 // Buffer of old x/y/theta positions. This is used so that we can have a
254 // reference for exactly where we thought a camera was when it took an image.
255 aos::RingBuffer<OldPosition, 500 / kBranchPeriod> old_positions_;
256
James Kuszmaul29c59522022-02-12 16:44:26 -0800257 CombinedState current_state_;
258 aos::monotonic_clock::time_point t_ = aos::monotonic_clock::min_time;
259 bool using_model_;
260
James Kuszmaul5ed29dd2022-02-13 18:32:06 -0800261 // X position of the IMU, in meters. 0 = center of robot, positive = ahead of
262 // center, negative = behind center.
263 double long_offset_ = -0.15;
264
James Kuszmaul29c59522022-02-12 16:44:26 -0800265 double last_residual_ = 0.0;
266 double filtered_residual_ = 0.0;
267 Eigen::Vector2d filtered_residual_accel_ = Eigen::Vector2d::Zero();
268 Eigen::Vector3d abs_accel_ = Eigen::Vector3d::Zero();
269 double velocity_residual_ = 0.0;
270 double accel_residual_ = 0.0;
271 double theta_rate_residual_ = 0.0;
272 int hysteresis_count_ = 0;
James Kuszmaul10d3fd42022-02-25 21:57:36 -0800273 Eigen::Quaterniond last_orientation_ = Eigen::Quaterniond::Identity();
James Kuszmaul29c59522022-02-12 16:44:26 -0800274
275 int clock_resets_ = 0;
276
James Kuszmaul8c4f6592022-02-26 15:49:30 -0800277 std::optional<aos::monotonic_clock::time_point> last_turret_update_;
278 double latest_turret_position_ = 0.0;
279 double latest_turret_velocity_ = 0.0;
280
281 // Stuff to track faults.
282 static constexpr size_t kNumRejectionReasons =
283 static_cast<int>(RejectionReason::MAX) -
284 static_cast<int>(RejectionReason::MIN) + 1;
285
286 struct Statistics {
287 int total_accepted = 0;
288 int total_candidates = 0;
289 static_assert(0 == static_cast<int>(RejectionReason::MIN));
290 static_assert(
291 kNumRejectionReasons ==
292 sizeof(
293 std::invoke_result<decltype(EnumValuesRejectionReason)>::type) /
294 sizeof(RejectionReason),
295 "RejectionReason has non-contiguous error values.");
296 std::array<int, kNumRejectionReasons> rejection_counts;
297 };
298 Statistics statistics_;
299
James Kuszmaul0dedb5e2022-03-05 16:02:20 -0800300 aos::SizedArray<TargetEstimateDebugT, kDebugBufferSize> image_debugs_;
301
James Kuszmaul29c59522022-02-12 16:44:26 -0800302 friend class testing::LocalizerTest;
303};
304
305class EventLoopLocalizer {
306 public:
James Kuszmaul0dedb5e2022-03-05 16:02:20 -0800307 static constexpr std::chrono::milliseconds kMinVisualizationPeriod{100};
308
James Kuszmaul29c59522022-02-12 16:44:26 -0800309 EventLoopLocalizer(
310 aos::EventLoop *event_loop,
311 const control_loops::drivetrain::DrivetrainConfig<double> &dt_config);
312
James Kuszmaul5ed29dd2022-02-13 18:32:06 -0800313 ModelBasedLocalizer *localizer() { return &model_based_; }
314
James Kuszmaul29c59522022-02-12 16:44:26 -0800315 private:
James Kuszmaul8c4f6592022-02-26 15:49:30 -0800316 std::optional<aos::monotonic_clock::duration> ClockOffset(
317 std::string_view pi);
James Kuszmaul29c59522022-02-12 16:44:26 -0800318 aos::EventLoop *event_loop_;
319 ModelBasedLocalizer model_based_;
320 aos::Sender<LocalizerStatus> status_sender_;
321 aos::Sender<LocalizerOutput> output_sender_;
James Kuszmaul0dedb5e2022-03-05 16:02:20 -0800322 aos::Sender<LocalizerVisualization> visualization_sender_;
James Kuszmaul29c59522022-02-12 16:44:26 -0800323 aos::Fetcher<frc971::control_loops::drivetrain::Output> output_fetcher_;
James Kuszmaul8c4f6592022-02-26 15:49:30 -0800324 aos::Fetcher<aos::message_bridge::ServerStatistics> clock_offset_fetcher_;
James Kuszmaul2b2f8772022-03-12 15:25:35 -0800325 std::array<aos::Fetcher<y2022::vision::TargetEstimate>, 4>
326 target_estimate_fetchers_;
327 aos::Fetcher<y2022::control_loops::superstructure::Status>
328 superstructure_fetcher_;
James Kuszmaul29c59522022-02-12 16:44:26 -0800329 zeroing::ImuZeroer zeroer_;
330 aos::monotonic_clock::time_point last_output_send_ =
331 aos::monotonic_clock::min_time;
James Kuszmaul0dedb5e2022-03-05 16:02:20 -0800332 aos::monotonic_clock::time_point last_visualization_send_ =
333 aos::monotonic_clock::min_time;
James Kuszmaul5ed29dd2022-02-13 18:32:06 -0800334 std::optional<aos::monotonic_clock::time_point> last_pico_timestamp_;
335 aos::monotonic_clock::duration pico_offset_error_;
336 // t = pico_offset_ + pico_timestamp.
337 // Note that this can drift over sufficiently long time periods!
338 std::optional<std::chrono::nanoseconds> pico_offset_;
339
340 zeroing::UnwrapSensor left_encoder_;
341 zeroing::UnwrapSensor right_encoder_;
James Kuszmaul29c59522022-02-12 16:44:26 -0800342};
343} // namespace frc971::controls
James Kuszmaul51fa1ae2022-02-26 00:49:57 -0800344#endif // Y2022_LOCALIZER_LOCALIZER_H_