blob: f5c8dabf796fdeaf3349052b3288f95adca03b1a [file] [log] [blame]
Milind Upadhyay7c205222022-11-16 18:20:58 -08001#include "frc971/vision/target_mapper.h"
2
Milind Upadhyayc5beba12022-12-17 17:41:20 -08003#include "absl/strings/str_format.h"
Philipp Schrader790cb542023-07-05 21:06:52 -07004
Milind Upadhyay7c205222022-11-16 18:20:58 -08005#include "frc971/control_loops/control_loop.h"
Milind Upadhyayc5beba12022-12-17 17:41:20 -08006#include "frc971/vision/ceres/pose_graph_3d_error_term.h"
Milind Upadhyay7c205222022-11-16 18:20:58 -08007#include "frc971/vision/geometry.h"
8
9DEFINE_uint64(max_num_iterations, 100,
10 "Maximum number of iterations for the ceres solver");
milind-ud62f80a2023-03-04 16:37:09 -080011DEFINE_double(distortion_noise_scalar, 1.0,
12 "Scale the target pose distortion factor by this when computing "
13 "the noise.");
milind-u8f4e43e2023-04-09 17:11:19 -070014DEFINE_int32(
milind-u6ff399f2023-03-24 18:33:38 -070015 frozen_target_id, 1,
16 "Freeze the pose of this target so the map can have one fixed point.");
milind-u8f4e43e2023-04-09 17:11:19 -070017DEFINE_int32(min_target_id, 1, "Minimum target id to solve for");
18DEFINE_int32(max_target_id, 8, "Maximum target id to solve for");
19DEFINE_bool(visualize_solver, false, "If true, visualize the solving process.");
milind-u401de982023-04-14 17:32:03 -070020// 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.
23DEFINE_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 Ostrowski463ee592024-03-07 00:08:24 -080026DEFINE_bool(do_map_fitting, false,
27 "Whether to do a final fit of the solved map to the original map");
Milind Upadhyay7c205222022-11-16 18:20:58 -080028
29namespace frc971::vision {
Milind Upadhyayc5beba12022-12-17 17:41:20 -080030Eigen::Affine3d PoseUtils::Pose3dToAffine3d(
31 const ceres::examples::Pose3d &pose3d) {
Milind Upadhyay7c205222022-11-16 18:20:58 -080032 Eigen::Affine3d H_world_pose =
Milind Upadhyayc5beba12022-12-17 17:41:20 -080033 Eigen::Translation3d(pose3d.p(0), pose3d.p(1), pose3d.p(2)) * pose3d.q;
Milind Upadhyay7c205222022-11-16 18:20:58 -080034 return H_world_pose;
35}
36
Milind Upadhyayc5beba12022-12-17 17:41:20 -080037ceres::examples::Pose3d PoseUtils::Affine3dToPose3d(const Eigen::Affine3d &H) {
38 return ceres::examples::Pose3d{.p = H.translation(),
39 .q = Eigen::Quaterniond(H.rotation())};
Milind Upadhyay7c205222022-11-16 18:20:58 -080040}
41
Milind Upadhyayc5beba12022-12-17 17:41:20 -080042ceres::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 Upadhyay7c205222022-11-16 18:20:58 -080047
48 // Get the location of 2 in the 1 frame
49 Eigen::Affine3d H_1_2 = H_world_1.inverse() * H_world_2;
Milind Upadhyayc5beba12022-12-17 17:41:20 -080050 return Affine3dToPose3d(H_1_2);
Milind Upadhyay7c205222022-11-16 18:20:58 -080051}
52
Milind Upadhyayc5beba12022-12-17 17:41:20 -080053ceres::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 Upadhyay7c205222022-11-16 18:20:58 -080058 auto H_world_2 = H_world_1 * H_1_2;
59
Milind Upadhyayc5beba12022-12-17 17:41:20 -080060 return Affine3dToPose3d(H_world_2);
Milind Upadhyay7c205222022-11-16 18:20:58 -080061}
62
Milind Upadhyayc5beba12022-12-17 17:41:20 -080063Eigen::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 Upadhyay7c205222022-11-16 18:20:58 -080070}
71
Milind Upadhyayc5beba12022-12-17 17:41:20 -080072Eigen::Vector3d PoseUtils::QuaternionToEulerAngles(
73 const Eigen::Quaterniond &q) {
74 return RotationMatrixToEulerAngles(q.toRotationMatrix());
Milind Upadhyay7c205222022-11-16 18:20:58 -080075}
76
Milind Upadhyayc5beba12022-12-17 17:41:20 -080077Eigen::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-u3f5f83c2023-01-29 15:23:51 -080086flatbuffers::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
99TargetMapper::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 Kuszmaulfeb89082024-02-21 14:00:15 -0800109 target_pose_fbs.orientation()->z())
110 .normalized()}};
milind-u3f5f83c2023-01-29 15:23:51 -0800111}
112
Milind Upadhyayc5beba12022-12-17 17:41:20 -0800113ceres::examples::VectorOfConstraints DataAdapter::MatchTargetDetections(
Milind Upadhyayec493912022-12-18 21:33:15 -0800114 const std::vector<DataAdapter::TimestampedDetection>
115 &timestamped_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 Upadhyayc5beba12022-12-17 17:41:20 -0800121 ceres::examples::VectorOfConstraints target_constraints;
milind-ud62f80a2023-03-04 16:37:09 -0800122 for (auto detection = timestamped_target_detections.begin() + 1;
123 detection < timestamped_target_detections.end(); detection++) {
124 auto last_detection = detection - 1;
Milind Upadhyayec493912022-12-18 21:33:15 -0800125
126 // Skip two consecutive detections of the same target, because the solver
127 // doesn't allow this
milind-ud62f80a2023-03-04 16:37:09 -0800128 if (detection->id == last_detection->id) {
Milind Upadhyayec493912022-12-18 21:33:15 -0800129 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-ud62f80a2023-03-04 16:37:09 -0800134 if ((detection->time - last_detection->time) > max_dt) {
Milind Upadhyayec493912022-12-18 21:33:15 -0800135 continue;
136 }
137
milind-ud62f80a2023-03-04 16:37:09 -0800138 auto confidence = ComputeConfidence(*last_detection, *detection);
Milind Upadhyayec493912022-12-18 21:33:15 -0800139 target_constraints.emplace_back(
milind-ud62f80a2023-03-04 16:37:09 -0800140 ComputeTargetConstraint(*last_detection, *detection, confidence));
Milind Upadhyayec493912022-12-18 21:33:15 -0800141 }
142
143 return target_constraints;
144}
145
Milind Upadhyayc5beba12022-12-17 17:41:20 -0800146TargetMapper::ConfidenceMatrix DataAdapter::ComputeConfidence(
milind-ud62f80a2023-03-04 16:37:09 -0800147 const TimestampedDetection &detection_start,
148 const TimestampedDetection &detection_end) {
Milind Upadhyay7c205222022-11-16 18:20:58 -0800149 constexpr size_t kX = 0;
150 constexpr size_t kY = 1;
Milind Upadhyayc5beba12022-12-17 17:41:20 -0800151 constexpr size_t kZ = 2;
152 constexpr size_t kOrientation1 = 3;
153 constexpr size_t kOrientation2 = 4;
154 constexpr size_t kOrientation3 = 5;
Milind Upadhyay7c205222022-11-16 18:20:58 -0800155
156 // Uncertainty matrix between start and end
Milind Upadhyayc5beba12022-12-17 17:41:20 -0800157 TargetMapper::ConfidenceMatrix P = TargetMapper::ConfidenceMatrix::Zero();
Milind Upadhyay7c205222022-11-16 18:20:58 -0800158
159 {
160 // Noise for odometry-based robot position measurements
Milind Upadhyayc5beba12022-12-17 17:41:20 -0800161 TargetMapper::ConfidenceMatrix Q_odometry =
162 TargetMapper::ConfidenceMatrix::Zero();
Milind Upadhyay7c205222022-11-16 18:20:58 -0800163 Q_odometry(kX, kX) = std::pow(0.045, 2);
164 Q_odometry(kY, kY) = std::pow(0.045, 2);
Milind Upadhyayc5beba12022-12-17 17:41:20 -0800165 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 Upadhyay7c205222022-11-16 18:20:58 -0800169
170 // Add uncertainty for robot position measurements from start to end
milind-ud62f80a2023-03-04 16:37:09 -0800171 int iterations = (detection_end.time - detection_start.time) /
172 frc971::controls::kLoopFrequency;
Milind Upadhyay7c205222022-11-16 18:20:58 -0800173 P += static_cast<double>(iterations) * Q_odometry;
174 }
175
176 {
Milind Upadhyayebf93ee2023-01-05 14:12:58 -0800177 // Noise for vision-based target localizations. Multiplying this matrix by
milind-u6ff399f2023-03-24 18:33:38 -0700178 // the distance from camera to target squared results in the uncertainty
179 // in that measurement
Milind Upadhyayc5beba12022-12-17 17:41:20 -0800180 TargetMapper::ConfidenceMatrix Q_vision =
181 TargetMapper::ConfidenceMatrix::Zero();
Milind Upadhyayebf93ee2023-01-05 14:12:58 -0800182 Q_vision(kX, kX) = std::pow(0.045, 2);
183 Q_vision(kY, kY) = std::pow(0.045, 2);
Milind Upadhyayc5beba12022-12-17 17:41:20 -0800184 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 Upadhyay7c205222022-11-16 18:20:58 -0800188
189 // Add uncertainty for the 2 vision measurements (1 at start and 1 at end)
milind-ufbc5c812023-04-06 21:24:29 -0700190 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 Upadhyay7c205222022-11-16 18:20:58 -0800198 }
199
200 return P.inverse();
201}
202
Milind Upadhyayc5beba12022-12-17 17:41:20 -0800203ceres::examples::Constraint3d DataAdapter::ComputeTargetConstraint(
Milind Upadhyay7c205222022-11-16 18:20:58 -0800204 const TimestampedDetection &target_detection_start,
Milind Upadhyay7c205222022-11-16 18:20:58 -0800205 const TimestampedDetection &target_detection_end,
Milind Upadhyayc5beba12022-12-17 17:41:20 -0800206 const TargetMapper::ConfidenceMatrix &confidence) {
Milind Upadhyay7c205222022-11-16 18:20:58 -0800207 // Compute the relative pose (constraint) between the two targets
208 Eigen::Affine3d H_targetstart_targetend =
Milind Upadhyayc5beba12022-12-17 17:41:20 -0800209 target_detection_start.H_robot_target.inverse() *
Milind Upadhyay7c205222022-11-16 18:20:58 -0800210 target_detection_end.H_robot_target;
Milind Upadhyayc5beba12022-12-17 17:41:20 -0800211 ceres::examples::Pose3d target_constraint =
212 PoseUtils::Affine3dToPose3d(H_targetstart_targetend);
Milind Upadhyay7c205222022-11-16 18:20:58 -0800213
milind-uf3ab8ba2023-02-04 17:56:16 -0800214 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 Upadhyayec493912022-12-18 21:33:15 -0800222}
223
Milind Upadhyay7c205222022-11-16 18:20:58 -0800224TargetMapper::TargetMapper(
Milind Upadhyaycd677a32022-12-04 13:06:43 -0800225 std::string_view target_poses_path,
Milind Upadhyayc5beba12022-12-17 17:41:20 -0800226 const ceres::examples::VectorOfConstraints &target_constraints)
milind-u8f4e43e2023-04-09 17:11:19 -0700227 : target_constraints_(target_constraints),
228 T_frozen_actual_(Eigen::Vector3d::Zero()),
229 R_frozen_actual_(Eigen::Quaterniond::Identity()),
Jim Ostrowski68e56172023-09-17 23:44:15 -0700230 vis_robot_(cv::Size(kImageWidth_, kImageHeight_)) {
Milind Upadhyaycd677a32022-12-04 13:06:43 -0800231 aos::FlatbufferDetachedBuffer<TargetMap> target_map =
232 aos::JsonFileToFlatbuffer<TargetMap>(target_poses_path);
233 for (const auto *target_pose_fbs : *target_map.message().target_poses()) {
milind-u8f4e43e2023-04-09 17:11:19 -0700234 ideal_target_poses_[target_pose_fbs->id()] =
milind-u3f5f83c2023-01-29 15:23:51 -0800235 PoseUtils::TargetPoseFromFbs(*target_pose_fbs).pose;
Milind Upadhyaycd677a32022-12-04 13:06:43 -0800236 }
milind-u8f4e43e2023-04-09 17:11:19 -0700237 target_poses_ = ideal_target_poses_;
milind-u526d5672023-04-17 20:09:10 -0700238 CountConstraints();
Milind Upadhyaycd677a32022-12-04 13:06:43 -0800239}
240
241TargetMapper::TargetMapper(
Milind Upadhyayc5beba12022-12-17 17:41:20 -0800242 const ceres::examples::MapOfPoses &target_poses,
243 const ceres::examples::VectorOfConstraints &target_constraints)
milind-u8f4e43e2023-04-09 17:11:19 -0700244 : ideal_target_poses_(target_poses),
245 target_poses_(ideal_target_poses_),
246 target_constraints_(target_constraints),
247 T_frozen_actual_(Eigen::Vector3d::Zero()),
248 R_frozen_actual_(Eigen::Quaterniond::Identity()),
Jim Ostrowski68e56172023-09-17 23:44:15 -0700249 vis_robot_(cv::Size(kImageWidth_, kImageHeight_)) {
milind-u526d5672023-04-17 20:09:10 -0700250 CountConstraints();
251}
252
253namespace {
254std::pair<TargetMapper::TargetId, TargetMapper::TargetId> MakeIdPair(
255 const ceres::examples::Constraint3d &constraint) {
256 auto min_id = std::min(constraint.id_begin, constraint.id_end);
257 auto max_id = std::max(constraint.id_begin, constraint.id_end);
258 return std::make_pair(min_id, max_id);
259}
260} // namespace
261
262void TargetMapper::CountConstraints() {
263 for (const auto &constraint : target_constraints_) {
264 auto id_pair = MakeIdPair(constraint);
265 if (constraint_counts_.count(id_pair) == 0) {
266 constraint_counts_[id_pair] = 0;
267 }
268 constraint_counts_[id_pair]++;
269 }
270}
Milind Upadhyay7c205222022-11-16 18:20:58 -0800271
272std::optional<TargetMapper::TargetPose> TargetMapper::GetTargetPoseById(
273 std::vector<TargetMapper::TargetPose> target_poses, TargetId target_id) {
274 for (auto target_pose : target_poses) {
275 if (target_pose.id == target_id) {
276 return target_pose;
277 }
278 }
279
280 return std::nullopt;
281}
282
Jim Ostrowski49be8232023-03-23 01:00:14 -0700283std::optional<TargetMapper::TargetPose> TargetMapper::GetTargetPoseById(
milind-u2ab4db12023-03-25 21:59:23 -0700284 TargetId target_id) const {
Jim Ostrowski49be8232023-03-23 01:00:14 -0700285 if (target_poses_.count(target_id) > 0) {
milind-u2ab4db12023-03-25 21:59:23 -0700286 return TargetMapper::TargetPose{target_id, target_poses_.at(target_id)};
Jim Ostrowski49be8232023-03-23 01:00:14 -0700287 }
288
289 return std::nullopt;
290}
291
Milind Upadhyayc5beba12022-12-17 17:41:20 -0800292// Taken from ceres/examples/slam/pose_graph_3d/pose_graph_3d.cc
293// Constructs the nonlinear least squares optimization problem from the pose
294// graph constraints.
milind-u8f4e43e2023-04-09 17:11:19 -0700295void TargetMapper::BuildTargetPoseOptimizationProblem(
Milind Upadhyayc5beba12022-12-17 17:41:20 -0800296 const ceres::examples::VectorOfConstraints &constraints,
297 ceres::examples::MapOfPoses *poses, ceres::Problem *problem) {
298 CHECK(poses != nullptr);
299 CHECK(problem != nullptr);
Milind Upadhyay7c205222022-11-16 18:20:58 -0800300 if (constraints.empty()) {
Milind Upadhyayc5beba12022-12-17 17:41:20 -0800301 LOG(INFO) << "No constraints, no problem to optimize.";
Milind Upadhyay7c205222022-11-16 18:20:58 -0800302 return;
303 }
304
milind-u13ff1a52023-01-22 17:10:49 -0800305 ceres::LossFunction *loss_function = new ceres::HuberLoss(2.0);
Milind Upadhyayc5beba12022-12-17 17:41:20 -0800306 ceres::LocalParameterization *quaternion_local_parameterization =
307 new ceres::EigenQuaternionParameterization;
Milind Upadhyay7c205222022-11-16 18:20:58 -0800308
Jim Ostrowski2f2685f2023-03-25 11:57:54 -0700309 int min_constraint_id = std::numeric_limits<int>::max();
310 int max_constraint_id = std::numeric_limits<int>::min();
311
Milind Upadhyayc5beba12022-12-17 17:41:20 -0800312 for (ceres::examples::VectorOfConstraints::const_iterator constraints_iter =
313 constraints.begin();
Milind Upadhyay7c205222022-11-16 18:20:58 -0800314 constraints_iter != constraints.end(); ++constraints_iter) {
Milind Upadhyayc5beba12022-12-17 17:41:20 -0800315 const ceres::examples::Constraint3d &constraint = *constraints_iter;
Milind Upadhyay7c205222022-11-16 18:20:58 -0800316
Milind Upadhyayc5beba12022-12-17 17:41:20 -0800317 ceres::examples::MapOfPoses::iterator pose_begin_iter =
Milind Upadhyay7c205222022-11-16 18:20:58 -0800318 poses->find(constraint.id_begin);
319 CHECK(pose_begin_iter != poses->end())
320 << "Pose with ID: " << constraint.id_begin << " not found.";
Milind Upadhyayc5beba12022-12-17 17:41:20 -0800321 ceres::examples::MapOfPoses::iterator pose_end_iter =
Milind Upadhyay7c205222022-11-16 18:20:58 -0800322 poses->find(constraint.id_end);
323 CHECK(pose_end_iter != poses->end())
324 << "Pose with ID: " << constraint.id_end << " not found.";
325
Milind Upadhyayc5beba12022-12-17 17:41:20 -0800326 const Eigen::Matrix<double, 6, 6> sqrt_information =
Milind Upadhyay7c205222022-11-16 18:20:58 -0800327 constraint.information.llt().matrixL();
milind-u526d5672023-04-17 20:09:10 -0700328
329 auto id_pair = MakeIdPair(constraint);
330 CHECK_GT(constraint_counts_.count(id_pair), 0ul)
331 << "Should have counted constraints for " << id_pair.first << "->"
332 << id_pair.second;
333
Jim Ostrowski2f2685f2023-03-25 11:57:54 -0700334 VLOG(1) << "Adding constraint pair: " << id_pair.first << " and "
335 << id_pair.second;
336 // Store min & max id's; assumes first id < second id
337 if (id_pair.first < min_constraint_id) {
338 min_constraint_id = id_pair.first;
339 }
340 if (id_pair.second > max_constraint_id) {
341 max_constraint_id = id_pair.second;
342 }
milind-u526d5672023-04-17 20:09:10 -0700343 // Normalize constraint cost by occurances
344 size_t constraint_count = constraint_counts_[id_pair];
345 // Scale all costs so the total cost comes out to more reasonable numbers
346 constexpr double kGlobalWeight = 1000.0;
347 double constraint_weight =
348 kGlobalWeight / static_cast<double>(constraint_count);
349
Milind Upadhyay7c205222022-11-16 18:20:58 -0800350 // Ceres will take ownership of the pointer.
351 ceres::CostFunction *cost_function =
milind-u526d5672023-04-17 20:09:10 -0700352 ceres::examples::PoseGraph3dErrorTerm::Create(
353 constraint.t_be, sqrt_information, constraint_weight);
Milind Upadhyay7c205222022-11-16 18:20:58 -0800354
Milind Upadhyayc5beba12022-12-17 17:41:20 -0800355 problem->AddResidualBlock(cost_function, loss_function,
356 pose_begin_iter->second.p.data(),
357 pose_begin_iter->second.q.coeffs().data(),
358 pose_end_iter->second.p.data(),
359 pose_end_iter->second.q.coeffs().data());
360
361 problem->SetParameterization(pose_begin_iter->second.q.coeffs().data(),
362 quaternion_local_parameterization);
363 problem->SetParameterization(pose_end_iter->second.q.coeffs().data(),
364 quaternion_local_parameterization);
Milind Upadhyay7c205222022-11-16 18:20:58 -0800365 }
366
Milind Upadhyayc5beba12022-12-17 17:41:20 -0800367 // The pose graph optimization problem has six DOFs that are not fully
milind-u3f5f83c2023-01-29 15:23:51 -0800368 // constrained. This is typically referred to as gauge freedom. You can
369 // apply a rigid body transformation to all the nodes and the optimization
370 // problem will still have the exact same cost. The Levenberg-Marquardt
371 // algorithm has internal damping which mitigates this issue, but it is
372 // better to properly constrain the gauge freedom. This can be done by
373 // setting one of the poses as constant so the optimizer cannot change it.
milind-u6ff399f2023-03-24 18:33:38 -0700374 CHECK_NE(poses->count(FLAGS_frozen_target_id), 0ul)
375 << "Got no poses for frozen target id " << FLAGS_frozen_target_id;
Jim Ostrowski2f2685f2023-03-25 11:57:54 -0700376 CHECK_GE(FLAGS_frozen_target_id, min_constraint_id)
377 << "target to freeze index " << FLAGS_frozen_target_id
378 << " must be in range of constraints, > " << min_constraint_id;
379 CHECK_LE(FLAGS_frozen_target_id, max_constraint_id)
380 << "target to freeze index " << FLAGS_frozen_target_id
381 << " must be in range of constraints, < " << max_constraint_id;
milind-u6ff399f2023-03-24 18:33:38 -0700382 ceres::examples::MapOfPoses::iterator pose_start_iter =
383 poses->find(FLAGS_frozen_target_id);
Milind Upadhyay7c205222022-11-16 18:20:58 -0800384 CHECK(pose_start_iter != poses->end()) << "There are no poses.";
Milind Upadhyayc5beba12022-12-17 17:41:20 -0800385 problem->SetParameterBlockConstant(pose_start_iter->second.p.data());
386 problem->SetParameterBlockConstant(pose_start_iter->second.q.coeffs().data());
Milind Upadhyay7c205222022-11-16 18:20:58 -0800387}
388
milind-u401de982023-04-14 17:32:03 -0700389std::unique_ptr<ceres::CostFunction>
390TargetMapper::BuildMapFittingOptimizationProblem(ceres::Problem *problem) {
Philipp Schradera6712522023-07-05 20:25:11 -0700391 // Set up robot visualization.
milind-u8f4e43e2023-04-09 17:11:19 -0700392 vis_robot_.ClearImage();
Jim Ostrowski68e56172023-09-17 23:44:15 -0700393 // Compute focal length so that image shows field with viewpoint at 10m above
394 // it (default for viewer)
395 const double kFocalLength = kImageWidth_ * 10.0 / kFieldWidth_;
396 vis_robot_.SetDefaultViewpoint(kImageWidth_, kFocalLength);
milind-u8f4e43e2023-04-09 17:11:19 -0700397
398 const size_t num_targets = FLAGS_max_target_id - FLAGS_min_target_id;
399 // Translation and rotation error for each target
400 const size_t num_residuals = num_targets * 6;
401 // Set up the only cost function (also known as residual). This uses
402 // auto-differentiation to obtain the derivative (jacobian).
milind-u401de982023-04-14 17:32:03 -0700403 std::unique_ptr<ceres::CostFunction> cost_function = std::make_unique<
404 ceres::AutoDiffCostFunction<TargetMapper, ceres::DYNAMIC, 3, 4>>(
405 this, num_residuals, ceres::DO_NOT_TAKE_OWNERSHIP);
milind-u8f4e43e2023-04-09 17:11:19 -0700406
407 ceres::LossFunction *loss_function = new ceres::HuberLoss(2.0);
408 ceres::LocalParameterization *quaternion_local_parameterization =
409 new ceres::EigenQuaternionParameterization;
410
milind-u401de982023-04-14 17:32:03 -0700411 problem->AddResidualBlock(cost_function.get(), loss_function,
milind-u8f4e43e2023-04-09 17:11:19 -0700412 T_frozen_actual_.vector().data(),
413 R_frozen_actual_.coeffs().data());
414 problem->SetParameterization(R_frozen_actual_.coeffs().data(),
415 quaternion_local_parameterization);
milind-u401de982023-04-14 17:32:03 -0700416 return cost_function;
milind-u8f4e43e2023-04-09 17:11:19 -0700417}
418
Milind Upadhyayc5beba12022-12-17 17:41:20 -0800419// Taken from ceres/examples/slam/pose_graph_3d/pose_graph_3d.cc
Milind Upadhyay7c205222022-11-16 18:20:58 -0800420bool TargetMapper::SolveOptimizationProblem(ceres::Problem *problem) {
421 CHECK_NOTNULL(problem);
422
423 ceres::Solver::Options options;
424 options.max_num_iterations = FLAGS_max_num_iterations;
425 options.linear_solver_type = ceres::SPARSE_NORMAL_CHOLESKY;
milind-u401de982023-04-14 17:32:03 -0700426 options.minimizer_progress_to_stdout = false;
Milind Upadhyay7c205222022-11-16 18:20:58 -0800427
428 ceres::Solver::Summary summary;
429 ceres::Solve(options, problem, &summary);
430
Milind Upadhyaycd677a32022-12-04 13:06:43 -0800431 LOG(INFO) << summary.FullReport() << '\n';
Milind Upadhyay7c205222022-11-16 18:20:58 -0800432
433 return summary.IsSolutionUsable();
434}
435
Milind Upadhyay05652cb2022-12-07 20:51:51 -0800436void TargetMapper::Solve(std::string_view field_name,
437 std::optional<std::string_view> output_dir) {
milind-u401de982023-04-14 17:32:03 -0700438 ceres::Problem target_pose_problem_1;
milind-u8f4e43e2023-04-09 17:11:19 -0700439 BuildTargetPoseOptimizationProblem(target_constraints_, &target_poses_,
milind-u401de982023-04-14 17:32:03 -0700440 &target_pose_problem_1);
441 CHECK(SolveOptimizationProblem(&target_pose_problem_1))
442 << "The target pose solve 1 was not successful, exiting.";
Milind Upadhyay7c205222022-11-16 18:20:58 -0800443
milind-u401de982023-04-14 17:32:03 -0700444 RemoveOutlierConstraints();
445
446 // Solve again once we've thrown out bad constraints
447 ceres::Problem target_pose_problem_2;
448 BuildTargetPoseOptimizationProblem(target_constraints_, &target_poses_,
449 &target_pose_problem_2);
450 CHECK(SolveOptimizationProblem(&target_pose_problem_2))
451 << "The target pose solve 2 was not successful, exiting.";
452
Jim Ostrowski463ee592024-03-07 00:08:24 -0800453 if (FLAGS_do_map_fitting) {
454 LOG(INFO) << "Solving the overall map's best alignment to the previous map";
455 ceres::Problem map_fitting_problem(
456 {.loss_function_ownership = ceres::DO_NOT_TAKE_OWNERSHIP});
457 std::unique_ptr<ceres::CostFunction> map_fitting_cost_function =
458 BuildMapFittingOptimizationProblem(&map_fitting_problem);
459 CHECK(SolveOptimizationProblem(&map_fitting_problem))
460 << "The map fitting solve was not successful, exiting.";
461 map_fitting_cost_function.release();
milind-u8f4e43e2023-04-09 17:11:19 -0700462
Jim Ostrowski463ee592024-03-07 00:08:24 -0800463 Eigen::Affine3d H_frozen_actual = T_frozen_actual_ * R_frozen_actual_;
464 LOG(INFO) << "H_frozen_actual: "
465 << PoseUtils::Affine3dToPose3d(H_frozen_actual);
milind-u8f4e43e2023-04-09 17:11:19 -0700466
Jim Ostrowski463ee592024-03-07 00:08:24 -0800467 auto H_world_frozen =
468 PoseUtils::Pose3dToAffine3d(target_poses_[FLAGS_frozen_target_id]);
469 auto H_world_frozenactual = H_world_frozen * H_frozen_actual;
milind-u8f4e43e2023-04-09 17:11:19 -0700470
Jim Ostrowski463ee592024-03-07 00:08:24 -0800471 // Offset the solved poses to become the actual ones
472 for (auto &[id, pose] : target_poses_) {
473 // Don't offset targets we didn't solve for
474 if (id < FLAGS_min_target_id || id > FLAGS_max_target_id) {
475 continue;
476 }
477
478 // Take the delta between the frozen target and the solved target, and put
479 // that on top of the actual pose of the frozen target
480 auto H_world_solved = PoseUtils::Pose3dToAffine3d(pose);
481 auto H_frozen_solved = H_world_frozen.inverse() * H_world_solved;
482 auto H_world_actual = H_world_frozenactual * H_frozen_solved;
483 pose = PoseUtils::Affine3dToPose3d(H_world_actual);
milind-u8f4e43e2023-04-09 17:11:19 -0700484 }
milind-u8f4e43e2023-04-09 17:11:19 -0700485 }
Milind Upadhyay7c205222022-11-16 18:20:58 -0800486
Milind Upadhyay05652cb2022-12-07 20:51:51 -0800487 auto map_json = MapToJson(field_name);
Milind Upadhyaycd677a32022-12-04 13:06:43 -0800488 VLOG(1) << "Solved target poses: " << map_json;
Milind Upadhyay05652cb2022-12-07 20:51:51 -0800489
490 if (output_dir.has_value()) {
491 std::string output_path =
492 absl::StrCat(output_dir.value(), "/", field_name, ".json");
493 LOG(INFO) << "Writing map to file: " << output_path;
494 aos::util::WriteStringToFileOrDie(output_path, map_json);
Milind Upadhyaycd677a32022-12-04 13:06:43 -0800495 }
milind-u401de982023-04-14 17:32:03 -0700496
497 for (TargetId id_start = FLAGS_min_target_id; id_start < FLAGS_max_target_id;
498 id_start++) {
499 for (TargetId id_end = id_start + 1; id_end <= FLAGS_max_target_id;
500 id_end++) {
501 auto H_start_end =
502 PoseUtils::Pose3dToAffine3d(target_poses_.at(id_start)).inverse() *
503 PoseUtils::Pose3dToAffine3d(target_poses_.at(id_end));
504 auto constraint = PoseUtils::Affine3dToPose3d(H_start_end);
Jim Ostrowski2f2685f2023-03-25 11:57:54 -0700505 VLOG(1) << id_start << "->" << id_end << ": " << constraint.p.norm()
506 << " meters";
milind-u401de982023-04-14 17:32:03 -0700507 }
508 }
Milind Upadhyaycd677a32022-12-04 13:06:43 -0800509}
510
Milind Upadhyay05652cb2022-12-07 20:51:51 -0800511std::string TargetMapper::MapToJson(std::string_view field_name) const {
Milind Upadhyaycd677a32022-12-04 13:06:43 -0800512 flatbuffers::FlatBufferBuilder fbb;
513
514 // Convert poses to flatbuffers
515 std::vector<flatbuffers::Offset<TargetPoseFbs>> target_poses_fbs;
516 for (const auto &[id, pose] : target_poses_) {
milind-u3f5f83c2023-01-29 15:23:51 -0800517 target_poses_fbs.emplace_back(
518 PoseUtils::TargetPoseToFbs(TargetPose{.id = id, .pose = pose}, &fbb));
Milind Upadhyaycd677a32022-12-04 13:06:43 -0800519 }
520
Milind Upadhyay05652cb2022-12-07 20:51:51 -0800521 const auto field_name_offset = fbb.CreateString(field_name);
522 flatbuffers::Offset<TargetMap> target_map_offset = CreateTargetMap(
523 fbb, fbb.CreateVector(target_poses_fbs), field_name_offset);
Milind Upadhyaycd677a32022-12-04 13:06:43 -0800524
525 return aos::FlatbufferToJson(
526 flatbuffers::GetMutableTemporaryPointer(fbb, target_map_offset),
527 {.multi_line = true});
Milind Upadhyay7c205222022-11-16 18:20:58 -0800528}
529
milind-u8f4e43e2023-04-09 17:11:19 -0700530namespace {
milind-u8f4e43e2023-04-09 17:11:19 -0700531// Hacks to extract a double from a scalar, which is either a ceres jet or a
532// double. Only used for debugging and displaying.
533template <typename S>
534double ScalarToDouble(S s) {
535 const double *ptr = reinterpret_cast<double *>(&s);
536 return *ptr;
537}
538
539template <typename S>
540Eigen::Affine3d ScalarAffineToDouble(Eigen::Transform<S, 3, Eigen::Affine> H) {
541 Eigen::Affine3d H_double;
542 for (size_t i = 0; i < H.rows(); i++) {
543 for (size_t j = 0; j < H.cols(); j++) {
544 H_double(i, j) = ScalarToDouble(H(i, j));
545 }
546 }
547 return H_double;
548}
549
550} // namespace
551
552template <typename S>
553bool TargetMapper::operator()(const S *const translation,
554 const S *const rotation, S *residual) const {
555 using Affine3s = Eigen::Transform<S, 3, Eigen::Affine>;
556 Eigen::Quaternion<S> R_frozen_actual(rotation[3], rotation[1], rotation[2],
557 rotation[0]);
558 Eigen::Translation<S, 3> T_frozen_actual(translation[0], translation[1],
559 translation[2]);
560 // Actual target pose in the frame of the fixed pose.
561 Affine3s H_frozen_actual = T_frozen_actual * R_frozen_actual;
562 VLOG(2) << "H_frozen_actual: "
563 << PoseUtils::Affine3dToPose3d(ScalarAffineToDouble(H_frozen_actual));
564
565 Affine3s H_world_frozen =
566 PoseUtils::Pose3dToAffine3d(target_poses_.at(FLAGS_frozen_target_id))
567 .cast<S>();
568 Affine3s H_world_frozenactual = H_world_frozen * H_frozen_actual;
569
570 size_t residual_index = 0;
571 if (FLAGS_visualize_solver) {
572 vis_robot_.ClearImage();
573 }
574
575 for (const auto &[id, solved_pose] : target_poses_) {
576 if (id < FLAGS_min_target_id || id > FLAGS_max_target_id) {
577 continue;
578 }
579
580 Affine3s H_world_ideal =
581 PoseUtils::Pose3dToAffine3d(ideal_target_poses_.at(id)).cast<S>();
582 Affine3s H_world_solved =
583 PoseUtils::Pose3dToAffine3d(solved_pose).cast<S>();
584 // Take the delta between the frozen target and the solved target, and put
585 // that on top of the actual pose of the frozen target
586 auto H_frozen_solved = H_world_frozen.inverse() * H_world_solved;
587 auto H_world_actual = H_world_frozenactual * H_frozen_solved;
588 VLOG(2) << id << ": " << H_world_actual.translation();
589 Affine3s H_ideal_actual = H_world_ideal.inverse() * H_world_actual;
590 auto T_ideal_actual = H_ideal_actual.translation();
591 VLOG(2) << "T_ideal_actual: " << T_ideal_actual;
592 VLOG(2);
593 auto R_ideal_actual = Eigen::AngleAxis<S>(H_ideal_actual.rotation());
594
milind-u401de982023-04-14 17:32:03 -0700595 // Weight translation errors higher than rotation.
596 // 1 m in position error = 0.01 radian (or ~0.573 degrees)
597 constexpr double kTranslationScalar = 1000.0;
598 constexpr double kRotationScalar = 100.0;
milind-u8f4e43e2023-04-09 17:11:19 -0700599
600 // Penalize based on how much our actual poses matches the ideal
601 // ones. We've already solved for the relative poses, now figure out
602 // where all of them fit in the world.
603 residual[residual_index++] = kTranslationScalar * T_ideal_actual(0);
604 residual[residual_index++] = kTranslationScalar * T_ideal_actual(1);
605 residual[residual_index++] = kTranslationScalar * T_ideal_actual(2);
606 residual[residual_index++] =
607 kRotationScalar * R_ideal_actual.angle() * R_ideal_actual.axis().x();
608 residual[residual_index++] =
609 kRotationScalar * R_ideal_actual.angle() * R_ideal_actual.axis().y();
610 residual[residual_index++] =
611 kRotationScalar * R_ideal_actual.angle() * R_ideal_actual.axis().z();
612
613 if (FLAGS_visualize_solver) {
Jim Ostrowski68e56172023-09-17 23:44:15 -0700614 LOG(INFO) << std::to_string(id) + std::string("-est") << " at "
615 << ScalarAffineToDouble(H_world_actual).matrix();
milind-u8f4e43e2023-04-09 17:11:19 -0700616 vis_robot_.DrawFrameAxes(ScalarAffineToDouble(H_world_actual),
Jim Ostrowski68e56172023-09-17 23:44:15 -0700617 std::to_string(id) + std::string("-est"),
618 cv::Scalar(0, 255, 0));
milind-u8f4e43e2023-04-09 17:11:19 -0700619 vis_robot_.DrawFrameAxes(ScalarAffineToDouble(H_world_ideal),
620 std::to_string(id), cv::Scalar(255, 255, 255));
621 }
622 }
623 if (FLAGS_visualize_solver) {
624 cv::imshow("Target maps", vis_robot_.image_);
625 cv::waitKey(0);
626 }
627
628 // Ceres can't handle residual values of exactly zero
629 for (size_t i = 0; i < residual_index; i++) {
630 if (residual[i] == S(0)) {
631 residual[i] = S(1e-9);
632 }
633 }
634
635 return true;
636}
637
milind-u401de982023-04-14 17:32:03 -0700638TargetMapper::PoseError TargetMapper::ComputeError(
639 const ceres::examples::Constraint3d &constraint) const {
640 // Compute the difference between the map-based transform of the end target
641 // in the start target frame, to the one from this constraint
642 auto H_start_end_map =
643 PoseUtils::Pose3dToAffine3d(target_poses_.at(constraint.id_begin))
644 .inverse() *
645 PoseUtils::Pose3dToAffine3d(target_poses_.at(constraint.id_end));
646 auto H_start_end_constraint = PoseUtils::Pose3dToAffine3d(constraint.t_be);
647 ceres::examples::Pose3d delta_pose = PoseUtils::Affine3dToPose3d(
648 H_start_end_map.inverse() * H_start_end_constraint);
649 double distance = delta_pose.p.norm();
650 Eigen::AngleAxisd err_angle(delta_pose.q);
651 double angle = std::abs(err_angle.angle());
652 return {.angle = angle, .distance = distance};
653}
654
655TargetMapper::Stats TargetMapper::ComputeStats() const {
656 Stats stats{.avg_err = {.angle = 0.0, .distance = 0.0},
657 .std_dev = {.angle = 0.0, .distance = 0.0},
658 .max_err = {.angle = 0.0, .distance = 0.0}};
659
660 for (const auto &constraint : target_constraints_) {
661 PoseError err = ComputeError(constraint);
662
663 // Update our statistics
664 stats.avg_err.distance += err.distance;
665 if (err.distance > stats.max_err.distance) {
666 stats.max_err.distance = err.distance;
667 }
668
669 stats.avg_err.angle += err.angle;
670 if (err.angle > stats.max_err.angle) {
671 stats.max_err.angle = err.angle;
672 }
673 }
674
675 stats.avg_err.distance /= static_cast<double>(target_constraints_.size());
676 stats.avg_err.angle /= static_cast<double>(target_constraints_.size());
677
678 for (const auto &constraint : target_constraints_) {
679 PoseError err = ComputeError(constraint);
680
681 // Update our statistics
682 stats.std_dev.distance +=
683 std::pow(err.distance - stats.avg_err.distance, 2);
684
685 stats.std_dev.angle += std::pow(err.angle - stats.avg_err.angle, 2);
686 }
687
688 stats.std_dev.distance = std::sqrt(
689 stats.std_dev.distance / static_cast<double>(target_constraints_.size()));
690 stats.std_dev.angle = std::sqrt(
691 stats.std_dev.angle / static_cast<double>(target_constraints_.size()));
692
693 return stats;
694}
695
696void TargetMapper::RemoveOutlierConstraints() {
697 stats_with_outliers_ = ComputeStats();
698 size_t original_size = target_constraints_.size();
699 target_constraints_.erase(
700 std::remove_if(
701 target_constraints_.begin(), target_constraints_.end(),
702 [&](const auto &constraint) {
703 PoseError err = ComputeError(constraint);
704 // Remove constraints with errors significantly above
705 // the average
706 if (err.distance > stats_with_outliers_.avg_err.distance +
707 FLAGS_outlier_std_devs *
708 stats_with_outliers_.std_dev.distance) {
709 return true;
710 }
711 if (err.angle > stats_with_outliers_.avg_err.angle +
712 FLAGS_outlier_std_devs *
713 stats_with_outliers_.std_dev.angle) {
714 return true;
715 }
716 return false;
717 }),
718 target_constraints_.end());
719
720 LOG(INFO) << "Removed " << (original_size - target_constraints_.size())
721 << " outlier constraints out of " << original_size << " total";
722}
723
724void TargetMapper::DumpStats(std::string_view path) const {
725 LOG(INFO) << "Dumping mapping stats to " << path;
726 Stats stats = ComputeStats();
727 std::ofstream fout(path.data());
728 fout << "Stats after outlier rejection: " << std::endl;
729 fout << "Average error - angle: " << stats.avg_err.angle
730 << ", distance: " << stats.avg_err.distance << std::endl
731 << std::endl;
732 fout << "Standard deviation - angle: " << stats.std_dev.angle
733 << ", distance: " << stats.std_dev.distance << std::endl
734 << std::endl;
735 fout << "Max error - angle: " << stats.max_err.angle
736 << ", distance: " << stats.max_err.distance << std::endl;
737
738 fout << std::endl << "Stats before outlier rejection:" << std::endl;
739 fout << "Average error - angle: " << stats_with_outliers_.avg_err.angle
740 << ", distance: " << stats_with_outliers_.avg_err.distance << std::endl
741 << std::endl;
742 fout << "Standard deviation - angle: " << stats_with_outliers_.std_dev.angle
743 << ", distance: " << stats_with_outliers_.std_dev.distance << std::endl
744 << std::endl;
745 fout << "Max error - angle: " << stats_with_outliers_.max_err.angle
746 << ", distance: " << stats_with_outliers_.max_err.distance << std::endl;
747
748 fout.flush();
749 fout.close();
750}
751
752void TargetMapper::DumpConstraints(std::string_view path) const {
753 LOG(INFO) << "Dumping target constraints to " << path;
754 std::ofstream fout(path.data());
755 for (const auto &constraint : target_constraints_) {
756 fout << constraint << std::endl;
757 }
758 fout.flush();
759 fout.close();
760}
761
milind-ufbc5c812023-04-06 21:24:29 -0700762} // namespace frc971::vision
763
Milind Upadhyayc5beba12022-12-17 17:41:20 -0800764std::ostream &operator<<(std::ostream &os, ceres::examples::Pose3d pose) {
milind-ufbc5c812023-04-06 21:24:29 -0700765 auto rpy = frc971::vision::PoseUtils::QuaternionToEulerAngles(pose.q);
Milind Upadhyayc5beba12022-12-17 17:41:20 -0800766 os << absl::StrFormat(
767 "{x: %.3f, y: %.3f, z: %.3f, roll: %.3f, pitch: "
768 "%.3f, yaw: %.3f}",
769 pose.p(0), pose.p(1), pose.p(2), rpy(0), rpy(1), rpy(2));
770 return os;
771}
772
773std::ostream &operator<<(std::ostream &os,
774 ceres::examples::Constraint3d constraint) {
775 os << absl::StrFormat("{id_begin: %d, id_end: %d, pose: ",
776 constraint.id_begin, constraint.id_end)
777 << constraint.t_be << "}";
778 return os;
779}