blob: ace366313b0e0aa51cfaeafea29fa12ea136bb02 [file] [log] [blame]
James Kuszmaul04a343c2023-02-20 16:38:22 -08001#include "y2023/localizer/localizer.h"
2
3#include "aos/containers/sized_array.h"
4#include "frc971/control_loops/drivetrain/localizer_generated.h"
5#include "frc971/control_loops/pose.h"
milind-u7a7f6662023-02-26 16:41:29 -08006#include "gflags/gflags.h"
James Kuszmaul04a343c2023-02-20 16:38:22 -08007#include "y2023/constants.h"
James Kuszmaul18008f82023-02-23 20:52:50 -08008#include "y2023/localizer/utils.h"
James Kuszmaul04a343c2023-02-20 16:38:22 -08009
milind-u7a7f6662023-02-26 16:41:29 -080010DEFINE_double(max_pose_error, 1e-6,
11 "Throw out target poses with a higher pose error than this");
milind-ua4f44ac2023-02-26 17:03:43 -080012DEFINE_double(distortion_noise_scalar, 1.0,
13 "Scale the target pose distortion factor by this when computing "
14 "the noise.");
milind-u7a7f6662023-02-26 16:41:29 -080015
James Kuszmaul04a343c2023-02-20 16:38:22 -080016namespace y2023::localizer {
17namespace {
18constexpr std::array<std::string_view, Localizer::kNumCameras> kPisToUse{
19 "pi1", "pi2", "pi3", "pi4"};
20
21size_t CameraIndexForName(std::string_view name) {
22 for (size_t index = 0; index < kPisToUse.size(); ++index) {
23 if (name == kPisToUse.at(index)) {
24 return index;
25 }
26 }
27 LOG(FATAL) << "No camera named " << name;
28}
29
30std::map<uint64_t, Localizer::Transform> GetTargetLocations(
31 const Constants &constants) {
32 CHECK(constants.has_target_map());
33 CHECK(constants.target_map()->has_target_poses());
34 std::map<uint64_t, Localizer::Transform> transforms;
35 for (const frc971::vision::TargetPoseFbs *target :
36 *constants.target_map()->target_poses()) {
37 CHECK(target->has_id());
38 CHECK(target->has_position());
39 CHECK(target->has_orientation());
40 CHECK_EQ(0u, transforms.count(target->id()));
41 transforms[target->id()] = PoseToTransform(target);
42 }
43 return transforms;
44}
45} // namespace
46
James Kuszmaul04a343c2023-02-20 16:38:22 -080047std::array<Localizer::CameraState, Localizer::kNumCameras>
48Localizer::MakeCameras(const Constants &constants, aos::EventLoop *event_loop) {
49 CHECK(constants.has_cameras());
50 std::array<Localizer::CameraState, Localizer::kNumCameras> cameras;
51 for (const CameraConfiguration *camera : *constants.cameras()) {
52 CHECK(camera->has_calibration());
53 const frc971::vision::calibration::CameraCalibration *calibration =
54 camera->calibration();
55 CHECK(!calibration->has_turret_extrinsics())
56 << "The 2023 robot does not have a turret.";
57 CHECK(calibration->has_node_name());
58 const size_t index =
59 CameraIndexForName(calibration->node_name()->string_view());
60 // We default-construct the extrinsics matrix to all-zeros; use that to
61 // sanity-check whether we have populated the matrix yet or not.
62 CHECK(cameras.at(index).extrinsics.norm() == 0)
63 << "Got multiple calibrations for "
64 << calibration->node_name()->string_view();
65 CHECK(calibration->has_fixed_extrinsics());
66 cameras.at(index).extrinsics =
67 frc971::control_loops::drivetrain::FlatbufferToTransformationMatrix(
68 *calibration->fixed_extrinsics());
69 cameras.at(index).debug_sender = event_loop->MakeSender<Visualization>(
70 absl::StrCat("/", calibration->node_name()->string_view(), "/camera"));
71 }
72 for (const CameraState &camera : cameras) {
73 CHECK(camera.extrinsics.norm() != 0) << "Missing a camera calibration.";
74 }
75 return cameras;
76}
77
78Localizer::Localizer(
79 aos::EventLoop *event_loop,
80 const frc971::control_loops::drivetrain::DrivetrainConfig<double> dt_config)
81 : event_loop_(event_loop),
82 dt_config_(dt_config),
83 constants_fetcher_(event_loop),
84 cameras_(MakeCameras(constants_fetcher_.constants(), event_loop)),
85 target_poses_(GetTargetLocations(constants_fetcher_.constants())),
86 down_estimator_(dt_config),
87 ekf_(dt_config),
88 observations_(&ekf_),
89 imu_watcher_(event_loop, dt_config,
90 y2023::constants::Values::DrivetrainEncoderToMeters(1),
91 std::bind(&Localizer::HandleImu, this, std::placeholders::_1,
92 std::placeholders::_2, std::placeholders::_3,
93 std::placeholders::_4, std::placeholders::_5)),
94 utils_(event_loop),
95 status_sender_(event_loop->MakeSender<Status>("/localizer")),
96 output_sender_(event_loop->MakeSender<frc971::controls::LocalizerOutput>(
97 "/localizer")) {
98 if (dt_config_.is_simulated) {
99 down_estimator_.assume_perfect_gravity();
100 }
101
102 for (size_t camera_index = 0; camera_index < kNumCameras; ++camera_index) {
103 const std::string_view pi_name = kPisToUse.at(camera_index);
104 event_loop->MakeWatcher(
105 absl::StrCat("/", pi_name, "/camera"),
106 [this, pi_name,
107 camera_index](const frc971::vision::TargetMap &targets) {
108 CHECK(targets.has_target_poses());
109 CHECK(targets.has_monotonic_timestamp_ns());
110 const std::optional<aos::monotonic_clock::duration> clock_offset =
111 utils_.ClockOffset(pi_name);
112 if (!clock_offset.has_value()) {
113 VLOG(1) << "Rejecting image due to disconnected message bridge at "
114 << event_loop_->monotonic_now();
115 cameras_.at(camera_index)
116 .rejection_counter.IncrementError(
117 RejectionReason::MESSAGE_BRIDGE_DISCONNECTED);
118 return;
119 }
120 const aos::monotonic_clock::time_point pi_capture_time(
121 std::chrono::nanoseconds(targets.monotonic_timestamp_ns()) -
122 clock_offset.value());
123 const aos::monotonic_clock::time_point capture_time =
124 pi_capture_time - imu_watcher_.pico_offset_error();
125 VLOG(2) << "Capture time of "
126 << targets.monotonic_timestamp_ns() * 1e-9
127 << " clock offset of "
128 << aos::time::DurationInSeconds(clock_offset.value())
129 << " pico error "
130 << aos::time::DurationInSeconds(
131 imu_watcher_.pico_offset_error());
132 if (pi_capture_time > event_loop_->context().monotonic_event_time) {
133 VLOG(1) << "Rejecting image due to being from future at "
134 << event_loop_->monotonic_now() << " with timestamp of "
135 << pi_capture_time << " and event time pf "
136 << event_loop_->context().monotonic_event_time;
137 cameras_.at(camera_index)
138 .rejection_counter.IncrementError(
139 RejectionReason::IMAGE_FROM_FUTURE);
140 return;
141 }
142 auto builder = cameras_.at(camera_index).debug_sender.MakeBuilder();
143 aos::SizedArray<flatbuffers::Offset<TargetEstimateDebug>, 20>
144 debug_offsets;
145 for (const frc971::vision::TargetPoseFbs *target :
146 *targets.target_poses()) {
147 VLOG(1) << "Handling target from " << camera_index;
148 auto offset = HandleTarget(camera_index, capture_time, *target,
149 builder.fbb());
150 if (debug_offsets.size() < debug_offsets.capacity()) {
151 debug_offsets.push_back(offset);
152 } else {
153 AOS_LOG(ERROR, "Dropped message from debug vector.");
154 }
155 }
156 auto vector_offset = builder.fbb()->CreateVector(
157 debug_offsets.data(), debug_offsets.size());
James Kuszmaulfb894572023-02-23 17:25:06 -0800158 auto stats_offset =
159 StatisticsForCamera(cameras_.at(camera_index), builder.fbb());
James Kuszmaul04a343c2023-02-20 16:38:22 -0800160 Visualization::Builder visualize_builder(*builder.fbb());
161 visualize_builder.add_targets(vector_offset);
James Kuszmaulfb894572023-02-23 17:25:06 -0800162 visualize_builder.add_statistics(stats_offset);
James Kuszmaul04a343c2023-02-20 16:38:22 -0800163 builder.CheckOk(builder.Send(visualize_builder.Finish()));
164 SendStatus();
165 });
166 }
167
168 event_loop_->AddPhasedLoop([this](int) { SendOutput(); },
169 std::chrono::milliseconds(5));
170
171 event_loop_->MakeWatcher(
172 "/drivetrain",
173 [this](
174 const frc971::control_loops::drivetrain::LocalizerControl &control) {
175 const double theta = control.keep_current_theta()
176 ? ekf_.X_hat(StateIdx::kTheta)
177 : control.theta();
178 const double left_encoder = ekf_.X_hat(StateIdx::kLeftEncoder);
179 const double right_encoder = ekf_.X_hat(StateIdx::kRightEncoder);
180 ekf_.ResetInitialState(
181 t_,
182 (HybridEkf::State() << control.x(), control.y(), theta,
183 left_encoder, 0, right_encoder, 0, 0, 0, 0, 0, 0)
184 .finished(),
185 ekf_.P());
186 });
187
188 ekf_.set_ignore_accel(true);
189 // Priority should be lower than the imu reading process, but non-zero.
190 event_loop->SetRuntimeRealtimePriority(10);
191 event_loop->OnRun([this, event_loop]() {
192 ekf_.ResetInitialState(event_loop->monotonic_now(),
193 HybridEkf::State::Zero(), ekf_.P());
194 });
195}
196
197void Localizer::HandleImu(aos::monotonic_clock::time_point sample_time_pico,
198 aos::monotonic_clock::time_point sample_time_pi,
199 std::optional<Eigen::Vector2d> encoders,
200 Eigen::Vector3d gyro, Eigen::Vector3d accel) {
201 last_encoder_readings_ = encoders;
202 // Ignore ivnalid readings; the HybridEkf will handle it reasonably.
203 if (!encoders.has_value()) {
204 return;
205 }
206 if (t_ == aos::monotonic_clock::min_time) {
207 t_ = sample_time_pico;
208 }
209 if (t_ + 10 * frc971::controls::ImuWatcher::kNominalDt < sample_time_pico) {
210 t_ = sample_time_pico;
211 ++clock_resets_;
212 }
213 const aos::monotonic_clock::duration dt = sample_time_pico - t_;
214 t_ = sample_time_pico;
215 // We don't actually use the down estimator currently, but it's really
216 // convenient for debugging.
217 down_estimator_.Predict(gyro, accel, dt);
218 const double yaw_rate = (dt_config_.imu_transform * gyro)(2);
219 ekf_.UpdateEncodersAndGyro(encoders.value()(0), encoders.value()(1), yaw_rate,
220 utils_.VoltageOrZero(sample_time_pi), accel, t_);
221 SendStatus();
222}
223
224flatbuffers::Offset<TargetEstimateDebug> Localizer::RejectImage(
225 int camera_index, RejectionReason reason,
226 TargetEstimateDebug::Builder *builder) {
227 builder->add_accepted(false);
228 builder->add_rejection_reason(reason);
229 cameras_.at(camera_index).rejection_counter.IncrementError(reason);
230 return builder->Finish();
231}
232
233flatbuffers::Offset<TargetEstimateDebug> Localizer::HandleTarget(
234 int camera_index, const aos::monotonic_clock::time_point capture_time,
235 const frc971::vision::TargetPoseFbs &target,
236 flatbuffers::FlatBufferBuilder *debug_fbb) {
237 ++total_candidate_targets_;
238 ++cameras_.at(camera_index).total_candidate_targets;
239
240 TargetEstimateDebug::Builder builder(*debug_fbb);
241 builder.add_camera(camera_index);
242 builder.add_image_age_sec(aos::time::DurationInSeconds(
243 event_loop_->monotonic_now() - capture_time));
244
245 const uint64_t target_id = target.id();
246 VLOG(2) << aos::FlatbufferToJson(&target);
247 if (target_poses_.count(target_id) == 0) {
248 VLOG(1) << "Rejecting target due to invalid ID " << target_id;
249 return RejectImage(camera_index, RejectionReason::NO_SUCH_TARGET, &builder);
250 }
251
252 const Transform &H_field_target = target_poses_.at(target_id);
253 const Transform &H_robot_camera = cameras_.at(camera_index).extrinsics;
254
255 const Transform H_camera_target = PoseToTransform(&target);
256
257 const Transform H_field_camera = H_field_target * H_camera_target.inverse();
258 // Back out the robot position that is implied by the current camera
259 // reading. Note that the Pose object ignores any roll/pitch components, so
260 // if the camera's extrinsics for pitch/roll are off, this should just
261 // ignore it.
262 const frc971::control_loops::Pose measured_camera_pose(H_field_camera);
263 builder.add_camera_x(measured_camera_pose.rel_pos().x());
264 builder.add_camera_y(measured_camera_pose.rel_pos().y());
265 // Because the camera uses Z as forwards rather than X, just calculate the
266 // debugging theta value using the transformation matrix directly.
267 builder.add_camera_theta(
268 std::atan2(H_field_camera(1, 2), H_field_camera(0, 2)));
269 // Calculate the camera-to-robot transformation matrix ignoring the
270 // pitch/roll of the camera.
271 const Transform H_camera_robot_stripped =
272 frc971::control_loops::Pose(H_robot_camera)
273 .AsTransformationMatrix()
274 .inverse();
275 const frc971::control_loops::Pose measured_pose(
276 measured_camera_pose.AsTransformationMatrix() * H_camera_robot_stripped);
277 // This "Z" is the robot pose directly implied by the camera results.
278 const Eigen::Matrix<double, 3, 1> Z(measured_pose.rel_pos().x(),
279 measured_pose.rel_pos().y(),
280 measured_pose.rel_theta());
281 builder.add_implied_robot_x(Z(Corrector::kX));
282 builder.add_implied_robot_y(Z(Corrector::kY));
283 builder.add_implied_robot_theta(Z(Corrector::kTheta));
284
285 // TODO(james): Tune this. Also, gain schedule for auto mode?
286 Eigen::Matrix<double, 3, 1> noises(1.0, 1.0, 0.5);
milind-ua4f44ac2023-02-26 17:03:43 -0800287 // Scale noise by the distortion factor for this detection
288 noises *= (1.0 + FLAGS_distortion_noise_scalar * target.distortion_factor());
James Kuszmaul04a343c2023-02-20 16:38:22 -0800289
290 Eigen::Matrix3d R = Eigen::Matrix3d::Zero();
291 R.diagonal() = noises.cwiseAbs2();
292 // In order to do the EKF correction, we determine the expected state based
293 // on the state at the time the image was captured; however, we insert the
294 // correction update itself at the current time. This is technically not
295 // quite correct, but saves substantial CPU usage & code complexity by
296 // making
297 // it so that we don't have to constantly rewind the entire EKF history.
298 const std::optional<State> state_at_capture =
299 ekf_.LastStateBeforeTime(capture_time);
300
301 if (!state_at_capture.has_value()) {
302 VLOG(1) << "Rejecting image due to being too old.";
303 return RejectImage(camera_index, RejectionReason::IMAGE_TOO_OLD, &builder);
milind-u7a7f6662023-02-26 16:41:29 -0800304 } else if (target.pose_error() > FLAGS_max_pose_error) {
305 VLOG(1) << "Rejecting target due to high pose error "
306 << target.pose_error();
307 return RejectImage(camera_index, RejectionReason::HIGH_POSE_ERROR,
308 &builder);
James Kuszmaul04a343c2023-02-20 16:38:22 -0800309 }
310
311 const Input U = ekf_.MostRecentInput();
312 VLOG(1) << "previous state " << ekf_.X_hat().topRows<3>().transpose();
313 // For the correction step, instead of passing in the measurement directly,
314 // we pass in (0, 0, 0) as the measurement and then for the expected
315 // measurement (Zhat) we calculate the error between the pose implied by
316 // the camera measurement and the current estimate of the
317 // pose. This doesn't affect any of the math, it just makes the code a bit
318 // more convenient to write given the Correct() interface we already have.
319 observations_.CorrectKnownH(Eigen::Vector3d::Zero(), &U,
320 Corrector(state_at_capture.value(), Z), R, t_);
321 ++total_accepted_targets_;
322 ++cameras_.at(camera_index).total_accepted_targets;
323 VLOG(1) << "new state " << ekf_.X_hat().topRows<3>().transpose();
James Kuszmaul71518872023-02-25 18:00:15 -0800324 builder.add_accepted(true);
James Kuszmaul04a343c2023-02-20 16:38:22 -0800325 return builder.Finish();
326}
327
328Localizer::Output Localizer::Corrector::H(const State &, const Input &) {
329 CHECK(Z_.allFinite());
330 Eigen::Vector3d Zhat = H_ * state_at_capture_ - Z_;
331 // Rewrap angle difference to put it back in range.
332 Zhat(2) = aos::math::NormalizeAngle(Zhat(2));
333 VLOG(1) << "Zhat " << Zhat.transpose() << " Z_ " << Z_.transpose()
334 << " state " << (H_ * state_at_capture_).transpose();
335 return Zhat;
336}
337
338void Localizer::SendOutput() {
339 auto builder = output_sender_.MakeBuilder();
340 frc971::controls::LocalizerOutput::Builder output_builder =
341 builder.MakeBuilder<frc971::controls::LocalizerOutput>();
342 output_builder.add_monotonic_timestamp_ns(
343 std::chrono::duration_cast<std::chrono::nanoseconds>(
344 event_loop_->context().monotonic_event_time.time_since_epoch())
345 .count());
346 output_builder.add_x(ekf_.X_hat(StateIdx::kX));
347 output_builder.add_y(ekf_.X_hat(StateIdx::kY));
348 output_builder.add_theta(ekf_.X_hat(StateIdx::kTheta));
349 output_builder.add_zeroed(imu_watcher_.zeroer().Zeroed());
350 output_builder.add_image_accepted_count(total_accepted_targets_);
351 const Eigen::Quaterniond &orientation =
352 Eigen::AngleAxis<double>(ekf_.X_hat(StateIdx::kTheta),
353 Eigen::Vector3d::UnitZ()) *
354 down_estimator_.X_hat();
355 frc971::controls::Quaternion quaternion;
356 quaternion.mutate_x(orientation.x());
357 quaternion.mutate_y(orientation.y());
358 quaternion.mutate_z(orientation.z());
359 quaternion.mutate_w(orientation.w());
360 output_builder.add_orientation(&quaternion);
361 builder.CheckOk(builder.Send(output_builder.Finish()));
362}
363
364flatbuffers::Offset<frc971::control_loops::drivetrain::LocalizerState>
365Localizer::PopulateState(flatbuffers::FlatBufferBuilder *fbb) const {
366 frc971::control_loops::drivetrain::LocalizerState::Builder builder(*fbb);
367 builder.add_x(ekf_.X_hat(StateIdx::kX));
368 builder.add_y(ekf_.X_hat(StateIdx::kY));
369 builder.add_theta(ekf_.X_hat(StateIdx::kTheta));
370 builder.add_left_velocity(ekf_.X_hat(StateIdx::kLeftVelocity));
371 builder.add_right_velocity(ekf_.X_hat(StateIdx::kRightVelocity));
372 builder.add_left_encoder(ekf_.X_hat(StateIdx::kLeftEncoder));
373 builder.add_right_encoder(ekf_.X_hat(StateIdx::kRightEncoder));
374 builder.add_left_voltage_error(ekf_.X_hat(StateIdx::kLeftVoltageError));
375 builder.add_right_voltage_error(ekf_.X_hat(StateIdx::kRightVoltageError));
376 builder.add_angular_error(ekf_.X_hat(StateIdx::kAngularError));
377 builder.add_longitudinal_velocity_offset(
378 ekf_.X_hat(StateIdx::kLongitudinalVelocityOffset));
379 builder.add_lateral_velocity(ekf_.X_hat(StateIdx::kLateralVelocity));
380 return builder.Finish();
381}
382
383flatbuffers::Offset<ImuStatus> Localizer::PopulateImu(
384 flatbuffers::FlatBufferBuilder *fbb) const {
385 const auto zeroer_offset = imu_watcher_.zeroer().PopulateStatus(fbb);
386 const auto failures_offset = imu_watcher_.PopulateImuFailures(fbb);
387 ImuStatus::Builder builder(*fbb);
388 builder.add_zeroed(imu_watcher_.zeroer().Zeroed());
389 builder.add_faulted_zero(imu_watcher_.zeroer().Faulted());
390 builder.add_zeroing(zeroer_offset);
391 if (imu_watcher_.pico_offset().has_value()) {
392 builder.add_pico_offset_ns(imu_watcher_.pico_offset().value().count());
393 builder.add_pico_offset_error_ns(imu_watcher_.pico_offset_error().count());
394 }
395 if (last_encoder_readings_.has_value()) {
396 builder.add_left_encoder(last_encoder_readings_.value()(0));
397 builder.add_right_encoder(last_encoder_readings_.value()(1));
398 }
399 builder.add_imu_failures(failures_offset);
400 return builder.Finish();
401}
402
James Kuszmaulfb894572023-02-23 17:25:06 -0800403flatbuffers::Offset<CumulativeStatistics> Localizer::StatisticsForCamera(
404 const CameraState &camera, flatbuffers::FlatBufferBuilder *fbb) {
405 const auto counts_offset = camera.rejection_counter.PopulateCounts(fbb);
406 CumulativeStatistics::Builder stats_builder(*fbb);
407 stats_builder.add_total_accepted(camera.total_accepted_targets);
408 stats_builder.add_total_candidates(camera.total_candidate_targets);
409 stats_builder.add_rejection_reasons(counts_offset);
410 return stats_builder.Finish();
411}
412
James Kuszmaul04a343c2023-02-20 16:38:22 -0800413void Localizer::SendStatus() {
414 auto builder = status_sender_.MakeBuilder();
415 std::array<flatbuffers::Offset<CumulativeStatistics>, kNumCameras>
416 stats_offsets;
417 for (size_t ii = 0; ii < kNumCameras; ++ii) {
James Kuszmaulfb894572023-02-23 17:25:06 -0800418 stats_offsets.at(ii) = StatisticsForCamera(cameras_.at(ii), builder.fbb());
James Kuszmaul04a343c2023-02-20 16:38:22 -0800419 }
420 auto stats_offset =
421 builder.fbb()->CreateVector(stats_offsets.data(), stats_offsets.size());
422 auto down_estimator_offset =
423 down_estimator_.PopulateStatus(builder.fbb(), t_);
424 auto imu_offset = PopulateImu(builder.fbb());
425 auto state_offset = PopulateState(builder.fbb());
426 Status::Builder status_builder = builder.MakeBuilder<Status>();
427 status_builder.add_state(state_offset);
428 status_builder.add_down_estimator(down_estimator_offset);
429 status_builder.add_imu(imu_offset);
430 status_builder.add_statistics(stats_offset);
431 builder.CheckOk(builder.Send(status_builder.Finish()));
432}
433
434} // namespace y2023::localizer