blob: b774e18408ffb21e0d2007a93658c0815385d4f5 [file] [log] [blame]
James Kuszmaul51fa1ae2022-02-26 00:49:57 -08001#include "y2022/localizer/localizer.h"
James Kuszmaul29c59522022-02-12 16:44:26 -08002
James Kuszmaulf6b69112022-03-12 21:34:39 -08003#include "aos/json_to_flatbuffer.h"
James Kuszmaul29c59522022-02-12 16:44:26 -08004#include "frc971/control_loops/c2d.h"
5#include "frc971/wpilib/imu_batch_generated.h"
James Kuszmaul5ed29dd2022-02-13 18:32:06 -08006#include "y2022/constants.h"
James Kuszmaul29c59522022-02-12 16:44:26 -08007
James Kuszmaulce491e42022-03-12 21:02:10 -08008DEFINE_bool(ignore_accelerometer, false,
9 "If set, ignores the accelerometer readings.");
10
James Kuszmaul29c59522022-02-12 16:44:26 -080011namespace frc971::controls {
12
13namespace {
14constexpr double kG = 9.80665;
James Kuszmaul9f2f53c2023-02-19 14:08:18 -080015static constexpr std::chrono::microseconds kNominalDt = ImuWatcher::kNominalDt;
James Kuszmaul8c4f6592022-02-26 15:49:30 -080016// Field position of the target (the 2022 target is conveniently in the middle
17// of the field....).
18constexpr double kVisionTargetX = 0.0;
19constexpr double kVisionTargetY = 0.0;
20
James Kuszmaulaa39d962022-03-06 14:54:28 -080021// Minimum confidence to require to use a target match.
James Kuszmaul1b918d82022-03-12 18:27:41 -080022constexpr double kMinTargetEstimateConfidence = 0.75;
James Kuszmaulaa39d962022-03-06 14:54:28 -080023
James Kuszmaul29c59522022-02-12 16:44:26 -080024template <int N>
25Eigen::Matrix<double, N, 1> MakeState(std::vector<double> values) {
26 CHECK_EQ(static_cast<size_t>(N), values.size());
27 Eigen::Matrix<double, N, 1> vector;
28 for (int ii = 0; ii < N; ++ii) {
29 vector(ii, 0) = values[ii];
30 }
31 return vector;
32}
James Kuszmaul29c59522022-02-12 16:44:26 -080033} // namespace
34
35ModelBasedLocalizer::ModelBasedLocalizer(
36 const control_loops::drivetrain::DrivetrainConfig<double> &dt_config)
37 : dt_config_(dt_config),
38 velocity_drivetrain_coefficients_(
39 dt_config.make_hybrid_drivetrain_velocity_loop()
40 .plant()
41 .coefficients()),
42 down_estimator_(dt_config) {
James Kuszmaul8c4f6592022-02-26 15:49:30 -080043 statistics_.rejection_counts.fill(0);
James Kuszmaulf6b69112022-03-12 21:34:39 -080044 CHECK_EQ(branches_.capacity(),
45 static_cast<size_t>(std::chrono::seconds(1) / kNominalDt /
46 kBranchPeriod));
James Kuszmaul29c59522022-02-12 16:44:26 -080047 if (dt_config_.is_simulated) {
48 down_estimator_.assume_perfect_gravity();
49 }
50 A_continuous_accel_.setZero();
51 A_continuous_model_.setZero();
52 B_continuous_accel_.setZero();
53 B_continuous_model_.setZero();
54
55 A_continuous_accel_(kX, kVelocityX) = 1.0;
56 A_continuous_accel_(kY, kVelocityY) = 1.0;
57
58 const double diameter = 2.0 * dt_config_.robot_radius;
59
60 A_continuous_model_(kTheta, kLeftVelocity) = -1.0 / diameter;
61 A_continuous_model_(kTheta, kRightVelocity) = 1.0 / diameter;
62 A_continuous_model_(kLeftEncoder, kLeftVelocity) = 1.0;
63 A_continuous_model_(kRightEncoder, kRightVelocity) = 1.0;
64 const auto &vel_coefs = velocity_drivetrain_coefficients_;
65 A_continuous_model_(kLeftVelocity, kLeftVelocity) =
66 vel_coefs.A_continuous(0, 0);
67 A_continuous_model_(kLeftVelocity, kRightVelocity) =
68 vel_coefs.A_continuous(0, 1);
69 A_continuous_model_(kRightVelocity, kLeftVelocity) =
70 vel_coefs.A_continuous(1, 0);
71 A_continuous_model_(kRightVelocity, kRightVelocity) =
72 vel_coefs.A_continuous(1, 1);
73
74 A_continuous_model_(kLeftVelocity, kLeftVoltageError) =
75 1 * vel_coefs.B_continuous(0, 0);
76 A_continuous_model_(kLeftVelocity, kRightVoltageError) =
77 1 * vel_coefs.B_continuous(0, 1);
78 A_continuous_model_(kRightVelocity, kLeftVoltageError) =
79 1 * vel_coefs.B_continuous(1, 0);
80 A_continuous_model_(kRightVelocity, kRightVoltageError) =
81 1 * vel_coefs.B_continuous(1, 1);
82
83 B_continuous_model_.block<1, 2>(kLeftVelocity, kLeftVoltage) =
84 vel_coefs.B_continuous.row(0);
85 B_continuous_model_.block<1, 2>(kRightVelocity, kLeftVoltage) =
86 vel_coefs.B_continuous.row(1);
87
88 B_continuous_accel_(kVelocityX, kAccelX) = 1.0;
89 B_continuous_accel_(kVelocityY, kAccelY) = 1.0;
90 B_continuous_accel_(kTheta, kThetaRate) = 1.0;
91
92 Q_continuous_model_.setZero();
James Kuszmaul8c4f6592022-02-26 15:49:30 -080093 Q_continuous_model_.diagonal() << 1e-2, 1e-2, 1e-8, 1e-2, 1e-0, 1e-0, 1e-2,
James Kuszmaul29c59522022-02-12 16:44:26 -080094 1e-0, 1e-0;
95
James Kuszmaul8c4f6592022-02-26 15:49:30 -080096 Q_continuous_accel_.setZero();
97 Q_continuous_accel_.diagonal() << 1e-2, 1e-2, 1e-20, 1e-4, 1e-4;
98
James Kuszmaul29c59522022-02-12 16:44:26 -080099 P_model_ = Q_continuous_model_ * aos::time::DurationInSeconds(kNominalDt);
James Kuszmaul8c4f6592022-02-26 15:49:30 -0800100
101 // We can precalculate the discretizations of the accel model because it is
102 // actually LTI.
103
104 DiscretizeQAFast(Q_continuous_accel_, A_continuous_accel_, kNominalDt,
105 &Q_discrete_accel_, &A_discrete_accel_);
106 P_accel_ = Q_discrete_accel_;
Milind Upadhyayd67e9cf2022-03-13 13:56:57 -0700107
108 led_outputs_.fill(LedOutput::ON);
James Kuszmaul29c59522022-02-12 16:44:26 -0800109}
110
111Eigen::Matrix<double, ModelBasedLocalizer::kNModelStates,
112 ModelBasedLocalizer::kNModelStates>
113ModelBasedLocalizer::AModel(
114 const ModelBasedLocalizer::ModelState &state) const {
115 Eigen::Matrix<double, kNModelStates, kNModelStates> A = A_continuous_model_;
116 const double theta = state(kTheta);
117 const double stheta = std::sin(theta);
118 const double ctheta = std::cos(theta);
119 const double velocity = (state(kLeftVelocity) + state(kRightVelocity)) / 2.0;
120 A(kX, kTheta) = -stheta * velocity;
121 A(kX, kLeftVelocity) = ctheta / 2.0;
122 A(kX, kRightVelocity) = ctheta / 2.0;
123 A(kY, kTheta) = ctheta * velocity;
124 A(kY, kLeftVelocity) = stheta / 2.0;
125 A(kY, kRightVelocity) = stheta / 2.0;
126 return A;
127}
128
129Eigen::Matrix<double, ModelBasedLocalizer::kNAccelStates,
130 ModelBasedLocalizer::kNAccelStates>
131ModelBasedLocalizer::AAccel() const {
132 return A_continuous_accel_;
133}
134
135ModelBasedLocalizer::ModelState ModelBasedLocalizer::DiffModel(
136 const ModelBasedLocalizer::ModelState &state,
137 const ModelBasedLocalizer::ModelInput &U) const {
138 ModelState x_dot = AModel(state) * state + B_continuous_model_ * U;
139 const double theta = state(kTheta);
140 const double stheta = std::sin(theta);
141 const double ctheta = std::cos(theta);
142 const double velocity = (state(kLeftVelocity) + state(kRightVelocity)) / 2.0;
143 x_dot(kX) = ctheta * velocity;
144 x_dot(kY) = stheta * velocity;
145 return x_dot;
146}
147
148ModelBasedLocalizer::AccelState ModelBasedLocalizer::DiffAccel(
149 const ModelBasedLocalizer::AccelState &state,
150 const ModelBasedLocalizer::AccelInput &U) const {
151 return AAccel() * state + B_continuous_accel_ * U;
152}
153
154ModelBasedLocalizer::ModelState ModelBasedLocalizer::UpdateModel(
155 const ModelBasedLocalizer::ModelState &model,
156 const ModelBasedLocalizer::ModelInput &input,
157 const aos::monotonic_clock::duration dt) const {
158 return control_loops::RungeKutta(
159 std::bind(&ModelBasedLocalizer::DiffModel, this, std::placeholders::_1,
160 input),
161 model, aos::time::DurationInSeconds(dt));
162}
163
164ModelBasedLocalizer::AccelState ModelBasedLocalizer::UpdateAccel(
165 const ModelBasedLocalizer::AccelState &accel,
166 const ModelBasedLocalizer::AccelInput &input,
167 const aos::monotonic_clock::duration dt) const {
168 return control_loops::RungeKutta(
169 std::bind(&ModelBasedLocalizer::DiffAccel, this, std::placeholders::_1,
170 input),
171 accel, aos::time::DurationInSeconds(dt));
172}
173
174ModelBasedLocalizer::AccelState ModelBasedLocalizer::AccelStateForModelState(
175 const ModelBasedLocalizer::ModelState &state) const {
176 const double robot_speed =
177 (state(kLeftVelocity) + state(kRightVelocity)) / 2.0;
James Kuszmaulf6b69112022-03-12 21:34:39 -0800178 const double lat_speed = (AModel(state) * state)(kTheta)*long_offset_;
James Kuszmaul5ed29dd2022-02-13 18:32:06 -0800179 const double velocity_x = std::cos(state(kTheta)) * robot_speed -
180 std::sin(state(kTheta)) * lat_speed;
181 const double velocity_y = std::sin(state(kTheta)) * robot_speed +
182 std::cos(state(kTheta)) * lat_speed;
James Kuszmaul29c59522022-02-12 16:44:26 -0800183 return (AccelState() << state(0), state(1), state(2), velocity_x, velocity_y)
184 .finished();
185}
186
187ModelBasedLocalizer::ModelState ModelBasedLocalizer::ModelStateForAccelState(
188 const ModelBasedLocalizer::AccelState &state,
189 const Eigen::Vector2d &encoders, const double yaw_rate) const {
190 const double robot_speed = state(kVelocityX) * std::cos(state(kTheta)) +
191 state(kVelocityY) * std::sin(state(kTheta));
192 const double radius = dt_config_.robot_radius;
193 const double left_velocity = robot_speed - yaw_rate * radius;
194 const double right_velocity = robot_speed + yaw_rate * radius;
195 return (ModelState() << state(0), state(1), state(2), encoders(0),
196 left_velocity, 0.0, encoders(1), right_velocity, 0.0)
197 .finished();
198}
199
200double ModelBasedLocalizer::ModelDivergence(
201 const ModelBasedLocalizer::CombinedState &state,
202 const ModelBasedLocalizer::AccelInput &accel_inputs,
203 const Eigen::Vector2d &filtered_accel,
204 const ModelBasedLocalizer::ModelInput &model_inputs) {
205 // Convert the model state into the acceleration-based state-space and check
206 // the distance between the two (should really be a weighted norm, but all the
207 // numbers are on ~the same scale).
James Kuszmaul5ed29dd2022-02-13 18:32:06 -0800208 // TODO(james): Maybe weight lateral velocity divergence different than
209 // longitudinal? Seems like we tend to get false-positives currently when in
210 // sharp turns.
211 // TODO(james): For off-center gyros, maybe reduce noise when turning?
James Kuszmaul29c59522022-02-12 16:44:26 -0800212 VLOG(2) << "divergence: "
213 << (state.accel_state - AccelStateForModelState(state.model_state))
214 .transpose();
215 const AccelState diff_accel = DiffAccel(state.accel_state, accel_inputs);
216 const ModelState diff_model = DiffModel(state.model_state, model_inputs);
217 const double model_lng_velocity =
218 (state.model_state(kLeftVelocity) + state.model_state(kRightVelocity)) /
219 2.0;
220 const double model_lng_accel =
James Kuszmaul5ed29dd2022-02-13 18:32:06 -0800221 (diff_model(kLeftVelocity) + diff_model(kRightVelocity)) / 2.0 -
222 diff_model(kTheta) * diff_model(kTheta) * long_offset_;
223 const double model_lat_accel = diff_model(kTheta) * model_lng_velocity;
224 const Eigen::Vector2d robot_frame_accel(model_lng_accel, model_lat_accel);
James Kuszmaul29c59522022-02-12 16:44:26 -0800225 const Eigen::Vector2d model_accel =
226 Eigen::AngleAxisd(state.model_state(kTheta), Eigen::Vector3d::UnitZ())
227 .toRotationMatrix()
228 .block<2, 2>(0, 0) *
229 robot_frame_accel;
230 const double accel_diff = (model_accel - filtered_accel).norm();
231 const double theta_rate_diff =
232 std::abs(diff_accel(kTheta) - diff_model(kTheta));
233
234 const Eigen::Vector2d accel_vel = state.accel_state.bottomRows<2>();
James Kuszmaul5ed29dd2022-02-13 18:32:06 -0800235 Eigen::Vector2d model_vel =
James Kuszmaul29c59522022-02-12 16:44:26 -0800236 AccelStateForModelState(state.model_state).bottomRows<2>();
237 velocity_residual_ = (accel_vel - model_vel).norm() /
238 (1.0 + accel_vel.norm() + model_vel.norm());
239 theta_rate_residual_ = theta_rate_diff;
240 accel_residual_ = accel_diff / 4.0;
241 return velocity_residual_ + theta_rate_residual_ + accel_residual_;
242}
243
James Kuszmaul5ed29dd2022-02-13 18:32:06 -0800244void ModelBasedLocalizer::UpdateState(
245 CombinedState *state,
246 const Eigen::Matrix<double, kNModelStates, kNModelOutputs> &K,
247 const Eigen::Matrix<double, kNModelOutputs, 1> &Z,
248 const Eigen::Matrix<double, kNModelOutputs, kNModelStates> &H,
249 const AccelInput &accel_input, const ModelInput &model_input,
250 aos::monotonic_clock::duration dt) {
251 state->accel_state = UpdateAccel(state->accel_state, accel_input, dt);
252 if (down_estimator_.consecutive_still() > 500.0) {
253 state->accel_state(kVelocityX) *= 0.9;
254 state->accel_state(kVelocityY) *= 0.9;
255 }
256 state->model_state = UpdateModel(state->model_state, model_input, dt);
257 state->model_state += K * (Z - H * state->model_state);
258}
259
James Kuszmaul5a5a7832022-03-16 23:15:08 -0700260void ModelBasedLocalizer::HandleImu(
261 aos::monotonic_clock::time_point t, const Eigen::Vector3d &gyro,
262 const Eigen::Vector3d &accel, const std::optional<Eigen::Vector2d> encoders,
263 const Eigen::Vector2d voltage) {
James Kuszmaul29c59522022-02-12 16:44:26 -0800264 VLOG(2) << t;
265 if (t_ == aos::monotonic_clock::min_time) {
266 t_ = t;
267 }
James Kuszmaul5f27d8b2022-03-17 09:08:26 -0700268 if (t_ + 10 * kNominalDt < t) {
James Kuszmaul29c59522022-02-12 16:44:26 -0800269 t_ = t;
270 ++clock_resets_;
271 }
272 const aos::monotonic_clock::duration dt = t - t_;
273 t_ = t;
274 down_estimator_.Predict(gyro, accel, dt);
275 // TODO(james): Should we prefer this or use the down-estimator corrected
James Kuszmaul5ed29dd2022-02-13 18:32:06 -0800276 // version? Using the down estimator is more principled, but does create more
277 // opportunities for subtle biases.
James Kuszmaul29c59522022-02-12 16:44:26 -0800278 const double yaw_rate = (dt_config_.imu_transform * gyro)(2);
279 const double diameter = 2.0 * dt_config_.robot_radius;
280
281 const Eigen::AngleAxis<double> orientation(
282 Eigen::AngleAxis<double>(xytheta()(kTheta), Eigen::Vector3d::UnitZ()) *
283 down_estimator_.X_hat());
James Kuszmaul10d3fd42022-02-25 21:57:36 -0800284 last_orientation_ = orientation;
James Kuszmaul29c59522022-02-12 16:44:26 -0800285
286 const Eigen::Vector3d absolute_accel =
287 orientation * dt_config_.imu_transform * kG * accel;
288 abs_accel_ = absolute_accel;
James Kuszmaul29c59522022-02-12 16:44:26 -0800289
290 VLOG(2) << "abs accel " << absolute_accel.transpose();
James Kuszmaul29c59522022-02-12 16:44:26 -0800291 VLOG(2) << "dt " << aos::time::DurationInSeconds(dt);
292
293 // Update all the branched states.
294 const AccelInput accel_input(absolute_accel.x(), absolute_accel.y(),
295 yaw_rate);
296 const ModelInput model_input(voltage);
297
298 const Eigen::Matrix<double, kNModelStates, kNModelStates> A_continuous =
299 AModel(current_state_.model_state);
300
301 Eigen::Matrix<double, kNModelStates, kNModelStates> A_discrete;
302 Eigen::Matrix<double, kNModelStates, kNModelStates> Q_discrete;
303
304 DiscretizeQAFast(Q_continuous_model_, A_continuous, dt, &Q_discrete,
305 &A_discrete);
306
307 P_model_ = A_discrete * P_model_ * A_discrete.transpose() + Q_discrete;
James Kuszmaul8c4f6592022-02-26 15:49:30 -0800308 P_accel_ = A_discrete_accel_ * P_accel_ * A_discrete_accel_.transpose() +
309 Q_discrete_accel_;
James Kuszmaul29c59522022-02-12 16:44:26 -0800310
311 Eigen::Matrix<double, kNModelOutputs, kNModelStates> H;
312 Eigen::Matrix<double, kNModelOutputs, kNModelOutputs> R;
313 {
314 H.setZero();
315 R.setZero();
316 H(0, kLeftEncoder) = 1.0;
317 H(1, kRightEncoder) = 1.0;
318 H(2, kRightVelocity) = 1.0 / diameter;
319 H(2, kLeftVelocity) = -1.0 / diameter;
320
321 R.diagonal() << 1e-9, 1e-9, 1e-13;
322 }
323
James Kuszmaul5a5a7832022-03-16 23:15:08 -0700324 const Eigen::Matrix<double, kNModelOutputs, 1> Z =
325 encoders.has_value()
326 ? Eigen::Vector3d(encoders.value()(0), encoders.value()(1), yaw_rate)
327 : Eigen::Vector3d(current_state_.model_state(kLeftEncoder),
328 current_state_.model_state(kRightEncoder),
329 yaw_rate);
James Kuszmaul29c59522022-02-12 16:44:26 -0800330
331 if (branches_.empty()) {
332 VLOG(2) << "Initializing";
James Kuszmaul5a5a7832022-03-16 23:15:08 -0700333 current_state_.model_state(kLeftEncoder) = Z(0);
334 current_state_.model_state(kRightEncoder) = Z(1);
James Kuszmaul29c59522022-02-12 16:44:26 -0800335 current_state_.branch_time = t;
336 branches_.Push(current_state_);
337 }
338
339 const Eigen::Matrix<double, kNModelStates, kNModelOutputs> K =
340 P_model_ * H.transpose() * (H * P_model_ * H.transpose() + R).inverse();
341 P_model_ = (Eigen::Matrix<double, kNModelStates, kNModelStates>::Identity() -
342 K * H) *
343 P_model_;
344 VLOG(2) << "K\n" << K;
345 VLOG(2) << "Z\n" << Z.transpose();
346
347 for (CombinedState &state : branches_) {
James Kuszmaul5ed29dd2022-02-13 18:32:06 -0800348 UpdateState(&state, K, Z, H, accel_input, model_input, dt);
James Kuszmaul29c59522022-02-12 16:44:26 -0800349 }
James Kuszmaul5ed29dd2022-02-13 18:32:06 -0800350 UpdateState(&current_state_, K, Z, H, accel_input, model_input, dt);
James Kuszmaul29c59522022-02-12 16:44:26 -0800351
352 VLOG(2) << "oildest accel " << branches_[0].accel_state.transpose();
353 VLOG(2) << "oildest accel diff "
354 << DiffAccel(branches_[0].accel_state, accel_input).transpose();
355 VLOG(2) << "oildest model " << branches_[0].model_state.transpose();
356
357 // Determine whether to switch modes--if we are currently in model-based mode,
358 // swap to accel-based if the two states have divergeed meaningfully in the
359 // oldest branch. If we are currently in accel-based, then swap back to model
360 // if the oldest model branch matches has matched the
361 filtered_residual_accel_ +=
362 0.01 * (accel_input.topRows<2>() - filtered_residual_accel_);
363 const double model_divergence =
364 branches_.full() ? ModelDivergence(branches_[0], accel_input,
365 filtered_residual_accel_, model_input)
366 : 0.0;
367 filtered_residual_ +=
368 (1.0 - std::exp(-aos::time::DurationInSeconds(kNominalDt) / 0.0095)) *
369 (model_divergence - filtered_residual_);
James Kuszmaul5ed29dd2022-02-13 18:32:06 -0800370 // TODO(james): Tune this more. Currently set to generally trust the model,
371 // perhaps a bit too much.
372 // When the residual exceeds the accel threshold, we start using the inertials
373 // alone; when it drops back below the model threshold, we go back to being
374 // model-based.
375 constexpr double kUseAccelThreshold = 2.0;
376 constexpr double kUseModelThreshold = 0.5;
James Kuszmaul29c59522022-02-12 16:44:26 -0800377 constexpr size_t kShareStates = kNModelStates;
378 static_assert(kUseModelThreshold < kUseAccelThreshold);
379 if (using_model_) {
James Kuszmaulce491e42022-03-12 21:02:10 -0800380 if (!FLAGS_ignore_accelerometer &&
381 filtered_residual_ > kUseAccelThreshold) {
James Kuszmaul29c59522022-02-12 16:44:26 -0800382 hysteresis_count_++;
383 } else {
384 hysteresis_count_ = 0;
385 }
386 if (hysteresis_count_ > 0) {
387 using_model_ = false;
388 // Grab the accel-based state from back when we started diverging.
389 // TODO(james): This creates a problematic selection bias, because
390 // we will tend to bias towards deliberately out-of-tune measurements.
391 current_state_.accel_state = branches_[0].accel_state;
392 current_state_.model_state = branches_[0].model_state;
393 current_state_.model_state = ModelStateForAccelState(
James Kuszmaul5a5a7832022-03-16 23:15:08 -0700394 current_state_.accel_state, Z.topRows<2>(), yaw_rate);
James Kuszmaul29c59522022-02-12 16:44:26 -0800395 } else {
396 VLOG(2) << "Normal branching";
James Kuszmaul29c59522022-02-12 16:44:26 -0800397 current_state_.accel_state =
398 AccelStateForModelState(current_state_.model_state);
399 current_state_.branch_time = t;
400 }
401 hysteresis_count_ = 0;
402 } else {
403 if (filtered_residual_ < kUseModelThreshold) {
404 hysteresis_count_++;
405 } else {
406 hysteresis_count_ = 0;
407 }
408 if (hysteresis_count_ > 100) {
409 using_model_ = true;
410 // Grab the model-based state from back when we stopped diverging.
411 current_state_.model_state.topRows<kShareStates>() =
James Kuszmaul5a5a7832022-03-16 23:15:08 -0700412 ModelStateForAccelState(branches_[0].accel_state, Z.topRows<2>(),
413 yaw_rate)
James Kuszmaul29c59522022-02-12 16:44:26 -0800414 .topRows<kShareStates>();
415 current_state_.accel_state =
416 AccelStateForModelState(current_state_.model_state);
417 } else {
James Kuszmaul29c59522022-02-12 16:44:26 -0800418 // TODO(james): Why was I leaving the encoders/wheel velocities in place?
James Kuszmaul29c59522022-02-12 16:44:26 -0800419 current_state_.model_state = ModelStateForAccelState(
James Kuszmaul5a5a7832022-03-16 23:15:08 -0700420 current_state_.accel_state, Z.topRows<2>(), yaw_rate);
James Kuszmaul29c59522022-02-12 16:44:26 -0800421 current_state_.branch_time = t;
422 }
423 }
424
425 // Generate a new branch, with the accel state reset based on the model-based
426 // state (really, just getting rid of the lateral velocity).
James Kuszmaul5ed29dd2022-02-13 18:32:06 -0800427 // By resetting the accel state in the new branch, this tries to minimize the
428 // odds of runaway lateral velocities. This doesn't help with runaway
429 // longitudinal velocities, however.
James Kuszmaul29c59522022-02-12 16:44:26 -0800430 CombinedState new_branch = current_state_;
James Kuszmaul5ed29dd2022-02-13 18:32:06 -0800431 new_branch.accel_state = AccelStateForModelState(new_branch.model_state);
James Kuszmaul29c59522022-02-12 16:44:26 -0800432 new_branch.accumulated_divergence = 0.0;
433
James Kuszmaul93825a02022-02-13 16:50:33 -0800434 ++branch_counter_;
435 if (branch_counter_ % kBranchPeriod == 0) {
436 branches_.Push(new_branch);
James Kuszmaul8c4f6592022-02-26 15:49:30 -0800437 old_positions_.Push(OldPosition{t, xytheta(), latest_turret_position_,
438 latest_turret_velocity_});
James Kuszmaul93825a02022-02-13 16:50:33 -0800439 branch_counter_ = 0;
440 }
James Kuszmaul29c59522022-02-12 16:44:26 -0800441
442 last_residual_ = model_divergence;
443
444 VLOG(2) << "Using " << (using_model_ ? "model" : "accel");
445 VLOG(2) << "Residual " << last_residual_;
446 VLOG(2) << "Filtered Residual " << filtered_residual_;
447 VLOG(2) << "buffer size " << branches_.size();
448 VLOG(2) << "Model state " << current_state_.model_state.transpose();
449 VLOG(2) << "Accel state " << current_state_.accel_state.transpose();
450 VLOG(2) << "Accel state for model "
James Kuszmaulf6b69112022-03-12 21:34:39 -0800451 << AccelStateForModelState(current_state_.model_state).transpose();
James Kuszmaul29c59522022-02-12 16:44:26 -0800452 VLOG(2) << "Input acce " << accel.transpose();
453 VLOG(2) << "Input gyro " << gyro.transpose();
454 VLOG(2) << "Input voltage " << voltage.transpose();
James Kuszmaul5a5a7832022-03-16 23:15:08 -0700455 VLOG(2) << "Input encoder " << Z.topRows<2>().transpose();
James Kuszmaul29c59522022-02-12 16:44:26 -0800456 VLOG(2) << "yaw rate " << yaw_rate;
457
458 CHECK(std::isfinite(last_residual_));
459}
460
James Kuszmaul8c4f6592022-02-26 15:49:30 -0800461const ModelBasedLocalizer::OldPosition ModelBasedLocalizer::GetStateForTime(
462 aos::monotonic_clock::time_point time) {
463 if (old_positions_.empty()) {
464 return OldPosition{};
465 }
466
467 aos::monotonic_clock::duration lowest_time_error =
468 aos::monotonic_clock::duration::max();
469 const OldPosition *best_match = nullptr;
470 for (const OldPosition &sample : old_positions_) {
471 const aos::monotonic_clock::duration time_error =
472 std::chrono::abs(sample.sample_time - time);
473 if (time_error < lowest_time_error) {
474 lowest_time_error = time_error;
475 best_match = &sample;
476 }
477 }
478 return *best_match;
479}
480
481namespace {
James Kuszmaul8c4f6592022-02-26 15:49:30 -0800482
483// Node names of the pis to listen for cameras from.
Milind Upadhyayd67e9cf2022-03-13 13:56:57 -0700484constexpr std::array<std::string_view, ModelBasedLocalizer::kNumPis> kPisToUse{
485 "pi1", "pi2", "pi3", "pi4"};
James Kuszmaulf6b69112022-03-12 21:34:39 -0800486} // namespace
James Kuszmaul8c4f6592022-02-26 15:49:30 -0800487
488const Eigen::Matrix<double, 4, 4> ModelBasedLocalizer::CameraTransform(
489 const OldPosition &state,
490 const frc971::vision::calibration::CameraCalibration *calibration,
491 std::optional<RejectionReason> *rejection_reason) const {
492 CHECK_NOTNULL(rejection_reason);
493 CHECK_NOTNULL(calibration);
494 // Per the CameraCalibration specification, we can actually determine whether
495 // the camera is the turret camera just from the presence of the
496 // turret_extrinsics member.
497 const bool is_turret = calibration->has_turret_extrinsics();
498 // Ignore readings when the turret is spinning too fast, on the assumption
499 // that the odds of screwing up the time compensation are higher.
500 // Note that the current number here is chosen pretty arbitrarily--1 rad / sec
501 // seems reasonable, but may be unnecessarily low or high.
502 constexpr double kMaxTurretVelocity = 1.0;
503 if (is_turret && std::abs(state.turret_velocity) > kMaxTurretVelocity &&
504 !rejection_reason->has_value()) {
505 *rejection_reason = RejectionReason::TURRET_TOO_FAST;
506 }
507 CHECK(calibration->has_fixed_extrinsics());
508 const Eigen::Matrix<double, 4, 4> fixed_extrinsics =
James Kuszmaule3df1ed2023-02-20 16:21:17 -0800509 control_loops::drivetrain::FlatbufferToTransformationMatrix(
510 *calibration->fixed_extrinsics());
James Kuszmaul8c4f6592022-02-26 15:49:30 -0800511
512 // Calculate the pose of the camera relative to the robot origin.
513 Eigen::Matrix<double, 4, 4> H_robot_camera = fixed_extrinsics;
514 if (is_turret) {
515 H_robot_camera =
516 H_robot_camera *
517 frc971::control_loops::TransformationMatrixForYaw<double>(
518 state.turret_position) *
James Kuszmaule3df1ed2023-02-20 16:21:17 -0800519 control_loops::drivetrain::FlatbufferToTransformationMatrix(
520 *calibration->turret_extrinsics());
James Kuszmaul8c4f6592022-02-26 15:49:30 -0800521 }
522 return H_robot_camera;
523}
524
525const std::optional<Eigen::Vector2d>
526ModelBasedLocalizer::CameraMeasuredRobotPosition(
527 const OldPosition &state, const y2022::vision::TargetEstimate *target,
James Kuszmaul0dedb5e2022-03-05 16:02:20 -0800528 std::optional<RejectionReason> *rejection_reason,
529 Eigen::Matrix<double, 4, 4> *H_field_camera_measured) const {
James Kuszmaul8c4f6592022-02-26 15:49:30 -0800530 if (!target->has_camera_calibration()) {
531 *rejection_reason = RejectionReason::NO_CALIBRATION;
532 return std::nullopt;
533 }
534 const Eigen::Matrix<double, 4, 4> H_robot_camera =
535 CameraTransform(state, target->camera_calibration(), rejection_reason);
536 const control_loops::Pose robot_pose(
537 {state.xytheta(0), state.xytheta(1), 0.0}, state.xytheta(2));
538 const Eigen::Matrix<double, 4, 4> H_field_robot =
539 robot_pose.AsTransformationMatrix();
540 // Current estimated pose of the camera in the global frame.
541 // Note that this is all really just an elaborate way of extracting the
542 // current estimated camera yaw, and nothing else.
543 const Eigen::Matrix<double, 4, 4> H_field_camera =
544 H_field_robot * H_robot_camera;
545 // Grab the implied yaw of the camera (the +Z axis is coming out of the front
546 // of the cameras).
547 const Eigen::Vector3d rotated_camera_z =
548 H_field_camera.block<3, 3>(0, 0) * Eigen::Vector3d(0, 0, 1);
549 const double camera_yaw =
550 std::atan2(rotated_camera_z.y(), rotated_camera_z.x());
551 // All right, now we need to use the heading and distance from the
552 // TargetEstimate, plus the yaw embedded in the camera_pose, to determine what
553 // the implied X/Y position of the robot is. To do this, we calculate the
554 // heading/distance from the target to the robot. The distance is easy, since
555 // that's the same as the distance from the robot to the target. The heading
556 // isn't too hard, but is obnoxious to think about, since the heading from the
557 // target to the robot is distinct from the heading from the robot to the
558 // target.
559
560 // Just to walk through examples to confirm that the below calculation is
561 // correct:
562 // * If yaw = 0, and angle_to_target = 0, we are at 180 deg relative to the
563 // target.
564 // * If yaw = 90 deg, and angle_to_target = 0, we are at -90 deg relative to
565 // the target.
566 // * If yaw = 0, and angle_to_target = 90 deg, we are at -90 deg relative to
567 // the target.
568 const double heading_from_target =
569 aos::math::NormalizeAngle(M_PI + camera_yaw + target->angle_to_target());
570 const double distance_from_target = target->distance();
571 // Extract the implied camera position on the field.
James Kuszmaul0dedb5e2022-03-05 16:02:20 -0800572 *H_field_camera_measured = H_field_camera;
James Kuszmaul8c4f6592022-02-26 15:49:30 -0800573 // TODO(james): Are we going to need to evict the roll/pitch components of the
574 // camera extrinsics this year as well?
James Kuszmaul0dedb5e2022-03-05 16:02:20 -0800575 (*H_field_camera_measured)(0, 3) =
James Kuszmaul8c4f6592022-02-26 15:49:30 -0800576 distance_from_target * std::cos(heading_from_target) + kVisionTargetX;
James Kuszmaul0dedb5e2022-03-05 16:02:20 -0800577 (*H_field_camera_measured)(1, 3) =
James Kuszmaul8c4f6592022-02-26 15:49:30 -0800578 distance_from_target * std::sin(heading_from_target) + kVisionTargetY;
579 const Eigen::Matrix<double, 4, 4> H_field_robot_measured =
James Kuszmaul0dedb5e2022-03-05 16:02:20 -0800580 *H_field_camera_measured * H_robot_camera.inverse();
James Kuszmaul8c4f6592022-02-26 15:49:30 -0800581 return H_field_robot_measured.block<2, 1>(0, 3);
582}
583
584void ModelBasedLocalizer::HandleImageMatch(
585 aos::monotonic_clock::time_point sample_time,
James Kuszmaul0dedb5e2022-03-05 16:02:20 -0800586 const y2022::vision::TargetEstimate *target, int camera_index) {
James Kuszmaul8c4f6592022-02-26 15:49:30 -0800587 std::optional<RejectionReason> rejection_reason;
588
James Kuszmaulaa39d962022-03-06 14:54:28 -0800589 if (target->confidence() < kMinTargetEstimateConfidence) {
590 rejection_reason = RejectionReason::LOW_CONFIDENCE;
591 TallyRejection(rejection_reason.value());
592 return;
593 }
594
James Kuszmaul8c4f6592022-02-26 15:49:30 -0800595 const OldPosition &state = GetStateForTime(sample_time);
James Kuszmaul0dedb5e2022-03-05 16:02:20 -0800596 Eigen::Matrix<double, 4, 4> H_field_camera_measured;
James Kuszmaul8c4f6592022-02-26 15:49:30 -0800597 const std::optional<Eigen::Vector2d> measured_robot_position =
James Kuszmaul0dedb5e2022-03-05 16:02:20 -0800598 CameraMeasuredRobotPosition(state, target, &rejection_reason,
599 &H_field_camera_measured);
James Kuszmaul8c4f6592022-02-26 15:49:30 -0800600 // Technically, rejection_reason should always be set if
601 // measured_robot_position is nullopt, but in the future we may have more
602 // recoverable rejection reasons that we wish to allow to propagate further
603 // into the process.
604 if (!measured_robot_position || rejection_reason.has_value()) {
605 CHECK(rejection_reason.has_value());
606 TallyRejection(rejection_reason.value());
607 return;
608 }
609
610 // Next, go through and do the actual Kalman corrections for the x/y
611 // measurement, for both the accel state and the model-based state.
612 const Eigen::Matrix<double, kNModelStates, kNModelStates> A_continuous_model =
613 AModel(current_state_.model_state);
614
615 Eigen::Matrix<double, kNModelStates, kNModelStates> A_discrete_model;
616 Eigen::Matrix<double, kNModelStates, kNModelStates> Q_discrete_model;
617
618 DiscretizeQAFast(Q_continuous_model_, A_continuous_model, kNominalDt,
619 &Q_discrete_model, &A_discrete_model);
620
621 Eigen::Matrix<double, 2, kNModelStates> H_model;
622 H_model.setZero();
623 Eigen::Matrix<double, 2, kNAccelStates> H_accel;
624 H_accel.setZero();
625 Eigen::Matrix<double, 2, 2> R;
626 R.setZero();
627 H_model(0, kX) = 1.0;
628 H_model(1, kY) = 1.0;
629 H_accel(0, kX) = 1.0;
630 H_accel(1, kY) = 1.0;
James Kuszmaul20014542022-04-06 21:35:44 -0700631 if (aggressive_corrections_) {
632 R.diagonal() << 1e-2, 1e-2;
633 } else {
634 R.diagonal() << 1e-0, 1e-0;
635 }
James Kuszmaul8c4f6592022-02-26 15:49:30 -0800636
637 const Eigen::Matrix<double, kNModelStates, 2> K_model =
638 P_model_ * H_model.transpose() *
639 (H_model * P_model_ * H_model.transpose() + R).inverse();
640 const Eigen::Matrix<double, kNAccelStates, 2> K_accel =
641 P_accel_ * H_accel.transpose() *
642 (H_accel * P_accel_ * H_accel.transpose() + R).inverse();
643 P_model_ = (Eigen::Matrix<double, kNModelStates, kNModelStates>::Identity() -
644 K_model * H_model) *
645 P_model_;
646 P_accel_ = (Eigen::Matrix<double, kNAccelStates, kNAccelStates>::Identity() -
647 K_accel * H_accel) *
648 P_accel_;
649 // And now we have to correct *everything* on all the branches:
650 for (CombinedState &state : branches_) {
651 state.model_state += K_model * (measured_robot_position.value() -
James Kuszmaulf6b69112022-03-12 21:34:39 -0800652 H_model * state.model_state);
James Kuszmaul8c4f6592022-02-26 15:49:30 -0800653 state.accel_state += K_accel * (measured_robot_position.value() -
James Kuszmaulf6b69112022-03-12 21:34:39 -0800654 H_accel * state.accel_state);
James Kuszmaul8c4f6592022-02-26 15:49:30 -0800655 }
656 current_state_.model_state +=
657 K_model *
658 (measured_robot_position.value() - H_model * current_state_.model_state);
659 current_state_.accel_state +=
660 K_accel *
661 (measured_robot_position.value() - H_accel * current_state_.accel_state);
662
663 statistics_.total_accepted++;
664 statistics_.total_candidates++;
James Kuszmaul0dedb5e2022-03-05 16:02:20 -0800665
666 const Eigen::Vector3d camera_z_in_field =
667 H_field_camera_measured.block<3, 3>(0, 0) * Eigen::Vector3d::UnitZ();
668 const double camera_yaw =
669 std::atan2(camera_z_in_field.y(), camera_z_in_field.x());
670
Milind Upadhyayd67e9cf2022-03-13 13:56:57 -0700671 // TODO(milind): actually control this
672 led_outputs_[camera_index] = LedOutput::ON;
673
James Kuszmaul0dedb5e2022-03-05 16:02:20 -0800674 TargetEstimateDebugT debug;
675 debug.camera = static_cast<uint8_t>(camera_index);
676 debug.camera_x = H_field_camera_measured(0, 3);
677 debug.camera_y = H_field_camera_measured(1, 3);
678 debug.camera_theta = camera_yaw;
679 debug.implied_robot_x = measured_robot_position.value().x();
680 debug.implied_robot_y = measured_robot_position.value().y();
681 debug.implied_robot_theta = xytheta()(2);
682 debug.implied_turret_goal =
683 aos::math::NormalizeAngle(camera_yaw + target->angle_to_target());
684 debug.accepted = true;
685 debug.image_age_sec = aos::time::DurationInSeconds(t_ - sample_time);
James Kuszmaul2b2f8772022-03-12 15:25:35 -0800686 CHECK_LT(image_debugs_.size(), kDebugBufferSize);
James Kuszmaul0dedb5e2022-03-05 16:02:20 -0800687 image_debugs_.push_back(debug);
James Kuszmaul8c4f6592022-02-26 15:49:30 -0800688}
689
690void ModelBasedLocalizer::HandleTurret(
691 aos::monotonic_clock::time_point sample_time, double turret_position,
692 double turret_velocity) {
693 last_turret_update_ = sample_time;
694 latest_turret_position_ = turret_position;
695 latest_turret_velocity_ = turret_velocity;
696}
697
James Kuszmaul29c59522022-02-12 16:44:26 -0800698void ModelBasedLocalizer::HandleReset(aos::monotonic_clock::time_point now,
699 const Eigen::Vector3d &xytheta) {
700 branches_.Reset();
James Kuszmaulf6b69112022-03-12 21:34:39 -0800701 t_ = now;
James Kuszmaul29c59522022-02-12 16:44:26 -0800702 using_model_ = true;
703 current_state_.model_state << xytheta(0), xytheta(1), xytheta(2),
704 current_state_.model_state(kLeftEncoder), 0.0, 0.0,
705 current_state_.model_state(kRightEncoder), 0.0, 0.0;
706 current_state_.accel_state =
707 AccelStateForModelState(current_state_.model_state);
708 last_residual_ = 0.0;
709 filtered_residual_ = 0.0;
710 filtered_residual_accel_.setZero();
711 abs_accel_.setZero();
712}
713
714flatbuffers::Offset<AccelBasedState> ModelBasedLocalizer::BuildAccelState(
715 flatbuffers::FlatBufferBuilder *fbb, const AccelState &state) {
716 AccelBasedState::Builder accel_state_builder(*fbb);
717 accel_state_builder.add_x(state(kX));
718 accel_state_builder.add_y(state(kY));
719 accel_state_builder.add_theta(state(kTheta));
720 accel_state_builder.add_velocity_x(state(kVelocityX));
721 accel_state_builder.add_velocity_y(state(kVelocityY));
722 return accel_state_builder.Finish();
723}
724
725flatbuffers::Offset<ModelBasedState> ModelBasedLocalizer::BuildModelState(
726 flatbuffers::FlatBufferBuilder *fbb, const ModelState &state) {
727 ModelBasedState::Builder model_state_builder(*fbb);
728 model_state_builder.add_x(state(kX));
729 model_state_builder.add_y(state(kY));
730 model_state_builder.add_theta(state(kTheta));
731 model_state_builder.add_left_encoder(state(kLeftEncoder));
732 model_state_builder.add_left_velocity(state(kLeftVelocity));
733 model_state_builder.add_left_voltage_error(state(kLeftVoltageError));
734 model_state_builder.add_right_encoder(state(kRightEncoder));
735 model_state_builder.add_right_velocity(state(kRightVelocity));
736 model_state_builder.add_right_voltage_error(state(kRightVoltageError));
737 return model_state_builder.Finish();
738}
739
James Kuszmaul0dedb5e2022-03-05 16:02:20 -0800740flatbuffers::Offset<CumulativeStatistics>
741ModelBasedLocalizer::PopulateStatistics(flatbuffers::FlatBufferBuilder *fbb) {
James Kuszmaul8c4f6592022-02-26 15:49:30 -0800742 const auto rejections_offset = fbb->CreateVector(
743 statistics_.rejection_counts.data(), statistics_.rejection_counts.size());
744
745 CumulativeStatistics::Builder stats_builder(*fbb);
746 stats_builder.add_total_accepted(statistics_.total_accepted);
747 stats_builder.add_total_candidates(statistics_.total_candidates);
748 stats_builder.add_rejection_reason_count(rejections_offset);
James Kuszmaul0dedb5e2022-03-05 16:02:20 -0800749 return stats_builder.Finish();
750}
751
752flatbuffers::Offset<ModelBasedStatus> ModelBasedLocalizer::PopulateStatus(
753 flatbuffers::FlatBufferBuilder *fbb) {
James Kuszmaul8c4f6592022-02-26 15:49:30 -0800754 const flatbuffers::Offset<CumulativeStatistics> stats_offset =
James Kuszmaul0dedb5e2022-03-05 16:02:20 -0800755 PopulateStatistics(fbb);
James Kuszmaul8c4f6592022-02-26 15:49:30 -0800756
James Kuszmaul29c59522022-02-12 16:44:26 -0800757 const flatbuffers::Offset<control_loops::drivetrain::DownEstimatorState>
758 down_estimator_offset = down_estimator_.PopulateStatus(fbb, t_);
759
760 const CombinedState &state = current_state_;
761
762 const flatbuffers::Offset<ModelBasedState> model_state_offset =
James Kuszmaulf6b69112022-03-12 21:34:39 -0800763 BuildModelState(fbb, state.model_state);
James Kuszmaul29c59522022-02-12 16:44:26 -0800764
765 const flatbuffers::Offset<AccelBasedState> accel_state_offset =
766 BuildAccelState(fbb, state.accel_state);
767
768 const flatbuffers::Offset<AccelBasedState> oldest_accel_state_offset =
769 branches_.empty() ? flatbuffers::Offset<AccelBasedState>()
770 : BuildAccelState(fbb, branches_[0].accel_state);
771
772 const flatbuffers::Offset<ModelBasedState> oldest_model_state_offset =
773 branches_.empty() ? flatbuffers::Offset<ModelBasedState>()
774 : BuildModelState(fbb, branches_[0].model_state);
775
776 ModelBasedStatus::Builder builder(*fbb);
777 builder.add_accel_state(accel_state_offset);
778 builder.add_oldest_accel_state(oldest_accel_state_offset);
779 builder.add_oldest_model_state(oldest_model_state_offset);
780 builder.add_model_state(model_state_offset);
781 builder.add_using_model(using_model_);
782 builder.add_residual(last_residual_);
783 builder.add_filtered_residual(filtered_residual_);
784 builder.add_velocity_residual(velocity_residual_);
785 builder.add_accel_residual(accel_residual_);
786 builder.add_theta_rate_residual(theta_rate_residual_);
787 builder.add_down_estimator(down_estimator_offset);
788 builder.add_x(xytheta()(0));
789 builder.add_y(xytheta()(1));
790 builder.add_theta(xytheta()(2));
791 builder.add_implied_accel_x(abs_accel_(0));
792 builder.add_implied_accel_y(abs_accel_(1));
793 builder.add_implied_accel_z(abs_accel_(2));
794 builder.add_clock_resets(clock_resets_);
James Kuszmaul8c4f6592022-02-26 15:49:30 -0800795 builder.add_statistics(stats_offset);
James Kuszmaul29c59522022-02-12 16:44:26 -0800796 return builder.Finish();
797}
798
James Kuszmaul0dedb5e2022-03-05 16:02:20 -0800799flatbuffers::Offset<LocalizerVisualization>
800ModelBasedLocalizer::PopulateVisualization(
801 flatbuffers::FlatBufferBuilder *fbb) {
802 const flatbuffers::Offset<CumulativeStatistics> stats_offset =
803 PopulateStatistics(fbb);
804
805 aos::SizedArray<flatbuffers::Offset<TargetEstimateDebug>, kDebugBufferSize>
806 debug_offsets;
807
James Kuszmaulf6b69112022-03-12 21:34:39 -0800808 for (const TargetEstimateDebugT &debug : image_debugs_) {
James Kuszmaul0dedb5e2022-03-05 16:02:20 -0800809 debug_offsets.push_back(PackTargetEstimateDebug(debug, fbb));
810 }
811
812 image_debugs_.clear();
813
814 const flatbuffers::Offset<
815 flatbuffers::Vector<flatbuffers::Offset<TargetEstimateDebug>>>
816 debug_offset =
817 fbb->CreateVector(debug_offsets.data(), debug_offsets.size());
818
819 LocalizerVisualization::Builder builder(*fbb);
820 builder.add_statistics(stats_offset);
821 builder.add_targets(debug_offset);
822 return builder.Finish();
823}
824
825void ModelBasedLocalizer::TallyRejection(const RejectionReason reason) {
826 statistics_.total_candidates++;
827 statistics_.rejection_counts[static_cast<size_t>(reason)]++;
828 TargetEstimateDebugT debug;
829 debug.accepted = false;
830 debug.rejection_reason = reason;
James Kuszmaul2b2f8772022-03-12 15:25:35 -0800831 CHECK_LT(image_debugs_.size(), kDebugBufferSize);
James Kuszmaul0dedb5e2022-03-05 16:02:20 -0800832 image_debugs_.push_back(debug);
833}
834
835flatbuffers::Offset<TargetEstimateDebug>
836ModelBasedLocalizer::PackTargetEstimateDebug(
837 const TargetEstimateDebugT &debug, flatbuffers::FlatBufferBuilder *fbb) {
838 if (!debug.accepted) {
839 TargetEstimateDebug::Builder builder(*fbb);
840 builder.add_accepted(debug.accepted);
841 builder.add_rejection_reason(debug.rejection_reason);
842 return builder.Finish();
843 } else {
844 flatbuffers::Offset<TargetEstimateDebug> offset =
845 TargetEstimateDebug::Pack(*fbb, &debug);
846 flatbuffers::GetMutableTemporaryPointer(*fbb, offset)
847 ->clear_rejection_reason();
848 return offset;
849 }
850}
851
James Kuszmaul29c59522022-02-12 16:44:26 -0800852EventLoopLocalizer::EventLoopLocalizer(
853 aos::EventLoop *event_loop,
854 const control_loops::drivetrain::DrivetrainConfig<double> &dt_config)
855 : event_loop_(event_loop),
856 model_based_(dt_config),
857 status_sender_(event_loop_->MakeSender<LocalizerStatus>("/localizer")),
858 output_sender_(event_loop_->MakeSender<LocalizerOutput>("/localizer")),
James Kuszmaul0dedb5e2022-03-05 16:02:20 -0800859 visualization_sender_(
860 event_loop_->MakeSender<LocalizerVisualization>("/localizer")),
James Kuszmaulf6b69112022-03-12 21:34:39 -0800861 superstructure_fetcher_(
862 event_loop_
863 ->MakeFetcher<y2022::control_loops::superstructure::Status>(
864 "/superstructure")),
James Kuszmaul9f2f53c2023-02-19 14:08:18 -0800865 imu_watcher_(event_loop, dt_config,
866 y2022::constants::Values::DrivetrainEncoderToMeters(1),
867 [this](aos::monotonic_clock::time_point sample_time_pico,
868 aos::monotonic_clock::time_point sample_time_pi,
869 std::optional<Eigen::Vector2d> encoders,
870 Eigen::Vector3d gyro, Eigen::Vector3d accel) {
871 HandleImu(sample_time_pico, sample_time_pi, encoders, gyro,
872 accel);
James Kuszmaul9a1733a2023-02-19 16:51:47 -0800873 }),
874 utils_(event_loop) {
James Kuszmaula391dde2022-03-17 00:03:30 -0700875 event_loop->SetRuntimeRealtimePriority(10);
James Kuszmaul29c59522022-02-12 16:44:26 -0800876 event_loop_->MakeWatcher(
877 "/drivetrain",
878 [this](
879 const frc971::control_loops::drivetrain::LocalizerControl &control) {
880 const double theta = control.keep_current_theta()
881 ? model_based_.xytheta()(2)
882 : control.theta();
883 model_based_.HandleReset(event_loop_->monotonic_now(),
James Kuszmaul8c4f6592022-02-26 15:49:30 -0800884 {control.x(), control.y(), theta});
James Kuszmaul29c59522022-02-12 16:44:26 -0800885 });
James Kuszmaul2b2f8772022-03-12 15:25:35 -0800886 aos::TimerHandler *superstructure_timer = event_loop_->AddTimer([this]() {
887 if (superstructure_fetcher_.Fetch()) {
888 const y2022::control_loops::superstructure::Status &status =
889 *superstructure_fetcher_.get();
890 if (!status.has_turret()) {
891 return;
892 }
893 CHECK(status.has_turret());
894 model_based_.HandleTurret(
895 superstructure_fetcher_.context().monotonic_event_time,
896 status.turret()->position(), status.turret()->velocity());
897 }
898 });
899 event_loop_->OnRun([this, superstructure_timer]() {
900 superstructure_timer->Setup(event_loop_->monotonic_now(),
901 std::chrono::milliseconds(20));
902 });
James Kuszmaul8c4f6592022-02-26 15:49:30 -0800903
James Kuszmaulf6b69112022-03-12 21:34:39 -0800904 for (size_t camera_index = 0; camera_index < kPisToUse.size();
905 ++camera_index) {
James Kuszmaul2b2f8772022-03-12 15:25:35 -0800906 CHECK_LT(camera_index, target_estimate_fetchers_.size());
907 target_estimate_fetchers_[camera_index] =
908 event_loop_->MakeFetcher<y2022::vision::TargetEstimate>(
909 absl::StrCat("/", kPisToUse[camera_index], "/camera"));
910 }
James Kuszmaulf6b69112022-03-12 21:34:39 -0800911 aos::TimerHandler *estimate_timer = event_loop_->AddTimer([this]() {
Philipp Schrader790cb542023-07-05 21:06:52 -0700912 const bool maybe_in_auto = utils_.MaybeInAutonomous();
913 model_based_.set_use_aggressive_image_corrections(!maybe_in_auto);
914 for (size_t camera_index = 0; camera_index < kPisToUse.size();
915 ++camera_index) {
916 if (model_based_.NumQueuedImageDebugs() ==
917 ModelBasedLocalizer::kDebugBufferSize ||
918 (last_visualization_send_ + kMinVisualizationPeriod <
919 event_loop_->monotonic_now())) {
920 auto builder = visualization_sender_.MakeBuilder();
921 visualization_sender_.CheckOk(
922 builder.Send(model_based_.PopulateVisualization(builder.fbb())));
923 }
924 if (target_estimate_fetchers_[camera_index].Fetch()) {
925 const std::optional<aos::monotonic_clock::duration> monotonic_offset =
926 utils_.ClockOffset(kPisToUse[camera_index]);
927 if (!monotonic_offset.has_value()) {
928 model_based_.TallyRejection(
929 RejectionReason::MESSAGE_BRIDGE_DISCONNECTED);
930 continue;
James Kuszmaul2b2f8772022-03-12 15:25:35 -0800931 }
Philipp Schrader790cb542023-07-05 21:06:52 -0700932 // TODO(james): Get timestamp from message contents.
933 aos::monotonic_clock::time_point capture_time(
934 target_estimate_fetchers_[camera_index]
935 .context()
936 .monotonic_remote_time -
937 monotonic_offset.value());
938 if (capture_time > target_estimate_fetchers_[camera_index]
939 .context()
940 .monotonic_event_time) {
941 model_based_.TallyRejection(RejectionReason::IMAGE_FROM_FUTURE);
942 continue;
James Kuszmaulf6b69112022-03-12 21:34:39 -0800943 }
Philipp Schrader790cb542023-07-05 21:06:52 -0700944 capture_time -= imu_watcher_.pico_offset_error();
945 model_based_.HandleImageMatch(
946 capture_time, target_estimate_fetchers_[camera_index].get(),
947 camera_index);
948 }
James Kuszmaulf6b69112022-03-12 21:34:39 -0800949 }
950 });
James Kuszmaul2b2f8772022-03-12 15:25:35 -0800951 event_loop_->OnRun([this, estimate_timer]() {
952 estimate_timer->Setup(event_loop_->monotonic_now(),
953 std::chrono::milliseconds(100));
954 });
James Kuszmaul9f2f53c2023-02-19 14:08:18 -0800955}
James Kuszmaul5f27d8b2022-03-17 09:08:26 -0700956
James Kuszmaul9f2f53c2023-02-19 14:08:18 -0800957void EventLoopLocalizer::HandleImu(
958 aos::monotonic_clock::time_point sample_time_pico,
959 aos::monotonic_clock::time_point sample_time_pi,
960 std::optional<Eigen::Vector2d> encoders, Eigen::Vector3d gyro,
961 Eigen::Vector3d accel) {
James Kuszmaul9a1733a2023-02-19 16:51:47 -0800962 model_based_.HandleImu(
963 sample_time_pico, gyro, accel, encoders,
964 utils_.VoltageOrZero(event_loop_->context().monotonic_event_time));
965
James Kuszmaul9f2f53c2023-02-19 14:08:18 -0800966 {
967 auto builder = status_sender_.MakeBuilder();
968 const flatbuffers::Offset<ModelBasedStatus> model_based_status =
969 model_based_.PopulateStatus(builder.fbb());
970 const flatbuffers::Offset<control_loops::drivetrain::ImuZeroerState>
971 zeroer_status = imu_watcher_.zeroer().PopulateStatus(builder.fbb());
972 const flatbuffers::Offset<ImuFailures> imu_failures =
973 imu_watcher_.PopulateImuFailures(builder.fbb());
974 LocalizerStatus::Builder status_builder =
975 builder.MakeBuilder<LocalizerStatus>();
976 status_builder.add_model_based(model_based_status);
977 status_builder.add_zeroed(imu_watcher_.zeroer().Zeroed());
978 status_builder.add_faulted_zero(imu_watcher_.zeroer().Faulted());
979 status_builder.add_zeroing(zeroer_status);
980 status_builder.add_imu_failures(imu_failures);
981 if (encoders.has_value()) {
982 status_builder.add_left_encoder(encoders.value()(0));
983 status_builder.add_right_encoder(encoders.value()(1));
984 }
985 if (imu_watcher_.pico_offset().has_value()) {
986 status_builder.add_pico_offset_ns(
987 imu_watcher_.pico_offset().value().count());
988 status_builder.add_pico_offset_error_ns(
989 imu_watcher_.pico_offset_error().count());
990 }
991 builder.CheckOk(builder.Send(status_builder.Finish()));
992 }
993 if (last_output_send_ + std::chrono::milliseconds(5) <
994 event_loop_->context().monotonic_event_time) {
995 auto builder = output_sender_.MakeBuilder();
Milind Upadhyayd67e9cf2022-03-13 13:56:57 -0700996
James Kuszmaul9f2f53c2023-02-19 14:08:18 -0800997 const auto led_outputs_offset = builder.fbb()->CreateVector(
998 model_based_.led_outputs().data(), model_based_.led_outputs().size());
Milind Upadhyayd67e9cf2022-03-13 13:56:57 -0700999
James Kuszmaul9f2f53c2023-02-19 14:08:18 -08001000 LocalizerOutput::Builder output_builder =
1001 builder.MakeBuilder<LocalizerOutput>();
1002 output_builder.add_monotonic_timestamp_ns(
1003 std::chrono::duration_cast<std::chrono::nanoseconds>(
1004 sample_time_pi.time_since_epoch())
1005 .count());
1006 output_builder.add_x(model_based_.xytheta()(0));
1007 output_builder.add_y(model_based_.xytheta()(1));
1008 output_builder.add_theta(model_based_.xytheta()(2));
1009 output_builder.add_zeroed(imu_watcher_.zeroer().Zeroed());
1010 output_builder.add_image_accepted_count(model_based_.total_accepted());
1011 const Eigen::Quaterniond &orientation = model_based_.orientation();
1012 Quaternion quaternion;
1013 quaternion.mutate_x(orientation.x());
1014 quaternion.mutate_y(orientation.y());
1015 quaternion.mutate_z(orientation.z());
1016 quaternion.mutate_w(orientation.w());
1017 output_builder.add_orientation(&quaternion);
1018 output_builder.add_led_outputs(led_outputs_offset);
1019 builder.CheckOk(builder.Send(output_builder.Finish()));
1020 last_output_send_ = event_loop_->monotonic_now();
1021 }
James Kuszmaul29c59522022-02-12 16:44:26 -08001022}
1023
James Kuszmaul29c59522022-02-12 16:44:26 -08001024} // namespace frc971::controls