blob: cb11c440b15f2a92173731748150458743a25aea [file] [log] [blame]
James Kuszmaul313e9ce2024-02-11 17:47:33 -08001#include "y2024/localizer/localizer.h"
2
Austin Schuh99f7c6a2024-06-25 22:07:44 -07003#include "absl/flags/flag.h"
James Kuszmaul313e9ce2024-02-11 17:47:33 -08004
5#include "aos/containers/sized_array.h"
6#include "frc971/control_loops/drivetrain/localizer_generated.h"
7#include "frc971/control_loops/pose.h"
James Kuszmaul86116c22024-03-15 22:50:34 -07008#include "frc971/math/flatbuffers_matrix.h"
James Kuszmaul313e9ce2024-02-11 17:47:33 -08009#include "frc971/vision/target_map_utils.h"
10#include "y2024/constants.h"
11
Austin Schuh99f7c6a2024-06-25 22:07:44 -070012ABSL_FLAG(double, max_pose_error, 1e-5,
13 "Throw out target poses with a higher pose error than this");
14ABSL_FLAG(double, max_distortion, 1000.0, "");
15ABSL_FLAG(double, max_pose_error_ratio, 0.4,
16 "Throw out target poses with a higher pose error ratio than this");
17ABSL_FLAG(double, distortion_noise_scalar, 4.0,
18 "Scale the target pose distortion factor by this when computing "
19 "the noise.");
20ABSL_FLAG(
21 double, max_implied_yaw_error, 5.0,
James Kuszmaul313e9ce2024-02-11 17:47:33 -080022 "Reject target poses that imply a robot yaw of more than this many degrees "
23 "off from our estimate.");
Austin Schuh99f7c6a2024-06-25 22:07:44 -070024ABSL_FLAG(
25 double, max_implied_teleop_yaw_error, 30.0,
James Kuszmaul313e9ce2024-02-11 17:47:33 -080026 "Reject target poses that imply a robot yaw of more than this many degrees "
27 "off from our estimate.");
Austin Schuh99f7c6a2024-06-25 22:07:44 -070028ABSL_FLAG(double, max_distance_to_target, 5.0,
29 "Reject target poses that have a 3d distance of more than this "
30 "many meters.");
31ABSL_FLAG(double, max_auto_image_robot_speed, 5.0,
32 "Reject target poses when the robot is travelling faster than "
33 "this speed in auto.");
34ABSL_FLAG(
35 bool, do_xytheta_corrections, false,
James Kuszmaul86116c22024-03-15 22:50:34 -070036 "If set, uses the x/y/theta corrector rather than a heading/distance/skew "
37 "one. This is better conditioned currently, but is theoretically worse due "
38 "to not capturing noise effectively.");
Austin Schuh99f7c6a2024-06-25 22:07:44 -070039ABSL_FLAG(bool, always_use_extra_tags, true,
40 "If set, we will use the \"deweighted\" tags even in auto mode (this "
41 "affects april tags whose field positions we do not trust as much).");
James Kuszmaul313e9ce2024-02-11 17:47:33 -080042
43namespace y2024::localizer {
44namespace {
45constexpr std::array<std::string_view, Localizer::kNumCameras>
Maxwell Henderson3279bc52024-03-01 09:50:53 -080046 kDetectionChannels{"/orin1/camera0", "/orin1/camera1", "/imu/camera0",
47 "/imu/camera1"};
James Kuszmaul313e9ce2024-02-11 17:47:33 -080048
49size_t CameraIndexForName(std::string_view name) {
50 for (size_t index = 0; index < kDetectionChannels.size(); ++index) {
51 if (name == kDetectionChannels.at(index)) {
52 return index;
53 }
54 }
55 LOG(FATAL) << "No camera channel named " << name;
56}
57
58std::map<uint64_t, Localizer::Transform> GetTargetLocations(
59 const Constants &constants) {
60 CHECK(constants.has_common());
61 CHECK(constants.common()->has_target_map());
62 CHECK(constants.common()->target_map()->has_target_poses());
63 std::map<uint64_t, Localizer::Transform> transforms;
64 for (const frc971::vision::TargetPoseFbs *target :
65 *constants.common()->target_map()->target_poses()) {
66 CHECK(target->has_id());
67 CHECK(target->has_position());
68 CHECK(target->has_orientation());
69 CHECK_EQ(0u, transforms.count(target->id()));
70 transforms[target->id()] = PoseToTransform(target);
71 }
72 return transforms;
73}
James Kuszmaul86116c22024-03-15 22:50:34 -070074
75// Returns the "nominal" covariance of localizer---i.e., the values to which it
76// tends to converge during normal operation. By initializing the localizer's
77// covariance this way, we reduce the likelihood that the first few corrections
78// we receive will result in insane jumps in robot state.
79Eigen::Matrix<double, Localizer::HybridEkf::kNStates,
80 Localizer::HybridEkf::kNStates>
81NominalCovariance() {
82 Eigen::Matrix<double, Localizer::HybridEkf::kNStates,
83 Localizer::HybridEkf::kNStates>
84 P_transpose;
85 // Grabbed from when the robot was in a steady-state.
James Kuszmaul592055e2024-03-23 20:12:59 -070086 P_transpose << 0.00478504226469438, 0.000253940126278529,
87 -0.000162526741742492, 2.25403185759796e-09, 0.0101734987442698,
88 2.25403195618803e-09, 0.0101734987442698, 0.0253922208811703,
89 0.0253922210268363, -2.21692792749728e-10, 1.30552506376491e-05,
90 8.24314992005184e-07, 0.000253940126278532, 0.00189751717312843,
91 0.000513974713526466, 2.03445653416419e-10, 0.00091777414692514,
92 2.03445505573468e-10, 0.00091777414692514, 0.002190445323373,
93 0.00219044511582939, 3.32473307499143e-10, 1.45178014834701e-06,
94 1.71788107973058e-05, -0.000162526741742491, 0.000513974713526467,
95 0.000241235997378754, -2.30353529071927e-12, -1.03627077991455e-05,
96 -2.30350039899681e-12, -1.03627077991157e-05, -6.36337811958761e-06,
97 -6.62065263890835e-06, 1.24447423005307e-09, -1.228397466134e-07,
98 2.45695800192927e-06, 2.25403185760077e-09, 2.0344565341686e-10,
99 -2.30353529071687e-12, 4.99964876555835e-09, 4.09452976434092e-08,
100 -1.11086080247582e-15, 4.09452976433419e-08, 1.61945884581856e-07,
101 1.61950413812579e-07, 4.58556491207338e-08, -1.0257731581937e-12,
102 3.0118336328036e-13, 0.0101734987442698, 0.000917774146925141,
103 -1.03627077991456e-05, 4.09452976433247e-08, 0.186711669156372,
104 4.09452978206736e-08, 0.186711669156351, 0.747606782854604,
105 0.747606783311591, -3.98476625129118e-10, 4.53292935526394e-05,
106 1.34809505728832e-06, 2.2540319561823e-09, 2.03445505573217e-10,
107 -2.30350039893596e-12, -1.11086077014401e-15, 4.09452978206229e-08,
108 4.99964876557609e-09, 4.0945297820556e-08, 1.61950414014674e-07,
109 1.61945884988215e-07, -4.58556492982177e-08, -1.02577287448067e-12,
110 3.01180296453645e-13, 0.0101734987442698, 0.000917774146925141,
111 -1.03627077991158e-05, 4.09452976433153e-08, 0.186711669156351,
112 4.09452978206613e-08, 0.186711669156372, 0.747606782852986,
113 0.747606783313209, -3.98476449084643e-10, 4.53292935526394e-05,
114 1.34809505728832e-06, 0.0253922208811701, 0.00219044532337299,
115 -6.36337811958279e-06, 1.61945884583411e-07, 0.747606782854602,
116 1.61950414014798e-07, 0.747606782852984, 4.36530695987946,
117 4.17234874741425, 7.37989263565032e-07, 0.000112905097332305,
118 1.0761727407346e-06, 0.025392221026836, 0.00219044511582942,
119 -6.62065263891535e-06, 1.61950413812353e-07, 0.747606783311594,
120 1.61945884987625e-07, 0.747606783313212, 4.17234874741427,
121 4.36530696204959, -7.39350829913324e-07, 0.000112905097765367,
122 1.07616825738023e-06, -2.21692793550929e-10, 3.32473307500738e-10,
123 1.24447423005688e-09, 4.58556491207295e-08, -3.98476620685685e-10,
124 -4.58556492984426e-08, -3.98476445724907e-10, 7.3798926341289e-07,
125 -7.39350829974392e-07, 0.212257282137077, -6.38021734059486e-13,
126 6.89673203238e-12, 1.30552506376492e-05, 1.451780148347e-06,
127 -1.22839746613403e-07, -1.02577315819363e-12, 4.53292935526395e-05,
128 -1.02577287448185e-12, 4.53292935526395e-05, 0.000112905097332305,
129 0.000112905097765368, -6.38021733687597e-13, 4.99487202342848e-05,
130 7.45706935797857e-09, 8.24314992005172e-07, 1.7178810797306e-05,
131 2.45695800192931e-06, 3.01183363281006e-13, 1.34809505728833e-06,
132 3.01180296453493e-13, 1.34809505728833e-06, 1.07617274073465e-06,
133 1.07616825738027e-06, 6.89673203233812e-12, 7.45706935797858e-09,
134 4.97065161286885e-05;
James Kuszmaul86116c22024-03-15 22:50:34 -0700135 return P_transpose.transpose();
136}
James Kuszmaul313e9ce2024-02-11 17:47:33 -0800137} // namespace
138
139std::array<Localizer::CameraState, Localizer::kNumCameras>
140Localizer::MakeCameras(const Constants &constants, aos::EventLoop *event_loop) {
James Kuszmaule8f550e2024-05-29 19:39:31 -0700141 CHECK(constants.has_cameras());
James Kuszmaul313e9ce2024-02-11 17:47:33 -0800142 std::array<Localizer::CameraState, Localizer::kNumCameras> cameras;
James Kuszmaule8f550e2024-05-29 19:39:31 -0700143 for (const CameraConfiguration *camera : *constants.cameras()) {
James Kuszmaul313e9ce2024-02-11 17:47:33 -0800144 CHECK(camera->has_calibration());
145 const frc971::vision::calibration::CameraCalibration *calibration =
146 camera->calibration();
147 CHECK(!calibration->has_turret_extrinsics())
148 << "The 2024 robot does not have cameras on a turret.";
149 CHECK(calibration->has_node_name());
150 const std::string channel_name =
151 absl::StrFormat("/%s/camera%d", calibration->node_name()->string_view(),
152 calibration->camera_number());
153 const size_t index = CameraIndexForName(channel_name);
154 // We default-construct the extrinsics matrix to all-zeros; use that to
155 // sanity-check whether we have populated the matrix yet or not.
156 CHECK(cameras.at(index).extrinsics.norm() == 0)
157 << "Got multiple calibrations for "
158 << calibration->node_name()->string_view();
159 CHECK(calibration->has_fixed_extrinsics());
160 cameras.at(index).extrinsics =
161 frc971::control_loops::drivetrain::FlatbufferToTransformationMatrix(
162 *calibration->fixed_extrinsics());
163 cameras.at(index).debug_sender =
164 event_loop->MakeSender<VisualizationStatic>(channel_name);
165 }
166 for (const CameraState &camera : cameras) {
167 CHECK(camera.extrinsics.norm() != 0) << "Missing a camera calibration.";
168 }
169 return cameras;
170}
171
172Localizer::Localizer(aos::EventLoop *event_loop)
173 : event_loop_(event_loop),
174 constants_fetcher_(event_loop),
Austin Schuh6bdcc372024-06-27 14:49:11 -0700175 dt_config_(frc971::control_loops::drivetrain::DrivetrainConfig<
176 double>::FromFlatbuffer(*[&]() {
177 CHECK(constants_fetcher_.constants().common() != nullptr);
178 CHECK(constants_fetcher_.constants().common()->drivetrain() != nullptr);
179 return constants_fetcher_.constants().common()->drivetrain();
180 }())),
James Kuszmaul313e9ce2024-02-11 17:47:33 -0800181 cameras_(MakeCameras(constants_fetcher_.constants(), event_loop)),
182 target_poses_(GetTargetLocations(constants_fetcher_.constants())),
183 down_estimator_(dt_config_),
James Kuszmaul86116c22024-03-15 22:50:34 -0700184 // Force the dt to 1 ms (the nominal IMU frequency) since we have observed
185 // issues with timing on the orins.
186 // TODO(james): Ostensibly, we should be able to use the timestamps from
187 // the IMU board itself for exactly this; however, I am currently worried
188 // about the impacts of clock drift in using that.
189 ekf_(dt_config_, std::chrono::milliseconds(1)),
James Kuszmaul313e9ce2024-02-11 17:47:33 -0800190 observations_(&ekf_),
James Kuszmaul86116c22024-03-15 22:50:34 -0700191 xyz_observations_(&ekf_),
James Kuszmaul313e9ce2024-02-11 17:47:33 -0800192 imu_watcher_(event_loop, dt_config_,
193 y2024::constants::Values::DrivetrainEncoderToMeters(1),
194 std::bind(&Localizer::HandleImu, this, std::placeholders::_1,
195 std::placeholders::_2, std::placeholders::_3,
196 std::placeholders::_4, std::placeholders::_5),
197 frc971::controls::ImuWatcher::TimestampSource::kPi),
198 utils_(event_loop),
199 status_sender_(event_loop->MakeSender<Status>("/localizer")),
200 output_sender_(event_loop->MakeSender<frc971::controls::LocalizerOutput>(
201 "/localizer")),
202 server_statistics_fetcher_(
203 event_loop_->MakeFetcher<aos::message_bridge::ServerStatistics>(
204 "/aos")),
205 client_statistics_fetcher_(
206 event_loop_->MakeFetcher<aos::message_bridge::ClientStatistics>(
James Kuszmaul86116c22024-03-15 22:50:34 -0700207 "/aos")),
208 control_fetcher_(event_loop_->MakeFetcher<
209 frc971::control_loops::drivetrain::LocalizerControl>(
210 "/drivetrain")) {
James Kuszmaul313e9ce2024-02-11 17:47:33 -0800211 if (dt_config_.is_simulated) {
212 down_estimator_.assume_perfect_gravity();
213 }
214
215 for (size_t camera_index = 0; camera_index < kNumCameras; ++camera_index) {
216 const std::string_view channel_name = kDetectionChannels.at(camera_index);
Austin Schuh6bdcc372024-06-27 14:49:11 -0700217 const aos::Channel *const channel =
218 event_loop->GetChannel<frc971::vision::TargetMap>(channel_name);
219 CHECK(channel != nullptr);
James Kuszmaul313e9ce2024-02-11 17:47:33 -0800220 event_loop->MakeWatcher(
221 channel_name, [this, channel,
222 camera_index](const frc971::vision::TargetMap &targets) {
223 CHECK(targets.has_target_poses());
224 CHECK(targets.has_monotonic_timestamp_ns());
225 const std::optional<aos::monotonic_clock::duration> clock_offset =
226 utils_.ClockOffset(channel->source_node()->string_view());
227 if (!clock_offset.has_value()) {
228 VLOG(1) << "Rejecting image due to disconnected message bridge at "
229 << event_loop_->monotonic_now();
230 cameras_.at(camera_index)
231 .rejection_counter.IncrementError(
232 RejectionReason::MESSAGE_BRIDGE_DISCONNECTED);
233 return;
234 }
235 const aos::monotonic_clock::time_point orin_capture_time(
236 std::chrono::nanoseconds(targets.monotonic_timestamp_ns()) -
237 clock_offset.value());
238 if (orin_capture_time > event_loop_->context().monotonic_event_time) {
239 VLOG(1) << "Rejecting image due to being from future at "
240 << event_loop_->monotonic_now() << " with timestamp of "
241 << orin_capture_time << " and event time pf "
242 << event_loop_->context().monotonic_event_time;
243 cameras_.at(camera_index)
244 .rejection_counter.IncrementError(
245 RejectionReason::IMAGE_FROM_FUTURE);
246 return;
247 }
248 auto debug_builder =
249 cameras_.at(camera_index).debug_sender.MakeStaticBuilder();
250 auto target_debug_list = debug_builder->add_targets();
251 // The static_length should already be 20.
252 CHECK(target_debug_list->reserve(20));
253 for (const frc971::vision::TargetPoseFbs *target :
254 *targets.target_poses()) {
255 VLOG(1) << "Handling target from " << camera_index;
256 HandleTarget(camera_index, orin_capture_time, *target,
257 target_debug_list->emplace_back());
258 }
259 StatisticsForCamera(cameras_.at(camera_index),
260 debug_builder->add_statistics());
261 debug_builder.CheckOk(debug_builder.Send());
262 SendStatus();
263 });
264 }
265
266 event_loop_->AddPhasedLoop([this](int) { SendOutput(); },
267 std::chrono::milliseconds(20));
268
269 event_loop_->MakeWatcher(
270 "/drivetrain",
271 [this](
272 const frc971::control_loops::drivetrain::LocalizerControl &control) {
James Kuszmaul86116c22024-03-15 22:50:34 -0700273 HandleControl(control);
James Kuszmaul313e9ce2024-02-11 17:47:33 -0800274 });
275
276 ekf_.set_ignore_accel(true);
277 // Priority should be lower than the imu reading process, but non-zero.
278 event_loop->SetRuntimeRealtimePriority(10);
279 event_loop->OnRun([this, event_loop]() {
280 ekf_.ResetInitialState(event_loop->monotonic_now(),
James Kuszmaul86116c22024-03-15 22:50:34 -0700281 HybridEkf::State::Zero(), NominalCovariance());
282 if (control_fetcher_.Fetch()) {
283 HandleControl(*control_fetcher_.get());
284 }
James Kuszmaul313e9ce2024-02-11 17:47:33 -0800285 });
286}
287
James Kuszmaul86116c22024-03-15 22:50:34 -0700288void Localizer::HandleControl(
289 const frc971::control_loops::drivetrain::LocalizerControl &control) {
290 // This is triggered whenever we need to force the X/Y/(maybe theta)
291 // position of the robot to a particular point---e.g., during pre-match
292 // setup, or when commanded by a button on the driverstation.
293
294 // For some forms of reset, we choose to keep our current yaw estimate
295 // rather than overriding it from the control message.
296 const double theta = control.keep_current_theta()
297 ? ekf_.X_hat(StateIdx::kTheta)
298 : control.theta();
299 // Encoder values need to be reset based on the current values to ensure
300 // that we don't get weird corrections on the next encoder update.
301 const double left_encoder = ekf_.X_hat(StateIdx::kLeftEncoder);
302 const double right_encoder = ekf_.X_hat(StateIdx::kRightEncoder);
303 ekf_.ResetInitialState(t_,
304 (HybridEkf::State() << control.x(), control.y(), theta,
305 left_encoder, 0, right_encoder, 0, 0, 0, 0, 0, 0)
306 .finished(),
307 NominalCovariance());
308 VLOG(1) << "Reset state";
309}
310
James Kuszmaul313e9ce2024-02-11 17:47:33 -0800311void Localizer::HandleImu(aos::monotonic_clock::time_point /*sample_time_pico*/,
312 aos::monotonic_clock::time_point sample_time_orin,
313 std::optional<Eigen::Vector2d> /*encoders*/,
314 Eigen::Vector3d gyro, Eigen::Vector3d accel) {
315 std::optional<Eigen::Vector2d> encoders = utils_.Encoders(sample_time_orin);
316 last_encoder_readings_ = encoders;
James Kuszmaul86116c22024-03-15 22:50:34 -0700317 VLOG(1) << "Got encoders";
James Kuszmaul313e9ce2024-02-11 17:47:33 -0800318 if (t_ == aos::monotonic_clock::min_time) {
319 t_ = sample_time_orin;
320 }
321 if (t_ + 10 * frc971::controls::ImuWatcher::kNominalDt < sample_time_orin) {
322 t_ = sample_time_orin;
323 ++clock_resets_;
324 }
325 const aos::monotonic_clock::duration dt = sample_time_orin - t_;
326 t_ = sample_time_orin;
327 // We don't actually use the down estimator currently, but it's really
328 // convenient for debugging.
329 down_estimator_.Predict(gyro, accel, dt);
330 const double yaw_rate = (dt_config_.imu_transform * gyro)(2);
James Kuszmaul2700e0f2024-03-16 16:45:48 -0700331 ekf_.UpdateEncodersAndGyro(
332 encoders.has_value() ? std::make_optional<double>(encoders.value()(0))
333 : std::nullopt,
334 encoders.has_value() ? std::make_optional<double>(encoders.value()(1))
335 : std::nullopt,
336 yaw_rate, utils_.VoltageOrZero(sample_time_orin), accel, t_);
James Kuszmaul313e9ce2024-02-11 17:47:33 -0800337 SendStatus();
338}
339
340void Localizer::RejectImage(int camera_index, RejectionReason reason,
341 TargetEstimateDebugStatic *builder) {
342 if (builder != nullptr) {
343 builder->set_accepted(false);
344 builder->set_rejection_reason(reason);
345 }
346 cameras_.at(camera_index).rejection_counter.IncrementError(reason);
347}
348
349// Only use april tags present in the target map; this method has also been used
350// (in the past) for ignoring april tags that tend to produce problematic
351// readings.
352bool Localizer::UseAprilTag(uint64_t target_id) {
James Kuszmaul86116c22024-03-15 22:50:34 -0700353 if (target_poses_.count(target_id) == 0) {
354 return false;
355 }
356 return true;
357}
358
359bool Localizer::DeweightAprilTag(uint64_t target_id) {
360 const flatbuffers::Vector<uint64_t> *ignore_tags = nullptr;
361
362 switch (utils_.Alliance()) {
363 case aos::Alliance::kRed:
Austin Schuh6bdcc372024-06-27 14:49:11 -0700364 ignore_tags =
365 constants_fetcher_.constants().common()->ignore_targets()->red();
366 CHECK(ignore_tags != nullptr);
James Kuszmaul86116c22024-03-15 22:50:34 -0700367 break;
368 case aos::Alliance::kBlue:
Austin Schuh6bdcc372024-06-27 14:49:11 -0700369 ignore_tags =
370 constants_fetcher_.constants().common()->ignore_targets()->blue();
371 CHECK(ignore_tags != nullptr);
James Kuszmaul86116c22024-03-15 22:50:34 -0700372 break;
373 case aos::Alliance::kInvalid:
374 return false;
375 }
376 return std::find(ignore_tags->begin(), ignore_tags->end(), target_id) !=
377 ignore_tags->end();
James Kuszmaul313e9ce2024-02-11 17:47:33 -0800378}
379
380namespace {
Austin Schuh99f7c6a2024-06-25 22:07:44 -0700381// converts a camera transformation matrix from treating the +z axis from
382// pointing straight out the lens to having the +x pointing straight out the
James Kuszmaul313e9ce2024-02-11 17:47:33 -0800383// lens, with +Z going "up" (i.e., -Y in the normal convention) and +Y going
384// leftwards (i.e., -X in the normal convention).
385Localizer::Transform ZToXCamera(const Localizer::Transform &transform) {
386 return transform *
387 Eigen::Matrix4d{
388 {0, -1, 0, 0}, {0, 0, -1, 0}, {1, 0, 0, 0}, {0, 0, 0, 1}};
389}
390} // namespace
391
392void Localizer::HandleTarget(
393 int camera_index, const aos::monotonic_clock::time_point capture_time,
394 const frc971::vision::TargetPoseFbs &target,
395 TargetEstimateDebugStatic *debug_builder) {
396 ++total_candidate_targets_;
397 ++cameras_.at(camera_index).total_candidate_targets;
398 const uint64_t target_id = target.id();
399
400 if (debug_builder == nullptr) {
401 AOS_LOG(ERROR, "Dropped message from debug vector.");
402 } else {
403 debug_builder->set_camera(camera_index);
404 debug_builder->set_image_age_sec(aos::time::DurationInSeconds(
405 event_loop_->monotonic_now() - capture_time));
406 debug_builder->set_image_monotonic_timestamp_ns(
407 std::chrono::duration_cast<std::chrono::nanoseconds>(
408 capture_time.time_since_epoch())
409 .count());
410 debug_builder->set_april_tag(target_id);
411 }
412 VLOG(2) << aos::FlatbufferToJson(&target);
413 if (!UseAprilTag(target_id)) {
414 VLOG(1) << "Rejecting target due to invalid ID " << target_id;
415 RejectImage(camera_index, RejectionReason::NO_SUCH_TARGET, debug_builder);
416 return;
417 }
James Kuszmaul86116c22024-03-15 22:50:34 -0700418 double april_tag_noise_scalar = 1.0;
419 if (DeweightAprilTag(target_id)) {
Austin Schuh99f7c6a2024-06-25 22:07:44 -0700420 if (!absl::GetFlag(FLAGS_always_use_extra_tags) &&
421 utils_.MaybeInAutonomous()) {
James Kuszmaul86116c22024-03-15 22:50:34 -0700422 VLOG(1) << "Rejecting target due to auto invalid ID " << target_id;
423 RejectImage(camera_index, RejectionReason::NO_SUCH_TARGET, debug_builder);
424 return;
425 } else {
James Kuszmaul592055e2024-03-23 20:12:59 -0700426 if (utils_.MaybeInAutonomous()) {
James Kuszmaul6caee212024-05-04 13:46:23 -0700427 april_tag_noise_scalar = 1.5;
James Kuszmaul592055e2024-03-23 20:12:59 -0700428 } else {
James Kuszmaul6caee212024-05-04 13:46:23 -0700429 if (target_id == 13 || target_id == 14) {
430 april_tag_noise_scalar = 5.0;
431 } else {
432 april_tag_noise_scalar = 5.0;
433 }
James Kuszmaul592055e2024-03-23 20:12:59 -0700434 }
James Kuszmaul86116c22024-03-15 22:50:34 -0700435 }
436 }
James Kuszmaul313e9ce2024-02-11 17:47:33 -0800437
438 const Transform &H_field_target = target_poses_.at(target_id);
439 const Transform &H_robot_camera = cameras_.at(camera_index).extrinsics;
440
441 const Transform H_camera_target = PoseToTransform(&target);
442
443 // In order to do the EKF correction, we determine the expected state based
444 // on the state at the time the image was captured; however, we insert the
445 // correction update itself at the current time. This is technically not
446 // quite correct, but saves substantial CPU usage & code complexity by
447 // making it so that we don't have to constantly rewind the entire EKF
448 // history.
449 const std::optional<State> state_at_capture =
450 ekf_.LastStateBeforeTime(capture_time);
451
452 if (!state_at_capture.has_value()) {
453 VLOG(1) << "Rejecting image due to being too old.";
454 return RejectImage(camera_index, RejectionReason::IMAGE_TOO_OLD,
455 debug_builder);
Austin Schuh99f7c6a2024-06-25 22:07:44 -0700456 } else if (target.pose_error() > absl::GetFlag(FLAGS_max_pose_error)) {
James Kuszmaul313e9ce2024-02-11 17:47:33 -0800457 VLOG(1) << "Rejecting target due to high pose error "
458 << target.pose_error();
459 return RejectImage(camera_index, RejectionReason::HIGH_POSE_ERROR,
460 debug_builder);
Austin Schuh99f7c6a2024-06-25 22:07:44 -0700461 } else if (target.pose_error_ratio() >
462 absl::GetFlag(FLAGS_max_pose_error_ratio)) {
James Kuszmaul313e9ce2024-02-11 17:47:33 -0800463 VLOG(1) << "Rejecting target due to high pose error ratio "
464 << target.pose_error_ratio();
465 return RejectImage(camera_index, RejectionReason::HIGH_POSE_ERROR_RATIO,
466 debug_builder);
467 }
468
James Kuszmaul592055e2024-03-23 20:12:59 -0700469 const double robot_speed =
470 (state_at_capture.value()(StateIdx::kLeftVelocity) +
471 state_at_capture.value()(StateIdx::kRightVelocity)) /
472 2.0;
473
James Kuszmaul313e9ce2024-02-11 17:47:33 -0800474 Corrector corrector(state_at_capture.value(), H_field_target, H_robot_camera,
475 H_camera_target);
476 const double distance_to_target = corrector.observed()(Corrector::kDistance);
477
478 // Heading, distance, skew at 1 meter.
James Kuszmaul592055e2024-03-23 20:12:59 -0700479 Eigen::Matrix<double, 3, 1> noises(0.03, 0.25, 0.15);
480 noises *= 2.0;
James Kuszmaul86116c22024-03-15 22:50:34 -0700481 const double distance_noise_scalar =
482 std::min(1.0, std::pow(distance_to_target, 2.0));
James Kuszmaul313e9ce2024-02-11 17:47:33 -0800483 noises(Corrector::kDistance) *= distance_noise_scalar;
484 noises(Corrector::kSkew) *= distance_noise_scalar;
485 // TODO(james): This is leftover from last year; figure out if we want it.
486 // Scale noise by the distortion factor for this detection
Austin Schuh99f7c6a2024-06-25 22:07:44 -0700487 noises *= (1.0 + absl::GetFlag(FLAGS_distortion_noise_scalar) *
488 target.distortion_factor());
James Kuszmaul86116c22024-03-15 22:50:34 -0700489 noises *= april_tag_noise_scalar;
James Kuszmaul592055e2024-03-23 20:12:59 -0700490 noises *= (1.0 + std::abs(robot_speed));
James Kuszmaul313e9ce2024-02-11 17:47:33 -0800491
492 Eigen::Matrix3d R = Eigen::Matrix3d::Zero();
493 R.diagonal() = noises.cwiseAbs2();
James Kuszmaul86116c22024-03-15 22:50:34 -0700494 const Eigen::Vector3d camera_position =
495 corrector.observed_camera_pose().abs_pos();
496 // Calculate the camera-to-robot transformation matrix ignoring the
497 // pitch/roll of the camera.
498 const Transform H_camera_robot_stripped =
499 frc971::control_loops::Pose(ZToXCamera(H_robot_camera))
500 .AsTransformationMatrix()
501 .inverse();
502 const frc971::control_loops::Pose measured_pose(
503 corrector.observed_camera_pose().AsTransformationMatrix() *
504 H_camera_robot_stripped);
James Kuszmaul313e9ce2024-02-11 17:47:33 -0800505 if (debug_builder != nullptr) {
James Kuszmaul313e9ce2024-02-11 17:47:33 -0800506 debug_builder->set_camera_x(camera_position.x());
507 debug_builder->set_camera_y(camera_position.y());
508 debug_builder->set_camera_theta(
509 corrector.observed_camera_pose().abs_theta());
James Kuszmaul313e9ce2024-02-11 17:47:33 -0800510 debug_builder->set_implied_robot_x(measured_pose.rel_pos().x());
511 debug_builder->set_implied_robot_y(measured_pose.rel_pos().y());
512 debug_builder->set_implied_robot_theta(measured_pose.rel_theta());
513
514 Corrector::PopulateMeasurement(corrector.expected(),
515 debug_builder->add_expected_observation());
516 Corrector::PopulateMeasurement(corrector.observed(),
517 debug_builder->add_actual_observation());
518 Corrector::PopulateMeasurement(noises, debug_builder->add_modeled_noise());
519 }
520
521 const double camera_yaw_error =
522 aos::math::NormalizeAngle(corrector.expected_camera_pose().abs_theta() -
523 corrector.observed_camera_pose().abs_theta());
524 constexpr double kDegToRad = M_PI / 180.0;
James Kuszmaul313e9ce2024-02-11 17:47:33 -0800525 const double yaw_threshold =
Austin Schuh99f7c6a2024-06-25 22:07:44 -0700526 (utils_.MaybeInAutonomous()
527 ? absl::GetFlag(FLAGS_max_implied_yaw_error)
528 : absl::GetFlag(FLAGS_max_implied_teleop_yaw_error)) *
James Kuszmaul313e9ce2024-02-11 17:47:33 -0800529 kDegToRad;
530
Austin Schuh99f7c6a2024-06-25 22:07:44 -0700531 if (target.distortion_factor() > absl::GetFlag(FLAGS_max_distortion)) {
James Kuszmaul86116c22024-03-15 22:50:34 -0700532 VLOG(1) << "Rejecting target due to high distortion.";
533 return RejectImage(camera_index, RejectionReason::HIGH_DISTORTION,
534 debug_builder);
535 } else if (utils_.MaybeInAutonomous() &&
Austin Schuh99f7c6a2024-06-25 22:07:44 -0700536 (std::abs(robot_speed) >
537 absl::GetFlag(FLAGS_max_auto_image_robot_speed))) {
James Kuszmaul313e9ce2024-02-11 17:47:33 -0800538 return RejectImage(camera_index, RejectionReason::ROBOT_TOO_FAST,
539 debug_builder);
540 } else if (std::abs(camera_yaw_error) > yaw_threshold) {
541 return RejectImage(camera_index, RejectionReason::HIGH_IMPLIED_YAW_ERROR,
542 debug_builder);
Austin Schuh99f7c6a2024-06-25 22:07:44 -0700543 } else if (distance_to_target > absl::GetFlag(FLAGS_max_distance_to_target)) {
James Kuszmaul313e9ce2024-02-11 17:47:33 -0800544 return RejectImage(camera_index, RejectionReason::HIGH_DISTANCE_TO_TARGET,
545 debug_builder);
546 }
547
548 const Input U = ekf_.MostRecentInput();
James Kuszmaul86116c22024-03-15 22:50:34 -0700549 VLOG(1) << "previous state " << ekf_.X_hat().transpose();
James Kuszmaul313e9ce2024-02-11 17:47:33 -0800550 const State prior_state = ekf_.X_hat();
551 // For the correction step, instead of passing in the measurement directly,
552 // we pass in (0, 0, 0) as the measurement and then for the expected
553 // measurement (Zhat) we calculate the error between the pose implied by
554 // the camera measurement and the current estimate of the
555 // pose. This doesn't affect any of the math, it just makes the code a bit
556 // more convenient to write given the Correct() interface we already have.
Austin Schuh99f7c6a2024-06-25 22:07:44 -0700557 if (absl::GetFlag(FLAGS_do_xytheta_corrections)) {
James Kuszmaul86116c22024-03-15 22:50:34 -0700558 Eigen::Vector3d Z(measured_pose.rel_pos().x(), measured_pose.rel_pos().y(),
559 measured_pose.rel_theta());
560 Eigen::Matrix<double, 3, 1> xyz_noises(0.2, 0.2, 0.5);
561 xyz_noises *= distance_noise_scalar;
562 xyz_noises *= april_tag_noise_scalar;
563 // Scale noise by the distortion factor for this detection
Austin Schuh99f7c6a2024-06-25 22:07:44 -0700564 xyz_noises *= (1.0 + absl::GetFlag(FLAGS_distortion_noise_scalar) *
565 target.distortion_factor());
James Kuszmaul86116c22024-03-15 22:50:34 -0700566
567 Eigen::Matrix3d R_xyz = Eigen::Matrix3d::Zero();
568 R_xyz.diagonal() = xyz_noises.cwiseAbs2();
569 xyz_observations_.CorrectKnownH(Eigen::Vector3d::Zero(), &U,
570 XyzCorrector(state_at_capture.value(), Z),
571 R_xyz, t_);
572 } else {
573 observations_.CorrectKnownH(Eigen::Vector3d::Zero(), &U, corrector, R, t_);
574 }
James Kuszmaul313e9ce2024-02-11 17:47:33 -0800575 ++total_accepted_targets_;
576 ++cameras_.at(camera_index).total_accepted_targets;
James Kuszmaul86116c22024-03-15 22:50:34 -0700577 VLOG(1) << "new state " << ekf_.X_hat().transpose();
James Kuszmaul313e9ce2024-02-11 17:47:33 -0800578 if (debug_builder != nullptr) {
579 debug_builder->set_correction_x(ekf_.X_hat()(StateIdx::kX) -
580 prior_state(StateIdx::kX));
581 debug_builder->set_correction_y(ekf_.X_hat()(StateIdx::kY) -
582 prior_state(StateIdx::kY));
583 debug_builder->set_correction_theta(ekf_.X_hat()(StateIdx::kTheta) -
584 prior_state(StateIdx::kTheta));
585 debug_builder->set_accepted(true);
James Kuszmaul86116c22024-03-15 22:50:34 -0700586 debug_builder->set_expected_robot_x(ekf_.X_hat()(StateIdx::kX));
587 debug_builder->set_expected_robot_y(ekf_.X_hat()(StateIdx::kY));
James Kuszmaul81d5f2d2024-04-05 21:57:14 -0700588 debug_builder->set_expected_robot_theta(
589 aos::math::NormalizeAngle(ekf_.X_hat()(StateIdx::kTheta)));
James Kuszmaul313e9ce2024-02-11 17:47:33 -0800590 }
591}
592
593void Localizer::SendOutput() {
594 auto builder = output_sender_.MakeBuilder();
595 frc971::controls::LocalizerOutput::Builder output_builder =
596 builder.MakeBuilder<frc971::controls::LocalizerOutput>();
597 output_builder.add_monotonic_timestamp_ns(
598 std::chrono::duration_cast<std::chrono::nanoseconds>(
599 event_loop_->context().monotonic_event_time.time_since_epoch())
600 .count());
601 output_builder.add_x(ekf_.X_hat(StateIdx::kX));
602 output_builder.add_y(ekf_.X_hat(StateIdx::kY));
603 output_builder.add_theta(ekf_.X_hat(StateIdx::kTheta));
604 output_builder.add_zeroed(imu_watcher_.zeroer().Zeroed());
605 output_builder.add_image_accepted_count(total_accepted_targets_);
606 const Eigen::Quaterniond &orientation =
607 Eigen::AngleAxis<double>(ekf_.X_hat(StateIdx::kTheta),
608 Eigen::Vector3d::UnitZ()) *
609 down_estimator_.X_hat();
610 frc971::controls::Quaternion quaternion;
611 quaternion.mutate_x(orientation.x());
612 quaternion.mutate_y(orientation.y());
613 quaternion.mutate_z(orientation.z());
614 quaternion.mutate_w(orientation.w());
615 output_builder.add_orientation(&quaternion);
616 server_statistics_fetcher_.Fetch();
617 client_statistics_fetcher_.Fetch();
618
619 bool orins_connected = true;
620
621 if (server_statistics_fetcher_.get()) {
622 for (const auto *orin_server_status :
623 *server_statistics_fetcher_->connections()) {
624 if (orin_server_status->state() ==
625 aos::message_bridge::State::DISCONNECTED) {
626 orins_connected = false;
627 }
628 }
629 }
630
631 if (client_statistics_fetcher_.get()) {
632 for (const auto *pi_client_status :
633 *client_statistics_fetcher_->connections()) {
634 if (pi_client_status->state() ==
635 aos::message_bridge::State::DISCONNECTED) {
636 orins_connected = false;
637 }
638 }
639 }
640
641 // The output message is year-agnostic, and retains "pi" naming for histrocial
642 // reasons.
643 output_builder.add_all_pis_connected(orins_connected);
644 builder.CheckOk(builder.Send(output_builder.Finish()));
645}
646
647flatbuffers::Offset<frc971::control_loops::drivetrain::LocalizerState>
648Localizer::PopulateState(const State &X_hat,
649 flatbuffers::FlatBufferBuilder *fbb) {
650 frc971::control_loops::drivetrain::LocalizerState::Builder builder(*fbb);
651 builder.add_x(X_hat(StateIdx::kX));
652 builder.add_y(X_hat(StateIdx::kY));
Stephan Pleines78df16d2024-04-03 20:45:26 -0700653 builder.add_theta(aos::math::NormalizeAngle(X_hat(StateIdx::kTheta)));
James Kuszmaul313e9ce2024-02-11 17:47:33 -0800654 builder.add_left_velocity(X_hat(StateIdx::kLeftVelocity));
655 builder.add_right_velocity(X_hat(StateIdx::kRightVelocity));
656 builder.add_left_encoder(X_hat(StateIdx::kLeftEncoder));
657 builder.add_right_encoder(X_hat(StateIdx::kRightEncoder));
658 builder.add_left_voltage_error(X_hat(StateIdx::kLeftVoltageError));
659 builder.add_right_voltage_error(X_hat(StateIdx::kRightVoltageError));
660 builder.add_angular_error(X_hat(StateIdx::kAngularError));
661 builder.add_longitudinal_velocity_offset(
662 X_hat(StateIdx::kLongitudinalVelocityOffset));
663 builder.add_lateral_velocity(X_hat(StateIdx::kLateralVelocity));
664 return builder.Finish();
665}
666
667flatbuffers::Offset<ImuStatus> Localizer::PopulateImu(
668 flatbuffers::FlatBufferBuilder *fbb) const {
669 const auto zeroer_offset = imu_watcher_.zeroer().PopulateStatus(fbb);
670 const auto failures_offset = imu_watcher_.PopulateImuFailures(fbb);
671 ImuStatus::Builder builder(*fbb);
672 builder.add_zeroed(imu_watcher_.zeroer().Zeroed());
673 builder.add_faulted_zero(imu_watcher_.zeroer().Faulted());
674 builder.add_zeroing(zeroer_offset);
675 if (imu_watcher_.pico_offset().has_value()) {
676 builder.add_board_offset_ns(imu_watcher_.pico_offset().value().count());
677 builder.add_board_offset_error_ns(imu_watcher_.pico_offset_error().count());
678 }
679 if (last_encoder_readings_.has_value()) {
680 builder.add_left_encoder(last_encoder_readings_.value()(0));
681 builder.add_right_encoder(last_encoder_readings_.value()(1));
682 }
683 builder.add_imu_failures(failures_offset);
684 return builder.Finish();
685}
686
687flatbuffers::Offset<CumulativeStatistics> Localizer::StatisticsForCamera(
688 const CameraState &camera, flatbuffers::FlatBufferBuilder *fbb) {
689 const auto counts_offset = camera.rejection_counter.PopulateCounts(fbb);
690 CumulativeStatistics::Builder stats_builder(*fbb);
691 stats_builder.add_total_accepted(camera.total_accepted_targets);
692 stats_builder.add_total_candidates(camera.total_candidate_targets);
693 stats_builder.add_rejection_reasons(counts_offset);
694 return stats_builder.Finish();
695}
696
697void Localizer::StatisticsForCamera(const CameraState &camera,
698 CumulativeStatisticsStatic *builder) {
699 camera.rejection_counter.PopulateCountsStaticFbs(
700 builder->add_rejection_reasons());
701 builder->set_total_accepted(camera.total_accepted_targets);
702 builder->set_total_candidates(camera.total_candidate_targets);
703}
704
705void Localizer::SendStatus() {
706 auto builder = status_sender_.MakeBuilder();
707 std::array<flatbuffers::Offset<CumulativeStatistics>, kNumCameras>
708 stats_offsets;
709 for (size_t ii = 0; ii < kNumCameras; ++ii) {
710 stats_offsets.at(ii) = StatisticsForCamera(cameras_.at(ii), builder.fbb());
711 }
712 auto stats_offset =
713 builder.fbb()->CreateVector(stats_offsets.data(), stats_offsets.size());
714 auto down_estimator_offset =
715 down_estimator_.PopulateStatus(builder.fbb(), t_);
716 auto imu_offset = PopulateImu(builder.fbb());
717 auto state_offset = PopulateState(ekf_.X_hat(), builder.fbb());
James Kuszmaul86116c22024-03-15 22:50:34 -0700718 // covariance is a square; we use the number of rows in the state as the rows
719 // and cols of the covariance.
720 auto covariance_offset =
721 frc971::FromEigen<State::RowsAtCompileTime, State::RowsAtCompileTime>(
722 ekf_.P(), builder.fbb());
James Kuszmaul313e9ce2024-02-11 17:47:33 -0800723 Status::Builder status_builder = builder.MakeBuilder<Status>();
724 status_builder.add_state(state_offset);
725 status_builder.add_down_estimator(down_estimator_offset);
726 status_builder.add_imu(imu_offset);
727 status_builder.add_statistics(stats_offset);
James Kuszmaul86116c22024-03-15 22:50:34 -0700728 status_builder.add_ekf_covariance(covariance_offset);
James Kuszmaul313e9ce2024-02-11 17:47:33 -0800729 builder.CheckOk(builder.Send(status_builder.Finish()));
730}
731
732Eigen::Vector3d Localizer::Corrector::HeadingDistanceSkew(
733 const Pose &relative_pose) {
734 const double heading = relative_pose.heading();
735 const double distance = relative_pose.xy_norm();
736 const double skew =
737 ::aos::math::NormalizeAngle(relative_pose.rel_theta() - heading);
738 return {heading, distance, skew};
739}
740
741Localizer::Corrector Localizer::Corrector::CalculateHeadingDistanceSkewH(
742 const State &state_at_capture, const Transform &H_field_target,
743 const Transform &H_robot_camera, const Transform &H_camera_target) {
744 const Transform H_field_camera = H_field_target * H_camera_target.inverse();
745 const Pose expected_robot_pose(
746 {state_at_capture(StateIdx::kX), state_at_capture(StateIdx::kY), 0.0},
747 state_at_capture(StateIdx::kTheta));
748 // Observed position on the field, reduced to just the 2-D pose.
749 const Pose observed_camera(ZToXCamera(H_field_camera));
750 const Pose expected_camera(expected_robot_pose.AsTransformationMatrix() *
751 ZToXCamera(H_robot_camera));
752 const Pose nominal_target(ZToXCamera(H_field_target));
753 const Pose observed_target = nominal_target.Rebase(&observed_camera);
754 const Pose expected_target = nominal_target.Rebase(&expected_camera);
755 return Localizer::Corrector{
756 expected_robot_pose,
757 observed_camera,
758 expected_camera,
759 HeadingDistanceSkew(expected_target),
760 HeadingDistanceSkew(observed_target),
761 frc971::control_loops::drivetrain::HMatrixForCameraHeadingDistanceSkew(
762 nominal_target, observed_camera)};
763}
764
765Localizer::Corrector::Corrector(const State &state_at_capture,
766 const Transform &H_field_target,
767 const Transform &H_robot_camera,
768 const Transform &H_camera_target)
769 : Corrector(CalculateHeadingDistanceSkewH(
770 state_at_capture, H_field_target, H_robot_camera, H_camera_target)) {}
771
772Localizer::Output Localizer::Corrector::H(const State &, const Input &) {
773 return expected_ - observed_;
774}
775
James Kuszmaul86116c22024-03-15 22:50:34 -0700776Localizer::Output Localizer::XyzCorrector::H(const State &, const Input &) {
777 CHECK(Z_.allFinite());
778 Eigen::Vector3d Zhat = H_ * state_at_capture_ - Z_;
779 // Rewrap angle difference to put it back in range.
780 Zhat(2) = aos::math::NormalizeAngle(Zhat(2));
781 VLOG(1) << "Zhat " << Zhat.transpose() << " Z_ " << Z_.transpose()
782 << " state " << (H_ * state_at_capture_).transpose();
783 return Zhat;
784}
785
James Kuszmaul313e9ce2024-02-11 17:47:33 -0800786} // namespace y2024::localizer