Milind Upadhyay | 7c20522 | 2022-11-16 18:20:58 -0800 | [diff] [blame] | 1 | #include "frc971/vision/target_mapper.h" |
| 2 | |
Milind Upadhyay | c5beba1 | 2022-12-17 17:41:20 -0800 | [diff] [blame] | 3 | #include "absl/strings/str_format.h" |
Philipp Schrader | 790cb54 | 2023-07-05 21:06:52 -0700 | [diff] [blame] | 4 | |
Milind Upadhyay | 7c20522 | 2022-11-16 18:20:58 -0800 | [diff] [blame] | 5 | #include "frc971/control_loops/control_loop.h" |
Milind Upadhyay | c5beba1 | 2022-12-17 17:41:20 -0800 | [diff] [blame] | 6 | #include "frc971/vision/ceres/pose_graph_3d_error_term.h" |
Milind Upadhyay | 7c20522 | 2022-11-16 18:20:58 -0800 | [diff] [blame] | 7 | #include "frc971/vision/geometry.h" |
| 8 | |
| 9 | DEFINE_uint64(max_num_iterations, 100, |
| 10 | "Maximum number of iterations for the ceres solver"); |
milind-u | d62f80a | 2023-03-04 16:37:09 -0800 | [diff] [blame] | 11 | DEFINE_double(distortion_noise_scalar, 1.0, |
| 12 | "Scale the target pose distortion factor by this when computing " |
| 13 | "the noise."); |
milind-u | 8f4e43e | 2023-04-09 17:11:19 -0700 | [diff] [blame] | 14 | DEFINE_int32( |
milind-u | 6ff399f | 2023-03-24 18:33:38 -0700 | [diff] [blame] | 15 | frozen_target_id, 1, |
| 16 | "Freeze the pose of this target so the map can have one fixed point."); |
milind-u | 8f4e43e | 2023-04-09 17:11:19 -0700 | [diff] [blame] | 17 | DEFINE_int32(min_target_id, 1, "Minimum target id to solve for"); |
| 18 | DEFINE_int32(max_target_id, 8, "Maximum target id to solve for"); |
| 19 | DEFINE_bool(visualize_solver, false, "If true, visualize the solving process."); |
milind-u | 401de98 | 2023-04-14 17:32:03 -0700 | [diff] [blame] | 20 | // This does seem like a strict threshold for a constaint to be considered an |
| 21 | // outlier, but most inliers were very close together and this is what worked |
| 22 | // best for map solving. |
| 23 | DEFINE_double(outlier_std_devs, 1.0, |
| 24 | "Number of standard deviations above average error needed for a " |
| 25 | "constraint to be considered an outlier and get removed."); |
Jim Ostrowski | 463ee59 | 2024-03-07 00:08:24 -0800 | [diff] [blame] | 26 | DEFINE_bool(do_map_fitting, false, |
| 27 | "Whether to do a final fit of the solved map to the original map"); |
Milind Upadhyay | 7c20522 | 2022-11-16 18:20:58 -0800 | [diff] [blame] | 28 | |
| 29 | namespace frc971::vision { |
Milind Upadhyay | c5beba1 | 2022-12-17 17:41:20 -0800 | [diff] [blame] | 30 | Eigen::Affine3d PoseUtils::Pose3dToAffine3d( |
| 31 | const ceres::examples::Pose3d &pose3d) { |
Milind Upadhyay | 7c20522 | 2022-11-16 18:20:58 -0800 | [diff] [blame] | 32 | Eigen::Affine3d H_world_pose = |
Milind Upadhyay | c5beba1 | 2022-12-17 17:41:20 -0800 | [diff] [blame] | 33 | Eigen::Translation3d(pose3d.p(0), pose3d.p(1), pose3d.p(2)) * pose3d.q; |
Milind Upadhyay | 7c20522 | 2022-11-16 18:20:58 -0800 | [diff] [blame] | 34 | return H_world_pose; |
| 35 | } |
| 36 | |
Milind Upadhyay | c5beba1 | 2022-12-17 17:41:20 -0800 | [diff] [blame] | 37 | ceres::examples::Pose3d PoseUtils::Affine3dToPose3d(const Eigen::Affine3d &H) { |
| 38 | return ceres::examples::Pose3d{.p = H.translation(), |
| 39 | .q = Eigen::Quaterniond(H.rotation())}; |
Milind Upadhyay | 7c20522 | 2022-11-16 18:20:58 -0800 | [diff] [blame] | 40 | } |
| 41 | |
Milind Upadhyay | c5beba1 | 2022-12-17 17:41:20 -0800 | [diff] [blame] | 42 | ceres::examples::Pose3d PoseUtils::ComputeRelativePose( |
| 43 | const ceres::examples::Pose3d &pose_1, |
| 44 | const ceres::examples::Pose3d &pose_2) { |
| 45 | Eigen::Affine3d H_world_1 = Pose3dToAffine3d(pose_1); |
| 46 | Eigen::Affine3d H_world_2 = Pose3dToAffine3d(pose_2); |
Milind Upadhyay | 7c20522 | 2022-11-16 18:20:58 -0800 | [diff] [blame] | 47 | |
| 48 | // Get the location of 2 in the 1 frame |
| 49 | Eigen::Affine3d H_1_2 = H_world_1.inverse() * H_world_2; |
Milind Upadhyay | c5beba1 | 2022-12-17 17:41:20 -0800 | [diff] [blame] | 50 | return Affine3dToPose3d(H_1_2); |
Milind Upadhyay | 7c20522 | 2022-11-16 18:20:58 -0800 | [diff] [blame] | 51 | } |
| 52 | |
Milind Upadhyay | c5beba1 | 2022-12-17 17:41:20 -0800 | [diff] [blame] | 53 | ceres::examples::Pose3d PoseUtils::ComputeOffsetPose( |
| 54 | const ceres::examples::Pose3d &pose_1, |
| 55 | const ceres::examples::Pose3d &pose_2_relative) { |
| 56 | auto H_world_1 = Pose3dToAffine3d(pose_1); |
| 57 | auto H_1_2 = Pose3dToAffine3d(pose_2_relative); |
Milind Upadhyay | 7c20522 | 2022-11-16 18:20:58 -0800 | [diff] [blame] | 58 | auto H_world_2 = H_world_1 * H_1_2; |
| 59 | |
Milind Upadhyay | c5beba1 | 2022-12-17 17:41:20 -0800 | [diff] [blame] | 60 | return Affine3dToPose3d(H_world_2); |
Milind Upadhyay | 7c20522 | 2022-11-16 18:20:58 -0800 | [diff] [blame] | 61 | } |
| 62 | |
Milind Upadhyay | c5beba1 | 2022-12-17 17:41:20 -0800 | [diff] [blame] | 63 | Eigen::Quaterniond PoseUtils::EulerAnglesToQuaternion( |
| 64 | const Eigen::Vector3d &rpy) { |
| 65 | Eigen::AngleAxisd roll_angle(rpy.x(), Eigen::Vector3d::UnitX()); |
| 66 | Eigen::AngleAxisd pitch_angle(rpy.y(), Eigen::Vector3d::UnitY()); |
| 67 | Eigen::AngleAxisd yaw_angle(rpy.z(), Eigen::Vector3d::UnitZ()); |
| 68 | |
| 69 | return yaw_angle * pitch_angle * roll_angle; |
Milind Upadhyay | 7c20522 | 2022-11-16 18:20:58 -0800 | [diff] [blame] | 70 | } |
| 71 | |
Milind Upadhyay | c5beba1 | 2022-12-17 17:41:20 -0800 | [diff] [blame] | 72 | Eigen::Vector3d PoseUtils::QuaternionToEulerAngles( |
| 73 | const Eigen::Quaterniond &q) { |
| 74 | return RotationMatrixToEulerAngles(q.toRotationMatrix()); |
Milind Upadhyay | 7c20522 | 2022-11-16 18:20:58 -0800 | [diff] [blame] | 75 | } |
| 76 | |
Milind Upadhyay | c5beba1 | 2022-12-17 17:41:20 -0800 | [diff] [blame] | 77 | Eigen::Vector3d PoseUtils::RotationMatrixToEulerAngles( |
| 78 | const Eigen::Matrix3d &R) { |
| 79 | double roll = aos::math::NormalizeAngle(std::atan2(R(2, 1), R(2, 2))); |
| 80 | double pitch = aos::math::NormalizeAngle(-std::asin(R(2, 0))); |
| 81 | double yaw = aos::math::NormalizeAngle(std::atan2(R(1, 0), R(0, 0))); |
| 82 | |
| 83 | return Eigen::Vector3d(roll, pitch, yaw); |
| 84 | } |
| 85 | |
milind-u | 3f5f83c | 2023-01-29 15:23:51 -0800 | [diff] [blame] | 86 | flatbuffers::Offset<TargetPoseFbs> PoseUtils::TargetPoseToFbs( |
| 87 | const TargetMapper::TargetPose &target_pose, |
| 88 | flatbuffers::FlatBufferBuilder *fbb) { |
| 89 | const auto position_offset = |
| 90 | CreatePosition(*fbb, target_pose.pose.p(0), target_pose.pose.p(1), |
| 91 | target_pose.pose.p(2)); |
| 92 | const auto orientation_offset = |
| 93 | CreateQuaternion(*fbb, target_pose.pose.q.w(), target_pose.pose.q.x(), |
| 94 | target_pose.pose.q.y(), target_pose.pose.q.z()); |
| 95 | return CreateTargetPoseFbs(*fbb, target_pose.id, position_offset, |
| 96 | orientation_offset); |
| 97 | } |
| 98 | |
| 99 | TargetMapper::TargetPose PoseUtils::TargetPoseFromFbs( |
| 100 | const TargetPoseFbs &target_pose_fbs) { |
| 101 | return {.id = static_cast<TargetMapper::TargetId>(target_pose_fbs.id()), |
| 102 | .pose = ceres::examples::Pose3d{ |
| 103 | Eigen::Vector3d(target_pose_fbs.position()->x(), |
| 104 | target_pose_fbs.position()->y(), |
| 105 | target_pose_fbs.position()->z()), |
| 106 | Eigen::Quaterniond(target_pose_fbs.orientation()->w(), |
| 107 | target_pose_fbs.orientation()->x(), |
| 108 | target_pose_fbs.orientation()->y(), |
James Kuszmaul | feb8908 | 2024-02-21 14:00:15 -0800 | [diff] [blame] | 109 | target_pose_fbs.orientation()->z()) |
| 110 | .normalized()}}; |
milind-u | 3f5f83c | 2023-01-29 15:23:51 -0800 | [diff] [blame] | 111 | } |
| 112 | |
Milind Upadhyay | c5beba1 | 2022-12-17 17:41:20 -0800 | [diff] [blame] | 113 | ceres::examples::VectorOfConstraints DataAdapter::MatchTargetDetections( |
Milind Upadhyay | ec49391 | 2022-12-18 21:33:15 -0800 | [diff] [blame] | 114 | const std::vector<DataAdapter::TimestampedDetection> |
| 115 | ×tamped_target_detections, |
| 116 | aos::distributed_clock::duration max_dt) { |
| 117 | CHECK_GE(timestamped_target_detections.size(), 2ul) |
| 118 | << "Must have at least 2 detections"; |
| 119 | |
| 120 | // Match consecutive detections |
Milind Upadhyay | c5beba1 | 2022-12-17 17:41:20 -0800 | [diff] [blame] | 121 | ceres::examples::VectorOfConstraints target_constraints; |
milind-u | d62f80a | 2023-03-04 16:37:09 -0800 | [diff] [blame] | 122 | for (auto detection = timestamped_target_detections.begin() + 1; |
| 123 | detection < timestamped_target_detections.end(); detection++) { |
| 124 | auto last_detection = detection - 1; |
Milind Upadhyay | ec49391 | 2022-12-18 21:33:15 -0800 | [diff] [blame] | 125 | |
| 126 | // Skip two consecutive detections of the same target, because the solver |
| 127 | // doesn't allow this |
milind-u | d62f80a | 2023-03-04 16:37:09 -0800 | [diff] [blame] | 128 | if (detection->id == last_detection->id) { |
Milind Upadhyay | ec49391 | 2022-12-18 21:33:15 -0800 | [diff] [blame] | 129 | continue; |
| 130 | } |
| 131 | |
| 132 | // Don't take into account constraints too far apart in time, because the |
| 133 | // recording device could have moved too much |
milind-u | d62f80a | 2023-03-04 16:37:09 -0800 | [diff] [blame] | 134 | if ((detection->time - last_detection->time) > max_dt) { |
Milind Upadhyay | ec49391 | 2022-12-18 21:33:15 -0800 | [diff] [blame] | 135 | continue; |
| 136 | } |
| 137 | |
milind-u | d62f80a | 2023-03-04 16:37:09 -0800 | [diff] [blame] | 138 | auto confidence = ComputeConfidence(*last_detection, *detection); |
Milind Upadhyay | ec49391 | 2022-12-18 21:33:15 -0800 | [diff] [blame] | 139 | target_constraints.emplace_back( |
milind-u | d62f80a | 2023-03-04 16:37:09 -0800 | [diff] [blame] | 140 | ComputeTargetConstraint(*last_detection, *detection, confidence)); |
Milind Upadhyay | ec49391 | 2022-12-18 21:33:15 -0800 | [diff] [blame] | 141 | } |
| 142 | |
| 143 | return target_constraints; |
| 144 | } |
| 145 | |
Milind Upadhyay | c5beba1 | 2022-12-17 17:41:20 -0800 | [diff] [blame] | 146 | TargetMapper::ConfidenceMatrix DataAdapter::ComputeConfidence( |
milind-u | d62f80a | 2023-03-04 16:37:09 -0800 | [diff] [blame] | 147 | const TimestampedDetection &detection_start, |
| 148 | const TimestampedDetection &detection_end) { |
Milind Upadhyay | 7c20522 | 2022-11-16 18:20:58 -0800 | [diff] [blame] | 149 | constexpr size_t kX = 0; |
| 150 | constexpr size_t kY = 1; |
Milind Upadhyay | c5beba1 | 2022-12-17 17:41:20 -0800 | [diff] [blame] | 151 | constexpr size_t kZ = 2; |
| 152 | constexpr size_t kOrientation1 = 3; |
| 153 | constexpr size_t kOrientation2 = 4; |
| 154 | constexpr size_t kOrientation3 = 5; |
Milind Upadhyay | 7c20522 | 2022-11-16 18:20:58 -0800 | [diff] [blame] | 155 | |
| 156 | // Uncertainty matrix between start and end |
Milind Upadhyay | c5beba1 | 2022-12-17 17:41:20 -0800 | [diff] [blame] | 157 | TargetMapper::ConfidenceMatrix P = TargetMapper::ConfidenceMatrix::Zero(); |
Milind Upadhyay | 7c20522 | 2022-11-16 18:20:58 -0800 | [diff] [blame] | 158 | |
| 159 | { |
| 160 | // Noise for odometry-based robot position measurements |
Milind Upadhyay | c5beba1 | 2022-12-17 17:41:20 -0800 | [diff] [blame] | 161 | TargetMapper::ConfidenceMatrix Q_odometry = |
| 162 | TargetMapper::ConfidenceMatrix::Zero(); |
Milind Upadhyay | 7c20522 | 2022-11-16 18:20:58 -0800 | [diff] [blame] | 163 | Q_odometry(kX, kX) = std::pow(0.045, 2); |
| 164 | Q_odometry(kY, kY) = std::pow(0.045, 2); |
Milind Upadhyay | c5beba1 | 2022-12-17 17:41:20 -0800 | [diff] [blame] | 165 | Q_odometry(kZ, kZ) = std::pow(0.045, 2); |
| 166 | Q_odometry(kOrientation1, kOrientation1) = std::pow(0.01, 2); |
| 167 | Q_odometry(kOrientation2, kOrientation2) = std::pow(0.01, 2); |
| 168 | Q_odometry(kOrientation3, kOrientation3) = std::pow(0.01, 2); |
Milind Upadhyay | 7c20522 | 2022-11-16 18:20:58 -0800 | [diff] [blame] | 169 | |
| 170 | // Add uncertainty for robot position measurements from start to end |
milind-u | d62f80a | 2023-03-04 16:37:09 -0800 | [diff] [blame] | 171 | int iterations = (detection_end.time - detection_start.time) / |
| 172 | frc971::controls::kLoopFrequency; |
Milind Upadhyay | 7c20522 | 2022-11-16 18:20:58 -0800 | [diff] [blame] | 173 | P += static_cast<double>(iterations) * Q_odometry; |
| 174 | } |
| 175 | |
| 176 | { |
Milind Upadhyay | ebf93ee | 2023-01-05 14:12:58 -0800 | [diff] [blame] | 177 | // Noise for vision-based target localizations. Multiplying this matrix by |
milind-u | 6ff399f | 2023-03-24 18:33:38 -0700 | [diff] [blame] | 178 | // the distance from camera to target squared results in the uncertainty |
| 179 | // in that measurement |
Milind Upadhyay | c5beba1 | 2022-12-17 17:41:20 -0800 | [diff] [blame] | 180 | TargetMapper::ConfidenceMatrix Q_vision = |
| 181 | TargetMapper::ConfidenceMatrix::Zero(); |
Milind Upadhyay | ebf93ee | 2023-01-05 14:12:58 -0800 | [diff] [blame] | 182 | Q_vision(kX, kX) = std::pow(0.045, 2); |
| 183 | Q_vision(kY, kY) = std::pow(0.045, 2); |
Milind Upadhyay | c5beba1 | 2022-12-17 17:41:20 -0800 | [diff] [blame] | 184 | Q_vision(kZ, kZ) = std::pow(0.045, 2); |
| 185 | Q_vision(kOrientation1, kOrientation1) = std::pow(0.02, 2); |
| 186 | Q_vision(kOrientation2, kOrientation2) = std::pow(0.02, 2); |
| 187 | Q_vision(kOrientation3, kOrientation3) = std::pow(0.02, 2); |
Milind Upadhyay | 7c20522 | 2022-11-16 18:20:58 -0800 | [diff] [blame] | 188 | |
| 189 | // Add uncertainty for the 2 vision measurements (1 at start and 1 at end) |
milind-u | fbc5c81 | 2023-04-06 21:24:29 -0700 | [diff] [blame] | 190 | P += Q_vision * std::pow(detection_start.distance_from_camera * |
| 191 | (1.0 + FLAGS_distortion_noise_scalar * |
| 192 | detection_start.distortion_factor), |
| 193 | 2); |
| 194 | P += Q_vision * std::pow(detection_end.distance_from_camera * |
| 195 | (1.0 + FLAGS_distortion_noise_scalar * |
| 196 | detection_end.distortion_factor), |
| 197 | 2); |
Milind Upadhyay | 7c20522 | 2022-11-16 18:20:58 -0800 | [diff] [blame] | 198 | } |
| 199 | |
| 200 | return P.inverse(); |
| 201 | } |
| 202 | |
Milind Upadhyay | c5beba1 | 2022-12-17 17:41:20 -0800 | [diff] [blame] | 203 | ceres::examples::Constraint3d DataAdapter::ComputeTargetConstraint( |
Milind Upadhyay | 7c20522 | 2022-11-16 18:20:58 -0800 | [diff] [blame] | 204 | const TimestampedDetection &target_detection_start, |
Milind Upadhyay | 7c20522 | 2022-11-16 18:20:58 -0800 | [diff] [blame] | 205 | const TimestampedDetection &target_detection_end, |
Milind Upadhyay | c5beba1 | 2022-12-17 17:41:20 -0800 | [diff] [blame] | 206 | const TargetMapper::ConfidenceMatrix &confidence) { |
Milind Upadhyay | 7c20522 | 2022-11-16 18:20:58 -0800 | [diff] [blame] | 207 | // Compute the relative pose (constraint) between the two targets |
| 208 | Eigen::Affine3d H_targetstart_targetend = |
Milind Upadhyay | c5beba1 | 2022-12-17 17:41:20 -0800 | [diff] [blame] | 209 | target_detection_start.H_robot_target.inverse() * |
Milind Upadhyay | 7c20522 | 2022-11-16 18:20:58 -0800 | [diff] [blame] | 210 | target_detection_end.H_robot_target; |
Milind Upadhyay | c5beba1 | 2022-12-17 17:41:20 -0800 | [diff] [blame] | 211 | ceres::examples::Pose3d target_constraint = |
| 212 | PoseUtils::Affine3dToPose3d(H_targetstart_targetend); |
Milind Upadhyay | 7c20522 | 2022-11-16 18:20:58 -0800 | [diff] [blame] | 213 | |
milind-u | f3ab8ba | 2023-02-04 17:56:16 -0800 | [diff] [blame] | 214 | const auto constraint_3d = |
| 215 | ceres::examples::Constraint3d{target_detection_start.id, |
| 216 | target_detection_end.id, |
| 217 | {target_constraint.p, target_constraint.q}, |
| 218 | confidence}; |
| 219 | |
| 220 | VLOG(2) << "Computed constraint: " << constraint_3d; |
| 221 | return constraint_3d; |
Milind Upadhyay | ec49391 | 2022-12-18 21:33:15 -0800 | [diff] [blame] | 222 | } |
| 223 | |
Milind Upadhyay | 7c20522 | 2022-11-16 18:20:58 -0800 | [diff] [blame] | 224 | TargetMapper::TargetMapper( |
Milind Upadhyay | cd677a3 | 2022-12-04 13:06:43 -0800 | [diff] [blame] | 225 | std::string_view target_poses_path, |
Milind Upadhyay | c5beba1 | 2022-12-17 17:41:20 -0800 | [diff] [blame] | 226 | const ceres::examples::VectorOfConstraints &target_constraints) |
milind-u | 8f4e43e | 2023-04-09 17:11:19 -0700 | [diff] [blame] | 227 | : target_constraints_(target_constraints), |
| 228 | T_frozen_actual_(Eigen::Vector3d::Zero()), |
| 229 | R_frozen_actual_(Eigen::Quaterniond::Identity()), |
Jim Ostrowski | 68e5617 | 2023-09-17 23:44:15 -0700 | [diff] [blame] | 230 | vis_robot_(cv::Size(kImageWidth_, kImageHeight_)) { |
Jim Ostrowski | 4527dd7 | 2024-03-07 00:20:15 -0800 | [diff] [blame^] | 231 | // Compute focal length so that image shows field with viewpoint at 10m above |
| 232 | // it (default for viewer) |
| 233 | const double focal_length = kImageWidth_ * 10.0 / kFieldWidth_; |
| 234 | vis_robot_.SetDefaultViewpoint(kImageWidth_, focal_length); |
| 235 | |
Milind Upadhyay | cd677a3 | 2022-12-04 13:06:43 -0800 | [diff] [blame] | 236 | aos::FlatbufferDetachedBuffer<TargetMap> target_map = |
| 237 | aos::JsonFileToFlatbuffer<TargetMap>(target_poses_path); |
| 238 | for (const auto *target_pose_fbs : *target_map.message().target_poses()) { |
milind-u | 8f4e43e | 2023-04-09 17:11:19 -0700 | [diff] [blame] | 239 | ideal_target_poses_[target_pose_fbs->id()] = |
milind-u | 3f5f83c | 2023-01-29 15:23:51 -0800 | [diff] [blame] | 240 | PoseUtils::TargetPoseFromFbs(*target_pose_fbs).pose; |
Milind Upadhyay | cd677a3 | 2022-12-04 13:06:43 -0800 | [diff] [blame] | 241 | } |
milind-u | 8f4e43e | 2023-04-09 17:11:19 -0700 | [diff] [blame] | 242 | target_poses_ = ideal_target_poses_; |
milind-u | 526d567 | 2023-04-17 20:09:10 -0700 | [diff] [blame] | 243 | CountConstraints(); |
Milind Upadhyay | cd677a3 | 2022-12-04 13:06:43 -0800 | [diff] [blame] | 244 | } |
| 245 | |
| 246 | TargetMapper::TargetMapper( |
Milind Upadhyay | c5beba1 | 2022-12-17 17:41:20 -0800 | [diff] [blame] | 247 | const ceres::examples::MapOfPoses &target_poses, |
| 248 | const ceres::examples::VectorOfConstraints &target_constraints) |
milind-u | 8f4e43e | 2023-04-09 17:11:19 -0700 | [diff] [blame] | 249 | : ideal_target_poses_(target_poses), |
| 250 | target_poses_(ideal_target_poses_), |
| 251 | target_constraints_(target_constraints), |
| 252 | T_frozen_actual_(Eigen::Vector3d::Zero()), |
| 253 | R_frozen_actual_(Eigen::Quaterniond::Identity()), |
Jim Ostrowski | 68e5617 | 2023-09-17 23:44:15 -0700 | [diff] [blame] | 254 | vis_robot_(cv::Size(kImageWidth_, kImageHeight_)) { |
milind-u | 526d567 | 2023-04-17 20:09:10 -0700 | [diff] [blame] | 255 | CountConstraints(); |
| 256 | } |
| 257 | |
| 258 | namespace { |
| 259 | std::pair<TargetMapper::TargetId, TargetMapper::TargetId> MakeIdPair( |
| 260 | const ceres::examples::Constraint3d &constraint) { |
| 261 | auto min_id = std::min(constraint.id_begin, constraint.id_end); |
| 262 | auto max_id = std::max(constraint.id_begin, constraint.id_end); |
| 263 | return std::make_pair(min_id, max_id); |
| 264 | } |
| 265 | } // namespace |
| 266 | |
| 267 | void TargetMapper::CountConstraints() { |
| 268 | for (const auto &constraint : target_constraints_) { |
| 269 | auto id_pair = MakeIdPair(constraint); |
| 270 | if (constraint_counts_.count(id_pair) == 0) { |
| 271 | constraint_counts_[id_pair] = 0; |
| 272 | } |
| 273 | constraint_counts_[id_pair]++; |
| 274 | } |
| 275 | } |
Milind Upadhyay | 7c20522 | 2022-11-16 18:20:58 -0800 | [diff] [blame] | 276 | |
| 277 | std::optional<TargetMapper::TargetPose> TargetMapper::GetTargetPoseById( |
| 278 | std::vector<TargetMapper::TargetPose> target_poses, TargetId target_id) { |
| 279 | for (auto target_pose : target_poses) { |
| 280 | if (target_pose.id == target_id) { |
| 281 | return target_pose; |
| 282 | } |
| 283 | } |
| 284 | |
| 285 | return std::nullopt; |
| 286 | } |
| 287 | |
Jim Ostrowski | 49be823 | 2023-03-23 01:00:14 -0700 | [diff] [blame] | 288 | std::optional<TargetMapper::TargetPose> TargetMapper::GetTargetPoseById( |
milind-u | 2ab4db1 | 2023-03-25 21:59:23 -0700 | [diff] [blame] | 289 | TargetId target_id) const { |
Jim Ostrowski | 49be823 | 2023-03-23 01:00:14 -0700 | [diff] [blame] | 290 | if (target_poses_.count(target_id) > 0) { |
milind-u | 2ab4db1 | 2023-03-25 21:59:23 -0700 | [diff] [blame] | 291 | return TargetMapper::TargetPose{target_id, target_poses_.at(target_id)}; |
Jim Ostrowski | 49be823 | 2023-03-23 01:00:14 -0700 | [diff] [blame] | 292 | } |
| 293 | |
| 294 | return std::nullopt; |
| 295 | } |
| 296 | |
Milind Upadhyay | c5beba1 | 2022-12-17 17:41:20 -0800 | [diff] [blame] | 297 | // Taken from ceres/examples/slam/pose_graph_3d/pose_graph_3d.cc |
| 298 | // Constructs the nonlinear least squares optimization problem from the pose |
| 299 | // graph constraints. |
milind-u | 8f4e43e | 2023-04-09 17:11:19 -0700 | [diff] [blame] | 300 | void TargetMapper::BuildTargetPoseOptimizationProblem( |
Milind Upadhyay | c5beba1 | 2022-12-17 17:41:20 -0800 | [diff] [blame] | 301 | const ceres::examples::VectorOfConstraints &constraints, |
| 302 | ceres::examples::MapOfPoses *poses, ceres::Problem *problem) { |
| 303 | CHECK(poses != nullptr); |
| 304 | CHECK(problem != nullptr); |
Milind Upadhyay | 7c20522 | 2022-11-16 18:20:58 -0800 | [diff] [blame] | 305 | if (constraints.empty()) { |
Milind Upadhyay | c5beba1 | 2022-12-17 17:41:20 -0800 | [diff] [blame] | 306 | LOG(INFO) << "No constraints, no problem to optimize."; |
Milind Upadhyay | 7c20522 | 2022-11-16 18:20:58 -0800 | [diff] [blame] | 307 | return; |
| 308 | } |
| 309 | |
milind-u | 13ff1a5 | 2023-01-22 17:10:49 -0800 | [diff] [blame] | 310 | ceres::LossFunction *loss_function = new ceres::HuberLoss(2.0); |
Milind Upadhyay | c5beba1 | 2022-12-17 17:41:20 -0800 | [diff] [blame] | 311 | ceres::LocalParameterization *quaternion_local_parameterization = |
| 312 | new ceres::EigenQuaternionParameterization; |
Milind Upadhyay | 7c20522 | 2022-11-16 18:20:58 -0800 | [diff] [blame] | 313 | |
Jim Ostrowski | 2f2685f | 2023-03-25 11:57:54 -0700 | [diff] [blame] | 314 | int min_constraint_id = std::numeric_limits<int>::max(); |
| 315 | int max_constraint_id = std::numeric_limits<int>::min(); |
| 316 | |
Milind Upadhyay | c5beba1 | 2022-12-17 17:41:20 -0800 | [diff] [blame] | 317 | for (ceres::examples::VectorOfConstraints::const_iterator constraints_iter = |
| 318 | constraints.begin(); |
Milind Upadhyay | 7c20522 | 2022-11-16 18:20:58 -0800 | [diff] [blame] | 319 | constraints_iter != constraints.end(); ++constraints_iter) { |
Milind Upadhyay | c5beba1 | 2022-12-17 17:41:20 -0800 | [diff] [blame] | 320 | const ceres::examples::Constraint3d &constraint = *constraints_iter; |
Milind Upadhyay | 7c20522 | 2022-11-16 18:20:58 -0800 | [diff] [blame] | 321 | |
Milind Upadhyay | c5beba1 | 2022-12-17 17:41:20 -0800 | [diff] [blame] | 322 | ceres::examples::MapOfPoses::iterator pose_begin_iter = |
Milind Upadhyay | 7c20522 | 2022-11-16 18:20:58 -0800 | [diff] [blame] | 323 | poses->find(constraint.id_begin); |
| 324 | CHECK(pose_begin_iter != poses->end()) |
| 325 | << "Pose with ID: " << constraint.id_begin << " not found."; |
Milind Upadhyay | c5beba1 | 2022-12-17 17:41:20 -0800 | [diff] [blame] | 326 | ceres::examples::MapOfPoses::iterator pose_end_iter = |
Milind Upadhyay | 7c20522 | 2022-11-16 18:20:58 -0800 | [diff] [blame] | 327 | poses->find(constraint.id_end); |
| 328 | CHECK(pose_end_iter != poses->end()) |
| 329 | << "Pose with ID: " << constraint.id_end << " not found."; |
| 330 | |
Milind Upadhyay | c5beba1 | 2022-12-17 17:41:20 -0800 | [diff] [blame] | 331 | const Eigen::Matrix<double, 6, 6> sqrt_information = |
Milind Upadhyay | 7c20522 | 2022-11-16 18:20:58 -0800 | [diff] [blame] | 332 | constraint.information.llt().matrixL(); |
milind-u | 526d567 | 2023-04-17 20:09:10 -0700 | [diff] [blame] | 333 | |
| 334 | auto id_pair = MakeIdPair(constraint); |
| 335 | CHECK_GT(constraint_counts_.count(id_pair), 0ul) |
| 336 | << "Should have counted constraints for " << id_pair.first << "->" |
| 337 | << id_pair.second; |
| 338 | |
Jim Ostrowski | 2f2685f | 2023-03-25 11:57:54 -0700 | [diff] [blame] | 339 | VLOG(1) << "Adding constraint pair: " << id_pair.first << " and " |
| 340 | << id_pair.second; |
| 341 | // Store min & max id's; assumes first id < second id |
| 342 | if (id_pair.first < min_constraint_id) { |
| 343 | min_constraint_id = id_pair.first; |
| 344 | } |
| 345 | if (id_pair.second > max_constraint_id) { |
| 346 | max_constraint_id = id_pair.second; |
| 347 | } |
Jim Ostrowski | 4527dd7 | 2024-03-07 00:20:15 -0800 | [diff] [blame^] | 348 | // Normalize constraint cost by occurrences |
milind-u | 526d567 | 2023-04-17 20:09:10 -0700 | [diff] [blame] | 349 | size_t constraint_count = constraint_counts_[id_pair]; |
| 350 | // Scale all costs so the total cost comes out to more reasonable numbers |
| 351 | constexpr double kGlobalWeight = 1000.0; |
| 352 | double constraint_weight = |
| 353 | kGlobalWeight / static_cast<double>(constraint_count); |
| 354 | |
Milind Upadhyay | 7c20522 | 2022-11-16 18:20:58 -0800 | [diff] [blame] | 355 | // Ceres will take ownership of the pointer. |
| 356 | ceres::CostFunction *cost_function = |
milind-u | 526d567 | 2023-04-17 20:09:10 -0700 | [diff] [blame] | 357 | ceres::examples::PoseGraph3dErrorTerm::Create( |
| 358 | constraint.t_be, sqrt_information, constraint_weight); |
Milind Upadhyay | 7c20522 | 2022-11-16 18:20:58 -0800 | [diff] [blame] | 359 | |
Milind Upadhyay | c5beba1 | 2022-12-17 17:41:20 -0800 | [diff] [blame] | 360 | problem->AddResidualBlock(cost_function, loss_function, |
| 361 | pose_begin_iter->second.p.data(), |
| 362 | pose_begin_iter->second.q.coeffs().data(), |
| 363 | pose_end_iter->second.p.data(), |
| 364 | pose_end_iter->second.q.coeffs().data()); |
| 365 | |
| 366 | problem->SetParameterization(pose_begin_iter->second.q.coeffs().data(), |
| 367 | quaternion_local_parameterization); |
| 368 | problem->SetParameterization(pose_end_iter->second.q.coeffs().data(), |
| 369 | quaternion_local_parameterization); |
Milind Upadhyay | 7c20522 | 2022-11-16 18:20:58 -0800 | [diff] [blame] | 370 | } |
| 371 | |
Milind Upadhyay | c5beba1 | 2022-12-17 17:41:20 -0800 | [diff] [blame] | 372 | // The pose graph optimization problem has six DOFs that are not fully |
milind-u | 3f5f83c | 2023-01-29 15:23:51 -0800 | [diff] [blame] | 373 | // constrained. This is typically referred to as gauge freedom. You can |
| 374 | // apply a rigid body transformation to all the nodes and the optimization |
| 375 | // problem will still have the exact same cost. The Levenberg-Marquardt |
| 376 | // algorithm has internal damping which mitigates this issue, but it is |
| 377 | // better to properly constrain the gauge freedom. This can be done by |
| 378 | // setting one of the poses as constant so the optimizer cannot change it. |
milind-u | 6ff399f | 2023-03-24 18:33:38 -0700 | [diff] [blame] | 379 | CHECK_NE(poses->count(FLAGS_frozen_target_id), 0ul) |
| 380 | << "Got no poses for frozen target id " << FLAGS_frozen_target_id; |
Jim Ostrowski | 2f2685f | 2023-03-25 11:57:54 -0700 | [diff] [blame] | 381 | CHECK_GE(FLAGS_frozen_target_id, min_constraint_id) |
| 382 | << "target to freeze index " << FLAGS_frozen_target_id |
| 383 | << " must be in range of constraints, > " << min_constraint_id; |
| 384 | CHECK_LE(FLAGS_frozen_target_id, max_constraint_id) |
| 385 | << "target to freeze index " << FLAGS_frozen_target_id |
| 386 | << " must be in range of constraints, < " << max_constraint_id; |
milind-u | 6ff399f | 2023-03-24 18:33:38 -0700 | [diff] [blame] | 387 | ceres::examples::MapOfPoses::iterator pose_start_iter = |
| 388 | poses->find(FLAGS_frozen_target_id); |
Milind Upadhyay | 7c20522 | 2022-11-16 18:20:58 -0800 | [diff] [blame] | 389 | CHECK(pose_start_iter != poses->end()) << "There are no poses."; |
Milind Upadhyay | c5beba1 | 2022-12-17 17:41:20 -0800 | [diff] [blame] | 390 | problem->SetParameterBlockConstant(pose_start_iter->second.p.data()); |
| 391 | problem->SetParameterBlockConstant(pose_start_iter->second.q.coeffs().data()); |
Milind Upadhyay | 7c20522 | 2022-11-16 18:20:58 -0800 | [diff] [blame] | 392 | } |
| 393 | |
milind-u | 401de98 | 2023-04-14 17:32:03 -0700 | [diff] [blame] | 394 | std::unique_ptr<ceres::CostFunction> |
| 395 | TargetMapper::BuildMapFittingOptimizationProblem(ceres::Problem *problem) { |
Philipp Schrader | a671252 | 2023-07-05 20:25:11 -0700 | [diff] [blame] | 396 | // Set up robot visualization. |
milind-u | 8f4e43e | 2023-04-09 17:11:19 -0700 | [diff] [blame] | 397 | vis_robot_.ClearImage(); |
milind-u | 8f4e43e | 2023-04-09 17:11:19 -0700 | [diff] [blame] | 398 | |
| 399 | const size_t num_targets = FLAGS_max_target_id - FLAGS_min_target_id; |
| 400 | // Translation and rotation error for each target |
| 401 | const size_t num_residuals = num_targets * 6; |
| 402 | // Set up the only cost function (also known as residual). This uses |
| 403 | // auto-differentiation to obtain the derivative (jacobian). |
milind-u | 401de98 | 2023-04-14 17:32:03 -0700 | [diff] [blame] | 404 | std::unique_ptr<ceres::CostFunction> cost_function = std::make_unique< |
| 405 | ceres::AutoDiffCostFunction<TargetMapper, ceres::DYNAMIC, 3, 4>>( |
| 406 | this, num_residuals, ceres::DO_NOT_TAKE_OWNERSHIP); |
milind-u | 8f4e43e | 2023-04-09 17:11:19 -0700 | [diff] [blame] | 407 | |
| 408 | ceres::LossFunction *loss_function = new ceres::HuberLoss(2.0); |
| 409 | ceres::LocalParameterization *quaternion_local_parameterization = |
| 410 | new ceres::EigenQuaternionParameterization; |
| 411 | |
milind-u | 401de98 | 2023-04-14 17:32:03 -0700 | [diff] [blame] | 412 | problem->AddResidualBlock(cost_function.get(), loss_function, |
milind-u | 8f4e43e | 2023-04-09 17:11:19 -0700 | [diff] [blame] | 413 | T_frozen_actual_.vector().data(), |
| 414 | R_frozen_actual_.coeffs().data()); |
| 415 | problem->SetParameterization(R_frozen_actual_.coeffs().data(), |
| 416 | quaternion_local_parameterization); |
milind-u | 401de98 | 2023-04-14 17:32:03 -0700 | [diff] [blame] | 417 | return cost_function; |
milind-u | 8f4e43e | 2023-04-09 17:11:19 -0700 | [diff] [blame] | 418 | } |
| 419 | |
Jim Ostrowski | 4527dd7 | 2024-03-07 00:20:15 -0800 | [diff] [blame^] | 420 | void TargetMapper::DisplayConstraintGraph() { |
| 421 | vis_robot_.ClearImage(); |
| 422 | for (auto constraint : constraint_counts_) { |
| 423 | Eigen::Vector3d start_line = |
| 424 | PoseUtils::Pose3dToAffine3d( |
| 425 | ideal_target_poses_.at(constraint.first.first)) |
| 426 | .translation(); |
| 427 | Eigen::Vector3d end_line = |
| 428 | PoseUtils::Pose3dToAffine3d( |
| 429 | ideal_target_poses_.at(constraint.first.second)) |
| 430 | .translation(); |
| 431 | // Weight the green intensity by # of constraints |
| 432 | // TODO: This could be improved |
| 433 | int color_scale = |
| 434 | 50 + std::min(155, static_cast<int>(constraint.second * 155.0 / 200.0)); |
| 435 | vis_robot_.DrawLine(start_line, end_line, cv::Scalar(0, color_scale, 0)); |
| 436 | } |
| 437 | |
| 438 | for (const auto &[id, solved_pose] : target_poses_) { |
| 439 | Eigen::Affine3d H_world_ideal = |
| 440 | PoseUtils::Pose3dToAffine3d(ideal_target_poses_.at(id)); |
| 441 | vis_robot_.DrawFrameAxes(H_world_ideal, std::to_string(id), |
| 442 | cv::Scalar(255, 255, 255)); |
| 443 | } |
| 444 | cv::imshow("Constraint graph", vis_robot_.image_); |
| 445 | cv::waitKey(0); |
| 446 | } |
| 447 | |
Milind Upadhyay | c5beba1 | 2022-12-17 17:41:20 -0800 | [diff] [blame] | 448 | // Taken from ceres/examples/slam/pose_graph_3d/pose_graph_3d.cc |
Milind Upadhyay | 7c20522 | 2022-11-16 18:20:58 -0800 | [diff] [blame] | 449 | bool TargetMapper::SolveOptimizationProblem(ceres::Problem *problem) { |
| 450 | CHECK_NOTNULL(problem); |
| 451 | |
| 452 | ceres::Solver::Options options; |
| 453 | options.max_num_iterations = FLAGS_max_num_iterations; |
| 454 | options.linear_solver_type = ceres::SPARSE_NORMAL_CHOLESKY; |
milind-u | 401de98 | 2023-04-14 17:32:03 -0700 | [diff] [blame] | 455 | options.minimizer_progress_to_stdout = false; |
Milind Upadhyay | 7c20522 | 2022-11-16 18:20:58 -0800 | [diff] [blame] | 456 | |
| 457 | ceres::Solver::Summary summary; |
| 458 | ceres::Solve(options, problem, &summary); |
| 459 | |
Milind Upadhyay | cd677a3 | 2022-12-04 13:06:43 -0800 | [diff] [blame] | 460 | LOG(INFO) << summary.FullReport() << '\n'; |
Milind Upadhyay | 7c20522 | 2022-11-16 18:20:58 -0800 | [diff] [blame] | 461 | |
| 462 | return summary.IsSolutionUsable(); |
| 463 | } |
| 464 | |
Milind Upadhyay | 05652cb | 2022-12-07 20:51:51 -0800 | [diff] [blame] | 465 | void TargetMapper::Solve(std::string_view field_name, |
| 466 | std::optional<std::string_view> output_dir) { |
milind-u | 401de98 | 2023-04-14 17:32:03 -0700 | [diff] [blame] | 467 | ceres::Problem target_pose_problem_1; |
milind-u | 8f4e43e | 2023-04-09 17:11:19 -0700 | [diff] [blame] | 468 | BuildTargetPoseOptimizationProblem(target_constraints_, &target_poses_, |
milind-u | 401de98 | 2023-04-14 17:32:03 -0700 | [diff] [blame] | 469 | &target_pose_problem_1); |
| 470 | CHECK(SolveOptimizationProblem(&target_pose_problem_1)) |
| 471 | << "The target pose solve 1 was not successful, exiting."; |
Milind Upadhyay | 7c20522 | 2022-11-16 18:20:58 -0800 | [diff] [blame] | 472 | |
milind-u | 401de98 | 2023-04-14 17:32:03 -0700 | [diff] [blame] | 473 | RemoveOutlierConstraints(); |
| 474 | |
Jim Ostrowski | 4527dd7 | 2024-03-07 00:20:15 -0800 | [diff] [blame^] | 475 | if (FLAGS_visualize_solver) { |
| 476 | LOG(INFO) << "Displaying constraint graph after removing outliers"; |
| 477 | DisplayConstraintGraph(); |
| 478 | } |
| 479 | |
milind-u | 401de98 | 2023-04-14 17:32:03 -0700 | [diff] [blame] | 480 | // Solve again once we've thrown out bad constraints |
| 481 | ceres::Problem target_pose_problem_2; |
| 482 | BuildTargetPoseOptimizationProblem(target_constraints_, &target_poses_, |
| 483 | &target_pose_problem_2); |
| 484 | CHECK(SolveOptimizationProblem(&target_pose_problem_2)) |
| 485 | << "The target pose solve 2 was not successful, exiting."; |
| 486 | |
Jim Ostrowski | 463ee59 | 2024-03-07 00:08:24 -0800 | [diff] [blame] | 487 | if (FLAGS_do_map_fitting) { |
| 488 | LOG(INFO) << "Solving the overall map's best alignment to the previous map"; |
| 489 | ceres::Problem map_fitting_problem( |
| 490 | {.loss_function_ownership = ceres::DO_NOT_TAKE_OWNERSHIP}); |
| 491 | std::unique_ptr<ceres::CostFunction> map_fitting_cost_function = |
| 492 | BuildMapFittingOptimizationProblem(&map_fitting_problem); |
| 493 | CHECK(SolveOptimizationProblem(&map_fitting_problem)) |
| 494 | << "The map fitting solve was not successful, exiting."; |
| 495 | map_fitting_cost_function.release(); |
milind-u | 8f4e43e | 2023-04-09 17:11:19 -0700 | [diff] [blame] | 496 | |
Jim Ostrowski | 463ee59 | 2024-03-07 00:08:24 -0800 | [diff] [blame] | 497 | Eigen::Affine3d H_frozen_actual = T_frozen_actual_ * R_frozen_actual_; |
| 498 | LOG(INFO) << "H_frozen_actual: " |
| 499 | << PoseUtils::Affine3dToPose3d(H_frozen_actual); |
milind-u | 8f4e43e | 2023-04-09 17:11:19 -0700 | [diff] [blame] | 500 | |
Jim Ostrowski | 463ee59 | 2024-03-07 00:08:24 -0800 | [diff] [blame] | 501 | auto H_world_frozen = |
| 502 | PoseUtils::Pose3dToAffine3d(target_poses_[FLAGS_frozen_target_id]); |
| 503 | auto H_world_frozenactual = H_world_frozen * H_frozen_actual; |
milind-u | 8f4e43e | 2023-04-09 17:11:19 -0700 | [diff] [blame] | 504 | |
Jim Ostrowski | 463ee59 | 2024-03-07 00:08:24 -0800 | [diff] [blame] | 505 | // Offset the solved poses to become the actual ones |
| 506 | for (auto &[id, pose] : target_poses_) { |
| 507 | // Don't offset targets we didn't solve for |
| 508 | if (id < FLAGS_min_target_id || id > FLAGS_max_target_id) { |
| 509 | continue; |
| 510 | } |
| 511 | |
| 512 | // Take the delta between the frozen target and the solved target, and put |
| 513 | // that on top of the actual pose of the frozen target |
| 514 | auto H_world_solved = PoseUtils::Pose3dToAffine3d(pose); |
| 515 | auto H_frozen_solved = H_world_frozen.inverse() * H_world_solved; |
| 516 | auto H_world_actual = H_world_frozenactual * H_frozen_solved; |
| 517 | pose = PoseUtils::Affine3dToPose3d(H_world_actual); |
milind-u | 8f4e43e | 2023-04-09 17:11:19 -0700 | [diff] [blame] | 518 | } |
milind-u | 8f4e43e | 2023-04-09 17:11:19 -0700 | [diff] [blame] | 519 | } |
Milind Upadhyay | 7c20522 | 2022-11-16 18:20:58 -0800 | [diff] [blame] | 520 | |
Milind Upadhyay | 05652cb | 2022-12-07 20:51:51 -0800 | [diff] [blame] | 521 | auto map_json = MapToJson(field_name); |
Milind Upadhyay | cd677a3 | 2022-12-04 13:06:43 -0800 | [diff] [blame] | 522 | VLOG(1) << "Solved target poses: " << map_json; |
Milind Upadhyay | 05652cb | 2022-12-07 20:51:51 -0800 | [diff] [blame] | 523 | |
| 524 | if (output_dir.has_value()) { |
| 525 | std::string output_path = |
| 526 | absl::StrCat(output_dir.value(), "/", field_name, ".json"); |
| 527 | LOG(INFO) << "Writing map to file: " << output_path; |
| 528 | aos::util::WriteStringToFileOrDie(output_path, map_json); |
Milind Upadhyay | cd677a3 | 2022-12-04 13:06:43 -0800 | [diff] [blame] | 529 | } |
milind-u | 401de98 | 2023-04-14 17:32:03 -0700 | [diff] [blame] | 530 | |
| 531 | for (TargetId id_start = FLAGS_min_target_id; id_start < FLAGS_max_target_id; |
| 532 | id_start++) { |
| 533 | for (TargetId id_end = id_start + 1; id_end <= FLAGS_max_target_id; |
| 534 | id_end++) { |
| 535 | auto H_start_end = |
| 536 | PoseUtils::Pose3dToAffine3d(target_poses_.at(id_start)).inverse() * |
| 537 | PoseUtils::Pose3dToAffine3d(target_poses_.at(id_end)); |
| 538 | auto constraint = PoseUtils::Affine3dToPose3d(H_start_end); |
Jim Ostrowski | 2f2685f | 2023-03-25 11:57:54 -0700 | [diff] [blame] | 539 | VLOG(1) << id_start << "->" << id_end << ": " << constraint.p.norm() |
| 540 | << " meters"; |
milind-u | 401de98 | 2023-04-14 17:32:03 -0700 | [diff] [blame] | 541 | } |
| 542 | } |
Milind Upadhyay | cd677a3 | 2022-12-04 13:06:43 -0800 | [diff] [blame] | 543 | } |
| 544 | |
Milind Upadhyay | 05652cb | 2022-12-07 20:51:51 -0800 | [diff] [blame] | 545 | std::string TargetMapper::MapToJson(std::string_view field_name) const { |
Milind Upadhyay | cd677a3 | 2022-12-04 13:06:43 -0800 | [diff] [blame] | 546 | flatbuffers::FlatBufferBuilder fbb; |
| 547 | |
| 548 | // Convert poses to flatbuffers |
| 549 | std::vector<flatbuffers::Offset<TargetPoseFbs>> target_poses_fbs; |
| 550 | for (const auto &[id, pose] : target_poses_) { |
milind-u | 3f5f83c | 2023-01-29 15:23:51 -0800 | [diff] [blame] | 551 | target_poses_fbs.emplace_back( |
| 552 | PoseUtils::TargetPoseToFbs(TargetPose{.id = id, .pose = pose}, &fbb)); |
Milind Upadhyay | cd677a3 | 2022-12-04 13:06:43 -0800 | [diff] [blame] | 553 | } |
| 554 | |
Milind Upadhyay | 05652cb | 2022-12-07 20:51:51 -0800 | [diff] [blame] | 555 | const auto field_name_offset = fbb.CreateString(field_name); |
| 556 | flatbuffers::Offset<TargetMap> target_map_offset = CreateTargetMap( |
| 557 | fbb, fbb.CreateVector(target_poses_fbs), field_name_offset); |
Milind Upadhyay | cd677a3 | 2022-12-04 13:06:43 -0800 | [diff] [blame] | 558 | |
| 559 | return aos::FlatbufferToJson( |
| 560 | flatbuffers::GetMutableTemporaryPointer(fbb, target_map_offset), |
| 561 | {.multi_line = true}); |
Milind Upadhyay | 7c20522 | 2022-11-16 18:20:58 -0800 | [diff] [blame] | 562 | } |
| 563 | |
milind-u | 8f4e43e | 2023-04-09 17:11:19 -0700 | [diff] [blame] | 564 | namespace { |
milind-u | 8f4e43e | 2023-04-09 17:11:19 -0700 | [diff] [blame] | 565 | // Hacks to extract a double from a scalar, which is either a ceres jet or a |
| 566 | // double. Only used for debugging and displaying. |
| 567 | template <typename S> |
| 568 | double ScalarToDouble(S s) { |
| 569 | const double *ptr = reinterpret_cast<double *>(&s); |
| 570 | return *ptr; |
| 571 | } |
| 572 | |
| 573 | template <typename S> |
| 574 | Eigen::Affine3d ScalarAffineToDouble(Eigen::Transform<S, 3, Eigen::Affine> H) { |
| 575 | Eigen::Affine3d H_double; |
| 576 | for (size_t i = 0; i < H.rows(); i++) { |
| 577 | for (size_t j = 0; j < H.cols(); j++) { |
| 578 | H_double(i, j) = ScalarToDouble(H(i, j)); |
| 579 | } |
| 580 | } |
| 581 | return H_double; |
| 582 | } |
| 583 | |
| 584 | } // namespace |
| 585 | |
| 586 | template <typename S> |
| 587 | bool TargetMapper::operator()(const S *const translation, |
| 588 | const S *const rotation, S *residual) const { |
| 589 | using Affine3s = Eigen::Transform<S, 3, Eigen::Affine>; |
| 590 | Eigen::Quaternion<S> R_frozen_actual(rotation[3], rotation[1], rotation[2], |
| 591 | rotation[0]); |
| 592 | Eigen::Translation<S, 3> T_frozen_actual(translation[0], translation[1], |
| 593 | translation[2]); |
| 594 | // Actual target pose in the frame of the fixed pose. |
| 595 | Affine3s H_frozen_actual = T_frozen_actual * R_frozen_actual; |
| 596 | VLOG(2) << "H_frozen_actual: " |
| 597 | << PoseUtils::Affine3dToPose3d(ScalarAffineToDouble(H_frozen_actual)); |
| 598 | |
| 599 | Affine3s H_world_frozen = |
| 600 | PoseUtils::Pose3dToAffine3d(target_poses_.at(FLAGS_frozen_target_id)) |
| 601 | .cast<S>(); |
| 602 | Affine3s H_world_frozenactual = H_world_frozen * H_frozen_actual; |
| 603 | |
| 604 | size_t residual_index = 0; |
| 605 | if (FLAGS_visualize_solver) { |
| 606 | vis_robot_.ClearImage(); |
| 607 | } |
| 608 | |
| 609 | for (const auto &[id, solved_pose] : target_poses_) { |
| 610 | if (id < FLAGS_min_target_id || id > FLAGS_max_target_id) { |
| 611 | continue; |
| 612 | } |
| 613 | |
| 614 | Affine3s H_world_ideal = |
| 615 | PoseUtils::Pose3dToAffine3d(ideal_target_poses_.at(id)).cast<S>(); |
| 616 | Affine3s H_world_solved = |
| 617 | PoseUtils::Pose3dToAffine3d(solved_pose).cast<S>(); |
| 618 | // Take the delta between the frozen target and the solved target, and put |
| 619 | // that on top of the actual pose of the frozen target |
| 620 | auto H_frozen_solved = H_world_frozen.inverse() * H_world_solved; |
| 621 | auto H_world_actual = H_world_frozenactual * H_frozen_solved; |
| 622 | VLOG(2) << id << ": " << H_world_actual.translation(); |
| 623 | Affine3s H_ideal_actual = H_world_ideal.inverse() * H_world_actual; |
| 624 | auto T_ideal_actual = H_ideal_actual.translation(); |
| 625 | VLOG(2) << "T_ideal_actual: " << T_ideal_actual; |
| 626 | VLOG(2); |
| 627 | auto R_ideal_actual = Eigen::AngleAxis<S>(H_ideal_actual.rotation()); |
| 628 | |
milind-u | 401de98 | 2023-04-14 17:32:03 -0700 | [diff] [blame] | 629 | // Weight translation errors higher than rotation. |
| 630 | // 1 m in position error = 0.01 radian (or ~0.573 degrees) |
| 631 | constexpr double kTranslationScalar = 1000.0; |
| 632 | constexpr double kRotationScalar = 100.0; |
milind-u | 8f4e43e | 2023-04-09 17:11:19 -0700 | [diff] [blame] | 633 | |
| 634 | // Penalize based on how much our actual poses matches the ideal |
| 635 | // ones. We've already solved for the relative poses, now figure out |
| 636 | // where all of them fit in the world. |
| 637 | residual[residual_index++] = kTranslationScalar * T_ideal_actual(0); |
| 638 | residual[residual_index++] = kTranslationScalar * T_ideal_actual(1); |
| 639 | residual[residual_index++] = kTranslationScalar * T_ideal_actual(2); |
| 640 | residual[residual_index++] = |
| 641 | kRotationScalar * R_ideal_actual.angle() * R_ideal_actual.axis().x(); |
| 642 | residual[residual_index++] = |
| 643 | kRotationScalar * R_ideal_actual.angle() * R_ideal_actual.axis().y(); |
| 644 | residual[residual_index++] = |
| 645 | kRotationScalar * R_ideal_actual.angle() * R_ideal_actual.axis().z(); |
| 646 | |
| 647 | if (FLAGS_visualize_solver) { |
Jim Ostrowski | 68e5617 | 2023-09-17 23:44:15 -0700 | [diff] [blame] | 648 | LOG(INFO) << std::to_string(id) + std::string("-est") << " at " |
| 649 | << ScalarAffineToDouble(H_world_actual).matrix(); |
milind-u | 8f4e43e | 2023-04-09 17:11:19 -0700 | [diff] [blame] | 650 | vis_robot_.DrawFrameAxes(ScalarAffineToDouble(H_world_actual), |
Jim Ostrowski | 68e5617 | 2023-09-17 23:44:15 -0700 | [diff] [blame] | 651 | std::to_string(id) + std::string("-est"), |
| 652 | cv::Scalar(0, 255, 0)); |
milind-u | 8f4e43e | 2023-04-09 17:11:19 -0700 | [diff] [blame] | 653 | vis_robot_.DrawFrameAxes(ScalarAffineToDouble(H_world_ideal), |
| 654 | std::to_string(id), cv::Scalar(255, 255, 255)); |
| 655 | } |
| 656 | } |
| 657 | if (FLAGS_visualize_solver) { |
| 658 | cv::imshow("Target maps", vis_robot_.image_); |
| 659 | cv::waitKey(0); |
| 660 | } |
| 661 | |
| 662 | // Ceres can't handle residual values of exactly zero |
| 663 | for (size_t i = 0; i < residual_index; i++) { |
| 664 | if (residual[i] == S(0)) { |
| 665 | residual[i] = S(1e-9); |
| 666 | } |
| 667 | } |
| 668 | |
| 669 | return true; |
| 670 | } |
| 671 | |
milind-u | 401de98 | 2023-04-14 17:32:03 -0700 | [diff] [blame] | 672 | TargetMapper::PoseError TargetMapper::ComputeError( |
| 673 | const ceres::examples::Constraint3d &constraint) const { |
| 674 | // Compute the difference between the map-based transform of the end target |
| 675 | // in the start target frame, to the one from this constraint |
| 676 | auto H_start_end_map = |
| 677 | PoseUtils::Pose3dToAffine3d(target_poses_.at(constraint.id_begin)) |
| 678 | .inverse() * |
| 679 | PoseUtils::Pose3dToAffine3d(target_poses_.at(constraint.id_end)); |
| 680 | auto H_start_end_constraint = PoseUtils::Pose3dToAffine3d(constraint.t_be); |
| 681 | ceres::examples::Pose3d delta_pose = PoseUtils::Affine3dToPose3d( |
| 682 | H_start_end_map.inverse() * H_start_end_constraint); |
| 683 | double distance = delta_pose.p.norm(); |
| 684 | Eigen::AngleAxisd err_angle(delta_pose.q); |
| 685 | double angle = std::abs(err_angle.angle()); |
| 686 | return {.angle = angle, .distance = distance}; |
| 687 | } |
| 688 | |
| 689 | TargetMapper::Stats TargetMapper::ComputeStats() const { |
| 690 | Stats stats{.avg_err = {.angle = 0.0, .distance = 0.0}, |
| 691 | .std_dev = {.angle = 0.0, .distance = 0.0}, |
| 692 | .max_err = {.angle = 0.0, .distance = 0.0}}; |
| 693 | |
| 694 | for (const auto &constraint : target_constraints_) { |
| 695 | PoseError err = ComputeError(constraint); |
| 696 | |
| 697 | // Update our statistics |
| 698 | stats.avg_err.distance += err.distance; |
| 699 | if (err.distance > stats.max_err.distance) { |
| 700 | stats.max_err.distance = err.distance; |
| 701 | } |
| 702 | |
| 703 | stats.avg_err.angle += err.angle; |
| 704 | if (err.angle > stats.max_err.angle) { |
| 705 | stats.max_err.angle = err.angle; |
| 706 | } |
| 707 | } |
| 708 | |
| 709 | stats.avg_err.distance /= static_cast<double>(target_constraints_.size()); |
| 710 | stats.avg_err.angle /= static_cast<double>(target_constraints_.size()); |
| 711 | |
| 712 | for (const auto &constraint : target_constraints_) { |
| 713 | PoseError err = ComputeError(constraint); |
| 714 | |
| 715 | // Update our statistics |
| 716 | stats.std_dev.distance += |
| 717 | std::pow(err.distance - stats.avg_err.distance, 2); |
| 718 | |
| 719 | stats.std_dev.angle += std::pow(err.angle - stats.avg_err.angle, 2); |
| 720 | } |
| 721 | |
| 722 | stats.std_dev.distance = std::sqrt( |
| 723 | stats.std_dev.distance / static_cast<double>(target_constraints_.size())); |
| 724 | stats.std_dev.angle = std::sqrt( |
| 725 | stats.std_dev.angle / static_cast<double>(target_constraints_.size())); |
| 726 | |
| 727 | return stats; |
| 728 | } |
| 729 | |
| 730 | void TargetMapper::RemoveOutlierConstraints() { |
| 731 | stats_with_outliers_ = ComputeStats(); |
| 732 | size_t original_size = target_constraints_.size(); |
| 733 | target_constraints_.erase( |
| 734 | std::remove_if( |
| 735 | target_constraints_.begin(), target_constraints_.end(), |
| 736 | [&](const auto &constraint) { |
| 737 | PoseError err = ComputeError(constraint); |
| 738 | // Remove constraints with errors significantly above |
| 739 | // the average |
| 740 | if (err.distance > stats_with_outliers_.avg_err.distance + |
| 741 | FLAGS_outlier_std_devs * |
| 742 | stats_with_outliers_.std_dev.distance) { |
| 743 | return true; |
| 744 | } |
| 745 | if (err.angle > stats_with_outliers_.avg_err.angle + |
| 746 | FLAGS_outlier_std_devs * |
| 747 | stats_with_outliers_.std_dev.angle) { |
| 748 | return true; |
| 749 | } |
| 750 | return false; |
| 751 | }), |
| 752 | target_constraints_.end()); |
| 753 | |
| 754 | LOG(INFO) << "Removed " << (original_size - target_constraints_.size()) |
| 755 | << " outlier constraints out of " << original_size << " total"; |
| 756 | } |
| 757 | |
| 758 | void TargetMapper::DumpStats(std::string_view path) const { |
| 759 | LOG(INFO) << "Dumping mapping stats to " << path; |
| 760 | Stats stats = ComputeStats(); |
| 761 | std::ofstream fout(path.data()); |
| 762 | fout << "Stats after outlier rejection: " << std::endl; |
| 763 | fout << "Average error - angle: " << stats.avg_err.angle |
| 764 | << ", distance: " << stats.avg_err.distance << std::endl |
| 765 | << std::endl; |
| 766 | fout << "Standard deviation - angle: " << stats.std_dev.angle |
| 767 | << ", distance: " << stats.std_dev.distance << std::endl |
| 768 | << std::endl; |
| 769 | fout << "Max error - angle: " << stats.max_err.angle |
| 770 | << ", distance: " << stats.max_err.distance << std::endl; |
| 771 | |
| 772 | fout << std::endl << "Stats before outlier rejection:" << std::endl; |
| 773 | fout << "Average error - angle: " << stats_with_outliers_.avg_err.angle |
| 774 | << ", distance: " << stats_with_outliers_.avg_err.distance << std::endl |
| 775 | << std::endl; |
| 776 | fout << "Standard deviation - angle: " << stats_with_outliers_.std_dev.angle |
| 777 | << ", distance: " << stats_with_outliers_.std_dev.distance << std::endl |
| 778 | << std::endl; |
| 779 | fout << "Max error - angle: " << stats_with_outliers_.max_err.angle |
| 780 | << ", distance: " << stats_with_outliers_.max_err.distance << std::endl; |
| 781 | |
| 782 | fout.flush(); |
| 783 | fout.close(); |
| 784 | } |
| 785 | |
| 786 | void TargetMapper::DumpConstraints(std::string_view path) const { |
| 787 | LOG(INFO) << "Dumping target constraints to " << path; |
| 788 | std::ofstream fout(path.data()); |
| 789 | for (const auto &constraint : target_constraints_) { |
| 790 | fout << constraint << std::endl; |
| 791 | } |
| 792 | fout.flush(); |
| 793 | fout.close(); |
| 794 | } |
| 795 | |
milind-u | fbc5c81 | 2023-04-06 21:24:29 -0700 | [diff] [blame] | 796 | } // namespace frc971::vision |
| 797 | |
Milind Upadhyay | c5beba1 | 2022-12-17 17:41:20 -0800 | [diff] [blame] | 798 | std::ostream &operator<<(std::ostream &os, ceres::examples::Pose3d pose) { |
milind-u | fbc5c81 | 2023-04-06 21:24:29 -0700 | [diff] [blame] | 799 | auto rpy = frc971::vision::PoseUtils::QuaternionToEulerAngles(pose.q); |
Milind Upadhyay | c5beba1 | 2022-12-17 17:41:20 -0800 | [diff] [blame] | 800 | os << absl::StrFormat( |
| 801 | "{x: %.3f, y: %.3f, z: %.3f, roll: %.3f, pitch: " |
| 802 | "%.3f, yaw: %.3f}", |
| 803 | pose.p(0), pose.p(1), pose.p(2), rpy(0), rpy(1), rpy(2)); |
| 804 | return os; |
| 805 | } |
| 806 | |
| 807 | std::ostream &operator<<(std::ostream &os, |
| 808 | ceres::examples::Constraint3d constraint) { |
| 809 | os << absl::StrFormat("{id_begin: %d, id_end: %d, pose: ", |
| 810 | constraint.id_begin, constraint.id_end) |
| 811 | << constraint.t_be << "}"; |
| 812 | return os; |
| 813 | } |