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 | 5398fae | 2020-02-17 16:44:03 -0800 | [diff] [blame] | 26 | } // namespace |
| 27 | |
| 28 | Localizer::Localizer( |
| 29 | aos::EventLoop *event_loop, |
| 30 | const frc971::control_loops::drivetrain::DrivetrainConfig<double> |
| 31 | &dt_config) |
James Kuszmaul | 958b21e | 2020-02-26 21:51:40 -0800 | [diff] [blame] | 32 | : event_loop_(event_loop), |
| 33 | dt_config_(dt_config), |
| 34 | ekf_(dt_config), |
| 35 | clock_offset_fetcher_( |
| 36 | event_loop_->MakeFetcher<aos::message_bridge::ServerStatistics>( |
| 37 | "/aos")) { |
James Kuszmaul | 5398fae | 2020-02-17 16:44:03 -0800 | [diff] [blame] | 38 | // TODO(james): This doesn't really need to be a watcher; we could just use a |
| 39 | // fetcher for the superstructure status. |
| 40 | // This probably should be a Fetcher instead of a Watcher, but this |
| 41 | // seems simpler for the time being (although technically it should be |
| 42 | // possible to do everything we need to using just a Fetcher without |
| 43 | // even maintaining a separate buffer, but that seems overly cute). |
| 44 | event_loop_->MakeWatcher("/superstructure", |
| 45 | [this](const superstructure::Status &status) { |
| 46 | HandleSuperstructureStatus(status); |
| 47 | }); |
| 48 | |
James Kuszmaul | 286b428 | 2020-02-26 20:29:32 -0800 | [diff] [blame] | 49 | event_loop->OnRun([this, event_loop]() { |
| 50 | ekf_.ResetInitialState(event_loop->monotonic_now(), Ekf::State::Zero(), |
| 51 | ekf_.P()); |
| 52 | }); |
| 53 | |
James Kuszmaul | 5398fae | 2020-02-17 16:44:03 -0800 | [diff] [blame] | 54 | image_fetchers_.emplace_back( |
| 55 | event_loop_->MakeFetcher<frc971::vision::sift::ImageMatchResult>( |
Austin Schuh | 6aa77be | 2020-02-22 21:06:40 -0800 | [diff] [blame] | 56 | "/pi1/camera")); |
James Kuszmaul | 5398fae | 2020-02-17 16:44:03 -0800 | [diff] [blame] | 57 | |
| 58 | target_selector_.set_has_target(false); |
| 59 | } |
| 60 | |
| 61 | void Localizer::HandleSuperstructureStatus( |
| 62 | const y2020::control_loops::superstructure::Status &status) { |
| 63 | CHECK(status.has_turret()); |
| 64 | turret_data_.Push({event_loop_->monotonic_now(), status.turret()->position(), |
| 65 | status.turret()->velocity()}); |
| 66 | } |
| 67 | |
| 68 | Localizer::TurretData Localizer::GetTurretDataForTime( |
| 69 | aos::monotonic_clock::time_point time) { |
| 70 | if (turret_data_.empty()) { |
| 71 | return {}; |
| 72 | } |
| 73 | |
| 74 | aos::monotonic_clock::duration lowest_time_error = |
| 75 | aos::monotonic_clock::duration::max(); |
| 76 | TurretData best_data_match; |
| 77 | for (const auto &sample : turret_data_) { |
| 78 | const aos::monotonic_clock::duration time_error = |
| 79 | std::chrono::abs(sample.receive_time - time); |
| 80 | if (time_error < lowest_time_error) { |
| 81 | lowest_time_error = time_error; |
| 82 | best_data_match = sample; |
| 83 | } |
| 84 | } |
| 85 | return best_data_match; |
| 86 | } |
| 87 | |
| 88 | void Localizer::Update(const ::Eigen::Matrix<double, 2, 1> &U, |
| 89 | aos::monotonic_clock::time_point now, |
| 90 | double left_encoder, double right_encoder, |
| 91 | double gyro_rate, const Eigen::Vector3d &accel) { |
| 92 | for (auto &image_fetcher : image_fetchers_) { |
| 93 | while (image_fetcher.FetchNext()) { |
| 94 | HandleImageMatch(*image_fetcher); |
| 95 | } |
| 96 | } |
| 97 | ekf_.UpdateEncodersAndGyro(left_encoder, right_encoder, gyro_rate, U, accel, |
| 98 | now); |
| 99 | } |
| 100 | |
| 101 | void Localizer::HandleImageMatch( |
| 102 | const frc971::vision::sift::ImageMatchResult &result) { |
James Kuszmaul | 958b21e | 2020-02-26 21:51:40 -0800 | [diff] [blame] | 103 | std::chrono::nanoseconds monotonic_offset(0); |
| 104 | clock_offset_fetcher_.Fetch(); |
| 105 | if (clock_offset_fetcher_.get() != nullptr) { |
| 106 | for (const auto connection : *clock_offset_fetcher_->connections()) { |
| 107 | if (connection->has_node() && connection->node()->has_name() && |
| 108 | connection->node()->name()->string_view() == "pi1") { |
| 109 | monotonic_offset = |
| 110 | std::chrono::nanoseconds(connection->monotonic_offset()); |
| 111 | break; |
| 112 | } |
| 113 | } |
| 114 | } |
James Kuszmaul | 5398fae | 2020-02-17 16:44:03 -0800 | [diff] [blame] | 115 | aos::monotonic_clock::time_point capture_time( |
James Kuszmaul | 958b21e | 2020-02-26 21:51:40 -0800 | [diff] [blame] | 116 | std::chrono::nanoseconds(result.image_monotonic_timestamp_ns()) - |
| 117 | monotonic_offset); |
James Kuszmaul | 2d8fa2a | 2020-03-01 13:51:50 -0800 | [diff] [blame^] | 118 | VLOG(1) << "Got monotonic offset of " |
| 119 | << aos::time::DurationInSeconds(monotonic_offset) |
| 120 | << " when at time of " << event_loop_->monotonic_now() |
| 121 | << " and capture time estimate of " << capture_time; |
| 122 | if (capture_time > event_loop_->monotonic_now()) { |
| 123 | LOG(WARNING) << "Got camera frame from the future."; |
| 124 | return; |
| 125 | } |
James Kuszmaul | 5398fae | 2020-02-17 16:44:03 -0800 | [diff] [blame] | 126 | CHECK(result.has_camera_calibration()); |
| 127 | // Per the ImageMatchResult specification, we can actually determine whether |
| 128 | // the camera is the turret camera just from the presence of the |
| 129 | // turret_extrinsics member. |
| 130 | const bool is_turret = result.camera_calibration()->has_turret_extrinsics(); |
| 131 | const TurretData turret_data = GetTurretDataForTime(capture_time); |
| 132 | // Ignore readings when the turret is spinning too fast, on the assumption |
| 133 | // that the odds of screwing up the time compensation are higher. |
| 134 | // Note that the current number here is chosen pretty arbitrarily--1 rad / sec |
| 135 | // seems reasonable, but may be unnecessarily low or high. |
| 136 | constexpr double kMaxTurretVelocity = 1.0; |
| 137 | if (is_turret && std::abs(turret_data.velocity) > kMaxTurretVelocity) { |
| 138 | return; |
| 139 | } |
| 140 | CHECK(result.camera_calibration()->has_fixed_extrinsics()); |
| 141 | const Eigen::Matrix<double, 4, 4> fixed_extrinsics = |
| 142 | FlatbufferToTransformationMatrix( |
| 143 | *result.camera_calibration()->fixed_extrinsics()); |
| 144 | // Calculate the pose of the camera relative to the robot origin. |
James Kuszmaul | c51dbfe | 2020-02-23 15:39:00 -0800 | [diff] [blame] | 145 | Eigen::Matrix<double, 4, 4> H_robot_camera = fixed_extrinsics; |
James Kuszmaul | 5398fae | 2020-02-17 16:44:03 -0800 | [diff] [blame] | 146 | if (is_turret) { |
James Kuszmaul | c51dbfe | 2020-02-23 15:39:00 -0800 | [diff] [blame] | 147 | H_robot_camera = H_robot_camera * |
James Kuszmaul | 5398fae | 2020-02-17 16:44:03 -0800 | [diff] [blame] | 148 | frc971::control_loops::TransformationMatrixForYaw( |
| 149 | turret_data.position) * |
| 150 | FlatbufferToTransformationMatrix( |
| 151 | *result.camera_calibration()->turret_extrinsics()); |
| 152 | } |
| 153 | |
| 154 | if (!result.has_camera_poses()) { |
| 155 | return; |
| 156 | } |
| 157 | |
| 158 | for (const frc971::vision::sift::CameraPose *vision_result : |
| 159 | *result.camera_poses()) { |
| 160 | if (!vision_result->has_camera_to_target() || |
| 161 | !vision_result->has_field_to_target()) { |
| 162 | continue; |
| 163 | } |
James Kuszmaul | c51dbfe | 2020-02-23 15:39:00 -0800 | [diff] [blame] | 164 | const Eigen::Matrix<double, 4, 4> H_camera_target = |
James Kuszmaul | 5398fae | 2020-02-17 16:44:03 -0800 | [diff] [blame] | 165 | FlatbufferToTransformationMatrix(*vision_result->camera_to_target()); |
James Kuszmaul | c51dbfe | 2020-02-23 15:39:00 -0800 | [diff] [blame] | 166 | const Eigen::Matrix<double, 4, 4> H_field_target = |
James Kuszmaul | 5398fae | 2020-02-17 16:44:03 -0800 | [diff] [blame] | 167 | FlatbufferToTransformationMatrix(*vision_result->field_to_target()); |
| 168 | // Back out the robot position that is implied by the current camera |
| 169 | // reading. |
James Kuszmaul | c51dbfe | 2020-02-23 15:39:00 -0800 | [diff] [blame] | 170 | const Pose measured_pose(H_field_target * |
| 171 | (H_robot_camera * H_camera_target).inverse()); |
James Kuszmaul | 5398fae | 2020-02-17 16:44:03 -0800 | [diff] [blame] | 172 | const Eigen::Matrix<double, 3, 1> Z(measured_pose.rel_pos().x(), |
| 173 | measured_pose.rel_pos().y(), |
| 174 | measured_pose.rel_theta()); |
| 175 | // TODO(james): Figure out how to properly handle calculating the |
| 176 | // noise. Currently, the values are deliberately tuned so that image updates |
| 177 | // will not be trusted overly much. In theory, we should probably also be |
| 178 | // populating some cross-correlation terms. |
| 179 | // Note that these are the noise standard deviations (they are squared below |
| 180 | // to get variances). |
| 181 | Eigen::Matrix<double, 3, 1> noises(1.0, 1.0, 0.1); |
| 182 | // Augment the noise by the approximate rotational speed of the |
| 183 | // camera. This should help account for the fact that, while we are |
| 184 | // spinning, slight timing errors in the camera/turret data will tend to |
| 185 | // have mutch more drastic effects on the results. |
| 186 | noises *= 1.0 + std::abs((right_velocity() - left_velocity()) / |
| 187 | (2.0 * dt_config_.robot_radius) + |
| 188 | (is_turret ? turret_data.velocity : 0.0)); |
| 189 | Eigen::Matrix3d R = Eigen::Matrix3d::Zero(); |
| 190 | R.diagonal() = noises.cwiseAbs2(); |
| 191 | Eigen::Matrix<double, HybridEkf::kNOutputs, HybridEkf::kNStates> H; |
| 192 | H.setZero(); |
| 193 | H(0, StateIdx::kX) = 1; |
| 194 | H(1, StateIdx::kY) = 1; |
| 195 | H(2, StateIdx::kTheta) = 1; |
| 196 | ekf_.Correct(Z, nullptr, {}, [H, Z](const State &X, const Input &) { |
| 197 | Eigen::Vector3d Zhat = H * X; |
| 198 | // In order to deal with wrapping of the |
| 199 | // angle, calculate an expected angle that is |
| 200 | // in the range (Z(2) - pi, Z(2) + pi]. |
| 201 | const double angle_error = |
| 202 | aos::math::NormalizeAngle( |
| 203 | X(StateIdx::kTheta) - Z(2)); |
| 204 | Zhat(2) = Z(2) + angle_error; |
| 205 | return Zhat; |
| 206 | }, |
| 207 | [H](const State &) { return H; }, R, capture_time); |
| 208 | } |
| 209 | } |
| 210 | |
| 211 | } // namespace drivetrain |
| 212 | } // namespace control_loops |
| 213 | } // namespace y2020 |