blob: 55bf16a4652bf4dcb002649927ca79a7d7ec412a [file] [log] [blame]
James Kuszmaul5398fae2020-02-17 16:44:03 -08001#include "y2020/control_loops/drivetrain/localizer.h"
2
3#include "y2020/constants.h"
4
5namespace y2020 {
6namespace control_loops {
7namespace drivetrain {
8
9namespace {
10// Converts a flatbuffer TransformationMatrix to an Eigen matrix. Technically,
11// this should be able to do a single memcpy, but the extra verbosity here seems
12// appropriate.
James Kuszmauld478f872020-03-16 20:54:27 -070013Eigen::Matrix<float, 4, 4> FlatbufferToTransformationMatrix(
James Kuszmaul5398fae2020-02-17 16:44:03 -080014 const frc971::vision::sift::TransformationMatrix &flatbuffer) {
15 CHECK_EQ(16u, CHECK_NOTNULL(flatbuffer.data())->size());
James Kuszmauld478f872020-03-16 20:54:27 -070016 Eigen::Matrix<float, 4, 4> result;
James Kuszmaul5398fae2020-02-17 16:44:03 -080017 result.setIdentity();
18 for (int row = 0; row < 4; ++row) {
19 for (int col = 0; col < 4; ++col) {
20 result(row, col) = (*flatbuffer.data())[row * 4 + col];
21 }
22 }
23 return result;
24}
James Kuszmaul958b21e2020-02-26 21:51:40 -080025
James Kuszmaulc6723cf2020-03-01 14:45:59 -080026// Indices of the pis to use.
James Kuszmaul9c128122021-03-22 22:24:36 -070027const std::array<std::string, 5> kPisToUse{"pi1", "pi2", "pi3", "pi4", "pi5"};
James Kuszmaulc6723cf2020-03-01 14:45:59 -080028
James Kuszmaul66efe832020-03-16 19:38:33 -070029// Calculates the pose implied by the camera target, just based on
30// distance/heading components.
James Kuszmaul5a46c8d2021-09-03 19:33:48 -070031Eigen::Vector3f CalculateImpliedPose(const Eigen::Matrix4f &H_field_target,
James Kuszmaul66efe832020-03-16 19:38:33 -070032 const Localizer::Pose &pose_robot_target) {
33 // This code overrides the pose sent directly from the camera code and
34 // effectively distills it down to just a distance + heading estimate, on
35 // the presumption that these signals will tend to be much lower noise and
36 // better-conditioned than other portions of the robot pose.
37 // As such, this code assumes that the current estimate of the robot
38 // heading is correct and then, given the heading from the camera to the
39 // target and the distance from the camera to the target, calculates the
40 // position that the robot would have to be at to make the current camera
41 // heading + distance correct. This X/Y implied robot position is then
42 // used as the measurement in the EKF, rather than the X/Y that is
43 // directly returned from the vision processing. This means that
44 // the cameras will not correct any drift in the robot heading estimate
45 // but will compensate for X/Y position in a way that prioritizes keeping
46 // an accurate distance + heading to the goal.
47
48 // Calculate the heading to the robot in the target's coordinate frame.
James Kuszmaul5a46c8d2021-09-03 19:33:48 -070049 // Reminder on what the numbers mean:
50 // rel_theta: The orientation of the target in the robot frame.
51 // heading: heading from the robot to the target in the robot frame. I.e.,
52 // atan2(y, x) for x/y of the target in the robot frame.
James Kuszmauld478f872020-03-16 20:54:27 -070053 const float implied_heading_from_target = aos::math::NormalizeAngle(
James Kuszmaul5a46c8d2021-09-03 19:33:48 -070054 M_PI - pose_robot_target.rel_theta() + pose_robot_target.heading());
James Kuszmauld478f872020-03-16 20:54:27 -070055 const float implied_distance = pose_robot_target.xy_norm();
56 const Eigen::Vector4f robot_pose_in_target_frame(
James Kuszmaul66efe832020-03-16 19:38:33 -070057 implied_distance * std::cos(implied_heading_from_target),
58 implied_distance * std::sin(implied_heading_from_target), 0, 1);
James Kuszmauld478f872020-03-16 20:54:27 -070059 const Eigen::Vector4f implied_pose =
James Kuszmaul66efe832020-03-16 19:38:33 -070060 H_field_target * robot_pose_in_target_frame;
61 return implied_pose.topRows<3>();
62}
63
James Kuszmaul5398fae2020-02-17 16:44:03 -080064} // namespace
65
66Localizer::Localizer(
67 aos::EventLoop *event_loop,
68 const frc971::control_loops::drivetrain::DrivetrainConfig<double>
69 &dt_config)
James Kuszmaul958b21e2020-02-26 21:51:40 -080070 : event_loop_(event_loop),
71 dt_config_(dt_config),
72 ekf_(dt_config),
73 clock_offset_fetcher_(
74 event_loop_->MakeFetcher<aos::message_bridge::ServerStatistics>(
James Kuszmaul5ff8a862021-09-25 17:29:43 -070075 "/aos")),
76 debug_sender_(
77 event_loop_
78 ->MakeSender<y2020::control_loops::drivetrain::LocalizerDebug>(
79 "/drivetrain")) {
James Kuszmaul91aa0cf2021-02-13 13:15:06 -080080 // TODO(james): The down estimator has trouble handling situations where the
81 // robot is constantly wiggling but not actually moving much, and can cause
82 // drift when using accelerometer readings.
83 ekf_.set_ignore_accel(true);
James Kuszmaul5398fae2020-02-17 16:44:03 -080084 // TODO(james): This doesn't really need to be a watcher; we could just use a
85 // fetcher for the superstructure status.
86 // This probably should be a Fetcher instead of a Watcher, but this
87 // seems simpler for the time being (although technically it should be
88 // possible to do everything we need to using just a Fetcher without
89 // even maintaining a separate buffer, but that seems overly cute).
90 event_loop_->MakeWatcher("/superstructure",
91 [this](const superstructure::Status &status) {
92 HandleSuperstructureStatus(status);
93 });
94
James Kuszmaul286b4282020-02-26 20:29:32 -080095 event_loop->OnRun([this, event_loop]() {
James Kuszmauld478f872020-03-16 20:54:27 -070096 ekf_.ResetInitialState(event_loop->monotonic_now(),
97 HybridEkf::State::Zero(), ekf_.P());
James Kuszmaul286b4282020-02-26 20:29:32 -080098 });
99
James Kuszmaulc6723cf2020-03-01 14:45:59 -0800100 for (const auto &pi : kPisToUse) {
101 image_fetchers_.emplace_back(
102 event_loop_->MakeFetcher<frc971::vision::sift::ImageMatchResult>(
103 "/" + pi + "/camera"));
104 }
James Kuszmaul5398fae2020-02-17 16:44:03 -0800105
106 target_selector_.set_has_target(false);
107}
108
James Kuszmaulbcd96fc2020-10-12 20:29:32 -0700109void Localizer::Reset(
110 aos::monotonic_clock::time_point t,
111 const frc971::control_loops::drivetrain::HybridEkf<double>::State &state) {
112 // Go through and clear out all of the fetchers so that we don't get behind.
113 for (auto &fetcher : image_fetchers_) {
114 fetcher.Fetch();
115 }
116 ekf_.ResetInitialState(t, state.cast<float>(), ekf_.P());
117}
118
James Kuszmaul5398fae2020-02-17 16:44:03 -0800119void Localizer::HandleSuperstructureStatus(
120 const y2020::control_loops::superstructure::Status &status) {
121 CHECK(status.has_turret());
122 turret_data_.Push({event_loop_->monotonic_now(), status.turret()->position(),
123 status.turret()->velocity()});
124}
125
126Localizer::TurretData Localizer::GetTurretDataForTime(
127 aos::monotonic_clock::time_point time) {
128 if (turret_data_.empty()) {
129 return {};
130 }
131
132 aos::monotonic_clock::duration lowest_time_error =
133 aos::monotonic_clock::duration::max();
134 TurretData best_data_match;
135 for (const auto &sample : turret_data_) {
136 const aos::monotonic_clock::duration time_error =
137 std::chrono::abs(sample.receive_time - time);
138 if (time_error < lowest_time_error) {
139 lowest_time_error = time_error;
140 best_data_match = sample;
141 }
142 }
143 return best_data_match;
144}
145
James Kuszmaul06257f42020-05-09 15:40:09 -0700146void Localizer::Update(const Eigen::Matrix<double, 2, 1> &U,
James Kuszmaul5398fae2020-02-17 16:44:03 -0800147 aos::monotonic_clock::time_point now,
148 double left_encoder, double right_encoder,
149 double gyro_rate, const Eigen::Vector3d &accel) {
James Kuszmauld478f872020-03-16 20:54:27 -0700150 ekf_.UpdateEncodersAndGyro(left_encoder, right_encoder, gyro_rate,
151 U.cast<float>(), accel.cast<float>(), now);
James Kuszmaul5ff8a862021-09-25 17:29:43 -0700152 auto builder = debug_sender_.MakeBuilder();
153 aos::SizedArray<flatbuffers::Offset<ImageMatchDebug>, 25> debug_offsets;
James Kuszmaulc6723cf2020-03-01 14:45:59 -0800154 for (size_t ii = 0; ii < kPisToUse.size(); ++ii) {
155 auto &image_fetcher = image_fetchers_[ii];
James Kuszmaul5398fae2020-02-17 16:44:03 -0800156 while (image_fetcher.FetchNext()) {
James Kuszmaul5ff8a862021-09-25 17:29:43 -0700157 const auto offsets = HandleImageMatch(ii, kPisToUse[ii], *image_fetcher,
158 now, builder.fbb());
159 for (const auto offset : offsets) {
160 debug_offsets.push_back(offset);
161 }
James Kuszmaul5398fae2020-02-17 16:44:03 -0800162 }
163 }
James Kuszmaul5ff8a862021-09-25 17:29:43 -0700164 const auto vector_offset =
165 builder.fbb()->CreateVector(debug_offsets.data(), debug_offsets.size());
166 LocalizerDebug::Builder debug_builder = builder.MakeBuilder<LocalizerDebug>();
167 debug_builder.add_matches(vector_offset);
168 CHECK(builder.Send(debug_builder.Finish()));
James Kuszmaul5398fae2020-02-17 16:44:03 -0800169}
170
James Kuszmaul5ff8a862021-09-25 17:29:43 -0700171aos::SizedArray<flatbuffers::Offset<ImageMatchDebug>, 5>
172Localizer::HandleImageMatch(
173 size_t camera_index, std::string_view pi,
174 const frc971::vision::sift::ImageMatchResult &result,
175 aos::monotonic_clock::time_point now, flatbuffers::FlatBufferBuilder *fbb) {
176 aos::SizedArray<flatbuffers::Offset<ImageMatchDebug>, 5> debug_offsets;
177
James Kuszmaul958b21e2020-02-26 21:51:40 -0800178 std::chrono::nanoseconds monotonic_offset(0);
179 clock_offset_fetcher_.Fetch();
180 if (clock_offset_fetcher_.get() != nullptr) {
181 for (const auto connection : *clock_offset_fetcher_->connections()) {
182 if (connection->has_node() && connection->node()->has_name() &&
James Kuszmaulc6723cf2020-03-01 14:45:59 -0800183 connection->node()->name()->string_view() == pi) {
James Kuszmaul958b21e2020-02-26 21:51:40 -0800184 monotonic_offset =
185 std::chrono::nanoseconds(connection->monotonic_offset());
186 break;
187 }
188 }
189 }
James Kuszmaul5398fae2020-02-17 16:44:03 -0800190 aos::monotonic_clock::time_point capture_time(
James Kuszmaul958b21e2020-02-26 21:51:40 -0800191 std::chrono::nanoseconds(result.image_monotonic_timestamp_ns()) -
192 monotonic_offset);
James Kuszmaul2d8fa2a2020-03-01 13:51:50 -0800193 VLOG(1) << "Got monotonic offset of "
194 << aos::time::DurationInSeconds(monotonic_offset)
James Kuszmaul58cb1fe2020-03-07 16:18:59 -0800195 << " when at time of " << now << " and capture time estimate of "
196 << capture_time;
197 if (capture_time > now) {
James Kuszmaul2d8fa2a2020-03-01 13:51:50 -0800198 LOG(WARNING) << "Got camera frame from the future.";
James Kuszmaul5ff8a862021-09-25 17:29:43 -0700199 ImageMatchDebug::Builder builder(*fbb);
200 builder.add_camera(camera_index);
201 builder.add_accepted(false);
202 builder.add_rejection_reason(RejectionReason::IMAGE_FROM_FUTURE);
203 debug_offsets.push_back(builder.Finish());
204 return debug_offsets;
James Kuszmaul2d8fa2a2020-03-01 13:51:50 -0800205 }
James Kuszmaulbcd96fc2020-10-12 20:29:32 -0700206 if (!result.has_camera_calibration()) {
207 LOG(WARNING) << "Got camera frame without calibration data.";
James Kuszmaul5ff8a862021-09-25 17:29:43 -0700208 ImageMatchDebug::Builder builder(*fbb);
209 builder.add_camera(camera_index);
210 builder.add_accepted(false);
211 builder.add_rejection_reason(RejectionReason::NO_CALIBRATION);
212 debug_offsets.push_back(builder.Finish());
213 return debug_offsets;
James Kuszmaulbcd96fc2020-10-12 20:29:32 -0700214 }
James Kuszmaul5398fae2020-02-17 16:44:03 -0800215 // Per the ImageMatchResult specification, we can actually determine whether
216 // the camera is the turret camera just from the presence of the
217 // turret_extrinsics member.
218 const bool is_turret = result.camera_calibration()->has_turret_extrinsics();
219 const TurretData turret_data = GetTurretDataForTime(capture_time);
220 // Ignore readings when the turret is spinning too fast, on the assumption
221 // that the odds of screwing up the time compensation are higher.
222 // Note that the current number here is chosen pretty arbitrarily--1 rad / sec
223 // seems reasonable, but may be unnecessarily low or high.
James Kuszmauld478f872020-03-16 20:54:27 -0700224 constexpr float kMaxTurretVelocity = 1.0;
James Kuszmaul5398fae2020-02-17 16:44:03 -0800225 if (is_turret && std::abs(turret_data.velocity) > kMaxTurretVelocity) {
James Kuszmaul5ff8a862021-09-25 17:29:43 -0700226 ImageMatchDebug::Builder builder(*fbb);
227 builder.add_camera(camera_index);
228 builder.add_accepted(false);
229 builder.add_rejection_reason(RejectionReason::TURRET_TOO_FAST);
230 debug_offsets.push_back(builder.Finish());
231 return debug_offsets;
James Kuszmaul5398fae2020-02-17 16:44:03 -0800232 }
233 CHECK(result.camera_calibration()->has_fixed_extrinsics());
James Kuszmauld478f872020-03-16 20:54:27 -0700234 const Eigen::Matrix<float, 4, 4> fixed_extrinsics =
James Kuszmaul5398fae2020-02-17 16:44:03 -0800235 FlatbufferToTransformationMatrix(
236 *result.camera_calibration()->fixed_extrinsics());
James Kuszmaul58cb1fe2020-03-07 16:18:59 -0800237
James Kuszmaul5398fae2020-02-17 16:44:03 -0800238 // Calculate the pose of the camera relative to the robot origin.
James Kuszmauld478f872020-03-16 20:54:27 -0700239 Eigen::Matrix<float, 4, 4> H_robot_camera = fixed_extrinsics;
James Kuszmaul5398fae2020-02-17 16:44:03 -0800240 if (is_turret) {
James Kuszmaulc51dbfe2020-02-23 15:39:00 -0800241 H_robot_camera = H_robot_camera *
James Kuszmauld478f872020-03-16 20:54:27 -0700242 frc971::control_loops::TransformationMatrixForYaw<float>(
James Kuszmaul5398fae2020-02-17 16:44:03 -0800243 turret_data.position) *
244 FlatbufferToTransformationMatrix(
245 *result.camera_calibration()->turret_extrinsics());
246 }
247
248 if (!result.has_camera_poses()) {
James Kuszmaul5ff8a862021-09-25 17:29:43 -0700249 ImageMatchDebug::Builder builder(*fbb);
250 builder.add_camera(camera_index);
251 builder.add_accepted(false);
252 builder.add_rejection_reason(RejectionReason::NO_RESULTS);
253 debug_offsets.push_back(builder.Finish());
254 return debug_offsets;
James Kuszmaul5398fae2020-02-17 16:44:03 -0800255 }
256
James Kuszmaul5ff8a862021-09-25 17:29:43 -0700257 int index = -1;
James Kuszmaul5398fae2020-02-17 16:44:03 -0800258 for (const frc971::vision::sift::CameraPose *vision_result :
259 *result.camera_poses()) {
James Kuszmaul5ff8a862021-09-25 17:29:43 -0700260 ++index;
261
262 ImageMatchDebug::Builder builder(*fbb);
263 builder.add_camera(camera_index);
264 builder.add_pose_index(index);
265 builder.add_local_image_capture_time_ns(result.image_monotonic_timestamp_ns());
266 builder.add_roborio_image_capture_time_ns(
267 capture_time.time_since_epoch().count());
268 builder.add_image_age_sec(aos::time::DurationInSeconds(now - capture_time));
269
James Kuszmaul5398fae2020-02-17 16:44:03 -0800270 if (!vision_result->has_camera_to_target() ||
271 !vision_result->has_field_to_target()) {
James Kuszmaul5ff8a862021-09-25 17:29:43 -0700272 builder.add_accepted(false);
273 builder.add_rejection_reason(RejectionReason::NO_TRANSFORMS);
274 debug_offsets.push_back(builder.Finish());
James Kuszmaul5398fae2020-02-17 16:44:03 -0800275 continue;
276 }
James Kuszmauld478f872020-03-16 20:54:27 -0700277 const Eigen::Matrix<float, 4, 4> H_camera_target =
James Kuszmaul5398fae2020-02-17 16:44:03 -0800278 FlatbufferToTransformationMatrix(*vision_result->camera_to_target());
James Kuszmaul58cb1fe2020-03-07 16:18:59 -0800279
James Kuszmauld478f872020-03-16 20:54:27 -0700280 const Eigen::Matrix<float, 4, 4> H_field_target =
James Kuszmaul5398fae2020-02-17 16:44:03 -0800281 FlatbufferToTransformationMatrix(*vision_result->field_to_target());
282 // Back out the robot position that is implied by the current camera
James Kuszmaul715e7932021-04-05 20:45:57 -0700283 // reading. Note that the Pose object ignores any roll/pitch components, so
284 // if the camera's extrinsics for pitch/roll are off, this should just
285 // ignore it.
James Kuszmaulaca88782021-04-24 16:48:45 -0700286 const Pose measured_camera_pose(H_field_target * H_camera_target.inverse());
287 // Calculate the camera-to-robot transformation matrix ignoring the
288 // pitch/roll of the camera.
289 // TODO(james): This could probably be made a bit more efficient, but I
290 // don't think this is anywhere near our bottleneck currently.
291 const Eigen::Matrix<float, 4, 4> H_camera_robot_stripped =
292 Pose(H_robot_camera).AsTransformationMatrix().inverse();
293 const Pose measured_pose(measured_camera_pose.AsTransformationMatrix() *
294 H_camera_robot_stripped);
James Kuszmaul66efe832020-03-16 19:38:33 -0700295 // This "Z" is the robot pose directly implied by the camera results.
296 // Currently, we do not actually use this result directly. However, it is
297 // kept around in case we want to quickly re-enable it.
James Kuszmauld478f872020-03-16 20:54:27 -0700298 const Eigen::Matrix<float, 3, 1> Z(measured_pose.rel_pos().x(),
299 measured_pose.rel_pos().y(),
300 measured_pose.rel_theta());
James Kuszmaul58cb1fe2020-03-07 16:18:59 -0800301 // Pose of the target in the robot frame.
James Kuszmaul715e7932021-04-05 20:45:57 -0700302 // Note that we use measured_pose's transformation matrix rather than just
303 // doing H_robot_camera * H_camera_target because measured_pose ignores
304 // pitch/roll.
305 Pose pose_robot_target(measured_pose.AsTransformationMatrix().inverse() *
306 H_field_target);
James Kuszmaul5398fae2020-02-17 16:44:03 -0800307 // TODO(james): Figure out how to properly handle calculating the
308 // noise. Currently, the values are deliberately tuned so that image updates
309 // will not be trusted overly much. In theory, we should probably also be
310 // populating some cross-correlation terms.
311 // Note that these are the noise standard deviations (they are squared below
312 // to get variances).
James Kuszmauld478f872020-03-16 20:54:27 -0700313 Eigen::Matrix<float, 3, 1> noises(2.0, 2.0, 0.2);
James Kuszmaul5398fae2020-02-17 16:44:03 -0800314 // Augment the noise by the approximate rotational speed of the
315 // camera. This should help account for the fact that, while we are
316 // spinning, slight timing errors in the camera/turret data will tend to
317 // have mutch more drastic effects on the results.
318 noises *= 1.0 + std::abs((right_velocity() - left_velocity()) /
319 (2.0 * dt_config_.robot_radius) +
320 (is_turret ? turret_data.velocity : 0.0));
James Kuszmauld478f872020-03-16 20:54:27 -0700321 Eigen::Matrix3f R = Eigen::Matrix3f::Zero();
James Kuszmaul5398fae2020-02-17 16:44:03 -0800322 R.diagonal() = noises.cwiseAbs2();
James Kuszmauld478f872020-03-16 20:54:27 -0700323 Eigen::Matrix<float, HybridEkf::kNOutputs, HybridEkf::kNStates> H;
James Kuszmaul5398fae2020-02-17 16:44:03 -0800324 H.setZero();
325 H(0, StateIdx::kX) = 1;
326 H(1, StateIdx::kY) = 1;
James Kuszmaul58cb1fe2020-03-07 16:18:59 -0800327 // This is currently set to zero because we ignore the heading implied by
328 // the camera.
329 H(2, StateIdx::kTheta) = 0;
330 VLOG(1) << "Pose implied by target: " << Z.transpose()
331 << " and current pose " << x() << ", " << y() << ", " << theta()
332 << " Heading/dist/skew implied by target: "
333 << pose_robot_target.ToHeadingDistanceSkew().transpose();
James Kuszmauladd40ca2020-03-01 14:10:50 -0800334 // If the heading is off by too much, assume that we got a false-positive
335 // and don't use the correction.
James Kuszmauld478f872020-03-16 20:54:27 -0700336 if (std::abs(aos::math::DiffAngle<float>(theta(), Z(2))) > M_PI_2) {
James Kuszmauladd40ca2020-03-01 14:10:50 -0800337 AOS_LOG(WARNING, "Dropped image match due to heading mismatch.\n");
James Kuszmaul5ff8a862021-09-25 17:29:43 -0700338 builder.add_accepted(false);
339 builder.add_rejection_reason(RejectionReason::HIGH_THETA_DIFFERENCE);
340 debug_offsets.push_back(builder.Finish());
James Kuszmaul58cb1fe2020-03-07 16:18:59 -0800341 continue;
James Kuszmauladd40ca2020-03-01 14:10:50 -0800342 }
James Kuszmaul06257f42020-05-09 15:40:09 -0700343 // In order to do the EKF correction, we determine the expected state based
344 // on the state at the time the image was captured; however, we insert the
345 // correction update itself at the current time. This is technically not
346 // quite correct, but saves substantial CPU usage by making it so that we
347 // don't have to constantly rewind the entire EKF history.
348 const std::optional<State> state_at_capture =
349 ekf_.LastStateBeforeTime(capture_time);
350 if (!state_at_capture.has_value()) {
351 AOS_LOG(WARNING, "Dropped image match due to age of image.\n");
James Kuszmaul5ff8a862021-09-25 17:29:43 -0700352 builder.add_accepted(false);
353 builder.add_rejection_reason(RejectionReason::IMAGE_TOO_OLD);
354 debug_offsets.push_back(builder.Finish());
James Kuszmaul06257f42020-05-09 15:40:09 -0700355 continue;
356 }
James Kuszmaul5ff8a862021-09-25 17:29:43 -0700357
358 builder.add_implied_robot_x(Z(0));
359 builder.add_implied_robot_y(Z(1));
360 builder.add_implied_robot_theta(Z(2));
361
362 // Turret is zero when pointed backwards.
363 builder.add_implied_turret_goal(
364 aos::math::NormalizeAngle(M_PI + pose_robot_target.heading()));
365
366 std::optional<RejectionReason> correction_rejection;
James Kuszmaul06257f42020-05-09 15:40:09 -0700367 const Input U = ekf_.MostRecentInput();
James Kuszmaul66efe832020-03-16 19:38:33 -0700368 // For the correction step, instead of passing in the measurement directly,
369 // we pass in (0, 0, 0) as the measurement and then for the expected
370 // measurement (Zhat) we calculate the error between the implied and actual
371 // poses. This doesn't affect any of the math, it just makes the code a bit
372 // more convenient to write given the Correct() interface we already have.
James Kuszmaul5ff8a862021-09-25 17:29:43 -0700373 // Note: If we start going back to doing back-in-time rewinds, then we can't
374 // get away with passing things by reference.
James Kuszmaul58cb1fe2020-03-07 16:18:59 -0800375 ekf_.Correct(
James Kuszmaul06257f42020-05-09 15:40:09 -0700376 Eigen::Vector3f::Zero(), &U, {},
James Kuszmaul5ff8a862021-09-25 17:29:43 -0700377 [H, H_field_target, pose_robot_target, state_at_capture, &correction_rejection](
James Kuszmaul06257f42020-05-09 15:40:09 -0700378 const State &, const Input &) -> Eigen::Vector3f {
James Kuszmaul5a46c8d2021-09-03 19:33:48 -0700379 const Eigen::Vector3f Z =
380 CalculateImpliedPose(H_field_target, pose_robot_target);
James Kuszmaul66efe832020-03-16 19:38:33 -0700381 // Just in case we ever do encounter any, drop measurements if they
382 // have non-finite numbers.
383 if (!Z.allFinite()) {
384 AOS_LOG(WARNING, "Got measurement with infinites or NaNs.\n");
James Kuszmaul5ff8a862021-09-25 17:29:43 -0700385 correction_rejection = RejectionReason::NONFINITE_MEASUREMENT;
James Kuszmauld478f872020-03-16 20:54:27 -0700386 return Eigen::Vector3f::Zero();
James Kuszmaul66efe832020-03-16 19:38:33 -0700387 }
James Kuszmaul06257f42020-05-09 15:40:09 -0700388 Eigen::Vector3f Zhat = H * state_at_capture.value() - Z;
James Kuszmaul66efe832020-03-16 19:38:33 -0700389 // Rewrap angle difference to put it back in range. Note that this
390 // component of the error is currently ignored (see definition of H
391 // above).
392 Zhat(2) = aos::math::NormalizeAngle(Zhat(2));
James Kuszmaul58cb1fe2020-03-07 16:18:59 -0800393 // If the measurement implies that we are too far from the current
394 // estimate, then ignore it.
395 // Note that I am not entirely sure how much effect this actually has,
396 // because I primarily introduced it to make sure that any grossly
397 // invalid measurements get thrown out.
James Kuszmaul66efe832020-03-16 19:38:33 -0700398 if (Zhat.squaredNorm() > std::pow(10.0, 2)) {
James Kuszmaul5ff8a862021-09-25 17:29:43 -0700399 correction_rejection = RejectionReason::CORRECTION_TOO_LARGE;
James Kuszmauld478f872020-03-16 20:54:27 -0700400 return Eigen::Vector3f::Zero();
James Kuszmaul58cb1fe2020-03-07 16:18:59 -0800401 }
402 return Zhat;
403 },
James Kuszmaul06257f42020-05-09 15:40:09 -0700404 [H](const State &) { return H; }, R, now);
James Kuszmaul5ff8a862021-09-25 17:29:43 -0700405 if (correction_rejection) {
406 builder.add_accepted(false);
407 builder.add_rejection_reason(*correction_rejection);
408 } else {
409 builder.add_accepted(true);
410 }
411 debug_offsets.push_back(builder.Finish());
James Kuszmaul5398fae2020-02-17 16:44:03 -0800412 }
James Kuszmaul5ff8a862021-09-25 17:29:43 -0700413 return debug_offsets;
James Kuszmaul5398fae2020-02-17 16:44:03 -0800414}
415
416} // namespace drivetrain
417} // namespace control_loops
418} // namespace y2020