blob: 79035df39633f501eff5d7cff9d3820a4165d849 [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.
James Kuszmauld478f872020-03-16 20:54:27 -070013Eigen::Matrix<float, 4, 4> FlatbufferToTransformationMatrix(
James Kuszmaul5398fae2020-02-17 16:44:03 -080014 const frc971::vision::sift::TransformationMatrix &flatbuffer) {
15 CHECK_EQ(16u, CHECK_NOTNULL(flatbuffer.data())->size());
James Kuszmauld478f872020-03-16 20:54:27 -070016 Eigen::Matrix<float, 4, 4> result;
James Kuszmaul5398fae2020-02-17 16:44:03 -080017 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}
James Kuszmaul958b21e2020-02-26 21:51:40 -080025
James Kuszmaulc6723cf2020-03-01 14:45:59 -080026// Indices of the pis to use.
27const std::array<std::string, 3> kPisToUse{"pi1", "pi2", "pi3"};
28
James Kuszmaul66efe832020-03-16 19:38:33 -070029// Calculates the pose implied by the camera target, just based on
30// distance/heading components.
James Kuszmauld478f872020-03-16 20:54:27 -070031Eigen::Vector3f CalculateImpliedPose(const Localizer::State &X,
32 const Eigen::Matrix4f &H_field_target,
James Kuszmaul66efe832020-03-16 19:38:33 -070033 const Localizer::Pose &pose_robot_target) {
34 // This code overrides the pose sent directly from the camera code and
35 // effectively distills it down to just a distance + heading estimate, on
36 // the presumption that these signals will tend to be much lower noise and
37 // better-conditioned than other portions of the robot pose.
38 // As such, this code assumes that the current estimate of the robot
39 // heading is correct and then, given the heading from the camera to the
40 // target and the distance from the camera to the target, calculates the
41 // position that the robot would have to be at to make the current camera
42 // heading + distance correct. This X/Y implied robot position is then
43 // used as the measurement in the EKF, rather than the X/Y that is
44 // directly returned from the vision processing. This means that
45 // the cameras will not correct any drift in the robot heading estimate
46 // but will compensate for X/Y position in a way that prioritizes keeping
47 // an accurate distance + heading to the goal.
48
49 // Calculate the heading to the robot in the target's coordinate frame.
James Kuszmauld478f872020-03-16 20:54:27 -070050 const float implied_heading_from_target = aos::math::NormalizeAngle(
James Kuszmaul66efe832020-03-16 19:38:33 -070051 pose_robot_target.heading() + M_PI + X(Localizer::StateIdx::kTheta));
James Kuszmauld478f872020-03-16 20:54:27 -070052 const float implied_distance = pose_robot_target.xy_norm();
53 const Eigen::Vector4f robot_pose_in_target_frame(
James Kuszmaul66efe832020-03-16 19:38:33 -070054 implied_distance * std::cos(implied_heading_from_target),
55 implied_distance * std::sin(implied_heading_from_target), 0, 1);
James Kuszmauld478f872020-03-16 20:54:27 -070056 const Eigen::Vector4f implied_pose =
James Kuszmaul66efe832020-03-16 19:38:33 -070057 H_field_target * robot_pose_in_target_frame;
58 return implied_pose.topRows<3>();
59}
60
James Kuszmaul5398fae2020-02-17 16:44:03 -080061} // namespace
62
63Localizer::Localizer(
64 aos::EventLoop *event_loop,
65 const frc971::control_loops::drivetrain::DrivetrainConfig<double>
66 &dt_config)
James Kuszmaul958b21e2020-02-26 21:51:40 -080067 : event_loop_(event_loop),
68 dt_config_(dt_config),
69 ekf_(dt_config),
70 clock_offset_fetcher_(
71 event_loop_->MakeFetcher<aos::message_bridge::ServerStatistics>(
72 "/aos")) {
James Kuszmaul5398fae2020-02-17 16:44:03 -080073 // TODO(james): This doesn't really need to be a watcher; we could just use a
74 // fetcher for the superstructure status.
75 // This probably should be a Fetcher instead of a Watcher, but this
76 // seems simpler for the time being (although technically it should be
77 // possible to do everything we need to using just a Fetcher without
78 // even maintaining a separate buffer, but that seems overly cute).
79 event_loop_->MakeWatcher("/superstructure",
80 [this](const superstructure::Status &status) {
81 HandleSuperstructureStatus(status);
82 });
83
James Kuszmaul286b4282020-02-26 20:29:32 -080084 event_loop->OnRun([this, event_loop]() {
James Kuszmauld478f872020-03-16 20:54:27 -070085 ekf_.ResetInitialState(event_loop->monotonic_now(),
86 HybridEkf::State::Zero(), ekf_.P());
James Kuszmaul286b4282020-02-26 20:29:32 -080087 });
88
James Kuszmaulc6723cf2020-03-01 14:45:59 -080089 for (const auto &pi : kPisToUse) {
90 image_fetchers_.emplace_back(
91 event_loop_->MakeFetcher<frc971::vision::sift::ImageMatchResult>(
92 "/" + pi + "/camera"));
93 }
James Kuszmaul5398fae2020-02-17 16:44:03 -080094
95 target_selector_.set_has_target(false);
96}
97
James Kuszmaulbcd96fc2020-10-12 20:29:32 -070098void Localizer::Reset(
99 aos::monotonic_clock::time_point t,
100 const frc971::control_loops::drivetrain::HybridEkf<double>::State &state) {
101 // Go through and clear out all of the fetchers so that we don't get behind.
102 for (auto &fetcher : image_fetchers_) {
103 fetcher.Fetch();
104 }
105 ekf_.ResetInitialState(t, state.cast<float>(), ekf_.P());
106}
107
James Kuszmaul5398fae2020-02-17 16:44:03 -0800108void Localizer::HandleSuperstructureStatus(
109 const y2020::control_loops::superstructure::Status &status) {
110 CHECK(status.has_turret());
111 turret_data_.Push({event_loop_->monotonic_now(), status.turret()->position(),
112 status.turret()->velocity()});
113}
114
115Localizer::TurretData Localizer::GetTurretDataForTime(
116 aos::monotonic_clock::time_point time) {
117 if (turret_data_.empty()) {
118 return {};
119 }
120
121 aos::monotonic_clock::duration lowest_time_error =
122 aos::monotonic_clock::duration::max();
123 TurretData best_data_match;
124 for (const auto &sample : turret_data_) {
125 const aos::monotonic_clock::duration time_error =
126 std::chrono::abs(sample.receive_time - time);
127 if (time_error < lowest_time_error) {
128 lowest_time_error = time_error;
129 best_data_match = sample;
130 }
131 }
132 return best_data_match;
133}
134
James Kuszmaul06257f42020-05-09 15:40:09 -0700135void Localizer::Update(const Eigen::Matrix<double, 2, 1> &U,
James Kuszmaul5398fae2020-02-17 16:44:03 -0800136 aos::monotonic_clock::time_point now,
137 double left_encoder, double right_encoder,
138 double gyro_rate, const Eigen::Vector3d &accel) {
James Kuszmauld478f872020-03-16 20:54:27 -0700139 ekf_.UpdateEncodersAndGyro(left_encoder, right_encoder, gyro_rate,
140 U.cast<float>(), accel.cast<float>(), now);
James Kuszmaulc6723cf2020-03-01 14:45:59 -0800141 for (size_t ii = 0; ii < kPisToUse.size(); ++ii) {
142 auto &image_fetcher = image_fetchers_[ii];
James Kuszmaul5398fae2020-02-17 16:44:03 -0800143 while (image_fetcher.FetchNext()) {
James Kuszmaul58cb1fe2020-03-07 16:18:59 -0800144 HandleImageMatch(kPisToUse[ii], *image_fetcher, now);
James Kuszmaul5398fae2020-02-17 16:44:03 -0800145 }
146 }
James Kuszmaul5398fae2020-02-17 16:44:03 -0800147}
148
149void Localizer::HandleImageMatch(
James Kuszmaul58cb1fe2020-03-07 16:18:59 -0800150 std::string_view pi, const frc971::vision::sift::ImageMatchResult &result,
151 aos::monotonic_clock::time_point now) {
James Kuszmaul958b21e2020-02-26 21:51:40 -0800152 std::chrono::nanoseconds monotonic_offset(0);
153 clock_offset_fetcher_.Fetch();
154 if (clock_offset_fetcher_.get() != nullptr) {
155 for (const auto connection : *clock_offset_fetcher_->connections()) {
156 if (connection->has_node() && connection->node()->has_name() &&
James Kuszmaulc6723cf2020-03-01 14:45:59 -0800157 connection->node()->name()->string_view() == pi) {
James Kuszmaul958b21e2020-02-26 21:51:40 -0800158 monotonic_offset =
159 std::chrono::nanoseconds(connection->monotonic_offset());
160 break;
161 }
162 }
163 }
James Kuszmaul5398fae2020-02-17 16:44:03 -0800164 aos::monotonic_clock::time_point capture_time(
James Kuszmaul958b21e2020-02-26 21:51:40 -0800165 std::chrono::nanoseconds(result.image_monotonic_timestamp_ns()) -
166 monotonic_offset);
James Kuszmaul2d8fa2a2020-03-01 13:51:50 -0800167 VLOG(1) << "Got monotonic offset of "
168 << aos::time::DurationInSeconds(monotonic_offset)
James Kuszmaul58cb1fe2020-03-07 16:18:59 -0800169 << " when at time of " << now << " and capture time estimate of "
170 << capture_time;
171 if (capture_time > now) {
James Kuszmaul2d8fa2a2020-03-01 13:51:50 -0800172 LOG(WARNING) << "Got camera frame from the future.";
173 return;
174 }
James Kuszmaulbcd96fc2020-10-12 20:29:32 -0700175 if (!result.has_camera_calibration()) {
176 LOG(WARNING) << "Got camera frame without calibration data.";
177 return;
178 }
James Kuszmaul5398fae2020-02-17 16:44:03 -0800179 // Per the ImageMatchResult specification, we can actually determine whether
180 // the camera is the turret camera just from the presence of the
181 // turret_extrinsics member.
182 const bool is_turret = result.camera_calibration()->has_turret_extrinsics();
183 const TurretData turret_data = GetTurretDataForTime(capture_time);
184 // Ignore readings when the turret is spinning too fast, on the assumption
185 // that the odds of screwing up the time compensation are higher.
186 // Note that the current number here is chosen pretty arbitrarily--1 rad / sec
187 // seems reasonable, but may be unnecessarily low or high.
James Kuszmauld478f872020-03-16 20:54:27 -0700188 constexpr float kMaxTurretVelocity = 1.0;
James Kuszmaul5398fae2020-02-17 16:44:03 -0800189 if (is_turret && std::abs(turret_data.velocity) > kMaxTurretVelocity) {
190 return;
191 }
192 CHECK(result.camera_calibration()->has_fixed_extrinsics());
James Kuszmauld478f872020-03-16 20:54:27 -0700193 const Eigen::Matrix<float, 4, 4> fixed_extrinsics =
James Kuszmaul5398fae2020-02-17 16:44:03 -0800194 FlatbufferToTransformationMatrix(
195 *result.camera_calibration()->fixed_extrinsics());
James Kuszmaul58cb1fe2020-03-07 16:18:59 -0800196
James Kuszmaul5398fae2020-02-17 16:44:03 -0800197 // Calculate the pose of the camera relative to the robot origin.
James Kuszmauld478f872020-03-16 20:54:27 -0700198 Eigen::Matrix<float, 4, 4> H_robot_camera = fixed_extrinsics;
James Kuszmaul5398fae2020-02-17 16:44:03 -0800199 if (is_turret) {
James Kuszmaulc51dbfe2020-02-23 15:39:00 -0800200 H_robot_camera = H_robot_camera *
James Kuszmauld478f872020-03-16 20:54:27 -0700201 frc971::control_loops::TransformationMatrixForYaw<float>(
James Kuszmaul5398fae2020-02-17 16:44:03 -0800202 turret_data.position) *
203 FlatbufferToTransformationMatrix(
204 *result.camera_calibration()->turret_extrinsics());
205 }
206
207 if (!result.has_camera_poses()) {
208 return;
209 }
210
211 for (const frc971::vision::sift::CameraPose *vision_result :
212 *result.camera_poses()) {
213 if (!vision_result->has_camera_to_target() ||
214 !vision_result->has_field_to_target()) {
215 continue;
216 }
James Kuszmauld478f872020-03-16 20:54:27 -0700217 const Eigen::Matrix<float, 4, 4> H_camera_target =
James Kuszmaul5398fae2020-02-17 16:44:03 -0800218 FlatbufferToTransformationMatrix(*vision_result->camera_to_target());
James Kuszmaul58cb1fe2020-03-07 16:18:59 -0800219
James Kuszmauld478f872020-03-16 20:54:27 -0700220 const Eigen::Matrix<float, 4, 4> H_field_target =
James Kuszmaul5398fae2020-02-17 16:44:03 -0800221 FlatbufferToTransformationMatrix(*vision_result->field_to_target());
222 // Back out the robot position that is implied by the current camera
223 // reading.
James Kuszmaulc51dbfe2020-02-23 15:39:00 -0800224 const Pose measured_pose(H_field_target *
225 (H_robot_camera * H_camera_target).inverse());
James Kuszmaul66efe832020-03-16 19:38:33 -0700226 // This "Z" is the robot pose directly implied by the camera results.
227 // Currently, we do not actually use this result directly. However, it is
228 // kept around in case we want to quickly re-enable it.
James Kuszmauld478f872020-03-16 20:54:27 -0700229 const Eigen::Matrix<float, 3, 1> Z(measured_pose.rel_pos().x(),
230 measured_pose.rel_pos().y(),
231 measured_pose.rel_theta());
James Kuszmaul58cb1fe2020-03-07 16:18:59 -0800232 // Pose of the target in the robot frame.
233 Pose pose_robot_target(H_robot_camera * H_camera_target);
James Kuszmaul5398fae2020-02-17 16:44:03 -0800234 // TODO(james): Figure out how to properly handle calculating the
235 // noise. Currently, the values are deliberately tuned so that image updates
236 // will not be trusted overly much. In theory, we should probably also be
237 // populating some cross-correlation terms.
238 // Note that these are the noise standard deviations (they are squared below
239 // to get variances).
James Kuszmauld478f872020-03-16 20:54:27 -0700240 Eigen::Matrix<float, 3, 1> noises(2.0, 2.0, 0.2);
James Kuszmaul5398fae2020-02-17 16:44:03 -0800241 // Augment the noise by the approximate rotational speed of the
242 // camera. This should help account for the fact that, while we are
243 // spinning, slight timing errors in the camera/turret data will tend to
244 // have mutch more drastic effects on the results.
245 noises *= 1.0 + std::abs((right_velocity() - left_velocity()) /
246 (2.0 * dt_config_.robot_radius) +
247 (is_turret ? turret_data.velocity : 0.0));
James Kuszmauld478f872020-03-16 20:54:27 -0700248 Eigen::Matrix3f R = Eigen::Matrix3f::Zero();
James Kuszmaul5398fae2020-02-17 16:44:03 -0800249 R.diagonal() = noises.cwiseAbs2();
James Kuszmauld478f872020-03-16 20:54:27 -0700250 Eigen::Matrix<float, HybridEkf::kNOutputs, HybridEkf::kNStates> H;
James Kuszmaul5398fae2020-02-17 16:44:03 -0800251 H.setZero();
252 H(0, StateIdx::kX) = 1;
253 H(1, StateIdx::kY) = 1;
James Kuszmaul58cb1fe2020-03-07 16:18:59 -0800254 // This is currently set to zero because we ignore the heading implied by
255 // the camera.
256 H(2, StateIdx::kTheta) = 0;
257 VLOG(1) << "Pose implied by target: " << Z.transpose()
258 << " and current pose " << x() << ", " << y() << ", " << theta()
259 << " Heading/dist/skew implied by target: "
260 << pose_robot_target.ToHeadingDistanceSkew().transpose();
James Kuszmauladd40ca2020-03-01 14:10:50 -0800261 // If the heading is off by too much, assume that we got a false-positive
262 // and don't use the correction.
James Kuszmauld478f872020-03-16 20:54:27 -0700263 if (std::abs(aos::math::DiffAngle<float>(theta(), Z(2))) > M_PI_2) {
James Kuszmauladd40ca2020-03-01 14:10:50 -0800264 AOS_LOG(WARNING, "Dropped image match due to heading mismatch.\n");
James Kuszmaul58cb1fe2020-03-07 16:18:59 -0800265 continue;
James Kuszmauladd40ca2020-03-01 14:10:50 -0800266 }
James Kuszmaul06257f42020-05-09 15:40:09 -0700267 // In order to do the EKF correction, we determine the expected state based
268 // on the state at the time the image was captured; however, we insert the
269 // correction update itself at the current time. This is technically not
270 // quite correct, but saves substantial CPU usage by making it so that we
271 // don't have to constantly rewind the entire EKF history.
272 const std::optional<State> state_at_capture =
273 ekf_.LastStateBeforeTime(capture_time);
274 if (!state_at_capture.has_value()) {
275 AOS_LOG(WARNING, "Dropped image match due to age of image.\n");
276 continue;
277 }
278 const Input U = ekf_.MostRecentInput();
James Kuszmaul66efe832020-03-16 19:38:33 -0700279 // For the correction step, instead of passing in the measurement directly,
280 // we pass in (0, 0, 0) as the measurement and then for the expected
281 // measurement (Zhat) we calculate the error between the implied and actual
282 // poses. This doesn't affect any of the math, it just makes the code a bit
283 // more convenient to write given the Correct() interface we already have.
James Kuszmaul58cb1fe2020-03-07 16:18:59 -0800284 ekf_.Correct(
James Kuszmaul06257f42020-05-09 15:40:09 -0700285 Eigen::Vector3f::Zero(), &U, {},
286 [H, H_field_target, pose_robot_target, state_at_capture](
287 const State &, const Input &) -> Eigen::Vector3f {
288 const Eigen::Vector3f Z = CalculateImpliedPose(
289 state_at_capture.value(), H_field_target, pose_robot_target);
James Kuszmaul66efe832020-03-16 19:38:33 -0700290 // Just in case we ever do encounter any, drop measurements if they
291 // have non-finite numbers.
292 if (!Z.allFinite()) {
293 AOS_LOG(WARNING, "Got measurement with infinites or NaNs.\n");
James Kuszmauld478f872020-03-16 20:54:27 -0700294 return Eigen::Vector3f::Zero();
James Kuszmaul66efe832020-03-16 19:38:33 -0700295 }
James Kuszmaul06257f42020-05-09 15:40:09 -0700296 Eigen::Vector3f Zhat = H * state_at_capture.value() - Z;
James Kuszmaul66efe832020-03-16 19:38:33 -0700297 // Rewrap angle difference to put it back in range. Note that this
298 // component of the error is currently ignored (see definition of H
299 // above).
300 Zhat(2) = aos::math::NormalizeAngle(Zhat(2));
James Kuszmaul58cb1fe2020-03-07 16:18:59 -0800301 // If the measurement implies that we are too far from the current
302 // estimate, then ignore it.
303 // Note that I am not entirely sure how much effect this actually has,
304 // because I primarily introduced it to make sure that any grossly
305 // invalid measurements get thrown out.
James Kuszmaul66efe832020-03-16 19:38:33 -0700306 if (Zhat.squaredNorm() > std::pow(10.0, 2)) {
James Kuszmauld478f872020-03-16 20:54:27 -0700307 return Eigen::Vector3f::Zero();
James Kuszmaul58cb1fe2020-03-07 16:18:59 -0800308 }
309 return Zhat;
310 },
James Kuszmaul06257f42020-05-09 15:40:09 -0700311 [H](const State &) { return H; }, R, now);
James Kuszmaul5398fae2020-02-17 16:44:03 -0800312 }
313}
314
315} // namespace drivetrain
316} // namespace control_loops
317} // namespace y2020