Momentum
A library for solving nonlinear optimization problems related to human body kinematics
Loading...
Searching...
No Matches
utility.cpp
Go to the documentation of this file.
1/*
2 * Copyright (c) Meta Platforms, Inc. and affiliates.
3 *
4 * This source code is licensed under the MIT license found in the
5 * LICENSE file in the root directory of this source tree.
6 */
7
9
12
13#include <Eigen/Eigenvalues>
14
15#include <algorithm>
16#include <limits>
17#include <type_traits>
18
19namespace momentum {
20
21namespace {
22
23template <typename T>
24constexpr T eulerTol() {
25 // Tolerance used to determine when sin(tol) can be considered approximately zero for the given
26 // floating-point type (float or double). These values have been chosen based on a balance between
27 // the precision of the floating-point type and numerical stability.
28 return Eps<T>(T(1e-6), T(1e-12));
29}
30
31} // namespace
32
33template <typename T>
35 // Reference: "Practical Parameterization of Rotations Using the Exponential Map"
36 // by F. Sebastian Grassia, Journal of Graphics Tools, 1998.
37 // https://www.cs.cmu.edu/~spiff/moedit99/expmap.pdf
38
39 // Compute the rotation angle (norm of the rotation vector)
40 const T theta = v.norm();
41
42 // For numerical stability, use Taylor series for small angles
43 // Threshold is sqrt(epsilon): ~3.5e-4 for float, ~1.5e-8 for double
44 constexpr T kSmallAngleThreshold = Eps<T>(T(3.5e-4), T(1.5e-8));
45
46 if (theta < kSmallAngleThreshold) {
47 // Taylor expansion of exp(v) = [cos(theta/2), sin(theta/2)/theta * v] about
48 // theta = 0, truncated at O(theta^2). The expansion avoids the cancellation that
49 // would occur in 1 - cos(theta/2) and the 0/0 division in sin(theta/2)/theta for
50 // tiny theta. The truncation error is ~O(theta^4), which at the threshold
51 // (sqrt(eps)) is on the order of eps^2 — well below floating-point precision.
52 // The explicit normalize() compensates for the residual ~theta^4 deviation from
53 // unit norm; the standard branch below produces a unit quaternion analytically
54 // and so does not need it.
55 const T theta2 = theta * theta;
56 const T w = T(1) - theta2 / T(8);
57 const T scale = T(0.5) * (T(1) - theta2 / T(24));
58
59 Quaternion<T> q(w, scale * v.x(), scale * v.y(), scale * v.z());
60 q.normalize();
61 return q;
62 } else {
63 // Standard computation: exp([0, v]) = [cos(theta), sin(theta)/theta * v]
64 const T halfTheta = theta / T(2);
65 const T sinHalfTheta = std::sin(halfTheta);
66 const T cosHalfTheta = std::cos(halfTheta);
67 const T scale = sinHalfTheta / theta;
68
69 return Quaternion<T>(cosHalfTheta, scale * v.x(), scale * v.y(), scale * v.z());
70 }
71}
72
73template <typename T>
75 // Reference: "Practical Parameterization of Rotations Using the Exponential Map"
76 // by F. Sebastian Grassia, Journal of Graphics Tools, 1998.
77 // https://www.cs.cmu.edu/~spiff/moedit99/expmap.pdf
78
79 // Ensure the quaternion is normalized
80 Quaternion<T> qNorm = q.normalized();
81
82 // Extract components
83 const T w = qNorm.w();
84 const Vector3<T> vec(qNorm.x(), qNorm.y(), qNorm.z());
85 const T vecNorm = vec.norm();
86
87 // For numerical stability, use Taylor series for small angles
88 // Threshold is sqrt(epsilon): ~3.5e-4 for float, ~1.5e-8 for double
89 constexpr T kSmallAngleThreshold = Eps<T>(T(3.5e-4), T(1.5e-8));
90
91 if (vecNorm < kSmallAngleThreshold) {
92 if (w > T(0)) {
93 // Close to identity: Taylor-expand log(q) = 2*atan2(||v||,w)/||v|| * v about
94 // ||v||=0 keeping w = sqrt(1-||v||^2). To O(||v||^2): log(q) ≈ 2*v*(1 + ||v||^2/6).
95 // This avoids the 0/0 in atan2/||v||.
96 const T vecNorm2 = vec.squaredNorm();
97 const T scale = T(2) * (T(1) + vecNorm2 / T(6));
98 return scale * vec;
99 } else {
100 // Close to -identity (a pi rotation): the log is multi-valued — any axis n
101 // gives the same -identity quaternion via exp(pi*n). We pick the x-axis
102 // arbitrarily for determinism. Callers that need a continuous log near pi
103 // should track the rotation axis externally.
104 return Vector3<T>(pi<T>(), T(0), T(0));
105 }
106 }
107
108 // Standard computation: log([w, v]) = 2 * atan2(||v||, w) / ||v|| * v.
109 // atan2 (rather than acos(w)) is used for accuracy near both 0 and pi.
110 const T theta = T(2) * std::atan2(vecNorm, w);
111 const T scale = theta / vecNorm;
112
113 return scale * vec;
114}
115
116// Reference: "Practical Parameterization of Rotations Using the Exponential Map"
117// by F. Sebastian Grassia, Journal of Graphics Tools, 1998.
118// https://www.cs.cmu.edu/~spiff/moedit99/expmap.pdf
119template <typename T>
120Eigen::Matrix<T, 3, 4> quaternionLogMapDerivative(const Quaternion<T>& q) {
121 // Ensure the quaternion is normalized
122 const Quaternion<T> qNorm = q.normalized();
123
124 // Extract components: q.coeffs() = [x, y, z, w]
125 const T w = qNorm.w();
126 const Vector3<T> vec(qNorm.x(), qNorm.y(), qNorm.z());
127 const T vecNorm = vec.norm();
128
129 // For numerical stability, use Taylor series for small angles
130 constexpr T kSmallAngleThreshold = Eps<T>(T(3.5e-4), T(1.5e-8));
131
132 Eigen::Matrix<T, 3, 4> jacobian;
133
134 if (vecNorm < kSmallAngleThreshold) {
135 // Near identity: log(q) ≈ 2 * vec * (1 + vec.squaredNorm()/6)
136 // For small ||vec||, we can compute the derivatives analytically
137 const T vecNorm2 = vec.squaredNorm();
138 const T scale = T(2) * (T(1) + vecNorm2 / T(6));
139
140 // d(log)/d(vec) ≈ 2 * I * (1 + vecNorm2/6) + 2 * vec * vec^T / 3
141 // Columns 0, 1, 2 are for x, y, z
142 for (int i = 0; i < 3; ++i) {
143 for (int j = 0; j < 3; ++j) {
144 jacobian(i, j) = (i == j ? scale : T(0)) + T(2) * vec(i) * vec(j) / T(3);
145 }
146 }
147
148 // d(log)/dw ≈ 0 for small angles (higher order terms)
149 // Column 3 is for w
150 jacobian.col(3).setZero();
151 } else {
152 // Standard computation: log([w, v]) = theta / ||v|| * v
153 // where theta = 2 * atan2(||v||, w)
154 const T theta = T(2) * std::atan2(vecNorm, w);
155 const T scale = theta / vecNorm;
156
157 // Compute d(theta)/dw and d(theta)/d(vec)
158 // theta = 2 * atan2(||v||, w)
159 // d(theta)/dw = -2 * ||v|| / (w^2 + ||v||^2)
160 // d(theta)/d(vec_i) = 2 * w * vec_i / (||v|| * (w^2 + ||v||^2))
161 const T denom = w * w + vecNorm * vecNorm;
162 const T dthetaDw = -T(2) * vecNorm / denom;
163 const Vector3<T> dthetaDvec = T(2) * w * vec / (vecNorm * denom);
164
165 // d(log)/d(vec_j) = d(theta/||v||)/d(vec_j) * v + (theta/||v||) * d(v)/d(vec_j)
166 // where d(theta/||v||)/d(vec_j) = d(theta)/d(vec_j) / ||v|| - theta * vec_j / ||v||^3
167 // Columns 0, 1, 2 are for x, y, z
168 for (int j = 0; j < 3; ++j) {
169 const T dScaleDvecj =
170 dthetaDvec(j) / vecNorm - theta * vec(j) / (vecNorm * vecNorm * vecNorm);
171 for (int i = 0; i < 3; ++i) {
172 jacobian(i, j) = dScaleDvecj * vec(i) + (i == j ? scale : T(0));
173 }
174 }
175
176 // Now compute d(log)/dw using product rule:
177 // log = (theta / ||v||) * v
178 // d(log)/dw = d(theta/||v||)/dw * v = (d(theta)/dw) / ||v|| * v
179 // Column 3 is for w
180 jacobian.col(3) = dthetaDw / vecNorm * vec;
181 }
182
183 return jacobian;
184}
185
186template <typename T>
188 const Matrix3<T>& m,
189 int axis0,
190 int axis1,
191 int axis2,
192 EulerConvention convention) {
193 if (convention == EulerConvention::Extrinsic) {
194 return rotationMatrixToEuler(m, axis2, axis1, axis0, EulerConvention::Intrinsic).reverse();
195 }
196
197 return m.eulerAngles(axis0, axis1, axis2);
198}
199
200template <typename T>
202 // If the convention is extrinsic, convert it to intrinsic and reverse the order
203 if (convention == EulerConvention::Extrinsic) {
205 }
206
207 // Reference: https://en.wikipedia.org/wiki/Euler_angles
208 // Rotation matrix representation:
209 // | r00 r01 r02 | | cy*cz -cy*sz sy |
210 // | r10 r11 r12 | = | cx*sz + sx*sy*cz cx*cz - sx*sy*sz -sx*cy |
211 // | r20 r21 r22 | | ... ... cx*cy |
212
213 // Computes the rotation matrix from Euler angles similarly in the following way but with a
214 // different Euler angle order: http://eecs.qmul.ac.uk/~gslabaugh/publications/euler.pdf
215 Vector3<T> res;
216 // Check if the matrix element m(0, 2) == sin(y) is not close to 1 or -1
217 if (m(0, 2) < T(1) - eulerTol<T>()) {
218 if (m(0, 2) > T(-1) + eulerTol<T>()) {
219 res.x() = std::atan2(-m(1, 2), m(2, 2));
220 res.y() = std::asin(m(0, 2));
221 res.z() = std::atan2(-m(0, 1), m(0, 0));
222 } else {
223 // Gimbal lock at sin(y) == -1: cos(y) == 0, so all entries with cy as a factor
224 // (m(0,0), m(0,1), m(1,2), m(2,2)) become zero. Use the remaining non-zero
225 // elements (m(1,0), m(1,1)) and choose res.x() = 0 to resolve the family of
226 // solutions; analytically the result has -res.x() - atan2(...) freedom.
227 res.x() = 0; // any angle can be OK, but we choose zero
228 res.y() = -pi<T>() * T(0.5); // choose in [-pi, pi]
229 res.z() = std::atan2(m(1, 0), m(1, 1)); // -res.x() - atan2(...) but we use res.x() == 0
230 }
231 } else {
232 // Gimbal lock at sin(y) == 1: same zero pattern as the sin(y) == -1 branch above;
233 // here the analytical freedom is res.x() - atan2(...).
234 res.x() = 0; // any angle can be OK, but we choose zero
235 res.y() = pi<T>() * T(0.5); // choose in [-pi, pi]
236 res.z() = std::atan2(m(1, 0), m(1, 1)); // res.x() - atan2(...) but we use res.x() == 0
237 }
238 return res;
239}
240
241template <typename T>
243 // If the convention is extrinsic, convert it to intrinsic and reverse the order
244 if (convention == EulerConvention::Extrinsic) {
246 }
247
248 // Reference: https://en.wikipedia.org/wiki/Euler_angles
249 // Rotation matrix representation. NOTE: in the matrix below, (cx,sx) denotes cos/sin
250 // of the FIRST returned angle (the Z rotation in ZYX), and (cz,sz) denotes the LAST
251 // (the X rotation). This labels-by-output-position convention is the opposite of the
252 // labels-by-rotation-axis convention used by eulerZYXToRotationMatrix; the indices
253 // and signs below are consistent under this aliasing.
254 // | r00 r01 r02 | | cx*cy cx*sy*sz - sx*cz sx*sz + cx*sy*cz |
255 // | r10 r11 r12 | = | sx*cy ... ... |
256 // | r20 r21 r22 | | -sy cy*sz cy*cz |
257
258 // Computes the rotation matrix from Euler angles following:
259 // http://eecs.qmul.ac.uk/~gslabaugh/publications/euler.pdf
260 Vector3<T> res;
261 // Check if the matrix element m(2, 0) == -sin(y) is not close to 1 or -1
262 if (m(2, 0) < T(1) - eulerTol<T>()) {
263 if (m(2, 0) > T(-1) + eulerTol<T>()) {
264 res.x() = std::atan2(m(1, 0), m(0, 0));
265 res.y() = std::asin(-m(2, 0));
266 res.z() = std::atan2(m(2, 1), m(2, 2));
267 } else {
268 // Gimbal lock at sin(y) close to 1 (since m(2,0) == -sin(y) is close to -1):
269 // cos(y) == 0 zeros m(0,0), m(1,0), m(2,1), m(2,2). Recover res.z from the
270 // remaining non-zero entries m(0,1), m(0,2); res.x has analytic freedom and
271 // we pin it to 0.
272 res.x() = 0; // any angle can be OK, but we choose zero
273 res.y() = pi<T>() * T(0.5); // choose in [-pi, pi]
274 res.z() = std::atan2(m(0, 1), m(0, 2)); // res.x() - atan2(...) but we use res.x() == 0
275 }
276 } else {
277 // Gimbal lock at sin(y) close to -1 (since m(2,0) == -sin(y) is close to 1):
278 // same zero pattern as above. The negated arguments to atan2 below are required
279 // because the analytic family is -res.x() - atan2(...), which simplifies to
280 // atan2(-m(0,1), -m(0,2)) at res.x()==0 — NOT the same as atan2(m(0,1),m(0,2)).
281 res.x() = 0; // any angle can be OK, but we choose zero
282 res.y() = -pi<T>() * T(0.5); // choose in [-pi, pi]
283 res.z() = std::atan2(-m(0, 1), -m(0, 2)); // -res.x() - atan2(...) but we use res.x() == 0
284 }
285 return res;
286}
287
288template <typename T>
290 const Vector3<T>& angles,
291 int axis0,
292 int axis1,
293 int axis2,
294 EulerConvention convention) {
295 if (convention == EulerConvention::Extrinsic) {
296 return eulerToQuaternion(
297 angles.reverse().eval(), axis2, axis1, axis0, EulerConvention::Intrinsic);
298 }
299
300 return Quaternion<T>(
301 AngleAxis<T>(angles[0], Vector3<T>::Unit(axis0)) *
302 AngleAxis<T>(angles[1], Vector3<T>::Unit(axis1)) *
303 AngleAxis<T>(angles[2], Vector3<T>::Unit(axis2)));
304}
305
306template <typename T>
308 const Vector3<T>& angles,
309 int axis0,
310 int axis1,
311 int axis2,
312 EulerConvention convention) {
313 return eulerToQuaternion<T>(angles, axis0, axis1, axis2, convention).toRotationMatrix();
314}
315
316template <typename T>
318 if (convention == EulerConvention::Extrinsic) {
319 return eulerZYXToRotationMatrix(angles.reverse().eval(), EulerConvention::Intrinsic);
320 }
321
322 // | r00 r01 r02 | | cy*cz -cy*sz sy |
323 // | r10 r11 r12 | = | cz*sx*sy+cx*sz cx*cz-sx*sy*sz -cy*sx |
324 // | r20 r21 r22 | | -cx*cz*sy+sx*sz cz*sx+cx*sy*sz cx*cy |
325
326 Matrix3<T> res;
327
328 const T cx = std::cos(angles[0]);
329 const T sx = std::sin(angles[0]);
330 const T cy = std::cos(angles[1]);
331 const T sy = std::sin(angles[1]);
332 const T cz = std::cos(angles[2]);
333 const T sz = std::sin(angles[2]);
334
335 res(0, 0) = cy * cz;
336 res(1, 0) = cx * sz + cz * sx * sy;
337 res(2, 0) = sx * sz - cx * cz * sy;
338
339 res(0, 1) = -cy * sz;
340 res(1, 1) = cx * cz - sx * sy * sz;
341 res(2, 1) = cz * sx + cx * sy * sz;
342
343 res(0, 2) = sy;
344 res(1, 2) = -cy * sx;
345 res(2, 2) = cx * cy;
346
347 return res;
348}
349
350template <typename T>
352 if (convention == EulerConvention::Extrinsic) {
353 return eulerXYZToRotationMatrix(angles.reverse().eval(), EulerConvention::Intrinsic);
354 }
355
356 // | r00 r01 r02 | | cy*cz cz*sx*sy-cx*sz cx*cz*sy+sx*sz |
357 // | r10 r11 r12 | = | cy*sz cx*cz+sx*sy*sz -cz*sx+cx*sy*sz |
358 // | r20 r21 r22 | | -sy cy*sx cx*cy |
359
360 Matrix3<T> res;
361
362 const T cz = std::cos(angles[0]);
363 const T sz = std::sin(angles[0]);
364 const T cy = std::cos(angles[1]);
365 const T sy = std::sin(angles[1]);
366 const T cx = std::cos(angles[2]);
367 const T sx = std::sin(angles[2]);
368
369 res(0, 0) = cz * cy;
370 res(1, 0) = sz * cy;
371 res(2, 0) = -sy;
372
373 res(0, 1) = cz * sy * sx - sz * cx;
374 res(1, 1) = sz * sy * sx + cz * cx;
375 res(2, 1) = cy * sx;
376
377 res(0, 2) = cz * sy * cx + sz * sx;
378 res(1, 2) = sz * sy * cx - cz * sx;
379 res(2, 2) = cy * cx;
380
381 return res;
382}
383
384template <typename T>
386 Vector3<T> res;
387 res.x() =
388 std::atan2(T(2) * (q.w() * q.x() + q.y() * q.z()), T(1) - T(2) * (sqr(q.x()) + sqr(q.y())));
389 // Non-unit inputs and floating-point drift can push the pitch term just outside asin's domain.
390 const T sinY = std::clamp(T(2) * (q.w() * q.y() - q.z() * q.x()), T(-1), T(1));
391 res.y() = std::asin(sinY);
392 res.z() =
393 std::atan2(T(2) * (q.w() * q.z() + q.x() * q.y()), T(1) - T(2) * (sqr(q.y()) + sqr(q.z())));
394 return res;
395}
396
398 // Markley et al. "Averaging Quaternions": the average is the unit eigenvector of
399 // M = sum_i w_i^2 * q_i * q_i^T corresponding to the largest eigenvalue. This is
400 // sign-invariant (q and -q produce the same outer product), so it sidesteps the
401 // double-cover ambiguity that breaks naive coefficient averaging.
402 // NOTE: When the i-th weight is missing, this falls back to weight 1, NOT to
403 // (sum of provided weights)/N — partially-specified weight vectors will yield
404 // an unevenly weighted average. Pass a complete `w` or none at all.
405 // NOTE: Weights enter quadratically because each q_i contributes (w_i*q_i)(w_i*q_i)^T.
406 Matrix4f Q = Matrix4f::Zero();
407
408 for (size_t i = 0; i < q.size(); i++) {
409 if (i < w.size()) {
410 Q += (q[i].coeffs() * w[i]) * (q[i].coeffs() * w[i]).transpose();
411 } else {
412 Q += q[i].coeffs() * q[i].coeffs().transpose();
413 }
414 }
415
416 // SelfAdjointEigenSolver sorts eigenvalues ascending, so col(3) is the eigenvector
417 // for the largest eigenvalue — i.e. the average quaternion (up to sign).
418 return Quaternionf(Eigen::SelfAdjointEigenSolver<Matrix4f>(Q).eigenvectors().col(3));
419}
420
421template <typename T>
423 const auto svd = mat.jacobiSvd(Eigen::ComputeThinU | Eigen::ComputeThinV);
424 VectorX<T> singularValues_inv = svd.singularValues();
425 const T maxSingularValue = singularValues_inv.size() > 0 ? singularValues_inv(0) : T(0);
426 if (maxSingularValue <= T(0)) {
427 return MatrixX<T>::Zero(mat.cols(), mat.rows());
428 }
429 // Singular values within the SVD's rounding error of zero count as zero. The cutoff scales with
430 // the matrix size and the largest singular value, as in MATLAB's pinv and numpy.linalg.lstsq.
431 const T pinvtoler =
432 T(std::max(mat.rows(), mat.cols())) * std::numeric_limits<T>::epsilon() * maxSingularValue;
433 for (int j = 0; j < singularValues_inv.size(); ++j) {
434 if (singularValues_inv(j) > pinvtoler) {
435 singularValues_inv(j) = T(1.0) / singularValues_inv(j);
436 } else {
437 singularValues_inv(j) = T(0);
438 }
439 }
440 return (svd.matrixV() * singularValues_inv.asDiagonal() * svd.matrixU().transpose());
441}
442
443template <typename T>
445 return pseudoInverse(mat.toDense());
446}
447
448template <typename T>
449std::tuple<bool, T, Eigen::Vector2<T>> closestPointsOnSegments(
450 const Eigen::Vector3<T>& o1,
451 const Eigen::Vector3<T>& d1,
452 const Eigen::Vector3<T>& o2,
453 const Eigen::Vector3<T>& d2,
454 const T maxDist) {
455 // Standard "closest points on two segments" algorithm: parametrize the segments as
456 // o_i + t * d_i for t in [0,1] and minimize the squared distance subject to that
457 // box constraint. The variables a,b,c,d,e and D = ac-b^2 are the standard names from
458 // the Geometric Tools formulation; sN/sD and tN/tD are the numerator/denominator of
459 // the s and t parameters carried as fractions to defer division until after clamping.
460 // d1 and d2 are NOT required to be unit vectors; their magnitudes set the segment
461 // length, and the returned res values are the parametric distances along d1/d2.
462 Eigen::Vector2<T> res;
463
464 const T maxSquareDist = maxDist * maxDist;
465
466 // first calculate closest point on the lines
467 const auto w = o1 - o2;
468 const auto a = d1.squaredNorm();
469 const auto b = d1.dot(d2);
470 const auto c = d2.squaredNorm();
471 const auto d = d1.dot(w);
472 const auto e = d2.dot(w);
473 const auto D = (a * c - b * b);
474 T sN;
475 T sD = D;
476 T tN;
477 T tD = D;
478
479 // D is the determinant of the 2x2 normal-equations matrix; when small, the segments
480 // are nearly parallel (or one direction has near-zero length) and the linear system
481 // is ill-conditioned, so we pin s=0 and solve for t along d2 only.
482 constexpr T kTolerance = Eps<T>(T(1e-7), T(1e-15));
483 if (D < kTolerance) {
484 sN = T(0);
485 sD = T(1);
486 tN = e;
487 tD = c;
488
489 // early check if we are too far
490 if (w.squaredNorm() > maxSquareDist) {
491 return std::make_tuple(false, std::numeric_limits<T>::max(), Eigen::Vector2<T>::Zero());
492 }
493 } else {
494 sN = (b * e - c * d);
495 tN = (a * e - b * d);
496
497 // early check if the infinite line is too far
498 if ((w + (d1 * sN / D) - (d2 * tN / D)).squaredNorm() > maxSquareDist) {
499 return std::make_tuple(false, std::numeric_limits<T>::max(), Eigen::Vector2<T>::Zero());
500 }
501
502 if (sN < T(0)) {
503 // sc < 0 => the s=0 edge is visible
504 sN = T(0);
505 tN = e;
506 tD = c;
507 } else if (sN > sD) {
508 // sc > 1 => the s=1 edge is visible
509 sN = sD;
510 tN = e + b;
511 tD = c;
512 }
513 }
514
515 // tc < 0 => the t=0 edge is visible
516 if (tN < T(0)) {
517 tN = T(0);
518 // recompute sc for this edge
519 if (-d < T(0)) {
520 sN = T(0);
521 } else if (-d > a) {
522 sN = sD;
523 } else {
524 sN = -d;
525 sD = a;
526 }
527 } else if (tN > tD) {
528 // tc > 1 => the t=1 edge is visible
529 tN = tD;
530 // recompute sc for this edge
531 if ((-d + b) < T(0)) {
532 sN = T(0);
533 } else if ((-d + b) > a) {
534 sN = sD;
535 } else {
536 sN = (-d + b);
537 sD = a;
538 }
539 }
540
541 // finally do the division to get sc and tc
542 // Check for small denominators to avoid division by zero or very small numbers
543 res[0] = (std::abs(sN) < kTolerance || std::abs(sD) < kTolerance) ? T(0) : sN / sD;
544 res[1] = (std::abs(tN) < kTolerance || std::abs(tD) < kTolerance) ? T(0) : tN / tD;
545
546 // get the difference of the two closest points
547 const auto dP = w + (d1 * res[0]) - (d2 * res[1]);
548
549 // check if this is acceptable
550 const T distance = dP.squaredNorm();
551 if (distance > maxSquareDist) {
552 return std::make_tuple(false, std::numeric_limits<T>::max(), Eigen::Vector2<T>::Zero());
553 }
554
555 return std::make_tuple(true, std::sqrt(distance), res);
556}
557
560
563
568
569template Eigen::Matrix<float, 3, 4> quaternionLogMapDerivative(const Quaternion<float>& q);
570template Eigen::Matrix<double, 3, 4> quaternionLogMapDerivative(const Quaternion<double>& q);
571
573 const Matrix3<float>& m,
574 int axis0,
575 int axis1,
576 int axis2,
577 EulerConvention convention);
578
580 const Matrix3<double>& m,
581 int axis0,
582 int axis1,
583 int axis2,
584 EulerConvention convention);
585
587 const Matrix3<float>& m,
588 EulerConvention convention);
589
591 const Matrix3<double>& m,
592 EulerConvention convention);
593
595 const Matrix3<float>& m,
596 EulerConvention convention);
597
599 const Matrix3<double>& m,
600 EulerConvention convention);
601
603 const Vector3<float>& angles,
604 int axis0,
605 int axis1,
606 int axis2,
607 EulerConvention convention);
608
610 const Vector3<double>& angles,
611 int axis0,
612 int axis1,
613 int axis2,
614 EulerConvention convention);
615
617 const Vector3<float>& angles,
618 int axis0,
619 int axis1,
620 int axis2,
621 EulerConvention convention);
622
624 const Vector3<double>& angles,
625 int axis0,
626 int axis1,
627 int axis2,
628 EulerConvention convention);
629
631 const Vector3<float>& angles,
632 EulerConvention convention);
633
635 const Vector3<double>& angles,
636 EulerConvention convention);
637
639 const Vector3<float>& angles,
640 EulerConvention convention);
641
643 const Vector3<double>& angles,
644 EulerConvention convention);
645
648
649template std::tuple<bool, float, Eigen::Vector2<float>> closestPointsOnSegments<float>(
650 const Eigen::Vector3<float>& o1,
651 const Eigen::Vector3<float>& d1,
652 const Eigen::Vector3<float>& o2,
653 const Eigen::Vector3<float>& d2,
654 const float maxDist);
655
656template std::tuple<bool, double, Eigen::Vector2<double>> closestPointsOnSegments<double>(
657 const Eigen::Vector3<double>& o1,
658 const Eigen::Vector3<double>& d1,
659 const Eigen::Vector3<double>& o2,
660 const Eigen::Vector3<double>& d2,
661 const double maxDist);
662
663namespace {
664
665// Rotation matrix for a single axis rotation.
666template <typename T>
667Matrix3<T> singleAxisRotationMatrix(int axis, T angle) {
668 return AngleAxis<T>(angle, Vector3<T>::Unit(axis)).toRotationMatrix();
669}
670
671// Derivative of a single axis rotation matrix with respect to the angle.
672template <typename T>
673Matrix3<T> singleAxisRotationMatrixDerivative(int axis, T angle) {
674 Matrix3<T> dR = Matrix3<T>::Zero();
675 const T c = std::cos(angle);
676 const T s = std::sin(angle);
677
678 if (axis == 0) { // X-axis
679 dR(1, 1) = -s;
680 dR(1, 2) = -c;
681 dR(2, 1) = c;
682 dR(2, 2) = -s;
683 } else if (axis == 1) { // Y-axis
684 dR(0, 0) = -s;
685 dR(0, 2) = c;
686 dR(2, 0) = -c;
687 dR(2, 2) = -s;
688 } else { // Z-axis
689 dR(0, 0) = -s;
690 dR(0, 1) = -c;
691 dR(1, 0) = c;
692 dR(1, 1) = -s;
693 }
694
695 return dR;
696}
697
698// Rotation matrix for a composition R(axis1) * R(axis0). Note the order: axis0 is
699// applied first (innermost), then axis1 — this matches the intrinsic angle ordering
700// used by the Gauss-Newton callers below.
701template <typename T>
702Matrix3<T> twoAxisRotationMatrix(int axis0, int axis1, const Vector2<T>& angles) {
703 return singleAxisRotationMatrix(axis1, angles[1]) * singleAxisRotationMatrix(axis0, angles[0]);
704}
705
706// Returns (dR/dangle0, dR/dangle1) for R = R(axis1) * R(axis0), via the product rule.
707template <typename T>
708std::pair<Matrix3<T>, Matrix3<T>>
709twoAxisRotationMatrixDerivatives(int axis0, int axis1, const Vector2<T>& angles) {
710 const Matrix3<T> R0 = singleAxisRotationMatrix(axis0, angles[0]);
711 const Matrix3<T> R1 = singleAxisRotationMatrix(axis1, angles[1]);
712 const Matrix3<T> dR0 = singleAxisRotationMatrixDerivative(axis0, angles[0]);
713 const Matrix3<T> dR1 = singleAxisRotationMatrixDerivative(axis1, angles[1]);
714
715 return {R1 * dR0, dR1 * R0};
716}
717
718// Gauss-Newton solver minimizing ||R(axis, angle) - target||_F^2 in the angle.
719template <typename T>
720T gaussNewtonSolveScalar(
721 const Matrix3<T>& target,
722 int axis,
723 T initialGuess = T(0),
724 int maxIterations = 20,
725 T tolerance = eulerTol<T>()) {
726 T angle = initialGuess;
727
728 T previousResidual = std::numeric_limits<T>::max();
729 for (int iter = 0; iter < maxIterations; ++iter) {
730 // Compute current rotation matrix and derivative
731 const Matrix3<T> R = singleAxisRotationMatrix(axis, angle);
732
733 // Compute residual (vectorized matrix difference)
734 const Matrix3<T> residualMatrix = R - target;
735 const T residual = residualMatrix.squaredNorm();
736
737 // Convergence: residual already small, OR residual decreased by less than tolerance
738 // since the last iteration. NOTE: the second clause also fires when the residual
739 // *increased* (previousResidual - residual is negative), so this also acts as a
740 // divergence guard rather than a strict monotone-progress check. It does NOT roll
741 // back the diverging step — the last `angle` is whatever the last GN iteration left.
742 if (residual < tolerance || (previousResidual - residual) < tolerance) {
743 break;
744 }
745 previousResidual = residual;
746
747 // Jacobian of the FLATTENED residual r(a) = vec(R(a) - target) w.r.t. the angle a
748 // (a 9x1 column). This is the residual-vector Jacobian, NOT the gradient of the
749 // squared norm — the householderQr().solve below performs a least-squares step
750 // J * delta ≈ -r, which is the Gauss-Newton update.
751 const Matrix3<T> dR = singleAxisRotationMatrixDerivative(axis, angle);
752 const Eigen::Matrix<T, 9, 1> jacobian = dR.reshaped(9, 1);
753
754 const Eigen::Vector<T, 9> residualVector = residualMatrix.reshaped(9, 1);
755
756 const Eigen::Vector<T, 1> delta = jacobian.householderQr().solve(-residualVector);
757
758 // No line search or trust-region — we trust the Gauss-Newton direction directly.
759 angle += delta(0);
760 }
761
762 return angle;
763}
764
765// Gauss-Newton solver minimizing ||R(axis0, axis1, angles) - target||_F^2 in the two-vector
766// of angles.
767template <typename T>
768Vector2<T> gaussNewtonSolveTwoAxis(
769 const Matrix3<T>& target,
770 int axis0,
771 int axis1,
772 const Vector2<T>& initialGuess = Vector2<T>::Zero(),
773 int maxIterations = 20,
774 T tolerance = eulerTol<T>()) {
775 Vector2<T> angles = initialGuess;
776
777 T previousResidualNorm = std::numeric_limits<T>::max();
778 for (int iter = 0; iter < maxIterations; ++iter) {
779 // Compute current rotation matrix and derivatives
780 const Matrix3<T> R = twoAxisRotationMatrix(axis0, axis1, angles);
781 const auto [dR0, dR1] = twoAxisRotationMatrixDerivatives(axis0, axis1, angles);
782
783 // Compute residual matrix and flatten to vector (9x1)
784 const Matrix3<T> residualMatrix = R - target;
785 const T residualNorm = residualMatrix.squaredNorm();
786
787 // Same convergence/divergence behavior as the scalar version above: the second
788 // clause exits both on slow progress and on residual increase, without rolling
789 // back the diverging step.
790 if (residualNorm < tolerance || (previousResidualNorm - residualNorm) < tolerance) {
791 break;
792 }
793 previousResidualNorm = residualNorm;
794
795 // Flatten residual matrix and derivative matrices using utility functions
796 const Eigen::Matrix<T, 9, 1> residualVector = residualMatrix.reshaped(9, 1);
797
798 Eigen::Matrix<T, 9, 2> jacobian;
799 jacobian.template block<9, 1>(0, 0) = dR0.reshaped(9, 1);
800 jacobian.template block<9, 1>(0, 1) = dR1.reshaped(9, 1);
801
802 // Gauss-Newton step solved as a 9x2 linear least-squares: minimize ||J*delta + r||.
803 const Vector2<T> delta = jacobian.householderQr().solve(-residualVector);
804
805 // Check if solution is valid
806 if (!delta.allFinite()) {
807 break;
808 }
809
810 angles = angles + delta;
811 }
812
813 return angles;
814}
815
816} // anonymous namespace
817
818template <typename T>
820 MT_CHECK(axis0 >= 0 && axis0 <= 2, "Invalid axis0");
821
822 // Always extract the best single-axis approximation using atan2 as initial guess
823 T initialGuess = T(0);
824 if (axis0 == 0) { // X-axis rotation
825 // For X-axis rotation: R_x(θ) has cos(θ) at (1,1) and (2,2), sin(θ) at (2,1), -sin(θ) at (1,2)
826 initialGuess = std::atan2(m(2, 1), m(1, 1));
827 } else if (axis0 == 1) { // Y-axis rotation
828 // For Y-axis rotation: R_y(θ) has cos(θ) at (0,0) and (2,2), sin(θ) at (0,2), -sin(θ) at (2,0)
829 initialGuess = std::atan2(m(0, 2), m(0, 0));
830 } else { // Z-axis rotation
831 // For Z-axis rotation: R_z(θ) has cos(θ) at (0,0) and (1,1), sin(θ) at (1,0), -sin(θ) at (0,1)
832 initialGuess = std::atan2(m(1, 0), m(0, 0));
833 }
834
835 // Refine the atan2 estimate with Gauss-Newton.
836 return gaussNewtonSolveScalar(m, axis0, initialGuess);
837}
838
839template <typename T>
840Vector2<T> rotationMatrixToTwoAxisEuler(const Matrix3<T>& m, int axis0, int axis1) {
841 MT_CHECK(axis0 != axis1, "Can't call two-axis rotation with the same axis");
842 MT_CHECK(axis0 >= 0 && axis0 <= 2, "Invalid axis0");
843 MT_CHECK(axis1 >= 0 && axis1 <= 2, "Invalid axis1");
844
845 return gaussNewtonSolveTwoAxis(
846 m,
847 axis0,
848 axis1,
849 Eigen::Vector2<T>{
851}
852
853template float rotationMatrixToOneAxisEuler(const Matrix3<float>& m, int axis0);
854template double rotationMatrixToOneAxisEuler(const Matrix3<double>& m, int axis0);
855
856template Vector2<float> rotationMatrixToTwoAxisEuler(const Matrix3<float>& m, int axis0, int axis1);
857template Vector2<double>
858rotationMatrixToTwoAxisEuler(const Matrix3<double>& m, int axis0, int axis1);
859
860} // namespace momentum
#define MT_CHECK(condition,...)
Runtime check macros with two interchangeable backends:
Definition checks.h:36
Quaternionf quaternionAverage(momentum::span< const Quaternionf > q, momentum::span< const float > w)
Computes the weighted average of multiple quaternions.
Definition utility.cpp:397
constexpr T Eps(T FloatEps=T(1e-7), T DoubleEps=T(1e-16))
Returns a type-appropriate tolerance/epsilon value.
Definition constants.h:30
Vector3< double > Vector3d
Definition types.h:261
Quaternion< double > Quaterniond
Definition types.h:387
T rotationMatrixToOneAxisEuler(const Matrix3< T > &m, int axis0)
Fits a single-axis Euler rotation to a rotation matrix.
Definition utility.cpp:819
Vector3< T > rotationMatrixToEuler(const Matrix3< T > &m, int axis0, int axis1, int axis2, EulerConvention convention)
Converts rotation matrix to Euler angles.
Definition utility.cpp:187
Quaternion< float > Quaternionf
Definition types.h:386
Vector3< T > rotationMatrixToEulerXYZ(const Matrix3< T > &m, EulerConvention convention)
An optimized version of rotationMatrixToEuler(m, 0, 1, 2, convention) or rotationMatrixToEuler(m,...
Definition utility.cpp:201
Matrix3< T > eulerXYZToRotationMatrix(const Vector3< T > &angles, EulerConvention convention)
An optimized version of eulerToRotationMatrix(angles, 0, 1, 2, convention) or eulerToRotationMatrix(a...
Definition utility.cpp:317
template std::tuple< bool, double, Eigen::Vector2< double > > closestPointsOnSegments< double >(const Eigen::Vector3< double > &o1, const Eigen::Vector3< double > &d1, const Eigen::Vector3< double > &o2, const Eigen::Vector3< double > &d2, const double maxDist)
Vector3< T > quaternionToEuler(const Quaternion< T > &q)
Converts a quaternion to Euler angles using the Extrinsic XYZ convention.
Definition utility.cpp:385
Eigen::Matrix< T, 3, 3 > Matrix3
Definition types.h:96
Vector3< T > rotationMatrixToEulerZYX(const Matrix3< T > &m, EulerConvention convention)
An optimized version of rotationMatrixToEuler(m, 2, 1, 0, convention) or rotationMatrixToEuler(m,...
Definition utility.cpp:242
Vector3< T > quaternionLogMap(const Quaternion< T > &q)
Computes the logarithmic map from a quaternion to a rotation vector (axis-angle in R^3).
Definition utility.cpp:74
Eigen::AngleAxis< T > AngleAxis
Definition types.h:374
EulerConvention
The Euler angles convention.
Definition utility.h:161
@ Extrinsic
The extrinsic convention.
Definition utility.h:178
@ Intrinsic
The intrinsic convention.
Definition utility.h:169
Vector2< T > rotationMatrixToTwoAxisEuler(const Matrix3< T > &m, int axis0, int axis1)
Fits a two-axis Euler rotation to a rotation matrix.
Definition utility.cpp:840
Vector< T, 2 > Vector2
Definition types.h:234
MatrixX< T > pseudoInverse(const MatrixX< T > &mat)
Calculates the pseudo-inverse of a matrix.
Definition utility.cpp:422
Eigen::Quaternion< T > Quaternion
Unit quaternion representing a 3D rotation.
Definition types.h:385
Eigen::Matrix< T, Dynamic, Dynamic > MatrixX
Dynamic-size, column-major dense matrix.
Definition types.h:80
Vector< T, Dynamic > VectorX
Dynamic-size column vector. Common return type for solver residuals and parameter vectors.
Definition types.h:207
template std::tuple< bool, float, Eigen::Vector2< float > > closestPointsOnSegments< float >(const Eigen::Vector3< float > &o1, const Eigen::Vector3< float > &d1, const Eigen::Vector3< float > &o2, const Eigen::Vector3< float > &d2, const float maxDist)
Eigen::SparseMatrix< T > SparseMatrix
Column-major sparse matrix.
Definition types.h:183
Matrix4< float > Matrix4f
Definition types.h:108
T sqr(const T &x)
Computes the square of a value.
Definition utility.h:47
std::tuple< bool, T, Eigen::Vector2< T > > closestPointsOnSegments(const Eigen::Vector3< T > &o1, const Eigen::Vector3< T > &d1, const Eigen::Vector3< T > &o2, const Eigen::Vector3< T > &d2, const T maxDist)
Returns the closest points on two line segments where the line segments are represented in origin and...
Definition utility.cpp:449
Matrix3< T > eulerToRotationMatrix(const Vector3< T > &angles, int axis0, int axis1, int axis2, EulerConvention convention)
Converts Euler angles to rotation matrix.
Definition utility.cpp:307
Matrix3< T > eulerZYXToRotationMatrix(const Vector3< T > &angles, EulerConvention convention)
An optimized version of eulerToRotationMatrix(angles, 2, 1, 0, convention) or eulerToRotationMatrix(a...
Definition utility.cpp:351
Quaternion< T > eulerToQuaternion(const Vector3< T > &angles, int axis0, int axis1, int axis2, EulerConvention convention)
Converts Euler angles to quaternion.
Definition utility.cpp:289
gsl::span< T > span
Span type alias using gsl::span (C++17 fallback).
Definition span_compat.h:54
Vector< T, 3 > Vector3
Definition types.h:236
Eigen::Matrix< T, 3, 4 > quaternionLogMapDerivative(const Quaternion< T > &q)
Computes the derivative of the logarithmic map with respect to quaternion components.
Definition utility.cpp:120
Vector3< float > Vector3f
Definition types.h:251
Quaternion< T > quaternionExpMap(const Vector3< T > &v)
Computes the exponential map from a rotation vector (axis-angle in R^3) to a quaternion.
Definition utility.cpp:34
constexpr T pi() noexcept
Returns the mathematical constant pi.
Definition constants.h:50