James Kuszmaul | 5398fae | 2020-02-17 16:44:03 -0800 | [diff] [blame] | 1 | #include "y2020/control_loops/drivetrain/localizer.h" |
| 2 | |
| 3 | #include "y2020/constants.h" |
| 4 | |
| 5 | namespace y2020 { |
| 6 | namespace control_loops { |
| 7 | namespace drivetrain { |
| 8 | |
| 9 | namespace { |
| 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. |
| 13 | Eigen::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 | } |
James Kuszmaul | 958b21e | 2020-02-26 21:51:40 -0800 | [diff] [blame] | 25 | |
James Kuszmaul | c6723cf | 2020-03-01 14:45:59 -0800 | [diff] [blame] | 26 | // Indices of the pis to use. |
| 27 | const std::array<std::string, 3> kPisToUse{"pi1", "pi2", "pi3"}; |
| 28 | |
James Kuszmaul | 5398fae | 2020-02-17 16:44:03 -0800 | [diff] [blame] | 29 | } // namespace |
| 30 | |
| 31 | Localizer::Localizer( |
| 32 | aos::EventLoop *event_loop, |
| 33 | const frc971::control_loops::drivetrain::DrivetrainConfig<double> |
| 34 | &dt_config) |
James Kuszmaul | 958b21e | 2020-02-26 21:51:40 -0800 | [diff] [blame] | 35 | : event_loop_(event_loop), |
| 36 | dt_config_(dt_config), |
| 37 | ekf_(dt_config), |
| 38 | clock_offset_fetcher_( |
| 39 | event_loop_->MakeFetcher<aos::message_bridge::ServerStatistics>( |
| 40 | "/aos")) { |
James Kuszmaul | 5398fae | 2020-02-17 16:44:03 -0800 | [diff] [blame] | 41 | // TODO(james): This doesn't really need to be a watcher; we could just use a |
| 42 | // fetcher for the superstructure status. |
| 43 | // This probably should be a Fetcher instead of a Watcher, but this |
| 44 | // seems simpler for the time being (although technically it should be |
| 45 | // possible to do everything we need to using just a Fetcher without |
| 46 | // even maintaining a separate buffer, but that seems overly cute). |
| 47 | event_loop_->MakeWatcher("/superstructure", |
| 48 | [this](const superstructure::Status &status) { |
| 49 | HandleSuperstructureStatus(status); |
| 50 | }); |
| 51 | |
James Kuszmaul | 286b428 | 2020-02-26 20:29:32 -0800 | [diff] [blame] | 52 | event_loop->OnRun([this, event_loop]() { |
| 53 | ekf_.ResetInitialState(event_loop->monotonic_now(), Ekf::State::Zero(), |
| 54 | ekf_.P()); |
| 55 | }); |
| 56 | |
James Kuszmaul | c6723cf | 2020-03-01 14:45:59 -0800 | [diff] [blame] | 57 | for (const auto &pi : kPisToUse) { |
| 58 | image_fetchers_.emplace_back( |
| 59 | event_loop_->MakeFetcher<frc971::vision::sift::ImageMatchResult>( |
| 60 | "/" + pi + "/camera")); |
| 61 | } |
James Kuszmaul | 5398fae | 2020-02-17 16:44:03 -0800 | [diff] [blame] | 62 | |
| 63 | target_selector_.set_has_target(false); |
| 64 | } |
| 65 | |
| 66 | void Localizer::HandleSuperstructureStatus( |
| 67 | const y2020::control_loops::superstructure::Status &status) { |
| 68 | CHECK(status.has_turret()); |
| 69 | turret_data_.Push({event_loop_->monotonic_now(), status.turret()->position(), |
| 70 | status.turret()->velocity()}); |
| 71 | } |
| 72 | |
| 73 | Localizer::TurretData Localizer::GetTurretDataForTime( |
| 74 | aos::monotonic_clock::time_point time) { |
| 75 | if (turret_data_.empty()) { |
| 76 | return {}; |
| 77 | } |
| 78 | |
| 79 | aos::monotonic_clock::duration lowest_time_error = |
| 80 | aos::monotonic_clock::duration::max(); |
| 81 | TurretData best_data_match; |
| 82 | for (const auto &sample : turret_data_) { |
| 83 | const aos::monotonic_clock::duration time_error = |
| 84 | std::chrono::abs(sample.receive_time - time); |
| 85 | if (time_error < lowest_time_error) { |
| 86 | lowest_time_error = time_error; |
| 87 | best_data_match = sample; |
| 88 | } |
| 89 | } |
| 90 | return best_data_match; |
| 91 | } |
| 92 | |
| 93 | void Localizer::Update(const ::Eigen::Matrix<double, 2, 1> &U, |
| 94 | aos::monotonic_clock::time_point now, |
| 95 | double left_encoder, double right_encoder, |
| 96 | double gyro_rate, const Eigen::Vector3d &accel) { |
James Kuszmaul | 58cb1fe | 2020-03-07 16:18:59 -0800 | [diff] [blame^] | 97 | ekf_.UpdateEncodersAndGyro(left_encoder, right_encoder, gyro_rate, U, accel, |
| 98 | now); |
James Kuszmaul | c6723cf | 2020-03-01 14:45:59 -0800 | [diff] [blame] | 99 | for (size_t ii = 0; ii < kPisToUse.size(); ++ii) { |
| 100 | auto &image_fetcher = image_fetchers_[ii]; |
James Kuszmaul | 5398fae | 2020-02-17 16:44:03 -0800 | [diff] [blame] | 101 | while (image_fetcher.FetchNext()) { |
James Kuszmaul | 58cb1fe | 2020-03-07 16:18:59 -0800 | [diff] [blame^] | 102 | HandleImageMatch(kPisToUse[ii], *image_fetcher, now); |
James Kuszmaul | 5398fae | 2020-02-17 16:44:03 -0800 | [diff] [blame] | 103 | } |
| 104 | } |
James Kuszmaul | 5398fae | 2020-02-17 16:44:03 -0800 | [diff] [blame] | 105 | } |
| 106 | |
| 107 | void Localizer::HandleImageMatch( |
James Kuszmaul | 58cb1fe | 2020-03-07 16:18:59 -0800 | [diff] [blame^] | 108 | std::string_view pi, const frc971::vision::sift::ImageMatchResult &result, |
| 109 | aos::monotonic_clock::time_point now) { |
James Kuszmaul | 958b21e | 2020-02-26 21:51:40 -0800 | [diff] [blame] | 110 | std::chrono::nanoseconds monotonic_offset(0); |
| 111 | clock_offset_fetcher_.Fetch(); |
| 112 | if (clock_offset_fetcher_.get() != nullptr) { |
| 113 | for (const auto connection : *clock_offset_fetcher_->connections()) { |
| 114 | if (connection->has_node() && connection->node()->has_name() && |
James Kuszmaul | c6723cf | 2020-03-01 14:45:59 -0800 | [diff] [blame] | 115 | connection->node()->name()->string_view() == pi) { |
James Kuszmaul | 958b21e | 2020-02-26 21:51:40 -0800 | [diff] [blame] | 116 | monotonic_offset = |
| 117 | std::chrono::nanoseconds(connection->monotonic_offset()); |
| 118 | break; |
| 119 | } |
| 120 | } |
| 121 | } |
James Kuszmaul | 5398fae | 2020-02-17 16:44:03 -0800 | [diff] [blame] | 122 | aos::monotonic_clock::time_point capture_time( |
James Kuszmaul | 958b21e | 2020-02-26 21:51:40 -0800 | [diff] [blame] | 123 | std::chrono::nanoseconds(result.image_monotonic_timestamp_ns()) - |
| 124 | monotonic_offset); |
James Kuszmaul | 2d8fa2a | 2020-03-01 13:51:50 -0800 | [diff] [blame] | 125 | VLOG(1) << "Got monotonic offset of " |
| 126 | << aos::time::DurationInSeconds(monotonic_offset) |
James Kuszmaul | 58cb1fe | 2020-03-07 16:18:59 -0800 | [diff] [blame^] | 127 | << " when at time of " << now << " and capture time estimate of " |
| 128 | << capture_time; |
| 129 | if (capture_time > now) { |
James Kuszmaul | 2d8fa2a | 2020-03-01 13:51:50 -0800 | [diff] [blame] | 130 | LOG(WARNING) << "Got camera frame from the future."; |
| 131 | return; |
| 132 | } |
James Kuszmaul | 5398fae | 2020-02-17 16:44:03 -0800 | [diff] [blame] | 133 | CHECK(result.has_camera_calibration()); |
| 134 | // Per the ImageMatchResult specification, we can actually determine whether |
| 135 | // the camera is the turret camera just from the presence of the |
| 136 | // turret_extrinsics member. |
| 137 | const bool is_turret = result.camera_calibration()->has_turret_extrinsics(); |
| 138 | const TurretData turret_data = GetTurretDataForTime(capture_time); |
| 139 | // Ignore readings when the turret is spinning too fast, on the assumption |
| 140 | // that the odds of screwing up the time compensation are higher. |
| 141 | // Note that the current number here is chosen pretty arbitrarily--1 rad / sec |
| 142 | // seems reasonable, but may be unnecessarily low or high. |
| 143 | constexpr double kMaxTurretVelocity = 1.0; |
| 144 | if (is_turret && std::abs(turret_data.velocity) > kMaxTurretVelocity) { |
| 145 | return; |
| 146 | } |
| 147 | CHECK(result.camera_calibration()->has_fixed_extrinsics()); |
| 148 | const Eigen::Matrix<double, 4, 4> fixed_extrinsics = |
| 149 | FlatbufferToTransformationMatrix( |
| 150 | *result.camera_calibration()->fixed_extrinsics()); |
James Kuszmaul | 58cb1fe | 2020-03-07 16:18:59 -0800 | [diff] [blame^] | 151 | |
James Kuszmaul | 5398fae | 2020-02-17 16:44:03 -0800 | [diff] [blame] | 152 | // Calculate the pose of the camera relative to the robot origin. |
James Kuszmaul | c51dbfe | 2020-02-23 15:39:00 -0800 | [diff] [blame] | 153 | Eigen::Matrix<double, 4, 4> H_robot_camera = fixed_extrinsics; |
James Kuszmaul | 5398fae | 2020-02-17 16:44:03 -0800 | [diff] [blame] | 154 | if (is_turret) { |
James Kuszmaul | c51dbfe | 2020-02-23 15:39:00 -0800 | [diff] [blame] | 155 | H_robot_camera = H_robot_camera * |
James Kuszmaul | 5398fae | 2020-02-17 16:44:03 -0800 | [diff] [blame] | 156 | frc971::control_loops::TransformationMatrixForYaw( |
| 157 | turret_data.position) * |
| 158 | FlatbufferToTransformationMatrix( |
| 159 | *result.camera_calibration()->turret_extrinsics()); |
| 160 | } |
| 161 | |
| 162 | if (!result.has_camera_poses()) { |
| 163 | return; |
| 164 | } |
| 165 | |
| 166 | for (const frc971::vision::sift::CameraPose *vision_result : |
| 167 | *result.camera_poses()) { |
| 168 | if (!vision_result->has_camera_to_target() || |
| 169 | !vision_result->has_field_to_target()) { |
| 170 | continue; |
| 171 | } |
James Kuszmaul | c51dbfe | 2020-02-23 15:39:00 -0800 | [diff] [blame] | 172 | const Eigen::Matrix<double, 4, 4> H_camera_target = |
James Kuszmaul | 5398fae | 2020-02-17 16:44:03 -0800 | [diff] [blame] | 173 | FlatbufferToTransformationMatrix(*vision_result->camera_to_target()); |
James Kuszmaul | 58cb1fe | 2020-03-07 16:18:59 -0800 | [diff] [blame^] | 174 | |
James Kuszmaul | c51dbfe | 2020-02-23 15:39:00 -0800 | [diff] [blame] | 175 | const Eigen::Matrix<double, 4, 4> H_field_target = |
James Kuszmaul | 5398fae | 2020-02-17 16:44:03 -0800 | [diff] [blame] | 176 | FlatbufferToTransformationMatrix(*vision_result->field_to_target()); |
| 177 | // Back out the robot position that is implied by the current camera |
| 178 | // reading. |
James Kuszmaul | c51dbfe | 2020-02-23 15:39:00 -0800 | [diff] [blame] | 179 | const Pose measured_pose(H_field_target * |
| 180 | (H_robot_camera * H_camera_target).inverse()); |
James Kuszmaul | 58cb1fe | 2020-03-07 16:18:59 -0800 | [diff] [blame^] | 181 | Eigen::Matrix<double, 3, 1> Z(measured_pose.rel_pos().x(), |
| 182 | measured_pose.rel_pos().y(), |
| 183 | measured_pose.rel_theta()); |
| 184 | // Pose of the target in the robot frame. |
| 185 | Pose pose_robot_target(H_robot_camera * H_camera_target); |
| 186 | // This code overrides the pose sent directly from the camera code and |
| 187 | // effectively distills it down to just a distance + heading estimate, on |
| 188 | // the presumption that these signals will tend to be much lower noise and |
| 189 | // better-conditioned than other portions of the robot pose. |
| 190 | // As such, this code assumes that the current estimate of the robot |
| 191 | // heading is correct and then, given the heading from the camera to the |
| 192 | // target and the distance from the camera to the target, calculates the |
| 193 | // position that the robot would have to be at to make the current camera |
| 194 | // heading + distance correct. This X/Y implied robot position is then |
| 195 | // used as the measurement in the EKF, rather than the X/Y that is |
| 196 | // directly returned from the vision processing. This means that |
| 197 | // the cameras will not correct any drift in the robot heading estimate |
| 198 | // but will compensate for X/Y position in a way that prioritizes keeping |
| 199 | // an accurate distance + heading to the goal. |
| 200 | { |
| 201 | // TODO(james): This doesn't do time-compensation properly--it uses the |
| 202 | // current robot heading to calculate an implied pose, rather than using |
| 203 | // the heading from when the picture was taken. |
| 204 | |
| 205 | // Calculate the heading to the robot in the target's coordinate frame. |
| 206 | const double implied_heading_from_target = aos::math::NormalizeAngle( |
| 207 | pose_robot_target.heading() + M_PI + theta()); |
| 208 | const double implied_distance = pose_robot_target.xy_norm(); |
| 209 | const Eigen::Vector4d robot_pose_in_target_frame( |
| 210 | implied_distance * std::cos(implied_heading_from_target), |
| 211 | implied_distance * std::sin(implied_heading_from_target), 0, 1); |
| 212 | const Eigen::Vector4d implied_pose = |
| 213 | H_field_target * robot_pose_in_target_frame; |
| 214 | Z.x() = implied_pose.x(); |
| 215 | Z.y() = implied_pose.y(); |
| 216 | } |
James Kuszmaul | 5398fae | 2020-02-17 16:44:03 -0800 | [diff] [blame] | 217 | // TODO(james): Figure out how to properly handle calculating the |
| 218 | // noise. Currently, the values are deliberately tuned so that image updates |
| 219 | // will not be trusted overly much. In theory, we should probably also be |
| 220 | // populating some cross-correlation terms. |
| 221 | // Note that these are the noise standard deviations (they are squared below |
| 222 | // to get variances). |
James Kuszmaul | 58cb1fe | 2020-03-07 16:18:59 -0800 | [diff] [blame^] | 223 | Eigen::Matrix<double, 3, 1> noises(2.0, 2.0, 0.2); |
James Kuszmaul | 5398fae | 2020-02-17 16:44:03 -0800 | [diff] [blame] | 224 | // Augment the noise by the approximate rotational speed of the |
| 225 | // camera. This should help account for the fact that, while we are |
| 226 | // spinning, slight timing errors in the camera/turret data will tend to |
| 227 | // have mutch more drastic effects on the results. |
| 228 | noises *= 1.0 + std::abs((right_velocity() - left_velocity()) / |
| 229 | (2.0 * dt_config_.robot_radius) + |
| 230 | (is_turret ? turret_data.velocity : 0.0)); |
| 231 | Eigen::Matrix3d R = Eigen::Matrix3d::Zero(); |
| 232 | R.diagonal() = noises.cwiseAbs2(); |
| 233 | Eigen::Matrix<double, HybridEkf::kNOutputs, HybridEkf::kNStates> H; |
| 234 | H.setZero(); |
| 235 | H(0, StateIdx::kX) = 1; |
| 236 | H(1, StateIdx::kY) = 1; |
James Kuszmaul | 58cb1fe | 2020-03-07 16:18:59 -0800 | [diff] [blame^] | 237 | // This is currently set to zero because we ignore the heading implied by |
| 238 | // the camera. |
| 239 | H(2, StateIdx::kTheta) = 0; |
| 240 | VLOG(1) << "Pose implied by target: " << Z.transpose() |
| 241 | << " and current pose " << x() << ", " << y() << ", " << theta() |
| 242 | << " Heading/dist/skew implied by target: " |
| 243 | << pose_robot_target.ToHeadingDistanceSkew().transpose(); |
James Kuszmaul | add40ca | 2020-03-01 14:10:50 -0800 | [diff] [blame] | 244 | // If the heading is off by too much, assume that we got a false-positive |
| 245 | // and don't use the correction. |
| 246 | if (std::abs(aos::math::DiffAngle(theta(), Z(2))) > M_PI_2) { |
| 247 | AOS_LOG(WARNING, "Dropped image match due to heading mismatch.\n"); |
James Kuszmaul | 58cb1fe | 2020-03-07 16:18:59 -0800 | [diff] [blame^] | 248 | continue; |
James Kuszmaul | add40ca | 2020-03-01 14:10:50 -0800 | [diff] [blame] | 249 | } |
James Kuszmaul | 58cb1fe | 2020-03-07 16:18:59 -0800 | [diff] [blame^] | 250 | // Just in case we ever do encounter any, drop measurements if they have |
| 251 | // non-finite numbers. |
| 252 | if (!Z.allFinite()) { |
| 253 | AOS_LOG(WARNING, "Got measurement with infinites or NaNs.\n"); |
| 254 | continue; |
| 255 | } |
| 256 | ekf_.Correct( |
| 257 | Z, nullptr, {}, |
| 258 | [H, Z](const State &X, const Input &) { |
| 259 | Eigen::Vector3d Zhat = H * X; |
| 260 | // In order to deal with wrapping of the angle, calculate an expected |
| 261 | // angle that is in the range (Z(2) - pi, Z(2) + pi]. |
| 262 | const double angle_error = |
| 263 | aos::math::NormalizeAngle(X(StateIdx::kTheta) - Z(2)); |
| 264 | Zhat(2) = Z(2) + angle_error; |
| 265 | // If the measurement implies that we are too far from the current |
| 266 | // estimate, then ignore it. |
| 267 | // Note that I am not entirely sure how much effect this actually has, |
| 268 | // because I primarily introduced it to make sure that any grossly |
| 269 | // invalid measurements get thrown out. |
| 270 | if ((Zhat - Z).squaredNorm() > std::pow(10.0, 2)) { |
| 271 | return Z; |
| 272 | } |
| 273 | return Zhat; |
| 274 | }, |
| 275 | [H](const State &) { return H; }, R, capture_time); |
James Kuszmaul | 5398fae | 2020-02-17 16:44:03 -0800 | [diff] [blame] | 276 | } |
| 277 | } |
| 278 | |
| 279 | } // namespace drivetrain |
| 280 | } // namespace control_loops |
| 281 | } // namespace y2020 |