blob: f2d76efe8ff653cae68f40d9a496b4cd3870d7b3 [file] [log] [blame]
James Kuszmaul29c59522022-02-12 16:44:26 -08001#ifndef Y2022_CONTROL_LOOPS_LOCALIZER_LOCALIZER_H_
2#define Y2022_CONTROL_LOOPS_LOCALIZER_LOCALIZER_H_
3
4#include "Eigen/Dense"
5#include "Eigen/Geometry"
6
7#include "aos/events/event_loop.h"
8#include "aos/containers/ring_buffer.h"
9#include "aos/time/time.h"
10#include "y2020/vision/sift/sift_generated.h"
11#include "y2022/control_loops/localizer/localizer_status_generated.h"
12#include "y2022/control_loops/localizer/localizer_output_generated.h"
13#include "frc971/control_loops/drivetrain/improved_down_estimator.h"
14#include "frc971/control_loops/drivetrain/drivetrain_position_generated.h"
15#include "frc971/control_loops/drivetrain/drivetrain_output_generated.h"
16#include "frc971/control_loops/drivetrain/localizer_generated.h"
17#include "frc971/zeroing/imu_zeroer.h"
18
19namespace frc971::controls {
20
21namespace testing {
22class LocalizerTest;
23}
24
25// Localizer implementation that makes use of a 6-axis IMU, encoder readings,
26// drivetrain voltages, and camera returns to localize the robot. Meant to
27// be run on a raspberry pi.
28//
29// This operates on the principle that the drivetrain can be in one of two
30// modes:
31// 1) A "normal" mode where it is obeying the regular drivetrain model, with
32// minimal lateral motion and no major external disturbances. This is
33// referred to as the "model" mode in the code/variable names.
34// 2) An non-holonomic mode where the robot is just flying around on a 2-D
35// plane with no meaningful constraints (referred to as an "accel" model
36// in the code, because we rely primarily on the accelerometer readings).
37//
38// In order to determine which mode to be in, we attempt to track whether the
39// two models are diverging substantially. In order to do this, we maintain a
40// 1-second long queue of "branches". A branch is generated every X iterations
41// and contains a model state and an accel state. When the branch starts, the
42// two will have identical states. For the remaining 1 second, the model state
43// will evolve purely according to the drivetrian model, and the accel state
44// will evolve purely using IMU readings.
45//
46// When the branch reaches 1 second in age, we calculate a residual associated
47// with how much the accel and model based states diverged. If they have
48// diverged substantially, that implies that the model is a poor match for
49// whatever has been happening to the robot in the past second, so if we were
50// previously relying on the model, we will override the current "actual"
51// state with the branched accel state, and then continue to update the accel
52// state based on IMU readings.
53// If we are currently in the accel state, we will continue generating branches
54// until the branches stop diverging--this will indicate that the model
55// matches the accelerometer readings again, and so we will swap back to
56// the model-based state.
57//
58// TODO:
59// * Implement paying attention to camera readings.
60// * Tune for ADIS16505/real robot.
61// * Tune down CPU usage to run on a pi.
62class ModelBasedLocalizer {
63 public:
64 static constexpr size_t kX = 0;
65 static constexpr size_t kY = 1;
66 static constexpr size_t kTheta = 2;
67
68 static constexpr size_t kVelocityX = 3;
69 static constexpr size_t kVelocityY = 4;
70 static constexpr size_t kNAccelStates = 5;
71
72 static constexpr size_t kLeftEncoder = 3;
73 static constexpr size_t kLeftVelocity = 4;
74 static constexpr size_t kLeftVoltageError = 5;
75 static constexpr size_t kRightEncoder = 6;
76 static constexpr size_t kRightVelocity = 7;
77 static constexpr size_t kRightVoltageError = 8;
78 static constexpr size_t kNModelStates = 9;
79
80 static constexpr size_t kNModelOutputs = 3;
81
82 static constexpr size_t kNAccelOuputs = 1;
83
84 static constexpr size_t kAccelX = 0;
85 static constexpr size_t kAccelY = 1;
86 static constexpr size_t kThetaRate = 2;
87 static constexpr size_t kNAccelInputs = 3;
88
89 static constexpr size_t kLeftVoltage = 0;
90 static constexpr size_t kRightVoltage = 1;
91 static constexpr size_t kNModelInputs = 2;
92
93 typedef Eigen::Matrix<double, kNModelStates, 1> ModelState;
94 typedef Eigen::Matrix<double, kNAccelStates, 1> AccelState;
95 typedef Eigen::Matrix<double, kNModelInputs, 1> ModelInput;
96 typedef Eigen::Matrix<double, kNAccelInputs, 1> AccelInput;
97
98 ModelBasedLocalizer(
99 const control_loops::drivetrain::DrivetrainConfig<double> &dt_config);
100 void HandleImu(aos::monotonic_clock::time_point t,
101 const Eigen::Vector3d &gyro, const Eigen::Vector3d &accel,
102 const Eigen::Vector2d encoders, const Eigen::Vector2d voltage);
103 void HandleImageMatch(aos::monotonic_clock::time_point,
104 const vision::sift::ImageMatchResult *) {
105 LOG(FATAL) << "Unimplemented.";
106 }
107 void HandleReset(aos::monotonic_clock::time_point,
108 const Eigen::Vector3d &xytheta);
109
110 flatbuffers::Offset<ModelBasedStatus> PopulateStatus(
111 flatbuffers::FlatBufferBuilder *fbb);
112
113 Eigen::Vector3d xytheta() const {
114 if (using_model_) {
115 return current_state_.model_state.block<3, 1>(0, 0);
116 } else {
117 return current_state_.accel_state.block<3, 1>(0, 0);
118 }
119 }
120
121 AccelState accel_state() const { return current_state_.accel_state; };
122
123 private:
124 struct CombinedState {
125 AccelState accel_state;
126 ModelState model_state;
127 aos::monotonic_clock::time_point branch_time;
128 double accumulated_divergence;
129 };
130
131 static flatbuffers::Offset<AccelBasedState> BuildAccelState(
132 flatbuffers::FlatBufferBuilder *fbb, const AccelState &state);
133
134 static flatbuffers::Offset<ModelBasedState> BuildModelState(
135 flatbuffers::FlatBufferBuilder *fbb, const ModelState &state);
136
137 Eigen::Matrix<double, kNModelStates, kNModelStates> AModel(
138 const ModelState &state) const;
139 Eigen::Matrix<double, kNAccelStates, kNAccelStates> AAccel() const;
140 ModelState DiffModel(const ModelState &state, const ModelInput &U) const;
141 AccelState DiffAccel(const AccelState &state, const AccelInput &U) const;
142
143 ModelState UpdateModel(const ModelState &model, const ModelInput &input,
144 aos::monotonic_clock::duration dt) const;
145 AccelState UpdateAccel(const AccelState &accel, const AccelInput &input,
146 aos::monotonic_clock::duration dt) const;
147
148 AccelState AccelStateForModelState(const ModelState &state) const;
149 ModelState ModelStateForAccelState(const AccelState &state,
150 const Eigen::Vector2d &encoders,
151 const double yaw_rate) const;
152 double ModelDivergence(const CombinedState &state,
153 const AccelInput &accel_inputs,
154 const Eigen::Vector2d &filtered_accel,
155 const ModelInput &model_inputs);
156
157 const control_loops::drivetrain::DrivetrainConfig<double> dt_config_;
158 const StateFeedbackHybridPlantCoefficients<2, 2, 2, double>
159 velocity_drivetrain_coefficients_;
160 Eigen::Matrix<double, kNModelStates, kNModelStates> A_continuous_model_;
161 Eigen::Matrix<double, kNAccelStates, kNAccelStates> A_continuous_accel_;
162 Eigen::Matrix<double, kNModelStates, kNModelInputs> B_continuous_model_;
163 Eigen::Matrix<double, kNAccelStates, kNAccelInputs> B_continuous_accel_;
164
165 Eigen::Matrix<double, kNModelStates, kNModelStates> Q_continuous_model_;
166
167 Eigen::Matrix<double, kNModelStates, kNModelStates> P_model_;
168 // When we are following the model, we will, on each iteration:
169 // 1) Perform a model-based update of a single state.
170 // 2) Add a hypothetical non-model-based entry based on the current state.
171 // 3) Evict too-old non-model-based entries.
172 control_loops::drivetrain::DrivetrainUkf down_estimator_;
173
174 // Buffer of old branches these are all created by initializing a new
175 // model-based state based on the current state, and then initializing a new
176 // accel-based state on top of that new model-based state (to eliminate the
177 // impact of any lateral motion).
178 // We then integrate up all of these states and observe how much the model and
179 // accel based states of each branch compare to one another.
180 aos::RingBuffer<CombinedState, 2000> branches_;
181
182 CombinedState current_state_;
183 aos::monotonic_clock::time_point t_ = aos::monotonic_clock::min_time;
184 bool using_model_;
185
186 double last_residual_ = 0.0;
187 double filtered_residual_ = 0.0;
188 Eigen::Vector2d filtered_residual_accel_ = Eigen::Vector2d::Zero();
189 Eigen::Vector3d abs_accel_ = Eigen::Vector3d::Zero();
190 double velocity_residual_ = 0.0;
191 double accel_residual_ = 0.0;
192 double theta_rate_residual_ = 0.0;
193 int hysteresis_count_ = 0;
194
195 int clock_resets_ = 0;
196
197 friend class testing::LocalizerTest;
198};
199
200class EventLoopLocalizer {
201 public:
202 EventLoopLocalizer(
203 aos::EventLoop *event_loop,
204 const control_loops::drivetrain::DrivetrainConfig<double> &dt_config);
205
206 private:
207 aos::EventLoop *event_loop_;
208 ModelBasedLocalizer model_based_;
209 aos::Sender<LocalizerStatus> status_sender_;
210 aos::Sender<LocalizerOutput> output_sender_;
211 aos::Fetcher<frc971::control_loops::drivetrain::Position> position_fetcher_;
212 aos::Fetcher<frc971::control_loops::drivetrain::Output> output_fetcher_;
213 zeroing::ImuZeroer zeroer_;
214 aos::monotonic_clock::time_point last_output_send_ =
215 aos::monotonic_clock::min_time;
216};
217} // namespace frc971::controls
218#endif // Y2022_CONTROL_LOOPS_LOCALIZER_LOCALIZER_H_