blob: 2d31144f10fae421cd0368224421e24a3983f0ed [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 Kuszmauled6fca42021-09-25 17:58:30 -070026// Offset to add to the pi's yaw in its extrinsics, to account for issues in the
27// calibrated extrinsics.
28constexpr double kTurretPiOffset = 0.0;
29
James Kuszmaulc6723cf2020-03-01 14:45:59 -080030// Indices of the pis to use.
James Kuszmaul9c128122021-03-22 22:24:36 -070031const std::array<std::string, 5> kPisToUse{"pi1", "pi2", "pi3", "pi4", "pi5"};
James Kuszmaulc6723cf2020-03-01 14:45:59 -080032
James Kuszmauled177c42021-09-30 18:53:08 -070033float CalculateYaw(const Eigen::Matrix4f &transform) {
34 const Eigen::Vector2f yaw_coords =
35 (transform * Eigen::Vector4f(1, 0, 0, 0)).topRows<2>();
36 return std::atan2(yaw_coords(1), yaw_coords(0));
37}
38
James Kuszmaul66efe832020-03-16 19:38:33 -070039// Calculates the pose implied by the camera target, just based on
40// distance/heading components.
James Kuszmauled177c42021-09-30 18:53:08 -070041Eigen::Vector3f CalculateImpliedPose(const float correction_robot_theta,
42 const Eigen::Matrix4f &H_field_target,
James Kuszmaul66efe832020-03-16 19:38:33 -070043 const Localizer::Pose &pose_robot_target) {
44 // This code overrides the pose sent directly from the camera code and
45 // effectively distills it down to just a distance + heading estimate, on
46 // the presumption that these signals will tend to be much lower noise and
47 // better-conditioned than other portions of the robot pose.
James Kuszmauled177c42021-09-30 18:53:08 -070048 // As such, this code assumes that the provided estimate of the robot
James Kuszmaul66efe832020-03-16 19:38:33 -070049 // heading is correct and then, given the heading from the camera to the
50 // target and the distance from the camera to the target, calculates the
51 // position that the robot would have to be at to make the current camera
52 // heading + distance correct. This X/Y implied robot position is then
53 // used as the measurement in the EKF, rather than the X/Y that is
James Kuszmauled177c42021-09-30 18:53:08 -070054 // directly returned from the vision processing. If the provided
55 // correction_robot_theta is exactly identical to the current estimated robot
56 // yaw, then this means that the image corrections will not do anything to
57 // correct gyro drift; however, by making that tradeoff we can prioritize
58 // getting the turret angle to the target correct (without adding any new
59 // non-linearities to the EKF itself).
James Kuszmaul66efe832020-03-16 19:38:33 -070060
61 // Calculate the heading to the robot in the target's coordinate frame.
James Kuszmaul5a46c8d2021-09-03 19:33:48 -070062 // Reminder on what the numbers mean:
63 // rel_theta: The orientation of the target in the robot frame.
64 // heading: heading from the robot to the target in the robot frame. I.e.,
65 // atan2(y, x) for x/y of the target in the robot frame.
James Kuszmauled177c42021-09-30 18:53:08 -070066 const float implied_rel_theta =
67 CalculateYaw(H_field_target) - correction_robot_theta;
James Kuszmauld478f872020-03-16 20:54:27 -070068 const float implied_heading_from_target = aos::math::NormalizeAngle(
James Kuszmauled177c42021-09-30 18:53:08 -070069 M_PI - implied_rel_theta + pose_robot_target.heading());
James Kuszmauld478f872020-03-16 20:54:27 -070070 const float implied_distance = pose_robot_target.xy_norm();
71 const Eigen::Vector4f robot_pose_in_target_frame(
James Kuszmaul66efe832020-03-16 19:38:33 -070072 implied_distance * std::cos(implied_heading_from_target),
73 implied_distance * std::sin(implied_heading_from_target), 0, 1);
James Kuszmauled177c42021-09-30 18:53:08 -070074 const Eigen::Vector2f implied_xy =
75 (H_field_target * robot_pose_in_target_frame).topRows<2>();
76 return {implied_xy.x(), implied_xy.y(), correction_robot_theta};
James Kuszmaul66efe832020-03-16 19:38:33 -070077}
78
James Kuszmaul5398fae2020-02-17 16:44:03 -080079} // namespace
80
81Localizer::Localizer(
82 aos::EventLoop *event_loop,
83 const frc971::control_loops::drivetrain::DrivetrainConfig<double>
84 &dt_config)
James Kuszmaul958b21e2020-02-26 21:51:40 -080085 : event_loop_(event_loop),
86 dt_config_(dt_config),
87 ekf_(dt_config),
88 clock_offset_fetcher_(
89 event_loop_->MakeFetcher<aos::message_bridge::ServerStatistics>(
James Kuszmaul5ff8a862021-09-25 17:29:43 -070090 "/aos")),
91 debug_sender_(
92 event_loop_
93 ->MakeSender<y2020::control_loops::drivetrain::LocalizerDebug>(
94 "/drivetrain")) {
James Kuszmaul91aa0cf2021-02-13 13:15:06 -080095 // TODO(james): The down estimator has trouble handling situations where the
96 // robot is constantly wiggling but not actually moving much, and can cause
97 // drift when using accelerometer readings.
98 ekf_.set_ignore_accel(true);
James Kuszmaul5398fae2020-02-17 16:44:03 -080099 // TODO(james): This doesn't really need to be a watcher; we could just use a
100 // fetcher for the superstructure status.
101 // This probably should be a Fetcher instead of a Watcher, but this
102 // seems simpler for the time being (although technically it should be
103 // possible to do everything we need to using just a Fetcher without
104 // even maintaining a separate buffer, but that seems overly cute).
105 event_loop_->MakeWatcher("/superstructure",
106 [this](const superstructure::Status &status) {
107 HandleSuperstructureStatus(status);
108 });
109
James Kuszmaul286b4282020-02-26 20:29:32 -0800110 event_loop->OnRun([this, event_loop]() {
James Kuszmauld478f872020-03-16 20:54:27 -0700111 ekf_.ResetInitialState(event_loop->monotonic_now(),
112 HybridEkf::State::Zero(), ekf_.P());
James Kuszmaul286b4282020-02-26 20:29:32 -0800113 });
114
James Kuszmaulc6723cf2020-03-01 14:45:59 -0800115 for (const auto &pi : kPisToUse) {
116 image_fetchers_.emplace_back(
117 event_loop_->MakeFetcher<frc971::vision::sift::ImageMatchResult>(
118 "/" + pi + "/camera"));
119 }
James Kuszmaul5398fae2020-02-17 16:44:03 -0800120
121 target_selector_.set_has_target(false);
122}
123
James Kuszmaulbcd96fc2020-10-12 20:29:32 -0700124void Localizer::Reset(
125 aos::monotonic_clock::time_point t,
126 const frc971::control_loops::drivetrain::HybridEkf<double>::State &state) {
127 // Go through and clear out all of the fetchers so that we don't get behind.
128 for (auto &fetcher : image_fetchers_) {
129 fetcher.Fetch();
130 }
131 ekf_.ResetInitialState(t, state.cast<float>(), ekf_.P());
132}
133
James Kuszmaul5398fae2020-02-17 16:44:03 -0800134void Localizer::HandleSuperstructureStatus(
135 const y2020::control_loops::superstructure::Status &status) {
136 CHECK(status.has_turret());
137 turret_data_.Push({event_loop_->monotonic_now(), status.turret()->position(),
138 status.turret()->velocity()});
139}
140
141Localizer::TurretData Localizer::GetTurretDataForTime(
142 aos::monotonic_clock::time_point time) {
143 if (turret_data_.empty()) {
144 return {};
145 }
146
147 aos::monotonic_clock::duration lowest_time_error =
148 aos::monotonic_clock::duration::max();
149 TurretData best_data_match;
150 for (const auto &sample : turret_data_) {
151 const aos::monotonic_clock::duration time_error =
152 std::chrono::abs(sample.receive_time - time);
153 if (time_error < lowest_time_error) {
154 lowest_time_error = time_error;
155 best_data_match = sample;
156 }
157 }
158 return best_data_match;
159}
160
James Kuszmaul06257f42020-05-09 15:40:09 -0700161void Localizer::Update(const Eigen::Matrix<double, 2, 1> &U,
James Kuszmaul5398fae2020-02-17 16:44:03 -0800162 aos::monotonic_clock::time_point now,
163 double left_encoder, double right_encoder,
164 double gyro_rate, const Eigen::Vector3d &accel) {
James Kuszmauld478f872020-03-16 20:54:27 -0700165 ekf_.UpdateEncodersAndGyro(left_encoder, right_encoder, gyro_rate,
166 U.cast<float>(), accel.cast<float>(), now);
James Kuszmaul5ff8a862021-09-25 17:29:43 -0700167 auto builder = debug_sender_.MakeBuilder();
168 aos::SizedArray<flatbuffers::Offset<ImageMatchDebug>, 25> debug_offsets;
James Kuszmaulc6723cf2020-03-01 14:45:59 -0800169 for (size_t ii = 0; ii < kPisToUse.size(); ++ii) {
170 auto &image_fetcher = image_fetchers_[ii];
James Kuszmaul5398fae2020-02-17 16:44:03 -0800171 while (image_fetcher.FetchNext()) {
James Kuszmaul5ff8a862021-09-25 17:29:43 -0700172 const auto offsets = HandleImageMatch(ii, kPisToUse[ii], *image_fetcher,
173 now, builder.fbb());
174 for (const auto offset : offsets) {
175 debug_offsets.push_back(offset);
176 }
James Kuszmaul5398fae2020-02-17 16:44:03 -0800177 }
178 }
James Kuszmaul5ff8a862021-09-25 17:29:43 -0700179 const auto vector_offset =
180 builder.fbb()->CreateVector(debug_offsets.data(), debug_offsets.size());
181 LocalizerDebug::Builder debug_builder = builder.MakeBuilder<LocalizerDebug>();
182 debug_builder.add_matches(vector_offset);
183 CHECK(builder.Send(debug_builder.Finish()));
James Kuszmaul5398fae2020-02-17 16:44:03 -0800184}
185
James Kuszmaul5ff8a862021-09-25 17:29:43 -0700186aos::SizedArray<flatbuffers::Offset<ImageMatchDebug>, 5>
187Localizer::HandleImageMatch(
188 size_t camera_index, std::string_view pi,
189 const frc971::vision::sift::ImageMatchResult &result,
190 aos::monotonic_clock::time_point now, flatbuffers::FlatBufferBuilder *fbb) {
191 aos::SizedArray<flatbuffers::Offset<ImageMatchDebug>, 5> debug_offsets;
192
James Kuszmaul958b21e2020-02-26 21:51:40 -0800193 std::chrono::nanoseconds monotonic_offset(0);
194 clock_offset_fetcher_.Fetch();
195 if (clock_offset_fetcher_.get() != nullptr) {
196 for (const auto connection : *clock_offset_fetcher_->connections()) {
197 if (connection->has_node() && connection->node()->has_name() &&
James Kuszmaulc6723cf2020-03-01 14:45:59 -0800198 connection->node()->name()->string_view() == pi) {
James Kuszmaul958b21e2020-02-26 21:51:40 -0800199 monotonic_offset =
200 std::chrono::nanoseconds(connection->monotonic_offset());
201 break;
202 }
203 }
204 }
James Kuszmaul5398fae2020-02-17 16:44:03 -0800205 aos::monotonic_clock::time_point capture_time(
James Kuszmaul958b21e2020-02-26 21:51:40 -0800206 std::chrono::nanoseconds(result.image_monotonic_timestamp_ns()) -
207 monotonic_offset);
James Kuszmaul2d8fa2a2020-03-01 13:51:50 -0800208 VLOG(1) << "Got monotonic offset of "
209 << aos::time::DurationInSeconds(monotonic_offset)
James Kuszmaul58cb1fe2020-03-07 16:18:59 -0800210 << " when at time of " << now << " and capture time estimate of "
211 << capture_time;
212 if (capture_time > now) {
James Kuszmaul2d8fa2a2020-03-01 13:51:50 -0800213 LOG(WARNING) << "Got camera frame from the future.";
James Kuszmaul5ff8a862021-09-25 17:29:43 -0700214 ImageMatchDebug::Builder builder(*fbb);
215 builder.add_camera(camera_index);
216 builder.add_accepted(false);
217 builder.add_rejection_reason(RejectionReason::IMAGE_FROM_FUTURE);
218 debug_offsets.push_back(builder.Finish());
219 return debug_offsets;
James Kuszmaul2d8fa2a2020-03-01 13:51:50 -0800220 }
James Kuszmaulbcd96fc2020-10-12 20:29:32 -0700221 if (!result.has_camera_calibration()) {
222 LOG(WARNING) << "Got camera frame without calibration data.";
James Kuszmaul5ff8a862021-09-25 17:29:43 -0700223 ImageMatchDebug::Builder builder(*fbb);
224 builder.add_camera(camera_index);
225 builder.add_accepted(false);
226 builder.add_rejection_reason(RejectionReason::NO_CALIBRATION);
227 debug_offsets.push_back(builder.Finish());
228 return debug_offsets;
James Kuszmaulbcd96fc2020-10-12 20:29:32 -0700229 }
James Kuszmaul5398fae2020-02-17 16:44:03 -0800230 // Per the ImageMatchResult specification, we can actually determine whether
231 // the camera is the turret camera just from the presence of the
232 // turret_extrinsics member.
233 const bool is_turret = result.camera_calibration()->has_turret_extrinsics();
234 const TurretData turret_data = GetTurretDataForTime(capture_time);
235 // Ignore readings when the turret is spinning too fast, on the assumption
236 // that the odds of screwing up the time compensation are higher.
237 // Note that the current number here is chosen pretty arbitrarily--1 rad / sec
238 // seems reasonable, but may be unnecessarily low or high.
James Kuszmauld478f872020-03-16 20:54:27 -0700239 constexpr float kMaxTurretVelocity = 1.0;
James Kuszmaul5398fae2020-02-17 16:44:03 -0800240 if (is_turret && std::abs(turret_data.velocity) > kMaxTurretVelocity) {
James Kuszmaul5ff8a862021-09-25 17:29:43 -0700241 ImageMatchDebug::Builder builder(*fbb);
242 builder.add_camera(camera_index);
243 builder.add_accepted(false);
244 builder.add_rejection_reason(RejectionReason::TURRET_TOO_FAST);
245 debug_offsets.push_back(builder.Finish());
246 return debug_offsets;
James Kuszmaul5398fae2020-02-17 16:44:03 -0800247 }
248 CHECK(result.camera_calibration()->has_fixed_extrinsics());
James Kuszmauld478f872020-03-16 20:54:27 -0700249 const Eigen::Matrix<float, 4, 4> fixed_extrinsics =
James Kuszmaul5398fae2020-02-17 16:44:03 -0800250 FlatbufferToTransformationMatrix(
251 *result.camera_calibration()->fixed_extrinsics());
James Kuszmaul58cb1fe2020-03-07 16:18:59 -0800252
James Kuszmaul5398fae2020-02-17 16:44:03 -0800253 // Calculate the pose of the camera relative to the robot origin.
James Kuszmauld478f872020-03-16 20:54:27 -0700254 Eigen::Matrix<float, 4, 4> H_robot_camera = fixed_extrinsics;
James Kuszmaul5398fae2020-02-17 16:44:03 -0800255 if (is_turret) {
James Kuszmaulc51dbfe2020-02-23 15:39:00 -0800256 H_robot_camera = H_robot_camera *
James Kuszmauld478f872020-03-16 20:54:27 -0700257 frc971::control_loops::TransformationMatrixForYaw<float>(
James Kuszmauled6fca42021-09-25 17:58:30 -0700258 turret_data.position + kTurretPiOffset) *
James Kuszmaul5398fae2020-02-17 16:44:03 -0800259 FlatbufferToTransformationMatrix(
260 *result.camera_calibration()->turret_extrinsics());
261 }
262
263 if (!result.has_camera_poses()) {
James Kuszmaul5ff8a862021-09-25 17:29:43 -0700264 ImageMatchDebug::Builder builder(*fbb);
265 builder.add_camera(camera_index);
266 builder.add_accepted(false);
267 builder.add_rejection_reason(RejectionReason::NO_RESULTS);
268 debug_offsets.push_back(builder.Finish());
269 return debug_offsets;
James Kuszmaul5398fae2020-02-17 16:44:03 -0800270 }
271
James Kuszmaul5ff8a862021-09-25 17:29:43 -0700272 int index = -1;
James Kuszmaul5398fae2020-02-17 16:44:03 -0800273 for (const frc971::vision::sift::CameraPose *vision_result :
274 *result.camera_poses()) {
James Kuszmaul5ff8a862021-09-25 17:29:43 -0700275 ++index;
276
277 ImageMatchDebug::Builder builder(*fbb);
278 builder.add_camera(camera_index);
279 builder.add_pose_index(index);
280 builder.add_local_image_capture_time_ns(result.image_monotonic_timestamp_ns());
281 builder.add_roborio_image_capture_time_ns(
282 capture_time.time_since_epoch().count());
283 builder.add_image_age_sec(aos::time::DurationInSeconds(now - capture_time));
284
James Kuszmaul5398fae2020-02-17 16:44:03 -0800285 if (!vision_result->has_camera_to_target() ||
286 !vision_result->has_field_to_target()) {
James Kuszmaul5ff8a862021-09-25 17:29:43 -0700287 builder.add_accepted(false);
288 builder.add_rejection_reason(RejectionReason::NO_TRANSFORMS);
289 debug_offsets.push_back(builder.Finish());
James Kuszmaul5398fae2020-02-17 16:44:03 -0800290 continue;
291 }
James Kuszmauld478f872020-03-16 20:54:27 -0700292 const Eigen::Matrix<float, 4, 4> H_camera_target =
James Kuszmaul5398fae2020-02-17 16:44:03 -0800293 FlatbufferToTransformationMatrix(*vision_result->camera_to_target());
James Kuszmaul58cb1fe2020-03-07 16:18:59 -0800294
James Kuszmauld478f872020-03-16 20:54:27 -0700295 const Eigen::Matrix<float, 4, 4> H_field_target =
James Kuszmaul5398fae2020-02-17 16:44:03 -0800296 FlatbufferToTransformationMatrix(*vision_result->field_to_target());
297 // Back out the robot position that is implied by the current camera
James Kuszmaul715e7932021-04-05 20:45:57 -0700298 // reading. Note that the Pose object ignores any roll/pitch components, so
299 // if the camera's extrinsics for pitch/roll are off, this should just
300 // ignore it.
James Kuszmaulaca88782021-04-24 16:48:45 -0700301 const Pose measured_camera_pose(H_field_target * H_camera_target.inverse());
302 // Calculate the camera-to-robot transformation matrix ignoring the
303 // pitch/roll of the camera.
304 // TODO(james): This could probably be made a bit more efficient, but I
305 // don't think this is anywhere near our bottleneck currently.
306 const Eigen::Matrix<float, 4, 4> H_camera_robot_stripped =
307 Pose(H_robot_camera).AsTransformationMatrix().inverse();
308 const Pose measured_pose(measured_camera_pose.AsTransformationMatrix() *
309 H_camera_robot_stripped);
James Kuszmaul66efe832020-03-16 19:38:33 -0700310 // This "Z" is the robot pose directly implied by the camera results.
311 // Currently, we do not actually use this result directly. However, it is
312 // kept around in case we want to quickly re-enable it.
James Kuszmauld478f872020-03-16 20:54:27 -0700313 const Eigen::Matrix<float, 3, 1> Z(measured_pose.rel_pos().x(),
314 measured_pose.rel_pos().y(),
315 measured_pose.rel_theta());
James Kuszmaul58cb1fe2020-03-07 16:18:59 -0800316 // Pose of the target in the robot frame.
James Kuszmaul715e7932021-04-05 20:45:57 -0700317 // Note that we use measured_pose's transformation matrix rather than just
318 // doing H_robot_camera * H_camera_target because measured_pose ignores
319 // pitch/roll.
320 Pose pose_robot_target(measured_pose.AsTransformationMatrix().inverse() *
321 H_field_target);
James Kuszmaul5398fae2020-02-17 16:44:03 -0800322 // TODO(james): Figure out how to properly handle calculating the
323 // noise. Currently, the values are deliberately tuned so that image updates
324 // will not be trusted overly much. In theory, we should probably also be
325 // populating some cross-correlation terms.
326 // Note that these are the noise standard deviations (they are squared below
327 // to get variances).
James Kuszmauled6fca42021-09-25 17:58:30 -0700328 Eigen::Matrix<float, 3, 1> noises(2.0, 2.0, 0.5);
James Kuszmaul5398fae2020-02-17 16:44:03 -0800329 // Augment the noise by the approximate rotational speed of the
330 // camera. This should help account for the fact that, while we are
331 // spinning, slight timing errors in the camera/turret data will tend to
332 // have mutch more drastic effects on the results.
333 noises *= 1.0 + std::abs((right_velocity() - left_velocity()) /
334 (2.0 * dt_config_.robot_radius) +
335 (is_turret ? turret_data.velocity : 0.0));
James Kuszmauld478f872020-03-16 20:54:27 -0700336 Eigen::Matrix3f R = Eigen::Matrix3f::Zero();
James Kuszmaul5398fae2020-02-17 16:44:03 -0800337 R.diagonal() = noises.cwiseAbs2();
James Kuszmauld478f872020-03-16 20:54:27 -0700338 Eigen::Matrix<float, HybridEkf::kNOutputs, HybridEkf::kNStates> H;
James Kuszmaul5398fae2020-02-17 16:44:03 -0800339 H.setZero();
340 H(0, StateIdx::kX) = 1;
341 H(1, StateIdx::kY) = 1;
James Kuszmauled6fca42021-09-25 17:58:30 -0700342 H(2, StateIdx::kTheta) = 1;
James Kuszmaul58cb1fe2020-03-07 16:18:59 -0800343 VLOG(1) << "Pose implied by target: " << Z.transpose()
344 << " and current pose " << x() << ", " << y() << ", " << theta()
345 << " Heading/dist/skew implied by target: "
346 << pose_robot_target.ToHeadingDistanceSkew().transpose();
James Kuszmauladd40ca2020-03-01 14:10:50 -0800347 // If the heading is off by too much, assume that we got a false-positive
348 // and don't use the correction.
James Kuszmauld478f872020-03-16 20:54:27 -0700349 if (std::abs(aos::math::DiffAngle<float>(theta(), Z(2))) > M_PI_2) {
James Kuszmauladd40ca2020-03-01 14:10:50 -0800350 AOS_LOG(WARNING, "Dropped image match due to heading mismatch.\n");
James Kuszmaul5ff8a862021-09-25 17:29:43 -0700351 builder.add_accepted(false);
352 builder.add_rejection_reason(RejectionReason::HIGH_THETA_DIFFERENCE);
353 debug_offsets.push_back(builder.Finish());
James Kuszmaul58cb1fe2020-03-07 16:18:59 -0800354 continue;
James Kuszmauladd40ca2020-03-01 14:10:50 -0800355 }
James Kuszmaul06257f42020-05-09 15:40:09 -0700356 // In order to do the EKF correction, we determine the expected state based
357 // on the state at the time the image was captured; however, we insert the
358 // correction update itself at the current time. This is technically not
359 // quite correct, but saves substantial CPU usage by making it so that we
360 // don't have to constantly rewind the entire EKF history.
361 const std::optional<State> state_at_capture =
362 ekf_.LastStateBeforeTime(capture_time);
363 if (!state_at_capture.has_value()) {
364 AOS_LOG(WARNING, "Dropped image match due to age of image.\n");
James Kuszmaul5ff8a862021-09-25 17:29:43 -0700365 builder.add_accepted(false);
366 builder.add_rejection_reason(RejectionReason::IMAGE_TOO_OLD);
367 debug_offsets.push_back(builder.Finish());
James Kuszmaul06257f42020-05-09 15:40:09 -0700368 continue;
369 }
James Kuszmaul5ff8a862021-09-25 17:29:43 -0700370
371 builder.add_implied_robot_x(Z(0));
372 builder.add_implied_robot_y(Z(1));
373 builder.add_implied_robot_theta(Z(2));
374
375 // Turret is zero when pointed backwards.
376 builder.add_implied_turret_goal(
377 aos::math::NormalizeAngle(M_PI + pose_robot_target.heading()));
378
379 std::optional<RejectionReason> correction_rejection;
James Kuszmaul06257f42020-05-09 15:40:09 -0700380 const Input U = ekf_.MostRecentInput();
James Kuszmaul66efe832020-03-16 19:38:33 -0700381 // For the correction step, instead of passing in the measurement directly,
382 // we pass in (0, 0, 0) as the measurement and then for the expected
383 // measurement (Zhat) we calculate the error between the implied and actual
384 // poses. This doesn't affect any of the math, it just makes the code a bit
385 // more convenient to write given the Correct() interface we already have.
James Kuszmaul5ff8a862021-09-25 17:29:43 -0700386 // Note: If we start going back to doing back-in-time rewinds, then we can't
387 // get away with passing things by reference.
James Kuszmaul58cb1fe2020-03-07 16:18:59 -0800388 ekf_.Correct(
James Kuszmaul06257f42020-05-09 15:40:09 -0700389 Eigen::Vector3f::Zero(), &U, {},
James Kuszmauled177c42021-09-30 18:53:08 -0700390 [H, H_field_target, pose_robot_target, state_at_capture, Z,
391 &correction_rejection](const State &,
392 const Input &) -> Eigen::Vector3f {
393 // Weighting for how much to use the current robot heading estimate
394 // vs. the heading estimate from the image results. A value of 1.0
395 // completely ignores the measured heading, but will prioritize turret
396 // aiming above all else. A value of 0.0 will prioritize correcting
397 // any gyro heading drift.
398 constexpr float kImpliedWeight = 0.99;
399 const float z_yaw_diff = aos::math::NormalizeAngle(
400 state_at_capture.value()(Localizer::StateIdx::kTheta) - Z(2));
401 const float z_yaw = Z(2) + kImpliedWeight * z_yaw_diff;
James Kuszmauled6fca42021-09-25 17:58:30 -0700402 const Eigen::Vector3f Z_implied =
James Kuszmauled177c42021-09-30 18:53:08 -0700403 CalculateImpliedPose(z_yaw, H_field_target, pose_robot_target);
404 const Eigen::Vector3f Z_used = Z_implied;
James Kuszmaul66efe832020-03-16 19:38:33 -0700405 // Just in case we ever do encounter any, drop measurements if they
406 // have non-finite numbers.
407 if (!Z.allFinite()) {
408 AOS_LOG(WARNING, "Got measurement with infinites or NaNs.\n");
James Kuszmaul5ff8a862021-09-25 17:29:43 -0700409 correction_rejection = RejectionReason::NONFINITE_MEASUREMENT;
James Kuszmauld478f872020-03-16 20:54:27 -0700410 return Eigen::Vector3f::Zero();
James Kuszmaul66efe832020-03-16 19:38:33 -0700411 }
James Kuszmauled177c42021-09-30 18:53:08 -0700412 Eigen::Vector3f Zhat = H * state_at_capture.value() - Z_used;
James Kuszmaul66efe832020-03-16 19:38:33 -0700413 // Rewrap angle difference to put it back in range. Note that this
414 // component of the error is currently ignored (see definition of H
415 // above).
416 Zhat(2) = aos::math::NormalizeAngle(Zhat(2));
James Kuszmaul58cb1fe2020-03-07 16:18:59 -0800417 // If the measurement implies that we are too far from the current
418 // estimate, then ignore it.
419 // Note that I am not entirely sure how much effect this actually has,
420 // because I primarily introduced it to make sure that any grossly
421 // invalid measurements get thrown out.
James Kuszmaul66efe832020-03-16 19:38:33 -0700422 if (Zhat.squaredNorm() > std::pow(10.0, 2)) {
James Kuszmaul5ff8a862021-09-25 17:29:43 -0700423 correction_rejection = RejectionReason::CORRECTION_TOO_LARGE;
James Kuszmauld478f872020-03-16 20:54:27 -0700424 return Eigen::Vector3f::Zero();
James Kuszmaul58cb1fe2020-03-07 16:18:59 -0800425 }
426 return Zhat;
427 },
James Kuszmaul06257f42020-05-09 15:40:09 -0700428 [H](const State &) { return H; }, R, now);
James Kuszmaul5ff8a862021-09-25 17:29:43 -0700429 if (correction_rejection) {
430 builder.add_accepted(false);
431 builder.add_rejection_reason(*correction_rejection);
432 } else {
433 builder.add_accepted(true);
434 }
435 debug_offsets.push_back(builder.Finish());
James Kuszmaul5398fae2020-02-17 16:44:03 -0800436 }
James Kuszmaul5ff8a862021-09-25 17:29:43 -0700437 return debug_offsets;
James Kuszmaul5398fae2020-02-17 16:44:03 -0800438}
439
440} // namespace drivetrain
441} // namespace control_loops
442} // namespace y2020