blob: e9a61e18ae8f2d75917972d66aa12bf85a8b9ec3 [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,
113 const Eigen::Vector2d encoders, const Eigen::Vector2d voltage);
James Kuszmaul8c4f6592022-02-26 15:49:30 -0800114 void HandleTurret(aos::monotonic_clock::time_point sample_time,
115 double turret_position, double turret_velocity);
116 void HandleImageMatch(aos::monotonic_clock::time_point sample_time,
James Kuszmaul0dedb5e2022-03-05 16:02:20 -0800117 const y2022::vision::TargetEstimate *target,
118 int camera_index);
James Kuszmaul29c59522022-02-12 16:44:26 -0800119 void HandleReset(aos::monotonic_clock::time_point,
120 const Eigen::Vector3d &xytheta);
121
122 flatbuffers::Offset<ModelBasedStatus> PopulateStatus(
123 flatbuffers::FlatBufferBuilder *fbb);
124
125 Eigen::Vector3d xytheta() const {
126 if (using_model_) {
127 return current_state_.model_state.block<3, 1>(0, 0);
128 } else {
129 return current_state_.accel_state.block<3, 1>(0, 0);
130 }
131 }
132
James Kuszmaul10d3fd42022-02-25 21:57:36 -0800133 Eigen::Quaterniond orientation() const { return last_orientation_; }
134
James Kuszmaul29c59522022-02-12 16:44:26 -0800135 AccelState accel_state() const { return current_state_.accel_state; };
136
James Kuszmaul5ed29dd2022-02-13 18:32:06 -0800137 void set_longitudinal_offset(double offset) { long_offset_ = offset; }
138
James Kuszmaul0dedb5e2022-03-05 16:02:20 -0800139 void TallyRejection(const RejectionReason reason);
140
141 flatbuffers::Offset<LocalizerVisualization> PopulateVisualization(
142 flatbuffers::FlatBufferBuilder *fbb);
143
144 size_t NumQueuedImageDebugs() const { return image_debugs_.size(); }
James Kuszmaul8c4f6592022-02-26 15:49:30 -0800145
Milind Upadhyayd67e9cf2022-03-13 13:56:57 -0700146 std::array<LedOutput, kNumPis> led_outputs() const { return led_outputs_; }
147
James Kuszmaul29c59522022-02-12 16:44:26 -0800148 private:
149 struct CombinedState {
James Kuszmaul8c4f6592022-02-26 15:49:30 -0800150 AccelState accel_state = AccelState::Zero();
151 ModelState model_state = ModelState::Zero();
152 aos::monotonic_clock::time_point branch_time =
153 aos::monotonic_clock::min_time;
154 double accumulated_divergence = 0.0;
155 };
156
157 // Struct to store state data needed to perform a camera correction, since
158 // camera corrections require looking back in time.
159 struct OldPosition {
160 aos::monotonic_clock::time_point sample_time =
161 aos::monotonic_clock::min_time;
162 Eigen::Vector3d xytheta = Eigen::Vector3d::Zero();
163 double turret_position = 0.0;
164 double turret_velocity = 0.0;
James Kuszmaul29c59522022-02-12 16:44:26 -0800165 };
166
167 static flatbuffers::Offset<AccelBasedState> BuildAccelState(
168 flatbuffers::FlatBufferBuilder *fbb, const AccelState &state);
169
170 static flatbuffers::Offset<ModelBasedState> BuildModelState(
171 flatbuffers::FlatBufferBuilder *fbb, const ModelState &state);
172
173 Eigen::Matrix<double, kNModelStates, kNModelStates> AModel(
174 const ModelState &state) const;
175 Eigen::Matrix<double, kNAccelStates, kNAccelStates> AAccel() const;
176 ModelState DiffModel(const ModelState &state, const ModelInput &U) const;
177 AccelState DiffAccel(const AccelState &state, const AccelInput &U) const;
178
179 ModelState UpdateModel(const ModelState &model, const ModelInput &input,
180 aos::monotonic_clock::duration dt) const;
181 AccelState UpdateAccel(const AccelState &accel, const AccelInput &input,
182 aos::monotonic_clock::duration dt) const;
183
184 AccelState AccelStateForModelState(const ModelState &state) const;
185 ModelState ModelStateForAccelState(const AccelState &state,
186 const Eigen::Vector2d &encoders,
187 const double yaw_rate) const;
188 double ModelDivergence(const CombinedState &state,
189 const AccelInput &accel_inputs,
190 const Eigen::Vector2d &filtered_accel,
191 const ModelInput &model_inputs);
James Kuszmaul5ed29dd2022-02-13 18:32:06 -0800192 void UpdateState(
193 CombinedState *state,
194 const Eigen::Matrix<double, kNModelStates, kNModelOutputs> &K,
195 const Eigen::Matrix<double, kNModelOutputs, 1> &Z,
196 const Eigen::Matrix<double, kNModelOutputs, kNModelStates> &H,
197 const AccelInput &accel_input, const ModelInput &model_input,
198 aos::monotonic_clock::duration dt);
James Kuszmaul29c59522022-02-12 16:44:26 -0800199
James Kuszmaul8c4f6592022-02-26 15:49:30 -0800200 const OldPosition GetStateForTime(aos::monotonic_clock::time_point time);
201
202 // Returns the transformation to get from the camera frame to the robot frame
203 // for the specified state.
204 const Eigen::Matrix<double, 4, 4> CameraTransform(
205 const OldPosition &state,
206 const frc971::vision::calibration::CameraCalibration *calibration,
207 std::optional<RejectionReason> *rejection_reason) const;
208
209 // Returns the robot x/y position implied by the specified camera data and
210 // estimated state from that time.
James Kuszmaul0dedb5e2022-03-05 16:02:20 -0800211 // H_field_camera is passed in so that it can be used as a debugging output.
James Kuszmaul8c4f6592022-02-26 15:49:30 -0800212 const std::optional<Eigen::Vector2d> CameraMeasuredRobotPosition(
213 const OldPosition &state, const y2022::vision::TargetEstimate *target,
James Kuszmaul0dedb5e2022-03-05 16:02:20 -0800214 std::optional<RejectionReason> *rejection_reason,
215 Eigen::Matrix<double, 4, 4> *H_field_camera_measured) const;
216
217 flatbuffers::Offset<TargetEstimateDebug> PackTargetEstimateDebug(
218 const TargetEstimateDebugT &debug, flatbuffers::FlatBufferBuilder *fbb);
219
220 flatbuffers::Offset<CumulativeStatistics> PopulateStatistics(
221 flatbuffers::FlatBufferBuilder *fbb);
James Kuszmaul8c4f6592022-02-26 15:49:30 -0800222
James Kuszmaul29c59522022-02-12 16:44:26 -0800223 const control_loops::drivetrain::DrivetrainConfig<double> dt_config_;
224 const StateFeedbackHybridPlantCoefficients<2, 2, 2, double>
225 velocity_drivetrain_coefficients_;
226 Eigen::Matrix<double, kNModelStates, kNModelStates> A_continuous_model_;
227 Eigen::Matrix<double, kNAccelStates, kNAccelStates> A_continuous_accel_;
James Kuszmaul8c4f6592022-02-26 15:49:30 -0800228 Eigen::Matrix<double, kNAccelStates, kNAccelStates> A_discrete_accel_;
James Kuszmaul29c59522022-02-12 16:44:26 -0800229 Eigen::Matrix<double, kNModelStates, kNModelInputs> B_continuous_model_;
230 Eigen::Matrix<double, kNAccelStates, kNAccelInputs> B_continuous_accel_;
231
232 Eigen::Matrix<double, kNModelStates, kNModelStates> Q_continuous_model_;
233
234 Eigen::Matrix<double, kNModelStates, kNModelStates> P_model_;
James Kuszmaul8c4f6592022-02-26 15:49:30 -0800235
236 Eigen::Matrix<double, kNAccelStates, kNAccelStates> Q_continuous_accel_;
237 Eigen::Matrix<double, kNAccelStates, kNAccelStates> Q_discrete_accel_;
238
239 Eigen::Matrix<double, kNAccelStates, kNAccelStates> P_accel_;
240
241 control_loops::drivetrain::DrivetrainUkf down_estimator_;
242
James Kuszmaul29c59522022-02-12 16:44:26 -0800243 // When we are following the model, we will, on each iteration:
244 // 1) Perform a model-based update of a single state.
245 // 2) Add a hypothetical non-model-based entry based on the current state.
246 // 3) Evict too-old non-model-based entries.
James Kuszmaul29c59522022-02-12 16:44:26 -0800247
248 // Buffer of old branches these are all created by initializing a new
249 // model-based state based on the current state, and then initializing a new
250 // accel-based state on top of that new model-based state (to eliminate the
251 // impact of any lateral motion).
252 // We then integrate up all of these states and observe how much the model and
253 // accel based states of each branch compare to one another.
James Kuszmaul93825a02022-02-13 16:50:33 -0800254 aos::RingBuffer<CombinedState, 2000 / kBranchPeriod> branches_;
255 int branch_counter_ = 0;
James Kuszmaul29c59522022-02-12 16:44:26 -0800256
James Kuszmaul8c4f6592022-02-26 15:49:30 -0800257 // Buffer of old x/y/theta positions. This is used so that we can have a
258 // reference for exactly where we thought a camera was when it took an image.
259 aos::RingBuffer<OldPosition, 500 / kBranchPeriod> old_positions_;
260
James Kuszmaul29c59522022-02-12 16:44:26 -0800261 CombinedState current_state_;
262 aos::monotonic_clock::time_point t_ = aos::monotonic_clock::min_time;
263 bool using_model_;
264
James Kuszmaul5ed29dd2022-02-13 18:32:06 -0800265 // X position of the IMU, in meters. 0 = center of robot, positive = ahead of
266 // center, negative = behind center.
267 double long_offset_ = -0.15;
268
James Kuszmaul29c59522022-02-12 16:44:26 -0800269 double last_residual_ = 0.0;
270 double filtered_residual_ = 0.0;
271 Eigen::Vector2d filtered_residual_accel_ = Eigen::Vector2d::Zero();
272 Eigen::Vector3d abs_accel_ = Eigen::Vector3d::Zero();
273 double velocity_residual_ = 0.0;
274 double accel_residual_ = 0.0;
275 double theta_rate_residual_ = 0.0;
276 int hysteresis_count_ = 0;
James Kuszmaul10d3fd42022-02-25 21:57:36 -0800277 Eigen::Quaterniond last_orientation_ = Eigen::Quaterniond::Identity();
James Kuszmaul29c59522022-02-12 16:44:26 -0800278
279 int clock_resets_ = 0;
280
James Kuszmaul8c4f6592022-02-26 15:49:30 -0800281 std::optional<aos::monotonic_clock::time_point> last_turret_update_;
282 double latest_turret_position_ = 0.0;
283 double latest_turret_velocity_ = 0.0;
284
285 // Stuff to track faults.
286 static constexpr size_t kNumRejectionReasons =
287 static_cast<int>(RejectionReason::MAX) -
288 static_cast<int>(RejectionReason::MIN) + 1;
289
290 struct Statistics {
291 int total_accepted = 0;
292 int total_candidates = 0;
293 static_assert(0 == static_cast<int>(RejectionReason::MIN));
294 static_assert(
295 kNumRejectionReasons ==
296 sizeof(
297 std::invoke_result<decltype(EnumValuesRejectionReason)>::type) /
298 sizeof(RejectionReason),
299 "RejectionReason has non-contiguous error values.");
300 std::array<int, kNumRejectionReasons> rejection_counts;
301 };
302 Statistics statistics_;
303
James Kuszmaul0dedb5e2022-03-05 16:02:20 -0800304 aos::SizedArray<TargetEstimateDebugT, kDebugBufferSize> image_debugs_;
Milind Upadhyayd67e9cf2022-03-13 13:56:57 -0700305 std::array<LedOutput, kNumPis> led_outputs_;
James Kuszmaul0dedb5e2022-03-05 16:02:20 -0800306
James Kuszmaul29c59522022-02-12 16:44:26 -0800307 friend class testing::LocalizerTest;
308};
309
310class EventLoopLocalizer {
311 public:
James Kuszmaul0dedb5e2022-03-05 16:02:20 -0800312 static constexpr std::chrono::milliseconds kMinVisualizationPeriod{100};
313
James Kuszmaul29c59522022-02-12 16:44:26 -0800314 EventLoopLocalizer(
315 aos::EventLoop *event_loop,
316 const control_loops::drivetrain::DrivetrainConfig<double> &dt_config);
317
James Kuszmaul5ed29dd2022-02-13 18:32:06 -0800318 ModelBasedLocalizer *localizer() { return &model_based_; }
319
James Kuszmaul29c59522022-02-12 16:44:26 -0800320 private:
James Kuszmaul8c4f6592022-02-26 15:49:30 -0800321 std::optional<aos::monotonic_clock::duration> ClockOffset(
322 std::string_view pi);
James Kuszmaul29c59522022-02-12 16:44:26 -0800323 aos::EventLoop *event_loop_;
324 ModelBasedLocalizer model_based_;
325 aos::Sender<LocalizerStatus> status_sender_;
326 aos::Sender<LocalizerOutput> output_sender_;
James Kuszmaul0dedb5e2022-03-05 16:02:20 -0800327 aos::Sender<LocalizerVisualization> visualization_sender_;
James Kuszmaul29c59522022-02-12 16:44:26 -0800328 aos::Fetcher<frc971::control_loops::drivetrain::Output> output_fetcher_;
James Kuszmaul8c4f6592022-02-26 15:49:30 -0800329 aos::Fetcher<aos::message_bridge::ServerStatistics> clock_offset_fetcher_;
Milind Upadhyayd67e9cf2022-03-13 13:56:57 -0700330 std::array<aos::Fetcher<y2022::vision::TargetEstimate>,
331 ModelBasedLocalizer::kNumPis>
James Kuszmaul2b2f8772022-03-12 15:25:35 -0800332 target_estimate_fetchers_;
333 aos::Fetcher<y2022::control_loops::superstructure::Status>
334 superstructure_fetcher_;
James Kuszmaul29c59522022-02-12 16:44:26 -0800335 zeroing::ImuZeroer zeroer_;
336 aos::monotonic_clock::time_point last_output_send_ =
337 aos::monotonic_clock::min_time;
James Kuszmaul0dedb5e2022-03-05 16:02:20 -0800338 aos::monotonic_clock::time_point last_visualization_send_ =
339 aos::monotonic_clock::min_time;
James Kuszmaul5ed29dd2022-02-13 18:32:06 -0800340 std::optional<aos::monotonic_clock::time_point> last_pico_timestamp_;
341 aos::monotonic_clock::duration pico_offset_error_;
342 // t = pico_offset_ + pico_timestamp.
343 // Note that this can drift over sufficiently long time periods!
344 std::optional<std::chrono::nanoseconds> pico_offset_;
345
346 zeroing::UnwrapSensor left_encoder_;
347 zeroing::UnwrapSensor right_encoder_;
James Kuszmaul29c59522022-02-12 16:44:26 -0800348};
349} // namespace frc971::controls
James Kuszmaul51fa1ae2022-02-26 00:49:57 -0800350#endif // Y2022_LOCALIZER_LOCALIZER_H_