blob: 5ce62a019fdddd995333c71fbf7575cbe8e4e27a [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"
Milind Upadhyay7c205222022-11-16 18:20:58 -08004#include "frc971/control_loops/control_loop.h"
Milind Upadhyayc5beba12022-12-17 17:41:20 -08005#include "frc971/vision/ceres/pose_graph_3d_error_term.h"
Milind Upadhyay7c205222022-11-16 18:20:58 -08006#include "frc971/vision/geometry.h"
7
8DEFINE_uint64(max_num_iterations, 100,
9 "Maximum number of iterations for the ceres solver");
10
11namespace frc971::vision {
12
Milind Upadhyayc5beba12022-12-17 17:41:20 -080013Eigen::Affine3d PoseUtils::Pose3dToAffine3d(
14 const ceres::examples::Pose3d &pose3d) {
Milind Upadhyay7c205222022-11-16 18:20:58 -080015 Eigen::Affine3d H_world_pose =
Milind Upadhyayc5beba12022-12-17 17:41:20 -080016 Eigen::Translation3d(pose3d.p(0), pose3d.p(1), pose3d.p(2)) * pose3d.q;
Milind Upadhyay7c205222022-11-16 18:20:58 -080017 return H_world_pose;
18}
19
Milind Upadhyayc5beba12022-12-17 17:41:20 -080020ceres::examples::Pose3d PoseUtils::Affine3dToPose3d(const Eigen::Affine3d &H) {
21 return ceres::examples::Pose3d{.p = H.translation(),
22 .q = Eigen::Quaterniond(H.rotation())};
Milind Upadhyay7c205222022-11-16 18:20:58 -080023}
24
Milind Upadhyayc5beba12022-12-17 17:41:20 -080025ceres::examples::Pose3d PoseUtils::ComputeRelativePose(
26 const ceres::examples::Pose3d &pose_1,
27 const ceres::examples::Pose3d &pose_2) {
28 Eigen::Affine3d H_world_1 = Pose3dToAffine3d(pose_1);
29 Eigen::Affine3d H_world_2 = Pose3dToAffine3d(pose_2);
Milind Upadhyay7c205222022-11-16 18:20:58 -080030
31 // Get the location of 2 in the 1 frame
32 Eigen::Affine3d H_1_2 = H_world_1.inverse() * H_world_2;
Milind Upadhyayc5beba12022-12-17 17:41:20 -080033 return Affine3dToPose3d(H_1_2);
Milind Upadhyay7c205222022-11-16 18:20:58 -080034}
35
Milind Upadhyayc5beba12022-12-17 17:41:20 -080036ceres::examples::Pose3d PoseUtils::ComputeOffsetPose(
37 const ceres::examples::Pose3d &pose_1,
38 const ceres::examples::Pose3d &pose_2_relative) {
39 auto H_world_1 = Pose3dToAffine3d(pose_1);
40 auto H_1_2 = Pose3dToAffine3d(pose_2_relative);
Milind Upadhyay7c205222022-11-16 18:20:58 -080041 auto H_world_2 = H_world_1 * H_1_2;
42
Milind Upadhyayc5beba12022-12-17 17:41:20 -080043 return Affine3dToPose3d(H_world_2);
Milind Upadhyay7c205222022-11-16 18:20:58 -080044}
45
Milind Upadhyayc5beba12022-12-17 17:41:20 -080046Eigen::Quaterniond PoseUtils::EulerAnglesToQuaternion(
47 const Eigen::Vector3d &rpy) {
48 Eigen::AngleAxisd roll_angle(rpy.x(), Eigen::Vector3d::UnitX());
49 Eigen::AngleAxisd pitch_angle(rpy.y(), Eigen::Vector3d::UnitY());
50 Eigen::AngleAxisd yaw_angle(rpy.z(), Eigen::Vector3d::UnitZ());
51
52 return yaw_angle * pitch_angle * roll_angle;
Milind Upadhyay7c205222022-11-16 18:20:58 -080053}
54
Milind Upadhyayc5beba12022-12-17 17:41:20 -080055Eigen::Vector3d PoseUtils::QuaternionToEulerAngles(
56 const Eigen::Quaterniond &q) {
57 return RotationMatrixToEulerAngles(q.toRotationMatrix());
Milind Upadhyay7c205222022-11-16 18:20:58 -080058}
59
Milind Upadhyayc5beba12022-12-17 17:41:20 -080060Eigen::Vector3d PoseUtils::RotationMatrixToEulerAngles(
61 const Eigen::Matrix3d &R) {
62 double roll = aos::math::NormalizeAngle(std::atan2(R(2, 1), R(2, 2)));
63 double pitch = aos::math::NormalizeAngle(-std::asin(R(2, 0)));
64 double yaw = aos::math::NormalizeAngle(std::atan2(R(1, 0), R(0, 0)));
65
66 return Eigen::Vector3d(roll, pitch, yaw);
67}
68
69ceres::examples::VectorOfConstraints DataAdapter::MatchTargetDetections(
Milind Upadhyayec493912022-12-18 21:33:15 -080070 const std::vector<DataAdapter::TimestampedDetection>
71 &timestamped_target_detections,
72 aos::distributed_clock::duration max_dt) {
73 CHECK_GE(timestamped_target_detections.size(), 2ul)
74 << "Must have at least 2 detections";
75
76 // Match consecutive detections
Milind Upadhyayc5beba12022-12-17 17:41:20 -080077 ceres::examples::VectorOfConstraints target_constraints;
Milind Upadhyayec493912022-12-18 21:33:15 -080078 for (auto it = timestamped_target_detections.begin() + 1;
79 it < timestamped_target_detections.end(); it++) {
80 auto last_detection = *(it - 1);
81
82 // Skip two consecutive detections of the same target, because the solver
83 // doesn't allow this
84 if (it->id == last_detection.id) {
85 continue;
86 }
87
88 // Don't take into account constraints too far apart in time, because the
89 // recording device could have moved too much
90 if ((it->time - last_detection.time) > max_dt) {
91 continue;
92 }
93
Milind Upadhyayebf93ee2023-01-05 14:12:58 -080094 auto confidence = ComputeConfidence(last_detection.time, it->time,
95 last_detection.distance_from_camera,
96 it->distance_from_camera);
Milind Upadhyayec493912022-12-18 21:33:15 -080097 target_constraints.emplace_back(
98 ComputeTargetConstraint(last_detection, *it, confidence));
99 }
100
101 return target_constraints;
102}
103
Milind Upadhyayc5beba12022-12-17 17:41:20 -0800104TargetMapper::ConfidenceMatrix DataAdapter::ComputeConfidence(
Milind Upadhyay7c205222022-11-16 18:20:58 -0800105 aos::distributed_clock::time_point start,
Milind Upadhyayebf93ee2023-01-05 14:12:58 -0800106 aos::distributed_clock::time_point end, double distance_from_camera_start,
107 double distance_from_camera_end) {
Milind Upadhyay7c205222022-11-16 18:20:58 -0800108 constexpr size_t kX = 0;
109 constexpr size_t kY = 1;
Milind Upadhyayc5beba12022-12-17 17:41:20 -0800110 constexpr size_t kZ = 2;
111 constexpr size_t kOrientation1 = 3;
112 constexpr size_t kOrientation2 = 4;
113 constexpr size_t kOrientation3 = 5;
Milind Upadhyay7c205222022-11-16 18:20:58 -0800114
115 // Uncertainty matrix between start and end
Milind Upadhyayc5beba12022-12-17 17:41:20 -0800116 TargetMapper::ConfidenceMatrix P = TargetMapper::ConfidenceMatrix::Zero();
Milind Upadhyay7c205222022-11-16 18:20:58 -0800117
118 {
119 // Noise for odometry-based robot position measurements
Milind Upadhyayc5beba12022-12-17 17:41:20 -0800120 TargetMapper::ConfidenceMatrix Q_odometry =
121 TargetMapper::ConfidenceMatrix::Zero();
Milind Upadhyay7c205222022-11-16 18:20:58 -0800122 Q_odometry(kX, kX) = std::pow(0.045, 2);
123 Q_odometry(kY, kY) = std::pow(0.045, 2);
Milind Upadhyayc5beba12022-12-17 17:41:20 -0800124 Q_odometry(kZ, kZ) = std::pow(0.045, 2);
125 Q_odometry(kOrientation1, kOrientation1) = std::pow(0.01, 2);
126 Q_odometry(kOrientation2, kOrientation2) = std::pow(0.01, 2);
127 Q_odometry(kOrientation3, kOrientation3) = std::pow(0.01, 2);
Milind Upadhyay7c205222022-11-16 18:20:58 -0800128
129 // Add uncertainty for robot position measurements from start to end
130 int iterations = (end - start) / frc971::controls::kLoopFrequency;
131 P += static_cast<double>(iterations) * Q_odometry;
132 }
133
134 {
Milind Upadhyayebf93ee2023-01-05 14:12:58 -0800135 // Noise for vision-based target localizations. Multiplying this matrix by
136 // the distance from camera to target squared results in the uncertainty in
137 // that measurement
Milind Upadhyayc5beba12022-12-17 17:41:20 -0800138 TargetMapper::ConfidenceMatrix Q_vision =
139 TargetMapper::ConfidenceMatrix::Zero();
Milind Upadhyayebf93ee2023-01-05 14:12:58 -0800140 Q_vision(kX, kX) = std::pow(0.045, 2);
141 Q_vision(kY, kY) = std::pow(0.045, 2);
Milind Upadhyayc5beba12022-12-17 17:41:20 -0800142 Q_vision(kZ, kZ) = std::pow(0.045, 2);
143 Q_vision(kOrientation1, kOrientation1) = std::pow(0.02, 2);
144 Q_vision(kOrientation2, kOrientation2) = std::pow(0.02, 2);
145 Q_vision(kOrientation3, kOrientation3) = std::pow(0.02, 2);
Milind Upadhyay7c205222022-11-16 18:20:58 -0800146
147 // Add uncertainty for the 2 vision measurements (1 at start and 1 at end)
Milind Upadhyayebf93ee2023-01-05 14:12:58 -0800148 P += Q_vision * std::pow(distance_from_camera_start, 2);
149 P += Q_vision * std::pow(distance_from_camera_end, 2);
Milind Upadhyay7c205222022-11-16 18:20:58 -0800150 }
151
152 return P.inverse();
153}
154
Milind Upadhyayc5beba12022-12-17 17:41:20 -0800155ceres::examples::Constraint3d DataAdapter::ComputeTargetConstraint(
Milind Upadhyay7c205222022-11-16 18:20:58 -0800156 const TimestampedDetection &target_detection_start,
Milind Upadhyay7c205222022-11-16 18:20:58 -0800157 const TimestampedDetection &target_detection_end,
Milind Upadhyayc5beba12022-12-17 17:41:20 -0800158 const TargetMapper::ConfidenceMatrix &confidence) {
Milind Upadhyay7c205222022-11-16 18:20:58 -0800159 // Compute the relative pose (constraint) between the two targets
160 Eigen::Affine3d H_targetstart_targetend =
Milind Upadhyayc5beba12022-12-17 17:41:20 -0800161 target_detection_start.H_robot_target.inverse() *
Milind Upadhyay7c205222022-11-16 18:20:58 -0800162 target_detection_end.H_robot_target;
Milind Upadhyayc5beba12022-12-17 17:41:20 -0800163 ceres::examples::Pose3d target_constraint =
164 PoseUtils::Affine3dToPose3d(H_targetstart_targetend);
Milind Upadhyay7c205222022-11-16 18:20:58 -0800165
Milind Upadhyayc5beba12022-12-17 17:41:20 -0800166 return ceres::examples::Constraint3d{
167 target_detection_start.id,
168 target_detection_end.id,
169 {target_constraint.p, target_constraint.q},
170 confidence};
Milind Upadhyayec493912022-12-18 21:33:15 -0800171}
172
Milind Upadhyay7c205222022-11-16 18:20:58 -0800173TargetMapper::TargetMapper(
Milind Upadhyaycd677a32022-12-04 13:06:43 -0800174 std::string_view target_poses_path,
Milind Upadhyayc5beba12022-12-17 17:41:20 -0800175 const ceres::examples::VectorOfConstraints &target_constraints)
Milind Upadhyaycd677a32022-12-04 13:06:43 -0800176 : target_constraints_(target_constraints) {
177 aos::FlatbufferDetachedBuffer<TargetMap> target_map =
178 aos::JsonFileToFlatbuffer<TargetMap>(target_poses_path);
179 for (const auto *target_pose_fbs : *target_map.message().target_poses()) {
Milind Upadhyayc5beba12022-12-17 17:41:20 -0800180 target_poses_[target_pose_fbs->id()] = ceres::examples::Pose3d{
181 Eigen::Vector3d(target_pose_fbs->x(), target_pose_fbs->y(),
182 target_pose_fbs->z()),
183 PoseUtils::EulerAnglesToQuaternion(
184 Eigen::Vector3d(target_pose_fbs->roll(), target_pose_fbs->pitch(),
185 target_pose_fbs->yaw()))};
Milind Upadhyaycd677a32022-12-04 13:06:43 -0800186 }
187}
188
189TargetMapper::TargetMapper(
Milind Upadhyayc5beba12022-12-17 17:41:20 -0800190 const ceres::examples::MapOfPoses &target_poses,
191 const ceres::examples::VectorOfConstraints &target_constraints)
Milind Upadhyay7c205222022-11-16 18:20:58 -0800192 : target_poses_(target_poses), target_constraints_(target_constraints) {}
193
194std::optional<TargetMapper::TargetPose> TargetMapper::GetTargetPoseById(
195 std::vector<TargetMapper::TargetPose> target_poses, TargetId target_id) {
196 for (auto target_pose : target_poses) {
197 if (target_pose.id == target_id) {
198 return target_pose;
199 }
200 }
201
202 return std::nullopt;
203}
204
Milind Upadhyayc5beba12022-12-17 17:41:20 -0800205// Taken from ceres/examples/slam/pose_graph_3d/pose_graph_3d.cc
206// Constructs the nonlinear least squares optimization problem from the pose
207// graph constraints.
Milind Upadhyay7c205222022-11-16 18:20:58 -0800208void TargetMapper::BuildOptimizationProblem(
Milind Upadhyayc5beba12022-12-17 17:41:20 -0800209 const ceres::examples::VectorOfConstraints &constraints,
210 ceres::examples::MapOfPoses *poses, ceres::Problem *problem) {
211 CHECK(poses != nullptr);
212 CHECK(problem != nullptr);
Milind Upadhyay7c205222022-11-16 18:20:58 -0800213 if (constraints.empty()) {
Milind Upadhyayc5beba12022-12-17 17:41:20 -0800214 LOG(INFO) << "No constraints, no problem to optimize.";
Milind Upadhyay7c205222022-11-16 18:20:58 -0800215 return;
216 }
217
Milind Upadhyayc5beba12022-12-17 17:41:20 -0800218 ceres::LossFunction *loss_function = NULL;
219 ceres::LocalParameterization *quaternion_local_parameterization =
220 new ceres::EigenQuaternionParameterization;
Milind Upadhyay7c205222022-11-16 18:20:58 -0800221
Milind Upadhyayc5beba12022-12-17 17:41:20 -0800222 for (ceres::examples::VectorOfConstraints::const_iterator constraints_iter =
223 constraints.begin();
Milind Upadhyay7c205222022-11-16 18:20:58 -0800224 constraints_iter != constraints.end(); ++constraints_iter) {
Milind Upadhyayc5beba12022-12-17 17:41:20 -0800225 const ceres::examples::Constraint3d &constraint = *constraints_iter;
Milind Upadhyay7c205222022-11-16 18:20:58 -0800226
Milind Upadhyayc5beba12022-12-17 17:41:20 -0800227 ceres::examples::MapOfPoses::iterator pose_begin_iter =
Milind Upadhyay7c205222022-11-16 18:20:58 -0800228 poses->find(constraint.id_begin);
229 CHECK(pose_begin_iter != poses->end())
230 << "Pose with ID: " << constraint.id_begin << " not found.";
Milind Upadhyayc5beba12022-12-17 17:41:20 -0800231 ceres::examples::MapOfPoses::iterator pose_end_iter =
Milind Upadhyay7c205222022-11-16 18:20:58 -0800232 poses->find(constraint.id_end);
233 CHECK(pose_end_iter != poses->end())
234 << "Pose with ID: " << constraint.id_end << " not found.";
235
Milind Upadhyayc5beba12022-12-17 17:41:20 -0800236 const Eigen::Matrix<double, 6, 6> sqrt_information =
Milind Upadhyay7c205222022-11-16 18:20:58 -0800237 constraint.information.llt().matrixL();
238 // Ceres will take ownership of the pointer.
239 ceres::CostFunction *cost_function =
Milind Upadhyayc5beba12022-12-17 17:41:20 -0800240 ceres::examples::PoseGraph3dErrorTerm::Create(constraint.t_be,
241 sqrt_information);
Milind Upadhyay7c205222022-11-16 18:20:58 -0800242
Milind Upadhyayc5beba12022-12-17 17:41:20 -0800243 problem->AddResidualBlock(cost_function, loss_function,
244 pose_begin_iter->second.p.data(),
245 pose_begin_iter->second.q.coeffs().data(),
246 pose_end_iter->second.p.data(),
247 pose_end_iter->second.q.coeffs().data());
248
249 problem->SetParameterization(pose_begin_iter->second.q.coeffs().data(),
250 quaternion_local_parameterization);
251 problem->SetParameterization(pose_end_iter->second.q.coeffs().data(),
252 quaternion_local_parameterization);
Milind Upadhyay7c205222022-11-16 18:20:58 -0800253 }
254
Milind Upadhyayc5beba12022-12-17 17:41:20 -0800255 // The pose graph optimization problem has six DOFs that are not fully
Milind Upadhyay7c205222022-11-16 18:20:58 -0800256 // constrained. This is typically referred to as gauge freedom. You can apply
257 // a rigid body transformation to all the nodes and the optimization problem
258 // will still have the exact same cost. The Levenberg-Marquardt algorithm has
259 // internal damping which mitigates this issue, but it is better to properly
260 // constrain the gauge freedom. This can be done by setting one of the poses
261 // as constant so the optimizer cannot change it.
Milind Upadhyayc5beba12022-12-17 17:41:20 -0800262 ceres::examples::MapOfPoses::iterator pose_start_iter = poses->begin();
Milind Upadhyay7c205222022-11-16 18:20:58 -0800263 CHECK(pose_start_iter != poses->end()) << "There are no poses.";
Milind Upadhyayc5beba12022-12-17 17:41:20 -0800264 problem->SetParameterBlockConstant(pose_start_iter->second.p.data());
265 problem->SetParameterBlockConstant(pose_start_iter->second.q.coeffs().data());
Milind Upadhyay7c205222022-11-16 18:20:58 -0800266}
267
Milind Upadhyayc5beba12022-12-17 17:41:20 -0800268// Taken from ceres/examples/slam/pose_graph_3d/pose_graph_3d.cc
Milind Upadhyay7c205222022-11-16 18:20:58 -0800269bool TargetMapper::SolveOptimizationProblem(ceres::Problem *problem) {
270 CHECK_NOTNULL(problem);
271
272 ceres::Solver::Options options;
273 options.max_num_iterations = FLAGS_max_num_iterations;
274 options.linear_solver_type = ceres::SPARSE_NORMAL_CHOLESKY;
275
276 ceres::Solver::Summary summary;
277 ceres::Solve(options, problem, &summary);
278
Milind Upadhyaycd677a32022-12-04 13:06:43 -0800279 LOG(INFO) << summary.FullReport() << '\n';
Milind Upadhyay7c205222022-11-16 18:20:58 -0800280
281 return summary.IsSolutionUsable();
282}
283
Milind Upadhyay05652cb2022-12-07 20:51:51 -0800284void TargetMapper::Solve(std::string_view field_name,
285 std::optional<std::string_view> output_dir) {
Milind Upadhyay7c205222022-11-16 18:20:58 -0800286 ceres::Problem problem;
Milind Upadhyayc5beba12022-12-17 17:41:20 -0800287 BuildOptimizationProblem(target_constraints_, &target_poses_, &problem);
Milind Upadhyay7c205222022-11-16 18:20:58 -0800288
289 CHECK(SolveOptimizationProblem(&problem))
290 << "The solve was not successful, exiting.";
291
Milind Upadhyay05652cb2022-12-07 20:51:51 -0800292 auto map_json = MapToJson(field_name);
Milind Upadhyaycd677a32022-12-04 13:06:43 -0800293 VLOG(1) << "Solved target poses: " << map_json;
Milind Upadhyay05652cb2022-12-07 20:51:51 -0800294
295 if (output_dir.has_value()) {
296 std::string output_path =
297 absl::StrCat(output_dir.value(), "/", field_name, ".json");
298 LOG(INFO) << "Writing map to file: " << output_path;
299 aos::util::WriteStringToFileOrDie(output_path, map_json);
Milind Upadhyaycd677a32022-12-04 13:06:43 -0800300 }
301}
302
Milind Upadhyay05652cb2022-12-07 20:51:51 -0800303std::string TargetMapper::MapToJson(std::string_view field_name) const {
Milind Upadhyaycd677a32022-12-04 13:06:43 -0800304 flatbuffers::FlatBufferBuilder fbb;
305
306 // Convert poses to flatbuffers
307 std::vector<flatbuffers::Offset<TargetPoseFbs>> target_poses_fbs;
308 for (const auto &[id, pose] : target_poses_) {
309 TargetPoseFbs::Builder target_pose_builder(fbb);
310 target_pose_builder.add_id(id);
Milind Upadhyayc5beba12022-12-17 17:41:20 -0800311
312 target_pose_builder.add_x(pose.p(0));
313 target_pose_builder.add_y(pose.p(1));
314 target_pose_builder.add_z(pose.p(2));
315
316 auto rpy = PoseUtils::QuaternionToEulerAngles(pose.q);
317 target_pose_builder.add_roll(rpy.x());
318 target_pose_builder.add_pitch(rpy.y());
319 target_pose_builder.add_yaw(rpy.z());
Milind Upadhyaycd677a32022-12-04 13:06:43 -0800320
321 target_poses_fbs.emplace_back(target_pose_builder.Finish());
322 }
323
Milind Upadhyay05652cb2022-12-07 20:51:51 -0800324 const auto field_name_offset = fbb.CreateString(field_name);
325 flatbuffers::Offset<TargetMap> target_map_offset = CreateTargetMap(
326 fbb, fbb.CreateVector(target_poses_fbs), field_name_offset);
Milind Upadhyaycd677a32022-12-04 13:06:43 -0800327
328 return aos::FlatbufferToJson(
329 flatbuffers::GetMutableTemporaryPointer(fbb, target_map_offset),
330 {.multi_line = true});
Milind Upadhyay7c205222022-11-16 18:20:58 -0800331}
332
Milind Upadhyayc5beba12022-12-17 17:41:20 -0800333std::ostream &operator<<(std::ostream &os, ceres::examples::Pose3d pose) {
334 auto rpy = PoseUtils::QuaternionToEulerAngles(pose.q);
335 os << absl::StrFormat(
336 "{x: %.3f, y: %.3f, z: %.3f, roll: %.3f, pitch: "
337 "%.3f, yaw: %.3f}",
338 pose.p(0), pose.p(1), pose.p(2), rpy(0), rpy(1), rpy(2));
339 return os;
340}
341
342std::ostream &operator<<(std::ostream &os,
343 ceres::examples::Constraint3d constraint) {
344 os << absl::StrFormat("{id_begin: %d, id_end: %d, pose: ",
345 constraint.id_begin, constraint.id_end)
346 << constraint.t_be << "}";
347 return os;
348}
349
Milind Upadhyay7c205222022-11-16 18:20:58 -0800350} // namespace frc971::vision