James Kuszmaul | 5398fae | 2020-02-17 16:44:03 -0800 | [diff] [blame] | 1 | #include "y2020/control_loops/drivetrain/localizer.h" |
| 2 | |
Austin Schuh | 99f7c6a | 2024-06-25 22:07:44 -0700 | [diff] [blame^] | 3 | #include "absl/flags/flag.h" |
| 4 | |
James Kuszmaul | 5398fae | 2020-02-17 16:44:03 -0800 | [diff] [blame] | 5 | #include "y2020/constants.h" |
| 6 | |
Austin Schuh | 99f7c6a | 2024-06-25 22:07:44 -0700 | [diff] [blame^] | 7 | ABSL_FLAG(bool, send_empty_debug, false, |
| 8 | "If true, send LocalizerDebug messages on every tick, even if " |
| 9 | "they would be empty."); |
James Kuszmaul | f75ecd6 | 2021-10-23 14:33:46 -0700 | [diff] [blame] | 10 | |
Stephan Pleines | f63bde8 | 2024-01-13 15:59:33 -0800 | [diff] [blame] | 11 | namespace y2020::control_loops::drivetrain { |
James Kuszmaul | 5398fae | 2020-02-17 16:44:03 -0800 | [diff] [blame] | 12 | |
| 13 | namespace { |
| 14 | // Converts a flatbuffer TransformationMatrix to an Eigen matrix. Technically, |
| 15 | // this should be able to do a single memcpy, but the extra verbosity here seems |
| 16 | // appropriate. |
James Kuszmaul | d478f87 | 2020-03-16 20:54:27 -0700 | [diff] [blame] | 17 | Eigen::Matrix<float, 4, 4> FlatbufferToTransformationMatrix( |
James Kuszmaul | 5398fae | 2020-02-17 16:44:03 -0800 | [diff] [blame] | 18 | const frc971::vision::sift::TransformationMatrix &flatbuffer) { |
Austin Schuh | 6bdcc37 | 2024-06-27 14:49:11 -0700 | [diff] [blame] | 19 | CHECK(flatbuffer.data() != nullptr); |
| 20 | CHECK_EQ(16u, flatbuffer.data()->size()); |
James Kuszmaul | d478f87 | 2020-03-16 20:54:27 -0700 | [diff] [blame] | 21 | Eigen::Matrix<float, 4, 4> result; |
James Kuszmaul | 5398fae | 2020-02-17 16:44:03 -0800 | [diff] [blame] | 22 | result.setIdentity(); |
| 23 | for (int row = 0; row < 4; ++row) { |
| 24 | for (int col = 0; col < 4; ++col) { |
| 25 | result(row, col) = (*flatbuffer.data())[row * 4 + col]; |
| 26 | } |
| 27 | } |
| 28 | return result; |
| 29 | } |
James Kuszmaul | 958b21e | 2020-02-26 21:51:40 -0800 | [diff] [blame] | 30 | |
James Kuszmaul | ed6fca4 | 2021-09-25 17:58:30 -0700 | [diff] [blame] | 31 | // Offset to add to the pi's yaw in its extrinsics, to account for issues in the |
| 32 | // calibrated extrinsics. |
| 33 | constexpr double kTurretPiOffset = 0.0; |
| 34 | |
James Kuszmaul | c6723cf | 2020-03-01 14:45:59 -0800 | [diff] [blame] | 35 | // Indices of the pis to use. |
James Kuszmaul | 9c12812 | 2021-03-22 22:24:36 -0700 | [diff] [blame] | 36 | const std::array<std::string, 5> kPisToUse{"pi1", "pi2", "pi3", "pi4", "pi5"}; |
James Kuszmaul | c6723cf | 2020-03-01 14:45:59 -0800 | [diff] [blame] | 37 | |
James Kuszmaul | ed177c4 | 2021-09-30 18:53:08 -0700 | [diff] [blame] | 38 | float CalculateYaw(const Eigen::Matrix4f &transform) { |
| 39 | const Eigen::Vector2f yaw_coords = |
| 40 | (transform * Eigen::Vector4f(1, 0, 0, 0)).topRows<2>(); |
| 41 | return std::atan2(yaw_coords(1), yaw_coords(0)); |
| 42 | } |
| 43 | |
James Kuszmaul | 66efe83 | 2020-03-16 19:38:33 -0700 | [diff] [blame] | 44 | // Calculates the pose implied by the camera target, just based on |
| 45 | // distance/heading components. |
James Kuszmaul | ed177c4 | 2021-09-30 18:53:08 -0700 | [diff] [blame] | 46 | Eigen::Vector3f CalculateImpliedPose(const float correction_robot_theta, |
| 47 | const Eigen::Matrix4f &H_field_target, |
James Kuszmaul | 66efe83 | 2020-03-16 19:38:33 -0700 | [diff] [blame] | 48 | const Localizer::Pose &pose_robot_target) { |
| 49 | // This code overrides the pose sent directly from the camera code and |
| 50 | // effectively distills it down to just a distance + heading estimate, on |
| 51 | // the presumption that these signals will tend to be much lower noise and |
| 52 | // better-conditioned than other portions of the robot pose. |
James Kuszmaul | ed177c4 | 2021-09-30 18:53:08 -0700 | [diff] [blame] | 53 | // As such, this code assumes that the provided estimate of the robot |
James Kuszmaul | 66efe83 | 2020-03-16 19:38:33 -0700 | [diff] [blame] | 54 | // heading is correct and then, given the heading from the camera to the |
| 55 | // target and the distance from the camera to the target, calculates the |
| 56 | // position that the robot would have to be at to make the current camera |
| 57 | // heading + distance correct. This X/Y implied robot position is then |
| 58 | // used as the measurement in the EKF, rather than the X/Y that is |
James Kuszmaul | ed177c4 | 2021-09-30 18:53:08 -0700 | [diff] [blame] | 59 | // directly returned from the vision processing. If the provided |
| 60 | // correction_robot_theta is exactly identical to the current estimated robot |
| 61 | // yaw, then this means that the image corrections will not do anything to |
| 62 | // correct gyro drift; however, by making that tradeoff we can prioritize |
| 63 | // getting the turret angle to the target correct (without adding any new |
| 64 | // non-linearities to the EKF itself). |
James Kuszmaul | 66efe83 | 2020-03-16 19:38:33 -0700 | [diff] [blame] | 65 | |
| 66 | // Calculate the heading to the robot in the target's coordinate frame. |
James Kuszmaul | 5a46c8d | 2021-09-03 19:33:48 -0700 | [diff] [blame] | 67 | // Reminder on what the numbers mean: |
| 68 | // rel_theta: The orientation of the target in the robot frame. |
| 69 | // heading: heading from the robot to the target in the robot frame. I.e., |
| 70 | // atan2(y, x) for x/y of the target in the robot frame. |
James Kuszmaul | ed177c4 | 2021-09-30 18:53:08 -0700 | [diff] [blame] | 71 | const float implied_rel_theta = |
| 72 | CalculateYaw(H_field_target) - correction_robot_theta; |
James Kuszmaul | d478f87 | 2020-03-16 20:54:27 -0700 | [diff] [blame] | 73 | const float implied_heading_from_target = aos::math::NormalizeAngle( |
James Kuszmaul | ed177c4 | 2021-09-30 18:53:08 -0700 | [diff] [blame] | 74 | M_PI - implied_rel_theta + pose_robot_target.heading()); |
James Kuszmaul | d478f87 | 2020-03-16 20:54:27 -0700 | [diff] [blame] | 75 | const float implied_distance = pose_robot_target.xy_norm(); |
| 76 | const Eigen::Vector4f robot_pose_in_target_frame( |
James Kuszmaul | 66efe83 | 2020-03-16 19:38:33 -0700 | [diff] [blame] | 77 | implied_distance * std::cos(implied_heading_from_target), |
| 78 | implied_distance * std::sin(implied_heading_from_target), 0, 1); |
James Kuszmaul | ed177c4 | 2021-09-30 18:53:08 -0700 | [diff] [blame] | 79 | const Eigen::Vector2f implied_xy = |
| 80 | (H_field_target * robot_pose_in_target_frame).topRows<2>(); |
| 81 | return {implied_xy.x(), implied_xy.y(), correction_robot_theta}; |
James Kuszmaul | 66efe83 | 2020-03-16 19:38:33 -0700 | [diff] [blame] | 82 | } |
| 83 | |
James Kuszmaul | 5398fae | 2020-02-17 16:44:03 -0800 | [diff] [blame] | 84 | } // namespace |
| 85 | |
| 86 | Localizer::Localizer( |
| 87 | aos::EventLoop *event_loop, |
| 88 | const frc971::control_loops::drivetrain::DrivetrainConfig<double> |
| 89 | &dt_config) |
James Kuszmaul | 958b21e | 2020-02-26 21:51:40 -0800 | [diff] [blame] | 90 | : event_loop_(event_loop), |
| 91 | dt_config_(dt_config), |
| 92 | ekf_(dt_config), |
James Kuszmaul | 2971b5a | 2023-01-29 15:49:32 -0800 | [diff] [blame] | 93 | observations_(&ekf_), |
James Kuszmaul | 958b21e | 2020-02-26 21:51:40 -0800 | [diff] [blame] | 94 | clock_offset_fetcher_( |
| 95 | event_loop_->MakeFetcher<aos::message_bridge::ServerStatistics>( |
James Kuszmaul | 5ff8a86 | 2021-09-25 17:29:43 -0700 | [diff] [blame] | 96 | "/aos")), |
| 97 | debug_sender_( |
| 98 | event_loop_ |
| 99 | ->MakeSender<y2020::control_loops::drivetrain::LocalizerDebug>( |
| 100 | "/drivetrain")) { |
James Kuszmaul | f75ecd6 | 2021-10-23 14:33:46 -0700 | [diff] [blame] | 101 | statistics_.rejection_counts.fill(0); |
James Kuszmaul | 91aa0cf | 2021-02-13 13:15:06 -0800 | [diff] [blame] | 102 | // TODO(james): The down estimator has trouble handling situations where the |
| 103 | // robot is constantly wiggling but not actually moving much, and can cause |
| 104 | // drift when using accelerometer readings. |
| 105 | ekf_.set_ignore_accel(true); |
James Kuszmaul | 5398fae | 2020-02-17 16:44:03 -0800 | [diff] [blame] | 106 | // TODO(james): This doesn't really need to be a watcher; we could just use a |
| 107 | // fetcher for the superstructure status. |
| 108 | // This probably should be a Fetcher instead of a Watcher, but this |
| 109 | // seems simpler for the time being (although technically it should be |
| 110 | // possible to do everything we need to using just a Fetcher without |
| 111 | // even maintaining a separate buffer, but that seems overly cute). |
| 112 | event_loop_->MakeWatcher("/superstructure", |
| 113 | [this](const superstructure::Status &status) { |
| 114 | HandleSuperstructureStatus(status); |
| 115 | }); |
| 116 | |
James Kuszmaul | 286b428 | 2020-02-26 20:29:32 -0800 | [diff] [blame] | 117 | event_loop->OnRun([this, event_loop]() { |
James Kuszmaul | d478f87 | 2020-03-16 20:54:27 -0700 | [diff] [blame] | 118 | ekf_.ResetInitialState(event_loop->monotonic_now(), |
| 119 | HybridEkf::State::Zero(), ekf_.P()); |
James Kuszmaul | 286b428 | 2020-02-26 20:29:32 -0800 | [diff] [blame] | 120 | }); |
| 121 | |
James Kuszmaul | c6723cf | 2020-03-01 14:45:59 -0800 | [diff] [blame] | 122 | for (const auto &pi : kPisToUse) { |
| 123 | image_fetchers_.emplace_back( |
| 124 | event_loop_->MakeFetcher<frc971::vision::sift::ImageMatchResult>( |
| 125 | "/" + pi + "/camera")); |
| 126 | } |
James Kuszmaul | 5398fae | 2020-02-17 16:44:03 -0800 | [diff] [blame] | 127 | |
| 128 | target_selector_.set_has_target(false); |
| 129 | } |
| 130 | |
James Kuszmaul | bcd96fc | 2020-10-12 20:29:32 -0700 | [diff] [blame] | 131 | void Localizer::Reset( |
| 132 | aos::monotonic_clock::time_point t, |
| 133 | const frc971::control_loops::drivetrain::HybridEkf<double>::State &state) { |
| 134 | // Go through and clear out all of the fetchers so that we don't get behind. |
| 135 | for (auto &fetcher : image_fetchers_) { |
| 136 | fetcher.Fetch(); |
| 137 | } |
| 138 | ekf_.ResetInitialState(t, state.cast<float>(), ekf_.P()); |
| 139 | } |
| 140 | |
James Kuszmaul | 5398fae | 2020-02-17 16:44:03 -0800 | [diff] [blame] | 141 | void Localizer::HandleSuperstructureStatus( |
| 142 | const y2020::control_loops::superstructure::Status &status) { |
| 143 | CHECK(status.has_turret()); |
| 144 | turret_data_.Push({event_loop_->monotonic_now(), status.turret()->position(), |
| 145 | status.turret()->velocity()}); |
| 146 | } |
| 147 | |
| 148 | Localizer::TurretData Localizer::GetTurretDataForTime( |
| 149 | aos::monotonic_clock::time_point time) { |
| 150 | if (turret_data_.empty()) { |
| 151 | return {}; |
| 152 | } |
| 153 | |
| 154 | aos::monotonic_clock::duration lowest_time_error = |
| 155 | aos::monotonic_clock::duration::max(); |
| 156 | TurretData best_data_match; |
| 157 | for (const auto &sample : turret_data_) { |
| 158 | const aos::monotonic_clock::duration time_error = |
| 159 | std::chrono::abs(sample.receive_time - time); |
| 160 | if (time_error < lowest_time_error) { |
| 161 | lowest_time_error = time_error; |
| 162 | best_data_match = sample; |
| 163 | } |
| 164 | } |
| 165 | return best_data_match; |
| 166 | } |
| 167 | |
James Kuszmaul | 06257f4 | 2020-05-09 15:40:09 -0700 | [diff] [blame] | 168 | void Localizer::Update(const Eigen::Matrix<double, 2, 1> &U, |
James Kuszmaul | 5398fae | 2020-02-17 16:44:03 -0800 | [diff] [blame] | 169 | aos::monotonic_clock::time_point now, |
| 170 | double left_encoder, double right_encoder, |
| 171 | double gyro_rate, const Eigen::Vector3d &accel) { |
James Kuszmaul | d478f87 | 2020-03-16 20:54:27 -0700 | [diff] [blame] | 172 | ekf_.UpdateEncodersAndGyro(left_encoder, right_encoder, gyro_rate, |
| 173 | U.cast<float>(), accel.cast<float>(), now); |
James Kuszmaul | 5ff8a86 | 2021-09-25 17:29:43 -0700 | [diff] [blame] | 174 | auto builder = debug_sender_.MakeBuilder(); |
| 175 | aos::SizedArray<flatbuffers::Offset<ImageMatchDebug>, 25> debug_offsets; |
James Kuszmaul | c6723cf | 2020-03-01 14:45:59 -0800 | [diff] [blame] | 176 | for (size_t ii = 0; ii < kPisToUse.size(); ++ii) { |
| 177 | auto &image_fetcher = image_fetchers_[ii]; |
James Kuszmaul | 5398fae | 2020-02-17 16:44:03 -0800 | [diff] [blame] | 178 | while (image_fetcher.FetchNext()) { |
James Kuszmaul | 5ff8a86 | 2021-09-25 17:29:43 -0700 | [diff] [blame] | 179 | const auto offsets = HandleImageMatch(ii, kPisToUse[ii], *image_fetcher, |
| 180 | now, builder.fbb()); |
| 181 | for (const auto offset : offsets) { |
| 182 | debug_offsets.push_back(offset); |
| 183 | } |
James Kuszmaul | 5398fae | 2020-02-17 16:44:03 -0800 | [diff] [blame] | 184 | } |
| 185 | } |
Austin Schuh | 99f7c6a | 2024-06-25 22:07:44 -0700 | [diff] [blame^] | 186 | if (absl::GetFlag(FLAGS_send_empty_debug) || !debug_offsets.empty()) { |
James Kuszmaul | f75ecd6 | 2021-10-23 14:33:46 -0700 | [diff] [blame] | 187 | const auto vector_offset = |
| 188 | builder.fbb()->CreateVector(debug_offsets.data(), debug_offsets.size()); |
| 189 | const auto rejections_offset = |
| 190 | builder.fbb()->CreateVector(statistics_.rejection_counts.data(), |
| 191 | statistics_.rejection_counts.size()); |
| 192 | |
| 193 | CumulativeStatistics::Builder stats_builder = |
| 194 | builder.MakeBuilder<CumulativeStatistics>(); |
| 195 | stats_builder.add_total_accepted(statistics_.total_accepted); |
| 196 | stats_builder.add_total_candidates(statistics_.total_candidates); |
| 197 | stats_builder.add_rejection_reason_count(rejections_offset); |
| 198 | const auto stats_offset = stats_builder.Finish(); |
| 199 | |
| 200 | LocalizerDebug::Builder debug_builder = |
| 201 | builder.MakeBuilder<LocalizerDebug>(); |
| 202 | debug_builder.add_matches(vector_offset); |
| 203 | debug_builder.add_statistics(stats_offset); |
milind | 1f1dca3 | 2021-07-03 13:50:07 -0700 | [diff] [blame] | 204 | builder.CheckOk(builder.Send(debug_builder.Finish())); |
James Kuszmaul | f75ecd6 | 2021-10-23 14:33:46 -0700 | [diff] [blame] | 205 | } |
James Kuszmaul | 5398fae | 2020-02-17 16:44:03 -0800 | [diff] [blame] | 206 | } |
| 207 | |
James Kuszmaul | 5ff8a86 | 2021-09-25 17:29:43 -0700 | [diff] [blame] | 208 | aos::SizedArray<flatbuffers::Offset<ImageMatchDebug>, 5> |
| 209 | Localizer::HandleImageMatch( |
| 210 | size_t camera_index, std::string_view pi, |
| 211 | const frc971::vision::sift::ImageMatchResult &result, |
| 212 | aos::monotonic_clock::time_point now, flatbuffers::FlatBufferBuilder *fbb) { |
| 213 | aos::SizedArray<flatbuffers::Offset<ImageMatchDebug>, 5> debug_offsets; |
| 214 | |
James Kuszmaul | a3d1cd1 | 2021-10-23 22:30:45 -0700 | [diff] [blame] | 215 | std::chrono::nanoseconds monotonic_offset{0}; |
| 216 | bool message_bridge_connected = true; |
James Kuszmaul | 958b21e | 2020-02-26 21:51:40 -0800 | [diff] [blame] | 217 | clock_offset_fetcher_.Fetch(); |
| 218 | if (clock_offset_fetcher_.get() != nullptr) { |
| 219 | for (const auto connection : *clock_offset_fetcher_->connections()) { |
| 220 | if (connection->has_node() && connection->node()->has_name() && |
James Kuszmaul | c6723cf | 2020-03-01 14:45:59 -0800 | [diff] [blame] | 221 | connection->node()->name()->string_view() == pi) { |
James Kuszmaul | a3d1cd1 | 2021-10-23 22:30:45 -0700 | [diff] [blame] | 222 | if (connection->has_monotonic_offset()) { |
| 223 | monotonic_offset = |
| 224 | std::chrono::nanoseconds(connection->monotonic_offset()); |
| 225 | } else { |
| 226 | // If we don't have a monotonic offset, that means we aren't |
| 227 | // connected, in which case we should break the loop but shouldn't |
| 228 | // populate the offset. |
| 229 | message_bridge_connected = false; |
| 230 | } |
James Kuszmaul | 958b21e | 2020-02-26 21:51:40 -0800 | [diff] [blame] | 231 | break; |
| 232 | } |
| 233 | } |
| 234 | } |
James Kuszmaul | 5398fae | 2020-02-17 16:44:03 -0800 | [diff] [blame] | 235 | aos::monotonic_clock::time_point capture_time( |
James Kuszmaul | 958b21e | 2020-02-26 21:51:40 -0800 | [diff] [blame] | 236 | std::chrono::nanoseconds(result.image_monotonic_timestamp_ns()) - |
| 237 | monotonic_offset); |
James Kuszmaul | 2d8fa2a | 2020-03-01 13:51:50 -0800 | [diff] [blame] | 238 | VLOG(1) << "Got monotonic offset of " |
| 239 | << aos::time::DurationInSeconds(monotonic_offset) |
James Kuszmaul | 58cb1fe | 2020-03-07 16:18:59 -0800 | [diff] [blame] | 240 | << " when at time of " << now << " and capture time estimate of " |
| 241 | << capture_time; |
James Kuszmaul | f75ecd6 | 2021-10-23 14:33:46 -0700 | [diff] [blame] | 242 | std::optional<RejectionReason> rejection_reason; |
James Kuszmaul | a3d1cd1 | 2021-10-23 22:30:45 -0700 | [diff] [blame] | 243 | if (!message_bridge_connected) { |
| 244 | rejection_reason = RejectionReason::MESSAGE_BRIDGE_DISCONNECTED; |
| 245 | } else if (capture_time > now) { |
James Kuszmaul | f75ecd6 | 2021-10-23 14:33:46 -0700 | [diff] [blame] | 246 | rejection_reason = RejectionReason::IMAGE_FROM_FUTURE; |
James Kuszmaul | 2d8fa2a | 2020-03-01 13:51:50 -0800 | [diff] [blame] | 247 | } |
James Kuszmaul | bcd96fc | 2020-10-12 20:29:32 -0700 | [diff] [blame] | 248 | if (!result.has_camera_calibration()) { |
James Kuszmaul | 2971b5a | 2023-01-29 15:49:32 -0800 | [diff] [blame] | 249 | AOS_LOG(WARNING, "Got camera frame without calibration data.\n"); |
James Kuszmaul | 5ff8a86 | 2021-09-25 17:29:43 -0700 | [diff] [blame] | 250 | ImageMatchDebug::Builder builder(*fbb); |
| 251 | builder.add_camera(camera_index); |
| 252 | builder.add_accepted(false); |
| 253 | builder.add_rejection_reason(RejectionReason::NO_CALIBRATION); |
| 254 | debug_offsets.push_back(builder.Finish()); |
James Kuszmaul | f75ecd6 | 2021-10-23 14:33:46 -0700 | [diff] [blame] | 255 | statistics_.rejection_counts[static_cast<size_t>( |
| 256 | RejectionReason::NO_CALIBRATION)]++; |
James Kuszmaul | 5ff8a86 | 2021-09-25 17:29:43 -0700 | [diff] [blame] | 257 | return debug_offsets; |
James Kuszmaul | bcd96fc | 2020-10-12 20:29:32 -0700 | [diff] [blame] | 258 | } |
James Kuszmaul | 5398fae | 2020-02-17 16:44:03 -0800 | [diff] [blame] | 259 | // Per the ImageMatchResult specification, we can actually determine whether |
| 260 | // the camera is the turret camera just from the presence of the |
| 261 | // turret_extrinsics member. |
| 262 | const bool is_turret = result.camera_calibration()->has_turret_extrinsics(); |
| 263 | const TurretData turret_data = GetTurretDataForTime(capture_time); |
| 264 | // Ignore readings when the turret is spinning too fast, on the assumption |
| 265 | // that the odds of screwing up the time compensation are higher. |
| 266 | // Note that the current number here is chosen pretty arbitrarily--1 rad / sec |
| 267 | // seems reasonable, but may be unnecessarily low or high. |
James Kuszmaul | d478f87 | 2020-03-16 20:54:27 -0700 | [diff] [blame] | 268 | constexpr float kMaxTurretVelocity = 1.0; |
James Kuszmaul | a3d1cd1 | 2021-10-23 22:30:45 -0700 | [diff] [blame] | 269 | if (is_turret && std::abs(turret_data.velocity) > kMaxTurretVelocity && |
| 270 | !rejection_reason) { |
James Kuszmaul | f75ecd6 | 2021-10-23 14:33:46 -0700 | [diff] [blame] | 271 | rejection_reason = RejectionReason::TURRET_TOO_FAST; |
James Kuszmaul | 5398fae | 2020-02-17 16:44:03 -0800 | [diff] [blame] | 272 | } |
| 273 | CHECK(result.camera_calibration()->has_fixed_extrinsics()); |
James Kuszmaul | d478f87 | 2020-03-16 20:54:27 -0700 | [diff] [blame] | 274 | const Eigen::Matrix<float, 4, 4> fixed_extrinsics = |
James Kuszmaul | 5398fae | 2020-02-17 16:44:03 -0800 | [diff] [blame] | 275 | FlatbufferToTransformationMatrix( |
| 276 | *result.camera_calibration()->fixed_extrinsics()); |
James Kuszmaul | 58cb1fe | 2020-03-07 16:18:59 -0800 | [diff] [blame] | 277 | |
James Kuszmaul | 5398fae | 2020-02-17 16:44:03 -0800 | [diff] [blame] | 278 | // Calculate the pose of the camera relative to the robot origin. |
James Kuszmaul | d478f87 | 2020-03-16 20:54:27 -0700 | [diff] [blame] | 279 | Eigen::Matrix<float, 4, 4> H_robot_camera = fixed_extrinsics; |
James Kuszmaul | 5398fae | 2020-02-17 16:44:03 -0800 | [diff] [blame] | 280 | if (is_turret) { |
James Kuszmaul | c51dbfe | 2020-02-23 15:39:00 -0800 | [diff] [blame] | 281 | H_robot_camera = H_robot_camera * |
James Kuszmaul | d478f87 | 2020-03-16 20:54:27 -0700 | [diff] [blame] | 282 | frc971::control_loops::TransformationMatrixForYaw<float>( |
James Kuszmaul | ed6fca4 | 2021-09-25 17:58:30 -0700 | [diff] [blame] | 283 | turret_data.position + kTurretPiOffset) * |
James Kuszmaul | 5398fae | 2020-02-17 16:44:03 -0800 | [diff] [blame] | 284 | FlatbufferToTransformationMatrix( |
| 285 | *result.camera_calibration()->turret_extrinsics()); |
| 286 | } |
| 287 | |
| 288 | if (!result.has_camera_poses()) { |
James Kuszmaul | 5ff8a86 | 2021-09-25 17:29:43 -0700 | [diff] [blame] | 289 | ImageMatchDebug::Builder builder(*fbb); |
| 290 | builder.add_camera(camera_index); |
| 291 | builder.add_accepted(false); |
| 292 | builder.add_rejection_reason(RejectionReason::NO_RESULTS); |
| 293 | debug_offsets.push_back(builder.Finish()); |
James Kuszmaul | f75ecd6 | 2021-10-23 14:33:46 -0700 | [diff] [blame] | 294 | statistics_ |
| 295 | .rejection_counts[static_cast<size_t>(RejectionReason::NO_RESULTS)]++; |
James Kuszmaul | 5ff8a86 | 2021-09-25 17:29:43 -0700 | [diff] [blame] | 296 | return debug_offsets; |
James Kuszmaul | 5398fae | 2020-02-17 16:44:03 -0800 | [diff] [blame] | 297 | } |
| 298 | |
James Kuszmaul | 5ff8a86 | 2021-09-25 17:29:43 -0700 | [diff] [blame] | 299 | int index = -1; |
James Kuszmaul | 5398fae | 2020-02-17 16:44:03 -0800 | [diff] [blame] | 300 | for (const frc971::vision::sift::CameraPose *vision_result : |
| 301 | *result.camera_poses()) { |
James Kuszmaul | f75ecd6 | 2021-10-23 14:33:46 -0700 | [diff] [blame] | 302 | ++statistics_.total_candidates; |
James Kuszmaul | 5ff8a86 | 2021-09-25 17:29:43 -0700 | [diff] [blame] | 303 | ++index; |
| 304 | |
| 305 | ImageMatchDebug::Builder builder(*fbb); |
| 306 | builder.add_camera(camera_index); |
| 307 | builder.add_pose_index(index); |
milind | 1f1dca3 | 2021-07-03 13:50:07 -0700 | [diff] [blame] | 308 | builder.add_local_image_capture_time_ns( |
| 309 | result.image_monotonic_timestamp_ns()); |
James Kuszmaul | 5ff8a86 | 2021-09-25 17:29:43 -0700 | [diff] [blame] | 310 | builder.add_roborio_image_capture_time_ns( |
| 311 | capture_time.time_since_epoch().count()); |
| 312 | builder.add_image_age_sec(aos::time::DurationInSeconds(now - capture_time)); |
| 313 | |
James Kuszmaul | 5398fae | 2020-02-17 16:44:03 -0800 | [diff] [blame] | 314 | if (!vision_result->has_camera_to_target() || |
| 315 | !vision_result->has_field_to_target()) { |
James Kuszmaul | 5ff8a86 | 2021-09-25 17:29:43 -0700 | [diff] [blame] | 316 | builder.add_accepted(false); |
| 317 | builder.add_rejection_reason(RejectionReason::NO_TRANSFORMS); |
James Kuszmaul | f75ecd6 | 2021-10-23 14:33:46 -0700 | [diff] [blame] | 318 | statistics_.rejection_counts[static_cast<size_t>( |
| 319 | RejectionReason::NO_TRANSFORMS)]++; |
James Kuszmaul | 5ff8a86 | 2021-09-25 17:29:43 -0700 | [diff] [blame] | 320 | debug_offsets.push_back(builder.Finish()); |
James Kuszmaul | 5398fae | 2020-02-17 16:44:03 -0800 | [diff] [blame] | 321 | continue; |
| 322 | } |
James Kuszmaul | d478f87 | 2020-03-16 20:54:27 -0700 | [diff] [blame] | 323 | const Eigen::Matrix<float, 4, 4> H_camera_target = |
James Kuszmaul | 5398fae | 2020-02-17 16:44:03 -0800 | [diff] [blame] | 324 | FlatbufferToTransformationMatrix(*vision_result->camera_to_target()); |
James Kuszmaul | 58cb1fe | 2020-03-07 16:18:59 -0800 | [diff] [blame] | 325 | |
James Kuszmaul | d478f87 | 2020-03-16 20:54:27 -0700 | [diff] [blame] | 326 | const Eigen::Matrix<float, 4, 4> H_field_target = |
James Kuszmaul | 5398fae | 2020-02-17 16:44:03 -0800 | [diff] [blame] | 327 | FlatbufferToTransformationMatrix(*vision_result->field_to_target()); |
James Kuszmaul | f75ecd6 | 2021-10-23 14:33:46 -0700 | [diff] [blame] | 328 | const Eigen::Matrix<float, 4, 4> H_field_camera = |
| 329 | H_field_target * H_camera_target.inverse(); |
James Kuszmaul | 5398fae | 2020-02-17 16:44:03 -0800 | [diff] [blame] | 330 | // Back out the robot position that is implied by the current camera |
James Kuszmaul | 715e793 | 2021-04-05 20:45:57 -0700 | [diff] [blame] | 331 | // reading. Note that the Pose object ignores any roll/pitch components, so |
| 332 | // if the camera's extrinsics for pitch/roll are off, this should just |
| 333 | // ignore it. |
James Kuszmaul | f75ecd6 | 2021-10-23 14:33:46 -0700 | [diff] [blame] | 334 | const Pose measured_camera_pose(H_field_camera); |
| 335 | builder.add_camera_x(measured_camera_pose.rel_pos().x()); |
| 336 | builder.add_camera_y(measured_camera_pose.rel_pos().y()); |
| 337 | // Because the camera uses Z as forwards rather than X, just calculate the |
| 338 | // debugging theta value using the transformation matrix directly (note that |
| 339 | // the rest of this file deliberately does not care what convention the |
| 340 | // camera uses, since that is encoded in the extrinsics themselves). |
| 341 | builder.add_camera_theta( |
| 342 | std::atan2(H_field_camera(1, 2), H_field_camera(0, 2))); |
James Kuszmaul | aca8878 | 2021-04-24 16:48:45 -0700 | [diff] [blame] | 343 | // Calculate the camera-to-robot transformation matrix ignoring the |
| 344 | // pitch/roll of the camera. |
| 345 | // TODO(james): This could probably be made a bit more efficient, but I |
| 346 | // don't think this is anywhere near our bottleneck currently. |
| 347 | const Eigen::Matrix<float, 4, 4> H_camera_robot_stripped = |
| 348 | Pose(H_robot_camera).AsTransformationMatrix().inverse(); |
| 349 | const Pose measured_pose(measured_camera_pose.AsTransformationMatrix() * |
| 350 | H_camera_robot_stripped); |
James Kuszmaul | 66efe83 | 2020-03-16 19:38:33 -0700 | [diff] [blame] | 351 | // This "Z" is the robot pose directly implied by the camera results. |
| 352 | // Currently, we do not actually use this result directly. However, it is |
| 353 | // kept around in case we want to quickly re-enable it. |
James Kuszmaul | d478f87 | 2020-03-16 20:54:27 -0700 | [diff] [blame] | 354 | const Eigen::Matrix<float, 3, 1> Z(measured_pose.rel_pos().x(), |
| 355 | measured_pose.rel_pos().y(), |
| 356 | measured_pose.rel_theta()); |
James Kuszmaul | f75ecd6 | 2021-10-23 14:33:46 -0700 | [diff] [blame] | 357 | builder.add_implied_robot_x(Z(0)); |
| 358 | builder.add_implied_robot_y(Z(1)); |
| 359 | builder.add_implied_robot_theta(Z(2)); |
James Kuszmaul | 58cb1fe | 2020-03-07 16:18:59 -0800 | [diff] [blame] | 360 | // Pose of the target in the robot frame. |
James Kuszmaul | 715e793 | 2021-04-05 20:45:57 -0700 | [diff] [blame] | 361 | // Note that we use measured_pose's transformation matrix rather than just |
| 362 | // doing H_robot_camera * H_camera_target because measured_pose ignores |
| 363 | // pitch/roll. |
| 364 | Pose pose_robot_target(measured_pose.AsTransformationMatrix().inverse() * |
| 365 | H_field_target); |
James Kuszmaul | f75ecd6 | 2021-10-23 14:33:46 -0700 | [diff] [blame] | 366 | |
| 367 | // Turret is zero when pointed backwards. |
| 368 | builder.add_implied_turret_goal( |
| 369 | aos::math::NormalizeAngle(M_PI + pose_robot_target.heading())); |
| 370 | |
| 371 | // Since we've now built up all the information that is useful to include in |
| 372 | // the debug message, bail if we have reason to do so. |
| 373 | if (rejection_reason) { |
| 374 | builder.add_rejection_reason(*rejection_reason); |
| 375 | statistics_.rejection_counts[static_cast<size_t>(*rejection_reason)]++; |
| 376 | builder.add_accepted(false); |
| 377 | debug_offsets.push_back(builder.Finish()); |
| 378 | continue; |
| 379 | } |
| 380 | |
James Kuszmaul | 5398fae | 2020-02-17 16:44:03 -0800 | [diff] [blame] | 381 | // TODO(james): Figure out how to properly handle calculating the |
| 382 | // noise. Currently, the values are deliberately tuned so that image updates |
| 383 | // will not be trusted overly much. In theory, we should probably also be |
| 384 | // populating some cross-correlation terms. |
| 385 | // Note that these are the noise standard deviations (they are squared below |
| 386 | // to get variances). |
James Kuszmaul | ed6fca4 | 2021-09-25 17:58:30 -0700 | [diff] [blame] | 387 | Eigen::Matrix<float, 3, 1> noises(2.0, 2.0, 0.5); |
James Kuszmaul | 5398fae | 2020-02-17 16:44:03 -0800 | [diff] [blame] | 388 | // Augment the noise by the approximate rotational speed of the |
| 389 | // camera. This should help account for the fact that, while we are |
| 390 | // spinning, slight timing errors in the camera/turret data will tend to |
| 391 | // have mutch more drastic effects on the results. |
| 392 | noises *= 1.0 + std::abs((right_velocity() - left_velocity()) / |
| 393 | (2.0 * dt_config_.robot_radius) + |
| 394 | (is_turret ? turret_data.velocity : 0.0)); |
Austin Schuh | eb71863 | 2021-10-22 22:32:57 -0700 | [diff] [blame] | 395 | |
milind | 1f1dca3 | 2021-07-03 13:50:07 -0700 | [diff] [blame] | 396 | // Pay less attention to cameras that aren't actually on the turret, since |
| 397 | // they are less useful when it comes to actually making shots. |
Austin Schuh | eb71863 | 2021-10-22 22:32:57 -0700 | [diff] [blame] | 398 | if (!is_turret) { |
| 399 | noises *= 3.0; |
James Kuszmaul | 3b5de2c | 2021-10-30 10:47:32 -0700 | [diff] [blame] | 400 | } else { |
| 401 | noises /= 5.0; |
Austin Schuh | eb71863 | 2021-10-22 22:32:57 -0700 | [diff] [blame] | 402 | } |
| 403 | |
James Kuszmaul | d478f87 | 2020-03-16 20:54:27 -0700 | [diff] [blame] | 404 | Eigen::Matrix3f R = Eigen::Matrix3f::Zero(); |
James Kuszmaul | 5398fae | 2020-02-17 16:44:03 -0800 | [diff] [blame] | 405 | R.diagonal() = noises.cwiseAbs2(); |
James Kuszmaul | 58cb1fe | 2020-03-07 16:18:59 -0800 | [diff] [blame] | 406 | VLOG(1) << "Pose implied by target: " << Z.transpose() |
| 407 | << " and current pose " << x() << ", " << y() << ", " << theta() |
| 408 | << " Heading/dist/skew implied by target: " |
| 409 | << pose_robot_target.ToHeadingDistanceSkew().transpose(); |
James Kuszmaul | add40ca | 2020-03-01 14:10:50 -0800 | [diff] [blame] | 410 | // If the heading is off by too much, assume that we got a false-positive |
| 411 | // and don't use the correction. |
James Kuszmaul | d478f87 | 2020-03-16 20:54:27 -0700 | [diff] [blame] | 412 | if (std::abs(aos::math::DiffAngle<float>(theta(), Z(2))) > M_PI_2) { |
James Kuszmaul | add40ca | 2020-03-01 14:10:50 -0800 | [diff] [blame] | 413 | AOS_LOG(WARNING, "Dropped image match due to heading mismatch.\n"); |
James Kuszmaul | 5ff8a86 | 2021-09-25 17:29:43 -0700 | [diff] [blame] | 414 | builder.add_accepted(false); |
| 415 | builder.add_rejection_reason(RejectionReason::HIGH_THETA_DIFFERENCE); |
James Kuszmaul | f75ecd6 | 2021-10-23 14:33:46 -0700 | [diff] [blame] | 416 | statistics_.rejection_counts[static_cast<size_t>( |
| 417 | RejectionReason::HIGH_THETA_DIFFERENCE)]++; |
James Kuszmaul | 5ff8a86 | 2021-09-25 17:29:43 -0700 | [diff] [blame] | 418 | debug_offsets.push_back(builder.Finish()); |
James Kuszmaul | 58cb1fe | 2020-03-07 16:18:59 -0800 | [diff] [blame] | 419 | continue; |
James Kuszmaul | add40ca | 2020-03-01 14:10:50 -0800 | [diff] [blame] | 420 | } |
James Kuszmaul | 06257f4 | 2020-05-09 15:40:09 -0700 | [diff] [blame] | 421 | // In order to do the EKF correction, we determine the expected state based |
| 422 | // on the state at the time the image was captured; however, we insert the |
| 423 | // correction update itself at the current time. This is technically not |
| 424 | // quite correct, but saves substantial CPU usage by making it so that we |
| 425 | // don't have to constantly rewind the entire EKF history. |
| 426 | const std::optional<State> state_at_capture = |
| 427 | ekf_.LastStateBeforeTime(capture_time); |
| 428 | if (!state_at_capture.has_value()) { |
| 429 | AOS_LOG(WARNING, "Dropped image match due to age of image.\n"); |
James Kuszmaul | 5ff8a86 | 2021-09-25 17:29:43 -0700 | [diff] [blame] | 430 | builder.add_accepted(false); |
| 431 | builder.add_rejection_reason(RejectionReason::IMAGE_TOO_OLD); |
James Kuszmaul | f75ecd6 | 2021-10-23 14:33:46 -0700 | [diff] [blame] | 432 | statistics_.rejection_counts[static_cast<size_t>( |
| 433 | RejectionReason::IMAGE_TOO_OLD)]++; |
James Kuszmaul | 5ff8a86 | 2021-09-25 17:29:43 -0700 | [diff] [blame] | 434 | debug_offsets.push_back(builder.Finish()); |
James Kuszmaul | 06257f4 | 2020-05-09 15:40:09 -0700 | [diff] [blame] | 435 | continue; |
| 436 | } |
James Kuszmaul | 5ff8a86 | 2021-09-25 17:29:43 -0700 | [diff] [blame] | 437 | |
James Kuszmaul | 5ff8a86 | 2021-09-25 17:29:43 -0700 | [diff] [blame] | 438 | std::optional<RejectionReason> correction_rejection; |
James Kuszmaul | 06257f4 | 2020-05-09 15:40:09 -0700 | [diff] [blame] | 439 | const Input U = ekf_.MostRecentInput(); |
James Kuszmaul | 66efe83 | 2020-03-16 19:38:33 -0700 | [diff] [blame] | 440 | // For the correction step, instead of passing in the measurement directly, |
| 441 | // we pass in (0, 0, 0) as the measurement and then for the expected |
| 442 | // measurement (Zhat) we calculate the error between the implied and actual |
| 443 | // poses. This doesn't affect any of the math, it just makes the code a bit |
| 444 | // more convenient to write given the Correct() interface we already have. |
James Kuszmaul | 5ff8a86 | 2021-09-25 17:29:43 -0700 | [diff] [blame] | 445 | // Note: If we start going back to doing back-in-time rewinds, then we can't |
| 446 | // get away with passing things by reference. |
James Kuszmaul | 2971b5a | 2023-01-29 15:49:32 -0800 | [diff] [blame] | 447 | observations_.CorrectKnownH( |
| 448 | Eigen::Vector3f::Zero(), &U, |
| 449 | Corrector(H_field_target, pose_robot_target, state_at_capture.value(), |
| 450 | Z, &correction_rejection), |
| 451 | R, now); |
James Kuszmaul | 5ff8a86 | 2021-09-25 17:29:43 -0700 | [diff] [blame] | 452 | if (correction_rejection) { |
| 453 | builder.add_accepted(false); |
| 454 | builder.add_rejection_reason(*correction_rejection); |
James Kuszmaul | f75ecd6 | 2021-10-23 14:33:46 -0700 | [diff] [blame] | 455 | statistics_ |
| 456 | .rejection_counts[static_cast<size_t>(*correction_rejection)]++; |
James Kuszmaul | 5ff8a86 | 2021-09-25 17:29:43 -0700 | [diff] [blame] | 457 | } else { |
| 458 | builder.add_accepted(true); |
James Kuszmaul | f75ecd6 | 2021-10-23 14:33:46 -0700 | [diff] [blame] | 459 | statistics_.total_accepted++; |
James Kuszmaul | 5ff8a86 | 2021-09-25 17:29:43 -0700 | [diff] [blame] | 460 | } |
| 461 | debug_offsets.push_back(builder.Finish()); |
James Kuszmaul | 5398fae | 2020-02-17 16:44:03 -0800 | [diff] [blame] | 462 | } |
James Kuszmaul | 5ff8a86 | 2021-09-25 17:29:43 -0700 | [diff] [blame] | 463 | return debug_offsets; |
James Kuszmaul | 5398fae | 2020-02-17 16:44:03 -0800 | [diff] [blame] | 464 | } |
| 465 | |
James Kuszmaul | 2971b5a | 2023-01-29 15:49:32 -0800 | [diff] [blame] | 466 | Localizer::Output Localizer::Corrector::H(const State &, const Input &) { |
| 467 | // Weighting for how much to use the current robot heading estimate |
| 468 | // vs. the heading estimate from the image results. A value of 1.0 |
| 469 | // completely ignores the measured heading, but will prioritize turret |
| 470 | // aiming above all else. A value of 0.0 will prioritize correcting |
| 471 | // any gyro heading drift. |
| 472 | constexpr float kImpliedWeight = 0.99; |
| 473 | const float z_yaw_diff = aos::math::NormalizeAngle( |
| 474 | state_at_capture_(Localizer::StateIdx::kTheta) - Z_(2)); |
| 475 | const float z_yaw = Z_(2) + kImpliedWeight * z_yaw_diff; |
| 476 | const Eigen::Vector3f Z_implied = |
| 477 | CalculateImpliedPose(z_yaw, H_field_target_, pose_robot_target_); |
| 478 | const Eigen::Vector3f Z_used = Z_implied; |
| 479 | // Just in case we ever do encounter any, drop measurements if they |
| 480 | // have non-finite numbers. |
| 481 | if (!Z_.allFinite()) { |
| 482 | AOS_LOG(WARNING, "Got measurement with infinites or NaNs.\n"); |
| 483 | *correction_rejection_ = RejectionReason::NONFINITE_MEASUREMENT; |
| 484 | return Eigen::Vector3f::Zero(); |
| 485 | } |
| 486 | Eigen::Vector3f Zhat = H_ * state_at_capture_ - Z_used; |
| 487 | // Rewrap angle difference to put it back in range. Note that this |
| 488 | // component of the error is currently ignored (see definition of H |
| 489 | // above). |
| 490 | Zhat(2) = aos::math::NormalizeAngle(Zhat(2)); |
| 491 | // If the measurement implies that we are too far from the current |
| 492 | // estimate, then ignore it. |
| 493 | // Note that I am not entirely sure how much effect this actually has, |
| 494 | // because I primarily introduced it to make sure that any grossly |
| 495 | // invalid measurements get thrown out. |
| 496 | if (Zhat.squaredNorm() > std::pow(10.0, 2)) { |
| 497 | *correction_rejection_ = RejectionReason::CORRECTION_TOO_LARGE; |
| 498 | return Eigen::Vector3f::Zero(); |
| 499 | } |
| 500 | return Zhat; |
| 501 | } |
| 502 | |
Stephan Pleines | f63bde8 | 2024-01-13 15:59:33 -0800 | [diff] [blame] | 503 | } // namespace y2020::control_loops::drivetrain |