James Kuszmaul | 04a343c | 2023-02-20 16:38:22 -0800 | [diff] [blame] | 1 | #include "y2023/localizer/localizer.h" |
| 2 | |
| 3 | #include "aos/containers/sized_array.h" |
| 4 | #include "frc971/control_loops/drivetrain/localizer_generated.h" |
| 5 | #include "frc971/control_loops/pose.h" |
milind-u | 7a7f666 | 2023-02-26 16:41:29 -0800 | [diff] [blame] | 6 | #include "gflags/gflags.h" |
James Kuszmaul | 04a343c | 2023-02-20 16:38:22 -0800 | [diff] [blame] | 7 | #include "y2023/constants.h" |
James Kuszmaul | 18008f8 | 2023-02-23 20:52:50 -0800 | [diff] [blame] | 8 | #include "y2023/localizer/utils.h" |
James Kuszmaul | 04a343c | 2023-02-20 16:38:22 -0800 | [diff] [blame] | 9 | |
milind-u | 7a7f666 | 2023-02-26 16:41:29 -0800 | [diff] [blame] | 10 | DEFINE_double(max_pose_error, 1e-6, |
| 11 | "Throw out target poses with a higher pose error than this"); |
milind-u | 08fb972 | 2023-03-25 18:23:59 -0700 | [diff] [blame^] | 12 | DEFINE_double( |
| 13 | max_pose_error_ratio, 0.4, |
| 14 | "Throw out target poses with a higher pose error ratio than this"); |
milind-u | a4f44ac | 2023-02-26 17:03:43 -0800 | [diff] [blame] | 15 | DEFINE_double(distortion_noise_scalar, 1.0, |
| 16 | "Scale the target pose distortion factor by this when computing " |
| 17 | "the noise."); |
milind-u | 4860119 | 2023-03-11 19:44:46 -0800 | [diff] [blame] | 18 | DEFINE_double( |
James Kuszmaul | 3c6a968 | 2023-03-23 20:36:53 -0700 | [diff] [blame] | 19 | max_implied_yaw_error, 3.0, |
milind-u | 4860119 | 2023-03-11 19:44:46 -0800 | [diff] [blame] | 20 | "Reject target poses that imply a robot yaw of more than this many degrees " |
| 21 | "off from our estimate."); |
James Kuszmaul | 3c6a968 | 2023-03-23 20:36:53 -0700 | [diff] [blame] | 22 | DEFINE_double( |
| 23 | max_implied_teleop_yaw_error, 30.0, |
| 24 | "Reject target poses that imply a robot yaw of more than this many degrees " |
| 25 | "off from our estimate."); |
| 26 | DEFINE_double(max_distance_to_target, 3.5, |
milind-u | 4860119 | 2023-03-11 19:44:46 -0800 | [diff] [blame] | 27 | "Reject target poses that have a 3d distance of more than this " |
| 28 | "many meters."); |
James Kuszmaul | 3c6a968 | 2023-03-23 20:36:53 -0700 | [diff] [blame] | 29 | DEFINE_double(max_auto_image_robot_speed, 2.0, |
| 30 | "Reject target poses when the robot is travelling faster than " |
| 31 | "this speed in auto."); |
milind-u | 7a7f666 | 2023-02-26 16:41:29 -0800 | [diff] [blame] | 32 | |
James Kuszmaul | 04a343c | 2023-02-20 16:38:22 -0800 | [diff] [blame] | 33 | namespace y2023::localizer { |
| 34 | namespace { |
| 35 | constexpr std::array<std::string_view, Localizer::kNumCameras> kPisToUse{ |
| 36 | "pi1", "pi2", "pi3", "pi4"}; |
| 37 | |
| 38 | size_t CameraIndexForName(std::string_view name) { |
| 39 | for (size_t index = 0; index < kPisToUse.size(); ++index) { |
| 40 | if (name == kPisToUse.at(index)) { |
| 41 | return index; |
| 42 | } |
| 43 | } |
| 44 | LOG(FATAL) << "No camera named " << name; |
| 45 | } |
| 46 | |
| 47 | std::map<uint64_t, Localizer::Transform> GetTargetLocations( |
| 48 | const Constants &constants) { |
| 49 | CHECK(constants.has_target_map()); |
| 50 | CHECK(constants.target_map()->has_target_poses()); |
| 51 | std::map<uint64_t, Localizer::Transform> transforms; |
| 52 | for (const frc971::vision::TargetPoseFbs *target : |
| 53 | *constants.target_map()->target_poses()) { |
| 54 | CHECK(target->has_id()); |
| 55 | CHECK(target->has_position()); |
| 56 | CHECK(target->has_orientation()); |
| 57 | CHECK_EQ(0u, transforms.count(target->id())); |
| 58 | transforms[target->id()] = PoseToTransform(target); |
| 59 | } |
| 60 | return transforms; |
| 61 | } |
| 62 | } // namespace |
| 63 | |
James Kuszmaul | 04a343c | 2023-02-20 16:38:22 -0800 | [diff] [blame] | 64 | std::array<Localizer::CameraState, Localizer::kNumCameras> |
| 65 | Localizer::MakeCameras(const Constants &constants, aos::EventLoop *event_loop) { |
| 66 | CHECK(constants.has_cameras()); |
| 67 | std::array<Localizer::CameraState, Localizer::kNumCameras> cameras; |
| 68 | for (const CameraConfiguration *camera : *constants.cameras()) { |
| 69 | CHECK(camera->has_calibration()); |
| 70 | const frc971::vision::calibration::CameraCalibration *calibration = |
| 71 | camera->calibration(); |
| 72 | CHECK(!calibration->has_turret_extrinsics()) |
| 73 | << "The 2023 robot does not have a turret."; |
| 74 | CHECK(calibration->has_node_name()); |
| 75 | const size_t index = |
| 76 | CameraIndexForName(calibration->node_name()->string_view()); |
| 77 | // We default-construct the extrinsics matrix to all-zeros; use that to |
| 78 | // sanity-check whether we have populated the matrix yet or not. |
| 79 | CHECK(cameras.at(index).extrinsics.norm() == 0) |
| 80 | << "Got multiple calibrations for " |
| 81 | << calibration->node_name()->string_view(); |
| 82 | CHECK(calibration->has_fixed_extrinsics()); |
| 83 | cameras.at(index).extrinsics = |
| 84 | frc971::control_loops::drivetrain::FlatbufferToTransformationMatrix( |
| 85 | *calibration->fixed_extrinsics()); |
| 86 | cameras.at(index).debug_sender = event_loop->MakeSender<Visualization>( |
| 87 | absl::StrCat("/", calibration->node_name()->string_view(), "/camera")); |
| 88 | } |
| 89 | for (const CameraState &camera : cameras) { |
| 90 | CHECK(camera.extrinsics.norm() != 0) << "Missing a camera calibration."; |
| 91 | } |
| 92 | return cameras; |
| 93 | } |
| 94 | |
| 95 | Localizer::Localizer( |
| 96 | aos::EventLoop *event_loop, |
| 97 | const frc971::control_loops::drivetrain::DrivetrainConfig<double> dt_config) |
| 98 | : event_loop_(event_loop), |
| 99 | dt_config_(dt_config), |
| 100 | constants_fetcher_(event_loop), |
| 101 | cameras_(MakeCameras(constants_fetcher_.constants(), event_loop)), |
| 102 | target_poses_(GetTargetLocations(constants_fetcher_.constants())), |
| 103 | down_estimator_(dt_config), |
| 104 | ekf_(dt_config), |
| 105 | observations_(&ekf_), |
| 106 | imu_watcher_(event_loop, dt_config, |
| 107 | y2023::constants::Values::DrivetrainEncoderToMeters(1), |
| 108 | std::bind(&Localizer::HandleImu, this, std::placeholders::_1, |
| 109 | std::placeholders::_2, std::placeholders::_3, |
James Kuszmaul | 54fe9d0 | 2023-03-23 20:32:40 -0700 | [diff] [blame] | 110 | std::placeholders::_4, std::placeholders::_5), |
| 111 | frc971::controls::ImuWatcher::TimestampSource::kPi), |
James Kuszmaul | 04a343c | 2023-02-20 16:38:22 -0800 | [diff] [blame] | 112 | utils_(event_loop), |
| 113 | status_sender_(event_loop->MakeSender<Status>("/localizer")), |
| 114 | output_sender_(event_loop->MakeSender<frc971::controls::LocalizerOutput>( |
| 115 | "/localizer")) { |
| 116 | if (dt_config_.is_simulated) { |
| 117 | down_estimator_.assume_perfect_gravity(); |
| 118 | } |
| 119 | |
| 120 | for (size_t camera_index = 0; camera_index < kNumCameras; ++camera_index) { |
| 121 | const std::string_view pi_name = kPisToUse.at(camera_index); |
| 122 | event_loop->MakeWatcher( |
| 123 | absl::StrCat("/", pi_name, "/camera"), |
| 124 | [this, pi_name, |
| 125 | camera_index](const frc971::vision::TargetMap &targets) { |
| 126 | CHECK(targets.has_target_poses()); |
| 127 | CHECK(targets.has_monotonic_timestamp_ns()); |
| 128 | const std::optional<aos::monotonic_clock::duration> clock_offset = |
| 129 | utils_.ClockOffset(pi_name); |
| 130 | if (!clock_offset.has_value()) { |
| 131 | VLOG(1) << "Rejecting image due to disconnected message bridge at " |
| 132 | << event_loop_->monotonic_now(); |
| 133 | cameras_.at(camera_index) |
| 134 | .rejection_counter.IncrementError( |
| 135 | RejectionReason::MESSAGE_BRIDGE_DISCONNECTED); |
| 136 | return; |
| 137 | } |
| 138 | const aos::monotonic_clock::time_point pi_capture_time( |
| 139 | std::chrono::nanoseconds(targets.monotonic_timestamp_ns()) - |
| 140 | clock_offset.value()); |
| 141 | const aos::monotonic_clock::time_point capture_time = |
| 142 | pi_capture_time - imu_watcher_.pico_offset_error(); |
| 143 | VLOG(2) << "Capture time of " |
| 144 | << targets.monotonic_timestamp_ns() * 1e-9 |
| 145 | << " clock offset of " |
| 146 | << aos::time::DurationInSeconds(clock_offset.value()) |
| 147 | << " pico error " |
| 148 | << aos::time::DurationInSeconds( |
| 149 | imu_watcher_.pico_offset_error()); |
| 150 | if (pi_capture_time > event_loop_->context().monotonic_event_time) { |
| 151 | VLOG(1) << "Rejecting image due to being from future at " |
| 152 | << event_loop_->monotonic_now() << " with timestamp of " |
| 153 | << pi_capture_time << " and event time pf " |
| 154 | << event_loop_->context().monotonic_event_time; |
| 155 | cameras_.at(camera_index) |
| 156 | .rejection_counter.IncrementError( |
| 157 | RejectionReason::IMAGE_FROM_FUTURE); |
| 158 | return; |
| 159 | } |
| 160 | auto builder = cameras_.at(camera_index).debug_sender.MakeBuilder(); |
| 161 | aos::SizedArray<flatbuffers::Offset<TargetEstimateDebug>, 20> |
| 162 | debug_offsets; |
| 163 | for (const frc971::vision::TargetPoseFbs *target : |
| 164 | *targets.target_poses()) { |
| 165 | VLOG(1) << "Handling target from " << camera_index; |
| 166 | auto offset = HandleTarget(camera_index, capture_time, *target, |
| 167 | builder.fbb()); |
| 168 | if (debug_offsets.size() < debug_offsets.capacity()) { |
| 169 | debug_offsets.push_back(offset); |
| 170 | } else { |
| 171 | AOS_LOG(ERROR, "Dropped message from debug vector."); |
| 172 | } |
| 173 | } |
| 174 | auto vector_offset = builder.fbb()->CreateVector( |
| 175 | debug_offsets.data(), debug_offsets.size()); |
James Kuszmaul | fb89457 | 2023-02-23 17:25:06 -0800 | [diff] [blame] | 176 | auto stats_offset = |
| 177 | StatisticsForCamera(cameras_.at(camera_index), builder.fbb()); |
James Kuszmaul | 04a343c | 2023-02-20 16:38:22 -0800 | [diff] [blame] | 178 | Visualization::Builder visualize_builder(*builder.fbb()); |
| 179 | visualize_builder.add_targets(vector_offset); |
James Kuszmaul | fb89457 | 2023-02-23 17:25:06 -0800 | [diff] [blame] | 180 | visualize_builder.add_statistics(stats_offset); |
James Kuszmaul | 04a343c | 2023-02-20 16:38:22 -0800 | [diff] [blame] | 181 | builder.CheckOk(builder.Send(visualize_builder.Finish())); |
| 182 | SendStatus(); |
| 183 | }); |
| 184 | } |
| 185 | |
| 186 | event_loop_->AddPhasedLoop([this](int) { SendOutput(); }, |
James Kuszmaul | 456774b | 2023-03-08 21:29:15 -0800 | [diff] [blame] | 187 | std::chrono::milliseconds(20)); |
James Kuszmaul | 04a343c | 2023-02-20 16:38:22 -0800 | [diff] [blame] | 188 | |
| 189 | event_loop_->MakeWatcher( |
| 190 | "/drivetrain", |
| 191 | [this]( |
| 192 | const frc971::control_loops::drivetrain::LocalizerControl &control) { |
| 193 | const double theta = control.keep_current_theta() |
| 194 | ? ekf_.X_hat(StateIdx::kTheta) |
| 195 | : control.theta(); |
| 196 | const double left_encoder = ekf_.X_hat(StateIdx::kLeftEncoder); |
| 197 | const double right_encoder = ekf_.X_hat(StateIdx::kRightEncoder); |
| 198 | ekf_.ResetInitialState( |
| 199 | t_, |
| 200 | (HybridEkf::State() << control.x(), control.y(), theta, |
| 201 | left_encoder, 0, right_encoder, 0, 0, 0, 0, 0, 0) |
| 202 | .finished(), |
| 203 | ekf_.P()); |
| 204 | }); |
| 205 | |
| 206 | ekf_.set_ignore_accel(true); |
| 207 | // Priority should be lower than the imu reading process, but non-zero. |
| 208 | event_loop->SetRuntimeRealtimePriority(10); |
| 209 | event_loop->OnRun([this, event_loop]() { |
| 210 | ekf_.ResetInitialState(event_loop->monotonic_now(), |
| 211 | HybridEkf::State::Zero(), ekf_.P()); |
| 212 | }); |
| 213 | } |
| 214 | |
| 215 | void Localizer::HandleImu(aos::monotonic_clock::time_point sample_time_pico, |
| 216 | aos::monotonic_clock::time_point sample_time_pi, |
| 217 | std::optional<Eigen::Vector2d> encoders, |
| 218 | Eigen::Vector3d gyro, Eigen::Vector3d accel) { |
| 219 | last_encoder_readings_ = encoders; |
| 220 | // Ignore ivnalid readings; the HybridEkf will handle it reasonably. |
| 221 | if (!encoders.has_value()) { |
| 222 | return; |
| 223 | } |
| 224 | if (t_ == aos::monotonic_clock::min_time) { |
| 225 | t_ = sample_time_pico; |
| 226 | } |
| 227 | if (t_ + 10 * frc971::controls::ImuWatcher::kNominalDt < sample_time_pico) { |
| 228 | t_ = sample_time_pico; |
| 229 | ++clock_resets_; |
| 230 | } |
| 231 | const aos::monotonic_clock::duration dt = sample_time_pico - t_; |
| 232 | t_ = sample_time_pico; |
| 233 | // We don't actually use the down estimator currently, but it's really |
| 234 | // convenient for debugging. |
| 235 | down_estimator_.Predict(gyro, accel, dt); |
| 236 | const double yaw_rate = (dt_config_.imu_transform * gyro)(2); |
| 237 | ekf_.UpdateEncodersAndGyro(encoders.value()(0), encoders.value()(1), yaw_rate, |
| 238 | utils_.VoltageOrZero(sample_time_pi), accel, t_); |
| 239 | SendStatus(); |
| 240 | } |
| 241 | |
| 242 | flatbuffers::Offset<TargetEstimateDebug> Localizer::RejectImage( |
| 243 | int camera_index, RejectionReason reason, |
| 244 | TargetEstimateDebug::Builder *builder) { |
| 245 | builder->add_accepted(false); |
| 246 | builder->add_rejection_reason(reason); |
| 247 | cameras_.at(camera_index).rejection_counter.IncrementError(reason); |
| 248 | return builder->Finish(); |
| 249 | } |
| 250 | |
| 251 | flatbuffers::Offset<TargetEstimateDebug> Localizer::HandleTarget( |
| 252 | int camera_index, const aos::monotonic_clock::time_point capture_time, |
| 253 | const frc971::vision::TargetPoseFbs &target, |
| 254 | flatbuffers::FlatBufferBuilder *debug_fbb) { |
| 255 | ++total_candidate_targets_; |
| 256 | ++cameras_.at(camera_index).total_candidate_targets; |
| 257 | |
| 258 | TargetEstimateDebug::Builder builder(*debug_fbb); |
| 259 | builder.add_camera(camera_index); |
| 260 | builder.add_image_age_sec(aos::time::DurationInSeconds( |
| 261 | event_loop_->monotonic_now() - capture_time)); |
James Kuszmaul | e600d17 | 2023-03-12 10:19:44 -0700 | [diff] [blame] | 262 | builder.add_image_monotonic_timestamp_ns( |
| 263 | std::chrono::duration_cast<std::chrono::nanoseconds>( |
| 264 | capture_time.time_since_epoch()) |
| 265 | .count()); |
James Kuszmaul | 04a343c | 2023-02-20 16:38:22 -0800 | [diff] [blame] | 266 | |
| 267 | const uint64_t target_id = target.id(); |
James Kuszmaul | e600d17 | 2023-03-12 10:19:44 -0700 | [diff] [blame] | 268 | builder.add_april_tag(target_id); |
James Kuszmaul | 04a343c | 2023-02-20 16:38:22 -0800 | [diff] [blame] | 269 | VLOG(2) << aos::FlatbufferToJson(&target); |
| 270 | if (target_poses_.count(target_id) == 0) { |
| 271 | VLOG(1) << "Rejecting target due to invalid ID " << target_id; |
| 272 | return RejectImage(camera_index, RejectionReason::NO_SUCH_TARGET, &builder); |
| 273 | } |
| 274 | |
| 275 | const Transform &H_field_target = target_poses_.at(target_id); |
| 276 | const Transform &H_robot_camera = cameras_.at(camera_index).extrinsics; |
| 277 | |
| 278 | const Transform H_camera_target = PoseToTransform(&target); |
| 279 | |
| 280 | const Transform H_field_camera = H_field_target * H_camera_target.inverse(); |
| 281 | // Back out the robot position that is implied by the current camera |
| 282 | // reading. Note that the Pose object ignores any roll/pitch components, so |
| 283 | // if the camera's extrinsics for pitch/roll are off, this should just |
| 284 | // ignore it. |
| 285 | const frc971::control_loops::Pose measured_camera_pose(H_field_camera); |
| 286 | builder.add_camera_x(measured_camera_pose.rel_pos().x()); |
| 287 | builder.add_camera_y(measured_camera_pose.rel_pos().y()); |
| 288 | // Because the camera uses Z as forwards rather than X, just calculate the |
| 289 | // debugging theta value using the transformation matrix directly. |
| 290 | builder.add_camera_theta( |
| 291 | std::atan2(H_field_camera(1, 2), H_field_camera(0, 2))); |
| 292 | // Calculate the camera-to-robot transformation matrix ignoring the |
| 293 | // pitch/roll of the camera. |
| 294 | const Transform H_camera_robot_stripped = |
| 295 | frc971::control_loops::Pose(H_robot_camera) |
| 296 | .AsTransformationMatrix() |
| 297 | .inverse(); |
| 298 | const frc971::control_loops::Pose measured_pose( |
| 299 | measured_camera_pose.AsTransformationMatrix() * H_camera_robot_stripped); |
| 300 | // This "Z" is the robot pose directly implied by the camera results. |
| 301 | const Eigen::Matrix<double, 3, 1> Z(measured_pose.rel_pos().x(), |
| 302 | measured_pose.rel_pos().y(), |
| 303 | measured_pose.rel_theta()); |
| 304 | builder.add_implied_robot_x(Z(Corrector::kX)); |
| 305 | builder.add_implied_robot_y(Z(Corrector::kY)); |
| 306 | builder.add_implied_robot_theta(Z(Corrector::kTheta)); |
| 307 | |
milind-u | 5e055a0 | 2023-03-12 14:20:06 -0700 | [diff] [blame] | 308 | Eigen::AngleAxisd rvec_camera_target( |
| 309 | Eigen::Affine3d(H_camera_target).rotation()); |
| 310 | // Use y angle (around vertical axis) to compute skew |
| 311 | double skew = rvec_camera_target.axis().y() * rvec_camera_target.angle(); |
| 312 | builder.add_skew(skew); |
| 313 | |
milind-u | 4860119 | 2023-03-11 19:44:46 -0800 | [diff] [blame] | 314 | double distance_to_target = |
| 315 | Eigen::Affine3d(H_camera_target).translation().norm(); |
| 316 | |
James Kuszmaul | 04a343c | 2023-02-20 16:38:22 -0800 | [diff] [blame] | 317 | // TODO(james): Tune this. Also, gain schedule for auto mode? |
| 318 | Eigen::Matrix<double, 3, 1> noises(1.0, 1.0, 0.5); |
James Kuszmaul | 285a790 | 2023-03-05 18:06:36 -0800 | [diff] [blame] | 319 | noises /= 4.0; |
milind-u | a4f44ac | 2023-02-26 17:03:43 -0800 | [diff] [blame] | 320 | // Scale noise by the distortion factor for this detection |
milind-u | 4860119 | 2023-03-11 19:44:46 -0800 | [diff] [blame] | 321 | noises *= (1.0 + FLAGS_distortion_noise_scalar * target.distortion_factor() * |
| 322 | std::exp(distance_to_target)); |
James Kuszmaul | 04a343c | 2023-02-20 16:38:22 -0800 | [diff] [blame] | 323 | |
| 324 | Eigen::Matrix3d R = Eigen::Matrix3d::Zero(); |
| 325 | R.diagonal() = noises.cwiseAbs2(); |
| 326 | // In order to do the EKF correction, we determine the expected state based |
| 327 | // on the state at the time the image was captured; however, we insert the |
| 328 | // correction update itself at the current time. This is technically not |
| 329 | // quite correct, but saves substantial CPU usage & code complexity by |
| 330 | // making |
| 331 | // it so that we don't have to constantly rewind the entire EKF history. |
| 332 | const std::optional<State> state_at_capture = |
| 333 | ekf_.LastStateBeforeTime(capture_time); |
| 334 | |
| 335 | if (!state_at_capture.has_value()) { |
| 336 | VLOG(1) << "Rejecting image due to being too old."; |
| 337 | return RejectImage(camera_index, RejectionReason::IMAGE_TOO_OLD, &builder); |
milind-u | 7a7f666 | 2023-02-26 16:41:29 -0800 | [diff] [blame] | 338 | } else if (target.pose_error() > FLAGS_max_pose_error) { |
| 339 | VLOG(1) << "Rejecting target due to high pose error " |
| 340 | << target.pose_error(); |
| 341 | return RejectImage(camera_index, RejectionReason::HIGH_POSE_ERROR, |
| 342 | &builder); |
milind-u | 08fb972 | 2023-03-25 18:23:59 -0700 | [diff] [blame^] | 343 | } else if (target.pose_error_ratio() > FLAGS_max_pose_error_ratio) { |
| 344 | VLOG(1) << "Rejecting target due to high pose error ratio " |
| 345 | << target.pose_error_ratio(); |
| 346 | return RejectImage(camera_index, RejectionReason::HIGH_POSE_ERROR_RATIO, |
| 347 | &builder); |
James Kuszmaul | 9da3b7a | 2023-03-11 21:02:25 -0800 | [diff] [blame] | 348 | } |
| 349 | |
| 350 | double theta_at_capture = state_at_capture.value()(StateIdx::kTheta); |
| 351 | double camera_implied_theta = Z(Corrector::kTheta); |
| 352 | constexpr double kDegToRad = M_PI / 180.0; |
| 353 | |
James Kuszmaul | 3c6a968 | 2023-03-23 20:36:53 -0700 | [diff] [blame] | 354 | const double robot_speed = |
| 355 | (state_at_capture.value()(StateIdx::kLeftVelocity) + |
| 356 | state_at_capture.value()(StateIdx::kRightVelocity)) / |
| 357 | 2.0; |
| 358 | const double yaw_threshold = |
| 359 | (utils_.MaybeInAutonomous() ? FLAGS_max_implied_yaw_error |
| 360 | : FLAGS_max_implied_teleop_yaw_error) * |
| 361 | kDegToRad; |
| 362 | if (utils_.MaybeInAutonomous() && |
| 363 | (std::abs(robot_speed) > FLAGS_max_auto_image_robot_speed)) { |
| 364 | return RejectImage(camera_index, RejectionReason::ROBOT_TOO_FAST, &builder); |
| 365 | } else if (std::abs(aos::math::NormalizeAngle( |
| 366 | camera_implied_theta - theta_at_capture)) > yaw_threshold) { |
milind-u | 4860119 | 2023-03-11 19:44:46 -0800 | [diff] [blame] | 367 | return RejectImage(camera_index, RejectionReason::HIGH_IMPLIED_YAW_ERROR, |
| 368 | &builder); |
| 369 | } else if (distance_to_target > FLAGS_max_distance_to_target) { |
| 370 | return RejectImage(camera_index, RejectionReason::HIGH_DISTANCE_TO_TARGET, |
| 371 | &builder); |
James Kuszmaul | 04a343c | 2023-02-20 16:38:22 -0800 | [diff] [blame] | 372 | } |
| 373 | |
| 374 | const Input U = ekf_.MostRecentInput(); |
| 375 | VLOG(1) << "previous state " << ekf_.X_hat().topRows<3>().transpose(); |
James Kuszmaul | e600d17 | 2023-03-12 10:19:44 -0700 | [diff] [blame] | 376 | const State prior_state = ekf_.X_hat(); |
James Kuszmaul | 04a343c | 2023-02-20 16:38:22 -0800 | [diff] [blame] | 377 | // For the correction step, instead of passing in the measurement directly, |
| 378 | // we pass in (0, 0, 0) as the measurement and then for the expected |
| 379 | // measurement (Zhat) we calculate the error between the pose implied by |
| 380 | // the camera measurement and the current estimate of the |
| 381 | // pose. This doesn't affect any of the math, it just makes the code a bit |
| 382 | // more convenient to write given the Correct() interface we already have. |
| 383 | observations_.CorrectKnownH(Eigen::Vector3d::Zero(), &U, |
| 384 | Corrector(state_at_capture.value(), Z), R, t_); |
| 385 | ++total_accepted_targets_; |
| 386 | ++cameras_.at(camera_index).total_accepted_targets; |
| 387 | VLOG(1) << "new state " << ekf_.X_hat().topRows<3>().transpose(); |
James Kuszmaul | e600d17 | 2023-03-12 10:19:44 -0700 | [diff] [blame] | 388 | builder.add_correction_x(ekf_.X_hat()(StateIdx::kX) - |
| 389 | prior_state(StateIdx::kX)); |
| 390 | builder.add_correction_y(ekf_.X_hat()(StateIdx::kY) - |
| 391 | prior_state(StateIdx::kY)); |
| 392 | builder.add_correction_theta(ekf_.X_hat()(StateIdx::kTheta) - |
| 393 | prior_state(StateIdx::kTheta)); |
James Kuszmaul | 7151887 | 2023-02-25 18:00:15 -0800 | [diff] [blame] | 394 | builder.add_accepted(true); |
James Kuszmaul | 04a343c | 2023-02-20 16:38:22 -0800 | [diff] [blame] | 395 | return builder.Finish(); |
| 396 | } |
| 397 | |
| 398 | Localizer::Output Localizer::Corrector::H(const State &, const Input &) { |
| 399 | CHECK(Z_.allFinite()); |
| 400 | Eigen::Vector3d Zhat = H_ * state_at_capture_ - Z_; |
| 401 | // Rewrap angle difference to put it back in range. |
| 402 | Zhat(2) = aos::math::NormalizeAngle(Zhat(2)); |
| 403 | VLOG(1) << "Zhat " << Zhat.transpose() << " Z_ " << Z_.transpose() |
| 404 | << " state " << (H_ * state_at_capture_).transpose(); |
| 405 | return Zhat; |
| 406 | } |
| 407 | |
| 408 | void Localizer::SendOutput() { |
| 409 | auto builder = output_sender_.MakeBuilder(); |
| 410 | frc971::controls::LocalizerOutput::Builder output_builder = |
| 411 | builder.MakeBuilder<frc971::controls::LocalizerOutput>(); |
| 412 | output_builder.add_monotonic_timestamp_ns( |
| 413 | std::chrono::duration_cast<std::chrono::nanoseconds>( |
| 414 | event_loop_->context().monotonic_event_time.time_since_epoch()) |
| 415 | .count()); |
| 416 | output_builder.add_x(ekf_.X_hat(StateIdx::kX)); |
| 417 | output_builder.add_y(ekf_.X_hat(StateIdx::kY)); |
| 418 | output_builder.add_theta(ekf_.X_hat(StateIdx::kTheta)); |
| 419 | output_builder.add_zeroed(imu_watcher_.zeroer().Zeroed()); |
| 420 | output_builder.add_image_accepted_count(total_accepted_targets_); |
| 421 | const Eigen::Quaterniond &orientation = |
| 422 | Eigen::AngleAxis<double>(ekf_.X_hat(StateIdx::kTheta), |
| 423 | Eigen::Vector3d::UnitZ()) * |
| 424 | down_estimator_.X_hat(); |
| 425 | frc971::controls::Quaternion quaternion; |
| 426 | quaternion.mutate_x(orientation.x()); |
| 427 | quaternion.mutate_y(orientation.y()); |
| 428 | quaternion.mutate_z(orientation.z()); |
| 429 | quaternion.mutate_w(orientation.w()); |
| 430 | output_builder.add_orientation(&quaternion); |
| 431 | builder.CheckOk(builder.Send(output_builder.Finish())); |
| 432 | } |
| 433 | |
| 434 | flatbuffers::Offset<frc971::control_loops::drivetrain::LocalizerState> |
James Kuszmaul | e600d17 | 2023-03-12 10:19:44 -0700 | [diff] [blame] | 435 | Localizer::PopulateState(const State &X_hat, |
| 436 | flatbuffers::FlatBufferBuilder *fbb) { |
James Kuszmaul | 04a343c | 2023-02-20 16:38:22 -0800 | [diff] [blame] | 437 | frc971::control_loops::drivetrain::LocalizerState::Builder builder(*fbb); |
James Kuszmaul | e600d17 | 2023-03-12 10:19:44 -0700 | [diff] [blame] | 438 | builder.add_x(X_hat(StateIdx::kX)); |
| 439 | builder.add_y(X_hat(StateIdx::kY)); |
| 440 | builder.add_theta(X_hat(StateIdx::kTheta)); |
| 441 | builder.add_left_velocity(X_hat(StateIdx::kLeftVelocity)); |
| 442 | builder.add_right_velocity(X_hat(StateIdx::kRightVelocity)); |
| 443 | builder.add_left_encoder(X_hat(StateIdx::kLeftEncoder)); |
| 444 | builder.add_right_encoder(X_hat(StateIdx::kRightEncoder)); |
| 445 | builder.add_left_voltage_error(X_hat(StateIdx::kLeftVoltageError)); |
| 446 | builder.add_right_voltage_error(X_hat(StateIdx::kRightVoltageError)); |
| 447 | builder.add_angular_error(X_hat(StateIdx::kAngularError)); |
James Kuszmaul | 04a343c | 2023-02-20 16:38:22 -0800 | [diff] [blame] | 448 | builder.add_longitudinal_velocity_offset( |
James Kuszmaul | e600d17 | 2023-03-12 10:19:44 -0700 | [diff] [blame] | 449 | X_hat(StateIdx::kLongitudinalVelocityOffset)); |
| 450 | builder.add_lateral_velocity(X_hat(StateIdx::kLateralVelocity)); |
James Kuszmaul | 04a343c | 2023-02-20 16:38:22 -0800 | [diff] [blame] | 451 | return builder.Finish(); |
| 452 | } |
| 453 | |
| 454 | flatbuffers::Offset<ImuStatus> Localizer::PopulateImu( |
| 455 | flatbuffers::FlatBufferBuilder *fbb) const { |
| 456 | const auto zeroer_offset = imu_watcher_.zeroer().PopulateStatus(fbb); |
| 457 | const auto failures_offset = imu_watcher_.PopulateImuFailures(fbb); |
| 458 | ImuStatus::Builder builder(*fbb); |
| 459 | builder.add_zeroed(imu_watcher_.zeroer().Zeroed()); |
| 460 | builder.add_faulted_zero(imu_watcher_.zeroer().Faulted()); |
| 461 | builder.add_zeroing(zeroer_offset); |
| 462 | if (imu_watcher_.pico_offset().has_value()) { |
| 463 | builder.add_pico_offset_ns(imu_watcher_.pico_offset().value().count()); |
| 464 | builder.add_pico_offset_error_ns(imu_watcher_.pico_offset_error().count()); |
| 465 | } |
| 466 | if (last_encoder_readings_.has_value()) { |
| 467 | builder.add_left_encoder(last_encoder_readings_.value()(0)); |
| 468 | builder.add_right_encoder(last_encoder_readings_.value()(1)); |
| 469 | } |
| 470 | builder.add_imu_failures(failures_offset); |
| 471 | return builder.Finish(); |
| 472 | } |
| 473 | |
James Kuszmaul | fb89457 | 2023-02-23 17:25:06 -0800 | [diff] [blame] | 474 | flatbuffers::Offset<CumulativeStatistics> Localizer::StatisticsForCamera( |
| 475 | const CameraState &camera, flatbuffers::FlatBufferBuilder *fbb) { |
| 476 | const auto counts_offset = camera.rejection_counter.PopulateCounts(fbb); |
| 477 | CumulativeStatistics::Builder stats_builder(*fbb); |
| 478 | stats_builder.add_total_accepted(camera.total_accepted_targets); |
| 479 | stats_builder.add_total_candidates(camera.total_candidate_targets); |
| 480 | stats_builder.add_rejection_reasons(counts_offset); |
| 481 | return stats_builder.Finish(); |
| 482 | } |
| 483 | |
James Kuszmaul | 04a343c | 2023-02-20 16:38:22 -0800 | [diff] [blame] | 484 | void Localizer::SendStatus() { |
| 485 | auto builder = status_sender_.MakeBuilder(); |
| 486 | std::array<flatbuffers::Offset<CumulativeStatistics>, kNumCameras> |
| 487 | stats_offsets; |
| 488 | for (size_t ii = 0; ii < kNumCameras; ++ii) { |
James Kuszmaul | fb89457 | 2023-02-23 17:25:06 -0800 | [diff] [blame] | 489 | stats_offsets.at(ii) = StatisticsForCamera(cameras_.at(ii), builder.fbb()); |
James Kuszmaul | 04a343c | 2023-02-20 16:38:22 -0800 | [diff] [blame] | 490 | } |
| 491 | auto stats_offset = |
| 492 | builder.fbb()->CreateVector(stats_offsets.data(), stats_offsets.size()); |
| 493 | auto down_estimator_offset = |
| 494 | down_estimator_.PopulateStatus(builder.fbb(), t_); |
| 495 | auto imu_offset = PopulateImu(builder.fbb()); |
James Kuszmaul | e600d17 | 2023-03-12 10:19:44 -0700 | [diff] [blame] | 496 | auto state_offset = PopulateState(ekf_.X_hat(), builder.fbb()); |
James Kuszmaul | 04a343c | 2023-02-20 16:38:22 -0800 | [diff] [blame] | 497 | Status::Builder status_builder = builder.MakeBuilder<Status>(); |
| 498 | status_builder.add_state(state_offset); |
| 499 | status_builder.add_down_estimator(down_estimator_offset); |
| 500 | status_builder.add_imu(imu_offset); |
| 501 | status_builder.add_statistics(stats_offset); |
| 502 | builder.CheckOk(builder.Send(status_builder.Finish())); |
| 503 | } |
| 504 | |
| 505 | } // namespace y2023::localizer |