blob: a9e454a8ba2e20502e0a5e3af382396a2ad64f96 [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
43 image_fetchers_.emplace_back(
44 event_loop_->MakeFetcher<frc971::vision::sift::ImageMatchResult>(
45 "/camera"));
46
47 target_selector_.set_has_target(false);
48}
49
50void Localizer::HandleSuperstructureStatus(
51 const y2020::control_loops::superstructure::Status &status) {
52 CHECK(status.has_turret());
53 turret_data_.Push({event_loop_->monotonic_now(), status.turret()->position(),
54 status.turret()->velocity()});
55}
56
57Localizer::TurretData Localizer::GetTurretDataForTime(
58 aos::monotonic_clock::time_point time) {
59 if (turret_data_.empty()) {
60 return {};
61 }
62
63 aos::monotonic_clock::duration lowest_time_error =
64 aos::monotonic_clock::duration::max();
65 TurretData best_data_match;
66 for (const auto &sample : turret_data_) {
67 const aos::monotonic_clock::duration time_error =
68 std::chrono::abs(sample.receive_time - time);
69 if (time_error < lowest_time_error) {
70 lowest_time_error = time_error;
71 best_data_match = sample;
72 }
73 }
74 return best_data_match;
75}
76
77void Localizer::Update(const ::Eigen::Matrix<double, 2, 1> &U,
78 aos::monotonic_clock::time_point now,
79 double left_encoder, double right_encoder,
80 double gyro_rate, const Eigen::Vector3d &accel) {
81 for (auto &image_fetcher : image_fetchers_) {
82 while (image_fetcher.FetchNext()) {
83 HandleImageMatch(*image_fetcher);
84 }
85 }
86 ekf_.UpdateEncodersAndGyro(left_encoder, right_encoder, gyro_rate, U, accel,
87 now);
88}
89
90void Localizer::HandleImageMatch(
91 const frc971::vision::sift::ImageMatchResult &result) {
92 // TODO(james): compensate for capture time across multiple nodes correctly.
93 aos::monotonic_clock::time_point capture_time(
94 std::chrono::nanoseconds(result.image_monotonic_timestamp_ns()));
95 CHECK(result.has_camera_calibration());
96 // Per the ImageMatchResult specification, we can actually determine whether
97 // the camera is the turret camera just from the presence of the
98 // turret_extrinsics member.
99 const bool is_turret = result.camera_calibration()->has_turret_extrinsics();
100 const TurretData turret_data = GetTurretDataForTime(capture_time);
101 // Ignore readings when the turret is spinning too fast, on the assumption
102 // that the odds of screwing up the time compensation are higher.
103 // Note that the current number here is chosen pretty arbitrarily--1 rad / sec
104 // seems reasonable, but may be unnecessarily low or high.
105 constexpr double kMaxTurretVelocity = 1.0;
106 if (is_turret && std::abs(turret_data.velocity) > kMaxTurretVelocity) {
107 return;
108 }
109 CHECK(result.camera_calibration()->has_fixed_extrinsics());
110 const Eigen::Matrix<double, 4, 4> fixed_extrinsics =
111 FlatbufferToTransformationMatrix(
112 *result.camera_calibration()->fixed_extrinsics());
113 // Calculate the pose of the camera relative to the robot origin.
114 Eigen::Matrix<double, 4, 4> H_camera_robot = fixed_extrinsics;
115 if (is_turret) {
116 H_camera_robot = H_camera_robot *
117 frc971::control_loops::TransformationMatrixForYaw(
118 turret_data.position) *
119 FlatbufferToTransformationMatrix(
120 *result.camera_calibration()->turret_extrinsics());
121 }
122
123 if (!result.has_camera_poses()) {
124 return;
125 }
126
127 for (const frc971::vision::sift::CameraPose *vision_result :
128 *result.camera_poses()) {
129 if (!vision_result->has_camera_to_target() ||
130 !vision_result->has_field_to_target()) {
131 continue;
132 }
133 const Eigen::Matrix<double, 4, 4> H_target_camera =
134 FlatbufferToTransformationMatrix(*vision_result->camera_to_target());
135 const Eigen::Matrix<double, 4, 4> H_target_field =
136 FlatbufferToTransformationMatrix(*vision_result->field_to_target());
137 // Back out the robot position that is implied by the current camera
138 // reading.
139 const Pose measured_pose(H_target_field *
140 (H_camera_robot * H_target_camera).inverse());
141 const Eigen::Matrix<double, 3, 1> Z(measured_pose.rel_pos().x(),
142 measured_pose.rel_pos().y(),
143 measured_pose.rel_theta());
144 // TODO(james): Figure out how to properly handle calculating the
145 // noise. Currently, the values are deliberately tuned so that image updates
146 // will not be trusted overly much. In theory, we should probably also be
147 // populating some cross-correlation terms.
148 // Note that these are the noise standard deviations (they are squared below
149 // to get variances).
150 Eigen::Matrix<double, 3, 1> noises(1.0, 1.0, 0.1);
151 // Augment the noise by the approximate rotational speed of the
152 // camera. This should help account for the fact that, while we are
153 // spinning, slight timing errors in the camera/turret data will tend to
154 // have mutch more drastic effects on the results.
155 noises *= 1.0 + std::abs((right_velocity() - left_velocity()) /
156 (2.0 * dt_config_.robot_radius) +
157 (is_turret ? turret_data.velocity : 0.0));
158 Eigen::Matrix3d R = Eigen::Matrix3d::Zero();
159 R.diagonal() = noises.cwiseAbs2();
160 Eigen::Matrix<double, HybridEkf::kNOutputs, HybridEkf::kNStates> H;
161 H.setZero();
162 H(0, StateIdx::kX) = 1;
163 H(1, StateIdx::kY) = 1;
164 H(2, StateIdx::kTheta) = 1;
165 ekf_.Correct(Z, nullptr, {}, [H, Z](const State &X, const Input &) {
166 Eigen::Vector3d Zhat = H * X;
167 // In order to deal with wrapping of the
168 // angle, calculate an expected angle that is
169 // in the range (Z(2) - pi, Z(2) + pi].
170 const double angle_error =
171 aos::math::NormalizeAngle(
172 X(StateIdx::kTheta) - Z(2));
173 Zhat(2) = Z(2) + angle_error;
174 return Zhat;
175 },
176 [H](const State &) { return H; }, R, capture_time);
177 }
178}
179
180} // namespace drivetrain
181} // namespace control_loops
182} // namespace y2020