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 | c6723cf | 2020-03-01 14:45:59 -0800 | [diff] [blame] | 97 | for (size_t ii = 0; ii < kPisToUse.size(); ++ii) { |
| 98 | auto &image_fetcher = image_fetchers_[ii]; |
James Kuszmaul | 5398fae | 2020-02-17 16:44:03 -0800 | [diff] [blame] | 99 | while (image_fetcher.FetchNext()) { |
James Kuszmaul | c6723cf | 2020-03-01 14:45:59 -0800 | [diff] [blame] | 100 | HandleImageMatch(kPisToUse[ii], *image_fetcher); |
James Kuszmaul | 5398fae | 2020-02-17 16:44:03 -0800 | [diff] [blame] | 101 | } |
| 102 | } |
| 103 | ekf_.UpdateEncodersAndGyro(left_encoder, right_encoder, gyro_rate, U, accel, |
| 104 | now); |
| 105 | } |
| 106 | |
| 107 | void Localizer::HandleImageMatch( |
James Kuszmaul | c6723cf | 2020-03-01 14:45:59 -0800 | [diff] [blame] | 108 | std::string_view pi, const frc971::vision::sift::ImageMatchResult &result) { |
James Kuszmaul | 958b21e | 2020-02-26 21:51:40 -0800 | [diff] [blame] | 109 | std::chrono::nanoseconds monotonic_offset(0); |
| 110 | clock_offset_fetcher_.Fetch(); |
| 111 | if (clock_offset_fetcher_.get() != nullptr) { |
| 112 | for (const auto connection : *clock_offset_fetcher_->connections()) { |
| 113 | if (connection->has_node() && connection->node()->has_name() && |
James Kuszmaul | c6723cf | 2020-03-01 14:45:59 -0800 | [diff] [blame] | 114 | connection->node()->name()->string_view() == pi) { |
James Kuszmaul | 958b21e | 2020-02-26 21:51:40 -0800 | [diff] [blame] | 115 | monotonic_offset = |
| 116 | std::chrono::nanoseconds(connection->monotonic_offset()); |
| 117 | break; |
| 118 | } |
| 119 | } |
| 120 | } |
James Kuszmaul | 5398fae | 2020-02-17 16:44:03 -0800 | [diff] [blame] | 121 | aos::monotonic_clock::time_point capture_time( |
James Kuszmaul | 958b21e | 2020-02-26 21:51:40 -0800 | [diff] [blame] | 122 | std::chrono::nanoseconds(result.image_monotonic_timestamp_ns()) - |
| 123 | monotonic_offset); |
James Kuszmaul | 2d8fa2a | 2020-03-01 13:51:50 -0800 | [diff] [blame] | 124 | VLOG(1) << "Got monotonic offset of " |
| 125 | << aos::time::DurationInSeconds(monotonic_offset) |
| 126 | << " when at time of " << event_loop_->monotonic_now() |
| 127 | << " and capture time estimate of " << capture_time; |
| 128 | if (capture_time > event_loop_->monotonic_now()) { |
| 129 | LOG(WARNING) << "Got camera frame from the future."; |
| 130 | return; |
| 131 | } |
James Kuszmaul | 5398fae | 2020-02-17 16:44:03 -0800 | [diff] [blame] | 132 | CHECK(result.has_camera_calibration()); |
| 133 | // Per the ImageMatchResult specification, we can actually determine whether |
| 134 | // the camera is the turret camera just from the presence of the |
| 135 | // turret_extrinsics member. |
| 136 | const bool is_turret = result.camera_calibration()->has_turret_extrinsics(); |
| 137 | const TurretData turret_data = GetTurretDataForTime(capture_time); |
| 138 | // Ignore readings when the turret is spinning too fast, on the assumption |
| 139 | // that the odds of screwing up the time compensation are higher. |
| 140 | // Note that the current number here is chosen pretty arbitrarily--1 rad / sec |
| 141 | // seems reasonable, but may be unnecessarily low or high. |
| 142 | constexpr double kMaxTurretVelocity = 1.0; |
| 143 | if (is_turret && std::abs(turret_data.velocity) > kMaxTurretVelocity) { |
| 144 | return; |
| 145 | } |
| 146 | CHECK(result.camera_calibration()->has_fixed_extrinsics()); |
| 147 | const Eigen::Matrix<double, 4, 4> fixed_extrinsics = |
| 148 | FlatbufferToTransformationMatrix( |
| 149 | *result.camera_calibration()->fixed_extrinsics()); |
| 150 | // Calculate the pose of the camera relative to the robot origin. |
James Kuszmaul | c51dbfe | 2020-02-23 15:39:00 -0800 | [diff] [blame] | 151 | Eigen::Matrix<double, 4, 4> H_robot_camera = fixed_extrinsics; |
James Kuszmaul | 5398fae | 2020-02-17 16:44:03 -0800 | [diff] [blame] | 152 | if (is_turret) { |
James Kuszmaul | c51dbfe | 2020-02-23 15:39:00 -0800 | [diff] [blame] | 153 | H_robot_camera = H_robot_camera * |
James Kuszmaul | 5398fae | 2020-02-17 16:44:03 -0800 | [diff] [blame] | 154 | frc971::control_loops::TransformationMatrixForYaw( |
| 155 | turret_data.position) * |
| 156 | FlatbufferToTransformationMatrix( |
| 157 | *result.camera_calibration()->turret_extrinsics()); |
| 158 | } |
| 159 | |
| 160 | if (!result.has_camera_poses()) { |
| 161 | return; |
| 162 | } |
| 163 | |
| 164 | for (const frc971::vision::sift::CameraPose *vision_result : |
| 165 | *result.camera_poses()) { |
| 166 | if (!vision_result->has_camera_to_target() || |
| 167 | !vision_result->has_field_to_target()) { |
| 168 | continue; |
| 169 | } |
James Kuszmaul | c51dbfe | 2020-02-23 15:39:00 -0800 | [diff] [blame] | 170 | const Eigen::Matrix<double, 4, 4> H_camera_target = |
James Kuszmaul | 5398fae | 2020-02-17 16:44:03 -0800 | [diff] [blame] | 171 | FlatbufferToTransformationMatrix(*vision_result->camera_to_target()); |
James Kuszmaul | c51dbfe | 2020-02-23 15:39:00 -0800 | [diff] [blame] | 172 | const Eigen::Matrix<double, 4, 4> H_field_target = |
James Kuszmaul | 5398fae | 2020-02-17 16:44:03 -0800 | [diff] [blame] | 173 | FlatbufferToTransformationMatrix(*vision_result->field_to_target()); |
| 174 | // Back out the robot position that is implied by the current camera |
| 175 | // reading. |
James Kuszmaul | c51dbfe | 2020-02-23 15:39:00 -0800 | [diff] [blame] | 176 | const Pose measured_pose(H_field_target * |
| 177 | (H_robot_camera * H_camera_target).inverse()); |
James Kuszmaul | 5398fae | 2020-02-17 16:44:03 -0800 | [diff] [blame] | 178 | const Eigen::Matrix<double, 3, 1> Z(measured_pose.rel_pos().x(), |
| 179 | measured_pose.rel_pos().y(), |
| 180 | measured_pose.rel_theta()); |
| 181 | // TODO(james): Figure out how to properly handle calculating the |
| 182 | // noise. Currently, the values are deliberately tuned so that image updates |
| 183 | // will not be trusted overly much. In theory, we should probably also be |
| 184 | // populating some cross-correlation terms. |
| 185 | // Note that these are the noise standard deviations (they are squared below |
| 186 | // to get variances). |
| 187 | Eigen::Matrix<double, 3, 1> noises(1.0, 1.0, 0.1); |
| 188 | // Augment the noise by the approximate rotational speed of the |
| 189 | // camera. This should help account for the fact that, while we are |
| 190 | // spinning, slight timing errors in the camera/turret data will tend to |
| 191 | // have mutch more drastic effects on the results. |
| 192 | noises *= 1.0 + std::abs((right_velocity() - left_velocity()) / |
| 193 | (2.0 * dt_config_.robot_radius) + |
| 194 | (is_turret ? turret_data.velocity : 0.0)); |
| 195 | Eigen::Matrix3d R = Eigen::Matrix3d::Zero(); |
| 196 | R.diagonal() = noises.cwiseAbs2(); |
| 197 | Eigen::Matrix<double, HybridEkf::kNOutputs, HybridEkf::kNStates> H; |
| 198 | H.setZero(); |
| 199 | H(0, StateIdx::kX) = 1; |
| 200 | H(1, StateIdx::kY) = 1; |
| 201 | H(2, StateIdx::kTheta) = 1; |
| 202 | ekf_.Correct(Z, nullptr, {}, [H, Z](const State &X, const Input &) { |
| 203 | Eigen::Vector3d Zhat = H * X; |
| 204 | // In order to deal with wrapping of the |
| 205 | // angle, calculate an expected angle that is |
| 206 | // in the range (Z(2) - pi, Z(2) + pi]. |
| 207 | const double angle_error = |
| 208 | aos::math::NormalizeAngle( |
| 209 | X(StateIdx::kTheta) - Z(2)); |
| 210 | Zhat(2) = Z(2) + angle_error; |
| 211 | return Zhat; |
| 212 | }, |
| 213 | [H](const State &) { return H; }, R, capture_time); |
| 214 | } |
| 215 | } |
| 216 | |
| 217 | } // namespace drivetrain |
| 218 | } // namespace control_loops |
| 219 | } // namespace y2020 |