blob: 017879032027631692e0b04404a79405f314373e [file] [log] [blame]
James Kuszmaul5398fae2020-02-17 16:44:03 -08001#include "y2020/control_loops/drivetrain/localizer.h"
2
3#include "y2020/constants.h"
4
5namespace y2020 {
6namespace control_loops {
7namespace drivetrain {
8
9namespace {
10// Converts a flatbuffer TransformationMatrix to an Eigen matrix. Technically,
11// this should be able to do a single memcpy, but the extra verbosity here seems
12// appropriate.
13Eigen::Matrix<double, 4, 4> FlatbufferToTransformationMatrix(
14 const frc971::vision::sift::TransformationMatrix &flatbuffer) {
15 CHECK_EQ(16u, CHECK_NOTNULL(flatbuffer.data())->size());
16 Eigen::Matrix<double, 4, 4> result;
17 result.setIdentity();
18 for (int row = 0; row < 4; ++row) {
19 for (int col = 0; col < 4; ++col) {
20 result(row, col) = (*flatbuffer.data())[row * 4 + col];
21 }
22 }
23 return result;
24}
25} // namespace
26
27Localizer::Localizer(
28 aos::EventLoop *event_loop,
29 const frc971::control_loops::drivetrain::DrivetrainConfig<double>
30 &dt_config)
31 : event_loop_(event_loop), dt_config_(dt_config), ekf_(dt_config) {
32 // TODO(james): This doesn't really need to be a watcher; we could just use a
33 // fetcher for the superstructure status.
34 // This probably should be a Fetcher instead of a Watcher, but this
35 // seems simpler for the time being (although technically it should be
36 // possible to do everything we need to using just a Fetcher without
37 // even maintaining a separate buffer, but that seems overly cute).
38 event_loop_->MakeWatcher("/superstructure",
39 [this](const superstructure::Status &status) {
40 HandleSuperstructureStatus(status);
41 });
42
James Kuszmaul286b4282020-02-26 20:29:32 -080043 event_loop->OnRun([this, event_loop]() {
44 ekf_.ResetInitialState(event_loop->monotonic_now(), Ekf::State::Zero(),
45 ekf_.P());
46 });
47
James Kuszmaul5398fae2020-02-17 16:44:03 -080048 image_fetchers_.emplace_back(
49 event_loop_->MakeFetcher<frc971::vision::sift::ImageMatchResult>(
Austin Schuh6aa77be2020-02-22 21:06:40 -080050 "/pi1/camera"));
James Kuszmaul5398fae2020-02-17 16:44:03 -080051
52 target_selector_.set_has_target(false);
53}
54
55void Localizer::HandleSuperstructureStatus(
56 const y2020::control_loops::superstructure::Status &status) {
57 CHECK(status.has_turret());
58 turret_data_.Push({event_loop_->monotonic_now(), status.turret()->position(),
59 status.turret()->velocity()});
60}
61
62Localizer::TurretData Localizer::GetTurretDataForTime(
63 aos::monotonic_clock::time_point time) {
64 if (turret_data_.empty()) {
65 return {};
66 }
67
68 aos::monotonic_clock::duration lowest_time_error =
69 aos::monotonic_clock::duration::max();
70 TurretData best_data_match;
71 for (const auto &sample : turret_data_) {
72 const aos::monotonic_clock::duration time_error =
73 std::chrono::abs(sample.receive_time - time);
74 if (time_error < lowest_time_error) {
75 lowest_time_error = time_error;
76 best_data_match = sample;
77 }
78 }
79 return best_data_match;
80}
81
82void Localizer::Update(const ::Eigen::Matrix<double, 2, 1> &U,
83 aos::monotonic_clock::time_point now,
84 double left_encoder, double right_encoder,
85 double gyro_rate, const Eigen::Vector3d &accel) {
86 for (auto &image_fetcher : image_fetchers_) {
87 while (image_fetcher.FetchNext()) {
88 HandleImageMatch(*image_fetcher);
89 }
90 }
91 ekf_.UpdateEncodersAndGyro(left_encoder, right_encoder, gyro_rate, U, accel,
92 now);
93}
94
95void Localizer::HandleImageMatch(
96 const frc971::vision::sift::ImageMatchResult &result) {
97 // TODO(james): compensate for capture time across multiple nodes correctly.
98 aos::monotonic_clock::time_point capture_time(
99 std::chrono::nanoseconds(result.image_monotonic_timestamp_ns()));
100 CHECK(result.has_camera_calibration());
101 // Per the ImageMatchResult specification, we can actually determine whether
102 // the camera is the turret camera just from the presence of the
103 // turret_extrinsics member.
104 const bool is_turret = result.camera_calibration()->has_turret_extrinsics();
105 const TurretData turret_data = GetTurretDataForTime(capture_time);
106 // Ignore readings when the turret is spinning too fast, on the assumption
107 // that the odds of screwing up the time compensation are higher.
108 // Note that the current number here is chosen pretty arbitrarily--1 rad / sec
109 // seems reasonable, but may be unnecessarily low or high.
110 constexpr double kMaxTurretVelocity = 1.0;
111 if (is_turret && std::abs(turret_data.velocity) > kMaxTurretVelocity) {
112 return;
113 }
114 CHECK(result.camera_calibration()->has_fixed_extrinsics());
115 const Eigen::Matrix<double, 4, 4> fixed_extrinsics =
116 FlatbufferToTransformationMatrix(
117 *result.camera_calibration()->fixed_extrinsics());
118 // Calculate the pose of the camera relative to the robot origin.
James Kuszmaulc51dbfe2020-02-23 15:39:00 -0800119 Eigen::Matrix<double, 4, 4> H_robot_camera = fixed_extrinsics;
James Kuszmaul5398fae2020-02-17 16:44:03 -0800120 if (is_turret) {
James Kuszmaulc51dbfe2020-02-23 15:39:00 -0800121 H_robot_camera = H_robot_camera *
James Kuszmaul5398fae2020-02-17 16:44:03 -0800122 frc971::control_loops::TransformationMatrixForYaw(
123 turret_data.position) *
124 FlatbufferToTransformationMatrix(
125 *result.camera_calibration()->turret_extrinsics());
126 }
127
128 if (!result.has_camera_poses()) {
129 return;
130 }
131
132 for (const frc971::vision::sift::CameraPose *vision_result :
133 *result.camera_poses()) {
134 if (!vision_result->has_camera_to_target() ||
135 !vision_result->has_field_to_target()) {
136 continue;
137 }
James Kuszmaulc51dbfe2020-02-23 15:39:00 -0800138 const Eigen::Matrix<double, 4, 4> H_camera_target =
James Kuszmaul5398fae2020-02-17 16:44:03 -0800139 FlatbufferToTransformationMatrix(*vision_result->camera_to_target());
James Kuszmaulc51dbfe2020-02-23 15:39:00 -0800140 const Eigen::Matrix<double, 4, 4> H_field_target =
James Kuszmaul5398fae2020-02-17 16:44:03 -0800141 FlatbufferToTransformationMatrix(*vision_result->field_to_target());
142 // Back out the robot position that is implied by the current camera
143 // reading.
James Kuszmaulc51dbfe2020-02-23 15:39:00 -0800144 const Pose measured_pose(H_field_target *
145 (H_robot_camera * H_camera_target).inverse());
James Kuszmaul5398fae2020-02-17 16:44:03 -0800146 const Eigen::Matrix<double, 3, 1> Z(measured_pose.rel_pos().x(),
147 measured_pose.rel_pos().y(),
148 measured_pose.rel_theta());
149 // TODO(james): Figure out how to properly handle calculating the
150 // noise. Currently, the values are deliberately tuned so that image updates
151 // will not be trusted overly much. In theory, we should probably also be
152 // populating some cross-correlation terms.
153 // Note that these are the noise standard deviations (they are squared below
154 // to get variances).
155 Eigen::Matrix<double, 3, 1> noises(1.0, 1.0, 0.1);
156 // Augment the noise by the approximate rotational speed of the
157 // camera. This should help account for the fact that, while we are
158 // spinning, slight timing errors in the camera/turret data will tend to
159 // have mutch more drastic effects on the results.
160 noises *= 1.0 + std::abs((right_velocity() - left_velocity()) /
161 (2.0 * dt_config_.robot_radius) +
162 (is_turret ? turret_data.velocity : 0.0));
163 Eigen::Matrix3d R = Eigen::Matrix3d::Zero();
164 R.diagonal() = noises.cwiseAbs2();
165 Eigen::Matrix<double, HybridEkf::kNOutputs, HybridEkf::kNStates> H;
166 H.setZero();
167 H(0, StateIdx::kX) = 1;
168 H(1, StateIdx::kY) = 1;
169 H(2, StateIdx::kTheta) = 1;
170 ekf_.Correct(Z, nullptr, {}, [H, Z](const State &X, const Input &) {
171 Eigen::Vector3d Zhat = H * X;
172 // In order to deal with wrapping of the
173 // angle, calculate an expected angle that is
174 // in the range (Z(2) - pi, Z(2) + pi].
175 const double angle_error =
176 aos::math::NormalizeAngle(
177 X(StateIdx::kTheta) - Z(2));
178 Zhat(2) = Z(2) + angle_error;
179 return Zhat;
180 },
181 [H](const State &) { return H; }, R, capture_time);
182 }
183}
184
185} // namespace drivetrain
186} // namespace control_loops
187} // namespace y2020