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