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