blob: 650a0c582c5fa2428c79bdfc44749c0e1b19846c [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
James Kuszmaulf75ecd62021-10-23 14:33:46 -07005DEFINE_bool(send_empty_debug, false,
6 "If true, send LocalizerDebug messages on every tick, even if "
7 "they would be empty.");
8
James Kuszmaul5398fae2020-02-17 16:44:03 -08009namespace y2020 {
10namespace control_loops {
11namespace drivetrain {
12
13namespace {
14// Converts a flatbuffer TransformationMatrix to an Eigen matrix. Technically,
15// this should be able to do a single memcpy, but the extra verbosity here seems
16// appropriate.
James Kuszmauld478f872020-03-16 20:54:27 -070017Eigen::Matrix<float, 4, 4> FlatbufferToTransformationMatrix(
James Kuszmaul5398fae2020-02-17 16:44:03 -080018 const frc971::vision::sift::TransformationMatrix &flatbuffer) {
19 CHECK_EQ(16u, CHECK_NOTNULL(flatbuffer.data())->size());
James Kuszmauld478f872020-03-16 20:54:27 -070020 Eigen::Matrix<float, 4, 4> result;
James Kuszmaul5398fae2020-02-17 16:44:03 -080021 result.setIdentity();
22 for (int row = 0; row < 4; ++row) {
23 for (int col = 0; col < 4; ++col) {
24 result(row, col) = (*flatbuffer.data())[row * 4 + col];
25 }
26 }
27 return result;
28}
James Kuszmaul958b21e2020-02-26 21:51:40 -080029
James Kuszmauled6fca42021-09-25 17:58:30 -070030// Offset to add to the pi's yaw in its extrinsics, to account for issues in the
31// calibrated extrinsics.
32constexpr double kTurretPiOffset = 0.0;
33
James Kuszmaulc6723cf2020-03-01 14:45:59 -080034// Indices of the pis to use.
James Kuszmaul9c128122021-03-22 22:24:36 -070035const std::array<std::string, 5> kPisToUse{"pi1", "pi2", "pi3", "pi4", "pi5"};
James Kuszmaulc6723cf2020-03-01 14:45:59 -080036
James Kuszmauled177c42021-09-30 18:53:08 -070037float CalculateYaw(const Eigen::Matrix4f &transform) {
38 const Eigen::Vector2f yaw_coords =
39 (transform * Eigen::Vector4f(1, 0, 0, 0)).topRows<2>();
40 return std::atan2(yaw_coords(1), yaw_coords(0));
41}
42
James Kuszmaul66efe832020-03-16 19:38:33 -070043// Calculates the pose implied by the camera target, just based on
44// distance/heading components.
James Kuszmauled177c42021-09-30 18:53:08 -070045Eigen::Vector3f CalculateImpliedPose(const float correction_robot_theta,
46 const Eigen::Matrix4f &H_field_target,
James Kuszmaul66efe832020-03-16 19:38:33 -070047 const Localizer::Pose &pose_robot_target) {
48 // This code overrides the pose sent directly from the camera code and
49 // effectively distills it down to just a distance + heading estimate, on
50 // the presumption that these signals will tend to be much lower noise and
51 // better-conditioned than other portions of the robot pose.
James Kuszmauled177c42021-09-30 18:53:08 -070052 // As such, this code assumes that the provided estimate of the robot
James Kuszmaul66efe832020-03-16 19:38:33 -070053 // heading is correct and then, given the heading from the camera to the
54 // target and the distance from the camera to the target, calculates the
55 // position that the robot would have to be at to make the current camera
56 // heading + distance correct. This X/Y implied robot position is then
57 // used as the measurement in the EKF, rather than the X/Y that is
James Kuszmauled177c42021-09-30 18:53:08 -070058 // directly returned from the vision processing. If the provided
59 // correction_robot_theta is exactly identical to the current estimated robot
60 // yaw, then this means that the image corrections will not do anything to
61 // correct gyro drift; however, by making that tradeoff we can prioritize
62 // getting the turret angle to the target correct (without adding any new
63 // non-linearities to the EKF itself).
James Kuszmaul66efe832020-03-16 19:38:33 -070064
65 // Calculate the heading to the robot in the target's coordinate frame.
James Kuszmaul5a46c8d2021-09-03 19:33:48 -070066 // Reminder on what the numbers mean:
67 // rel_theta: The orientation of the target in the robot frame.
68 // heading: heading from the robot to the target in the robot frame. I.e.,
69 // atan2(y, x) for x/y of the target in the robot frame.
James Kuszmauled177c42021-09-30 18:53:08 -070070 const float implied_rel_theta =
71 CalculateYaw(H_field_target) - correction_robot_theta;
James Kuszmauld478f872020-03-16 20:54:27 -070072 const float implied_heading_from_target = aos::math::NormalizeAngle(
James Kuszmauled177c42021-09-30 18:53:08 -070073 M_PI - implied_rel_theta + pose_robot_target.heading());
James Kuszmauld478f872020-03-16 20:54:27 -070074 const float implied_distance = pose_robot_target.xy_norm();
75 const Eigen::Vector4f robot_pose_in_target_frame(
James Kuszmaul66efe832020-03-16 19:38:33 -070076 implied_distance * std::cos(implied_heading_from_target),
77 implied_distance * std::sin(implied_heading_from_target), 0, 1);
James Kuszmauled177c42021-09-30 18:53:08 -070078 const Eigen::Vector2f implied_xy =
79 (H_field_target * robot_pose_in_target_frame).topRows<2>();
80 return {implied_xy.x(), implied_xy.y(), correction_robot_theta};
James Kuszmaul66efe832020-03-16 19:38:33 -070081}
82
James Kuszmaul5398fae2020-02-17 16:44:03 -080083} // namespace
84
85Localizer::Localizer(
86 aos::EventLoop *event_loop,
87 const frc971::control_loops::drivetrain::DrivetrainConfig<double>
88 &dt_config)
James Kuszmaul958b21e2020-02-26 21:51:40 -080089 : event_loop_(event_loop),
90 dt_config_(dt_config),
91 ekf_(dt_config),
92 clock_offset_fetcher_(
93 event_loop_->MakeFetcher<aos::message_bridge::ServerStatistics>(
James Kuszmaul5ff8a862021-09-25 17:29:43 -070094 "/aos")),
95 debug_sender_(
96 event_loop_
97 ->MakeSender<y2020::control_loops::drivetrain::LocalizerDebug>(
98 "/drivetrain")) {
James Kuszmaulf75ecd62021-10-23 14:33:46 -070099 statistics_.rejection_counts.fill(0);
James Kuszmaul91aa0cf2021-02-13 13:15:06 -0800100 // TODO(james): The down estimator has trouble handling situations where the
101 // robot is constantly wiggling but not actually moving much, and can cause
102 // drift when using accelerometer readings.
103 ekf_.set_ignore_accel(true);
James Kuszmaul5398fae2020-02-17 16:44:03 -0800104 // TODO(james): This doesn't really need to be a watcher; we could just use a
105 // fetcher for the superstructure status.
106 // This probably should be a Fetcher instead of a Watcher, but this
107 // seems simpler for the time being (although technically it should be
108 // possible to do everything we need to using just a Fetcher without
109 // even maintaining a separate buffer, but that seems overly cute).
110 event_loop_->MakeWatcher("/superstructure",
111 [this](const superstructure::Status &status) {
112 HandleSuperstructureStatus(status);
113 });
114
James Kuszmaul286b4282020-02-26 20:29:32 -0800115 event_loop->OnRun([this, event_loop]() {
James Kuszmauld478f872020-03-16 20:54:27 -0700116 ekf_.ResetInitialState(event_loop->monotonic_now(),
117 HybridEkf::State::Zero(), ekf_.P());
James Kuszmaul286b4282020-02-26 20:29:32 -0800118 });
119
James Kuszmaulc6723cf2020-03-01 14:45:59 -0800120 for (const auto &pi : kPisToUse) {
121 image_fetchers_.emplace_back(
122 event_loop_->MakeFetcher<frc971::vision::sift::ImageMatchResult>(
123 "/" + pi + "/camera"));
124 }
James Kuszmaul5398fae2020-02-17 16:44:03 -0800125
126 target_selector_.set_has_target(false);
127}
128
James Kuszmaulbcd96fc2020-10-12 20:29:32 -0700129void Localizer::Reset(
130 aos::monotonic_clock::time_point t,
131 const frc971::control_loops::drivetrain::HybridEkf<double>::State &state) {
132 // Go through and clear out all of the fetchers so that we don't get behind.
133 for (auto &fetcher : image_fetchers_) {
134 fetcher.Fetch();
135 }
136 ekf_.ResetInitialState(t, state.cast<float>(), ekf_.P());
137}
138
James Kuszmaul5398fae2020-02-17 16:44:03 -0800139void Localizer::HandleSuperstructureStatus(
140 const y2020::control_loops::superstructure::Status &status) {
141 CHECK(status.has_turret());
142 turret_data_.Push({event_loop_->monotonic_now(), status.turret()->position(),
143 status.turret()->velocity()});
144}
145
146Localizer::TurretData Localizer::GetTurretDataForTime(
147 aos::monotonic_clock::time_point time) {
148 if (turret_data_.empty()) {
149 return {};
150 }
151
152 aos::monotonic_clock::duration lowest_time_error =
153 aos::monotonic_clock::duration::max();
154 TurretData best_data_match;
155 for (const auto &sample : turret_data_) {
156 const aos::monotonic_clock::duration time_error =
157 std::chrono::abs(sample.receive_time - time);
158 if (time_error < lowest_time_error) {
159 lowest_time_error = time_error;
160 best_data_match = sample;
161 }
162 }
163 return best_data_match;
164}
165
James Kuszmaul06257f42020-05-09 15:40:09 -0700166void Localizer::Update(const Eigen::Matrix<double, 2, 1> &U,
James Kuszmaul5398fae2020-02-17 16:44:03 -0800167 aos::monotonic_clock::time_point now,
168 double left_encoder, double right_encoder,
169 double gyro_rate, const Eigen::Vector3d &accel) {
James Kuszmauld478f872020-03-16 20:54:27 -0700170 ekf_.UpdateEncodersAndGyro(left_encoder, right_encoder, gyro_rate,
171 U.cast<float>(), accel.cast<float>(), now);
James Kuszmaul5ff8a862021-09-25 17:29:43 -0700172 auto builder = debug_sender_.MakeBuilder();
173 aos::SizedArray<flatbuffers::Offset<ImageMatchDebug>, 25> debug_offsets;
James Kuszmaulc6723cf2020-03-01 14:45:59 -0800174 for (size_t ii = 0; ii < kPisToUse.size(); ++ii) {
175 auto &image_fetcher = image_fetchers_[ii];
James Kuszmaul5398fae2020-02-17 16:44:03 -0800176 while (image_fetcher.FetchNext()) {
James Kuszmaul5ff8a862021-09-25 17:29:43 -0700177 const auto offsets = HandleImageMatch(ii, kPisToUse[ii], *image_fetcher,
178 now, builder.fbb());
179 for (const auto offset : offsets) {
180 debug_offsets.push_back(offset);
181 }
James Kuszmaul5398fae2020-02-17 16:44:03 -0800182 }
183 }
James Kuszmaulf75ecd62021-10-23 14:33:46 -0700184 if (FLAGS_send_empty_debug || !debug_offsets.empty()) {
185 const auto vector_offset =
186 builder.fbb()->CreateVector(debug_offsets.data(), debug_offsets.size());
187 const auto rejections_offset =
188 builder.fbb()->CreateVector(statistics_.rejection_counts.data(),
189 statistics_.rejection_counts.size());
190
191 CumulativeStatistics::Builder stats_builder =
192 builder.MakeBuilder<CumulativeStatistics>();
193 stats_builder.add_total_accepted(statistics_.total_accepted);
194 stats_builder.add_total_candidates(statistics_.total_candidates);
195 stats_builder.add_rejection_reason_count(rejections_offset);
196 const auto stats_offset = stats_builder.Finish();
197
198 LocalizerDebug::Builder debug_builder =
199 builder.MakeBuilder<LocalizerDebug>();
200 debug_builder.add_matches(vector_offset);
201 debug_builder.add_statistics(stats_offset);
202 CHECK(builder.Send(debug_builder.Finish()));
203 }
James Kuszmaul5398fae2020-02-17 16:44:03 -0800204}
205
James Kuszmaul5ff8a862021-09-25 17:29:43 -0700206aos::SizedArray<flatbuffers::Offset<ImageMatchDebug>, 5>
207Localizer::HandleImageMatch(
208 size_t camera_index, std::string_view pi,
209 const frc971::vision::sift::ImageMatchResult &result,
210 aos::monotonic_clock::time_point now, flatbuffers::FlatBufferBuilder *fbb) {
211 aos::SizedArray<flatbuffers::Offset<ImageMatchDebug>, 5> debug_offsets;
212
James Kuszmaul958b21e2020-02-26 21:51:40 -0800213 std::chrono::nanoseconds monotonic_offset(0);
214 clock_offset_fetcher_.Fetch();
215 if (clock_offset_fetcher_.get() != nullptr) {
216 for (const auto connection : *clock_offset_fetcher_->connections()) {
217 if (connection->has_node() && connection->node()->has_name() &&
James Kuszmaulc6723cf2020-03-01 14:45:59 -0800218 connection->node()->name()->string_view() == pi) {
James Kuszmaul958b21e2020-02-26 21:51:40 -0800219 monotonic_offset =
220 std::chrono::nanoseconds(connection->monotonic_offset());
221 break;
222 }
223 }
224 }
James Kuszmaul5398fae2020-02-17 16:44:03 -0800225 aos::monotonic_clock::time_point capture_time(
James Kuszmaul958b21e2020-02-26 21:51:40 -0800226 std::chrono::nanoseconds(result.image_monotonic_timestamp_ns()) -
227 monotonic_offset);
James Kuszmaul2d8fa2a2020-03-01 13:51:50 -0800228 VLOG(1) << "Got monotonic offset of "
229 << aos::time::DurationInSeconds(monotonic_offset)
James Kuszmaul58cb1fe2020-03-07 16:18:59 -0800230 << " when at time of " << now << " and capture time estimate of "
231 << capture_time;
James Kuszmaulf75ecd62021-10-23 14:33:46 -0700232 std::optional<RejectionReason> rejection_reason;
James Kuszmaul58cb1fe2020-03-07 16:18:59 -0800233 if (capture_time > now) {
James Kuszmaul2d8fa2a2020-03-01 13:51:50 -0800234 LOG(WARNING) << "Got camera frame from the future.";
James Kuszmaulf75ecd62021-10-23 14:33:46 -0700235 rejection_reason = RejectionReason::IMAGE_FROM_FUTURE;
James Kuszmaul2d8fa2a2020-03-01 13:51:50 -0800236 }
James Kuszmaulbcd96fc2020-10-12 20:29:32 -0700237 if (!result.has_camera_calibration()) {
238 LOG(WARNING) << "Got camera frame without calibration data.";
James Kuszmaul5ff8a862021-09-25 17:29:43 -0700239 ImageMatchDebug::Builder builder(*fbb);
240 builder.add_camera(camera_index);
241 builder.add_accepted(false);
242 builder.add_rejection_reason(RejectionReason::NO_CALIBRATION);
243 debug_offsets.push_back(builder.Finish());
James Kuszmaulf75ecd62021-10-23 14:33:46 -0700244 statistics_.rejection_counts[static_cast<size_t>(
245 RejectionReason::NO_CALIBRATION)]++;
James Kuszmaul5ff8a862021-09-25 17:29:43 -0700246 return debug_offsets;
James Kuszmaulbcd96fc2020-10-12 20:29:32 -0700247 }
James Kuszmaul5398fae2020-02-17 16:44:03 -0800248 // Per the ImageMatchResult specification, we can actually determine whether
249 // the camera is the turret camera just from the presence of the
250 // turret_extrinsics member.
251 const bool is_turret = result.camera_calibration()->has_turret_extrinsics();
252 const TurretData turret_data = GetTurretDataForTime(capture_time);
253 // Ignore readings when the turret is spinning too fast, on the assumption
254 // that the odds of screwing up the time compensation are higher.
255 // Note that the current number here is chosen pretty arbitrarily--1 rad / sec
256 // seems reasonable, but may be unnecessarily low or high.
James Kuszmauld478f872020-03-16 20:54:27 -0700257 constexpr float kMaxTurretVelocity = 1.0;
James Kuszmaul5398fae2020-02-17 16:44:03 -0800258 if (is_turret && std::abs(turret_data.velocity) > kMaxTurretVelocity) {
James Kuszmaulf75ecd62021-10-23 14:33:46 -0700259 rejection_reason = RejectionReason::TURRET_TOO_FAST;
James Kuszmaul5398fae2020-02-17 16:44:03 -0800260 }
261 CHECK(result.camera_calibration()->has_fixed_extrinsics());
James Kuszmauld478f872020-03-16 20:54:27 -0700262 const Eigen::Matrix<float, 4, 4> fixed_extrinsics =
James Kuszmaul5398fae2020-02-17 16:44:03 -0800263 FlatbufferToTransformationMatrix(
264 *result.camera_calibration()->fixed_extrinsics());
James Kuszmaul58cb1fe2020-03-07 16:18:59 -0800265
James Kuszmaul5398fae2020-02-17 16:44:03 -0800266 // Calculate the pose of the camera relative to the robot origin.
James Kuszmauld478f872020-03-16 20:54:27 -0700267 Eigen::Matrix<float, 4, 4> H_robot_camera = fixed_extrinsics;
James Kuszmaul5398fae2020-02-17 16:44:03 -0800268 if (is_turret) {
James Kuszmaulc51dbfe2020-02-23 15:39:00 -0800269 H_robot_camera = H_robot_camera *
James Kuszmauld478f872020-03-16 20:54:27 -0700270 frc971::control_loops::TransformationMatrixForYaw<float>(
James Kuszmauled6fca42021-09-25 17:58:30 -0700271 turret_data.position + kTurretPiOffset) *
James Kuszmaul5398fae2020-02-17 16:44:03 -0800272 FlatbufferToTransformationMatrix(
273 *result.camera_calibration()->turret_extrinsics());
274 }
275
276 if (!result.has_camera_poses()) {
James Kuszmaul5ff8a862021-09-25 17:29:43 -0700277 ImageMatchDebug::Builder builder(*fbb);
278 builder.add_camera(camera_index);
279 builder.add_accepted(false);
280 builder.add_rejection_reason(RejectionReason::NO_RESULTS);
281 debug_offsets.push_back(builder.Finish());
James Kuszmaulf75ecd62021-10-23 14:33:46 -0700282 statistics_
283 .rejection_counts[static_cast<size_t>(RejectionReason::NO_RESULTS)]++;
James Kuszmaul5ff8a862021-09-25 17:29:43 -0700284 return debug_offsets;
James Kuszmaul5398fae2020-02-17 16:44:03 -0800285 }
286
James Kuszmaul5ff8a862021-09-25 17:29:43 -0700287 int index = -1;
James Kuszmaul5398fae2020-02-17 16:44:03 -0800288 for (const frc971::vision::sift::CameraPose *vision_result :
289 *result.camera_poses()) {
James Kuszmaulf75ecd62021-10-23 14:33:46 -0700290 ++statistics_.total_candidates;
James Kuszmaul5ff8a862021-09-25 17:29:43 -0700291 ++index;
292
293 ImageMatchDebug::Builder builder(*fbb);
294 builder.add_camera(camera_index);
295 builder.add_pose_index(index);
296 builder.add_local_image_capture_time_ns(result.image_monotonic_timestamp_ns());
297 builder.add_roborio_image_capture_time_ns(
298 capture_time.time_since_epoch().count());
299 builder.add_image_age_sec(aos::time::DurationInSeconds(now - capture_time));
300
James Kuszmaul5398fae2020-02-17 16:44:03 -0800301 if (!vision_result->has_camera_to_target() ||
302 !vision_result->has_field_to_target()) {
James Kuszmaul5ff8a862021-09-25 17:29:43 -0700303 builder.add_accepted(false);
304 builder.add_rejection_reason(RejectionReason::NO_TRANSFORMS);
James Kuszmaulf75ecd62021-10-23 14:33:46 -0700305 statistics_.rejection_counts[static_cast<size_t>(
306 RejectionReason::NO_TRANSFORMS)]++;
James Kuszmaul5ff8a862021-09-25 17:29:43 -0700307 debug_offsets.push_back(builder.Finish());
James Kuszmaul5398fae2020-02-17 16:44:03 -0800308 continue;
309 }
James Kuszmauld478f872020-03-16 20:54:27 -0700310 const Eigen::Matrix<float, 4, 4> H_camera_target =
James Kuszmaul5398fae2020-02-17 16:44:03 -0800311 FlatbufferToTransformationMatrix(*vision_result->camera_to_target());
James Kuszmaul58cb1fe2020-03-07 16:18:59 -0800312
James Kuszmauld478f872020-03-16 20:54:27 -0700313 const Eigen::Matrix<float, 4, 4> H_field_target =
James Kuszmaul5398fae2020-02-17 16:44:03 -0800314 FlatbufferToTransformationMatrix(*vision_result->field_to_target());
James Kuszmaulf75ecd62021-10-23 14:33:46 -0700315 const Eigen::Matrix<float, 4, 4> H_field_camera =
316 H_field_target * H_camera_target.inverse();
James Kuszmaul5398fae2020-02-17 16:44:03 -0800317 // Back out the robot position that is implied by the current camera
James Kuszmaul715e7932021-04-05 20:45:57 -0700318 // reading. Note that the Pose object ignores any roll/pitch components, so
319 // if the camera's extrinsics for pitch/roll are off, this should just
320 // ignore it.
James Kuszmaulf75ecd62021-10-23 14:33:46 -0700321 const Pose measured_camera_pose(H_field_camera);
322 builder.add_camera_x(measured_camera_pose.rel_pos().x());
323 builder.add_camera_y(measured_camera_pose.rel_pos().y());
324 // Because the camera uses Z as forwards rather than X, just calculate the
325 // debugging theta value using the transformation matrix directly (note that
326 // the rest of this file deliberately does not care what convention the
327 // camera uses, since that is encoded in the extrinsics themselves).
328 builder.add_camera_theta(
329 std::atan2(H_field_camera(1, 2), H_field_camera(0, 2)));
James Kuszmaulaca88782021-04-24 16:48:45 -0700330 // Calculate the camera-to-robot transformation matrix ignoring the
331 // pitch/roll of the camera.
332 // TODO(james): This could probably be made a bit more efficient, but I
333 // don't think this is anywhere near our bottleneck currently.
334 const Eigen::Matrix<float, 4, 4> H_camera_robot_stripped =
335 Pose(H_robot_camera).AsTransformationMatrix().inverse();
336 const Pose measured_pose(measured_camera_pose.AsTransformationMatrix() *
337 H_camera_robot_stripped);
James Kuszmaul66efe832020-03-16 19:38:33 -0700338 // This "Z" is the robot pose directly implied by the camera results.
339 // Currently, we do not actually use this result directly. However, it is
340 // kept around in case we want to quickly re-enable it.
James Kuszmauld478f872020-03-16 20:54:27 -0700341 const Eigen::Matrix<float, 3, 1> Z(measured_pose.rel_pos().x(),
342 measured_pose.rel_pos().y(),
343 measured_pose.rel_theta());
James Kuszmaulf75ecd62021-10-23 14:33:46 -0700344 builder.add_implied_robot_x(Z(0));
345 builder.add_implied_robot_y(Z(1));
346 builder.add_implied_robot_theta(Z(2));
James Kuszmaul58cb1fe2020-03-07 16:18:59 -0800347 // Pose of the target in the robot frame.
James Kuszmaul715e7932021-04-05 20:45:57 -0700348 // Note that we use measured_pose's transformation matrix rather than just
349 // doing H_robot_camera * H_camera_target because measured_pose ignores
350 // pitch/roll.
351 Pose pose_robot_target(measured_pose.AsTransformationMatrix().inverse() *
352 H_field_target);
James Kuszmaulf75ecd62021-10-23 14:33:46 -0700353
354 // Turret is zero when pointed backwards.
355 builder.add_implied_turret_goal(
356 aos::math::NormalizeAngle(M_PI + pose_robot_target.heading()));
357
358 // Since we've now built up all the information that is useful to include in
359 // the debug message, bail if we have reason to do so.
360 if (rejection_reason) {
361 builder.add_rejection_reason(*rejection_reason);
362 statistics_.rejection_counts[static_cast<size_t>(*rejection_reason)]++;
363 builder.add_accepted(false);
364 debug_offsets.push_back(builder.Finish());
365 continue;
366 }
367
James Kuszmaul5398fae2020-02-17 16:44:03 -0800368 // TODO(james): Figure out how to properly handle calculating the
369 // noise. Currently, the values are deliberately tuned so that image updates
370 // will not be trusted overly much. In theory, we should probably also be
371 // populating some cross-correlation terms.
372 // Note that these are the noise standard deviations (they are squared below
373 // to get variances).
James Kuszmauled6fca42021-09-25 17:58:30 -0700374 Eigen::Matrix<float, 3, 1> noises(2.0, 2.0, 0.5);
James Kuszmaul5398fae2020-02-17 16:44:03 -0800375 // Augment the noise by the approximate rotational speed of the
376 // camera. This should help account for the fact that, while we are
377 // spinning, slight timing errors in the camera/turret data will tend to
378 // have mutch more drastic effects on the results.
379 noises *= 1.0 + std::abs((right_velocity() - left_velocity()) /
380 (2.0 * dt_config_.robot_radius) +
381 (is_turret ? turret_data.velocity : 0.0));
Austin Schuheb718632021-10-22 22:32:57 -0700382
383 // Pay less attention to cameras that aren't actually on the turret, since they
384 // are less useful when it comes to actually making shots.
385 if (!is_turret) {
386 noises *= 3.0;
387 }
388
James Kuszmauld478f872020-03-16 20:54:27 -0700389 Eigen::Matrix3f R = Eigen::Matrix3f::Zero();
James Kuszmaul5398fae2020-02-17 16:44:03 -0800390 R.diagonal() = noises.cwiseAbs2();
James Kuszmauld478f872020-03-16 20:54:27 -0700391 Eigen::Matrix<float, HybridEkf::kNOutputs, HybridEkf::kNStates> H;
James Kuszmaul5398fae2020-02-17 16:44:03 -0800392 H.setZero();
393 H(0, StateIdx::kX) = 1;
394 H(1, StateIdx::kY) = 1;
James Kuszmauled6fca42021-09-25 17:58:30 -0700395 H(2, StateIdx::kTheta) = 1;
James Kuszmaul58cb1fe2020-03-07 16:18:59 -0800396 VLOG(1) << "Pose implied by target: " << Z.transpose()
397 << " and current pose " << x() << ", " << y() << ", " << theta()
398 << " Heading/dist/skew implied by target: "
399 << pose_robot_target.ToHeadingDistanceSkew().transpose();
James Kuszmauladd40ca2020-03-01 14:10:50 -0800400 // If the heading is off by too much, assume that we got a false-positive
401 // and don't use the correction.
James Kuszmauld478f872020-03-16 20:54:27 -0700402 if (std::abs(aos::math::DiffAngle<float>(theta(), Z(2))) > M_PI_2) {
James Kuszmauladd40ca2020-03-01 14:10:50 -0800403 AOS_LOG(WARNING, "Dropped image match due to heading mismatch.\n");
James Kuszmaul5ff8a862021-09-25 17:29:43 -0700404 builder.add_accepted(false);
405 builder.add_rejection_reason(RejectionReason::HIGH_THETA_DIFFERENCE);
James Kuszmaulf75ecd62021-10-23 14:33:46 -0700406 statistics_.rejection_counts[static_cast<size_t>(
407 RejectionReason::HIGH_THETA_DIFFERENCE)]++;
James Kuszmaul5ff8a862021-09-25 17:29:43 -0700408 debug_offsets.push_back(builder.Finish());
James Kuszmaul58cb1fe2020-03-07 16:18:59 -0800409 continue;
James Kuszmauladd40ca2020-03-01 14:10:50 -0800410 }
James Kuszmaul06257f42020-05-09 15:40:09 -0700411 // In order to do the EKF correction, we determine the expected state based
412 // on the state at the time the image was captured; however, we insert the
413 // correction update itself at the current time. This is technically not
414 // quite correct, but saves substantial CPU usage by making it so that we
415 // don't have to constantly rewind the entire EKF history.
416 const std::optional<State> state_at_capture =
417 ekf_.LastStateBeforeTime(capture_time);
418 if (!state_at_capture.has_value()) {
419 AOS_LOG(WARNING, "Dropped image match due to age of image.\n");
James Kuszmaul5ff8a862021-09-25 17:29:43 -0700420 builder.add_accepted(false);
421 builder.add_rejection_reason(RejectionReason::IMAGE_TOO_OLD);
James Kuszmaulf75ecd62021-10-23 14:33:46 -0700422 statistics_.rejection_counts[static_cast<size_t>(
423 RejectionReason::IMAGE_TOO_OLD)]++;
James Kuszmaul5ff8a862021-09-25 17:29:43 -0700424 debug_offsets.push_back(builder.Finish());
James Kuszmaul06257f42020-05-09 15:40:09 -0700425 continue;
426 }
James Kuszmaul5ff8a862021-09-25 17:29:43 -0700427
James Kuszmaul5ff8a862021-09-25 17:29:43 -0700428 std::optional<RejectionReason> correction_rejection;
James Kuszmaul06257f42020-05-09 15:40:09 -0700429 const Input U = ekf_.MostRecentInput();
James Kuszmaul66efe832020-03-16 19:38:33 -0700430 // For the correction step, instead of passing in the measurement directly,
431 // we pass in (0, 0, 0) as the measurement and then for the expected
432 // measurement (Zhat) we calculate the error between the implied and actual
433 // poses. This doesn't affect any of the math, it just makes the code a bit
434 // more convenient to write given the Correct() interface we already have.
James Kuszmaul5ff8a862021-09-25 17:29:43 -0700435 // Note: If we start going back to doing back-in-time rewinds, then we can't
436 // get away with passing things by reference.
James Kuszmaul58cb1fe2020-03-07 16:18:59 -0800437 ekf_.Correct(
James Kuszmaul06257f42020-05-09 15:40:09 -0700438 Eigen::Vector3f::Zero(), &U, {},
James Kuszmauled177c42021-09-30 18:53:08 -0700439 [H, H_field_target, pose_robot_target, state_at_capture, Z,
440 &correction_rejection](const State &,
441 const Input &) -> Eigen::Vector3f {
442 // Weighting for how much to use the current robot heading estimate
443 // vs. the heading estimate from the image results. A value of 1.0
444 // completely ignores the measured heading, but will prioritize turret
445 // aiming above all else. A value of 0.0 will prioritize correcting
446 // any gyro heading drift.
447 constexpr float kImpliedWeight = 0.99;
448 const float z_yaw_diff = aos::math::NormalizeAngle(
449 state_at_capture.value()(Localizer::StateIdx::kTheta) - Z(2));
450 const float z_yaw = Z(2) + kImpliedWeight * z_yaw_diff;
James Kuszmauled6fca42021-09-25 17:58:30 -0700451 const Eigen::Vector3f Z_implied =
James Kuszmauled177c42021-09-30 18:53:08 -0700452 CalculateImpliedPose(z_yaw, H_field_target, pose_robot_target);
453 const Eigen::Vector3f Z_used = Z_implied;
James Kuszmaul66efe832020-03-16 19:38:33 -0700454 // Just in case we ever do encounter any, drop measurements if they
455 // have non-finite numbers.
456 if (!Z.allFinite()) {
457 AOS_LOG(WARNING, "Got measurement with infinites or NaNs.\n");
James Kuszmaul5ff8a862021-09-25 17:29:43 -0700458 correction_rejection = RejectionReason::NONFINITE_MEASUREMENT;
James Kuszmauld478f872020-03-16 20:54:27 -0700459 return Eigen::Vector3f::Zero();
James Kuszmaul66efe832020-03-16 19:38:33 -0700460 }
James Kuszmauled177c42021-09-30 18:53:08 -0700461 Eigen::Vector3f Zhat = H * state_at_capture.value() - Z_used;
James Kuszmaul66efe832020-03-16 19:38:33 -0700462 // Rewrap angle difference to put it back in range. Note that this
463 // component of the error is currently ignored (see definition of H
464 // above).
465 Zhat(2) = aos::math::NormalizeAngle(Zhat(2));
James Kuszmaul58cb1fe2020-03-07 16:18:59 -0800466 // If the measurement implies that we are too far from the current
467 // estimate, then ignore it.
468 // Note that I am not entirely sure how much effect this actually has,
469 // because I primarily introduced it to make sure that any grossly
470 // invalid measurements get thrown out.
James Kuszmaul66efe832020-03-16 19:38:33 -0700471 if (Zhat.squaredNorm() > std::pow(10.0, 2)) {
James Kuszmaul5ff8a862021-09-25 17:29:43 -0700472 correction_rejection = RejectionReason::CORRECTION_TOO_LARGE;
James Kuszmauld478f872020-03-16 20:54:27 -0700473 return Eigen::Vector3f::Zero();
James Kuszmaul58cb1fe2020-03-07 16:18:59 -0800474 }
475 return Zhat;
476 },
James Kuszmaul06257f42020-05-09 15:40:09 -0700477 [H](const State &) { return H; }, R, now);
James Kuszmaul5ff8a862021-09-25 17:29:43 -0700478 if (correction_rejection) {
479 builder.add_accepted(false);
480 builder.add_rejection_reason(*correction_rejection);
James Kuszmaulf75ecd62021-10-23 14:33:46 -0700481 statistics_
482 .rejection_counts[static_cast<size_t>(*correction_rejection)]++;
James Kuszmaul5ff8a862021-09-25 17:29:43 -0700483 } else {
484 builder.add_accepted(true);
James Kuszmaulf75ecd62021-10-23 14:33:46 -0700485 statistics_.total_accepted++;
James Kuszmaul5ff8a862021-09-25 17:29:43 -0700486 }
487 debug_offsets.push_back(builder.Finish());
James Kuszmaul5398fae2020-02-17 16:44:03 -0800488 }
James Kuszmaul5ff8a862021-09-25 17:29:43 -0700489 return debug_offsets;
James Kuszmaul5398fae2020-02-17 16:44:03 -0800490}
491
492} // namespace drivetrain
493} // namespace control_loops
494} // namespace y2020