Momentum
A library for solving nonlinear optimization problems related to human body kinematics
Loading...
Searching...
No Matches
fully_differentiable_orientation_error_function.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
15
16#include <algorithm>
17#include <atomic>
18#include <cassert>
19
20namespace momentum {
21
22template <typename T>
29
30template <typename T>
32 static std::vector<std::string> result = {kWeights, kOffsets, kTargets};
33 return result;
34}
35
36template <typename T>
38 const std::string& name) const {
39 if (name == kWeights) {
40 return constraints_.size();
41 }
42
43 if (name == kOffsets) {
44 return 4 * constraints_.size();
45 }
46
47 if (name == kTargets) {
48 return 4 * constraints_.size();
49 }
50
51 MT_THROW("Unknown input to FullyDifferentiableOrientationErrorFunctionT<T>::getInput: {}", name);
52}
53
54template <typename T>
56 const ModelParametersT<T>& /*params*/,
57 const SkeletonStateT<T>& state,
58 const MeshStateT<T>& /* meshState */) {
59 // loop over all constraints and calculate the error
60 double error = 0.0;
61
62 for (size_t i = 0; i < constraints_.size(); ++i) {
63 const OrientationConstraintT<T>& ct = constraints_[i];
64
65 // calculate orientation error
66 // Note: |R0 - RT|² is a valid norm on SO3, it doesn't have the same slope as the squared
67 // angle difference
68 // but it's derivative doesn't have a singularity at the minimum, so is more stable
69 const Eigen::Quaternion<T> rot = state.jointState[ct.parent].rotation() * ct.offset;
70 const Eigen::Matrix3<T> rotDiff = rot.toRotationMatrix() - ct.target.toRotationMatrix();
71 error += ct.weight * rotDiff.squaredNorm() * kOrientationWeight;
72 }
73
74 // return error
75 return error * this->weight_;
76}
77
78template <typename T>
80 const ModelParametersT<T>& /*params*/,
81 const SkeletonStateT<T>& state,
82 const MeshStateT<T>& /* meshState */,
83 Ref<Eigen::VectorX<T>> gradient) {
84 const auto& parameterTransform = this->parameterTransform_;
85
86 // storage for joint gradients
87 jointGrad_.setZero(parameterTransform.numAllModelParameters());
88
89 // loop over all constraints and calculate the error
90 double error = 0.0;
91
92 for (size_t i = 0; i < constraints_.size(); ++i) {
93 const OrientationConstraintT<T>& ct = constraints_[i];
94 if (ct.weight == 0) {
95 continue;
96 }
97
98 error += calculateOrientationGradient(state, constraints_[i], jointGrad_);
99 }
100
101 // convert joint gradient to parameter gradient and return
102 gradient.noalias() += jointGrad_ * this->weight_;
103
104 // return error
105 return error * this->weight_;
106}
107
108template <typename T>
110 const ModelParametersT<T>& params,
111 const SkeletonStateT<T>& state,
112 const MeshStateT<T>& /* meshState */,
113 Ref<Eigen::MatrixX<T>> jacobian,
114 Ref<Eigen::VectorX<T>> residual,
115 int& usedRows) {
116 // loop over all constraints and calculate the error
117 double error = 0.0;
118 std::atomic_int offset(0);
119
120 for (size_t i = 0; i < constraints_.size(); ++i) {
121 const OrientationConstraintT<T>& ct = constraints_[i];
122 if (ct.weight == 0) {
123 continue;
124 }
125
126 const auto currentOffset = offset.fetch_add(9, std::memory_order_relaxed);
127 error += calculateOrientationJacobian(
128 state,
129 constraints_[i],
130 jacobian.block(currentOffset, 0, 9, params.size()),
131 residual.middleRows(currentOffset, 9));
132 }
133
134 usedRows = gsl::narrow_cast<int>(jacobian.rows());
135
136 return error;
137}
138
139template <typename T>
140T FullyDifferentiableOrientationErrorFunctionT<T>::calculateOrientationJacobian(
141 const SkeletonStateT<T>& state,
142 const OrientationConstraintT<T>& constr,
143 Ref<Eigen::MatrixX<T>> jac,
144 Ref<Eigen::VectorX<T>> res) const {
145 const auto& parameterTransform = this->parameterTransform_;
146
147 // calculate orientation error
148 const Eigen::Quaternion<T> rot = state.jointState[constr.parent].rotation() * constr.offset;
149 const Eigen::Quaternion<T>& target = constr.target;
150 const Eigen::Matrix3<T> rotDiff = rot.toRotationMatrix() - target.toRotationMatrix();
151 const T wgt = kOrientationWeight * constr.weight * this->weight_;
152 const T swgt = std::sqrt(wgt);
153
154 // loop over all joints the constraint is attached to and calculate gradient
155 size_t jointIndex = constr.parent;
156 while (jointIndex != kInvalidIndex) {
157 // check for valid index
158 MT_CHECK(jointIndex < this->skeleton_.joints.size());
159
160 const size_t paramIndex = jointIndex * kParametersPerJoint;
161
162 // calculate derivatives based on active joints
163 for (size_t d = 0; d < 3; d++) {
164 if (this->activeJointParams_[paramIndex + 3 + d]) {
165 const Eigen::Vector3<T> axis = state.jointState[jointIndex].rotationAxis.col(d);
166 const Eigen::Matrix3<T> rotD = crossProductMatrix(axis) * rot * swgt;
167 const auto ja = Map<const Eigen::VectorX<T>>(rotD.data(), rotD.size());
168
169 // explicitly multiply with the parameter transform to generate parameter space gradients
170 for (auto index = parameterTransform.transform.outerIndexPtr()[paramIndex + 3 + d];
171 index < parameterTransform.transform.outerIndexPtr()[paramIndex + d + 3 + 1];
172 ++index) {
173 jac.col(parameterTransform.transform.innerIndexPtr()[index]) +=
174 ja * parameterTransform.transform.valuePtr()[index];
175 }
176 }
177 }
178
179 // go to the next joint
180 jointIndex = this->skeleton_.joints[jointIndex].parent;
181 }
182
183 res = Map<const Eigen::VectorX<T>>(rotDiff.data(), rotDiff.size()) * swgt;
184
185 return rotDiff.squaredNorm() * wgt;
186}
187
188template <typename T>
190 return constraints_.size() * 9;
191}
192
193template <typename T>
195 const OrientationConstraintT<T>& constraint) {
196 constraints_.push_back(constraint);
197}
198
199template <typename T>
200void FullyDifferentiableOrientationErrorFunctionT<T>::getInputImp(
201 const std::string& name,
202 Eigen::Ref<Eigen::VectorX<T>> value) const {
203 if (name == kWeights) {
204 for (size_t i = 0; i < constraints_.size(); ++i) {
205 value[i] = static_cast<T>(constraints_[i].weight);
206 }
207 } else if (name == kOffsets) {
208 for (size_t i = 0; i < constraints_.size(); ++i) {
209 value.template segment<4>(4 * i) = constraints_[i].offset.coeffs();
210 }
211 } else if (name == kTargets) {
212 for (size_t i = 0; i < constraints_.size(); ++i) {
213 value.template segment<4>(4 * i) = constraints_[i].target.coeffs();
214 }
215 } else {
216 MT_THROW("Unknown input to FullyDifferentiableOrientationFunctionT<T>::getInput: {}", name);
217 }
218}
219
220template <typename T>
221void FullyDifferentiableOrientationErrorFunctionT<T>::setInputImp(
222 const std::string& name,
223 Eigen::Ref<const Eigen::VectorX<T>> value) {
224 // Normalization is a tricky topic here. When we set the values, we must normalize normals and
225 // quaternions etc because the rest of the code won't work correctly without this (for example
226 // computing the angle between unnormalized vectors requires normalizing them first). However,
227 // if we do normalize the values that are passed in, then the derivatives of those values are
228 // no longer correct. For example, imagine that we pass in v = (1000, 0, 0) as the normal to a
229 // plane. Clearly we must turn this into (1, 0, 0) so the IK solve does something reasonable, but
230 // when we do we find that our dv/dTheta is off by a factor of 1000. It's hard to address that
231 // inside this code, the right way to do it is to require that the inputs be normalized inside
232 // Pytorch before getting passed in, which will ensure all the derivatives work out correctly.
233 if (name == kWeights) {
234 for (size_t i = 0; i < constraints_.size(); ++i) {
235 constraints_[i].weight = static_cast<float>(value[i]);
236 }
237 } else if (name == kOffsets) {
238 for (size_t i = 0; i < constraints_.size(); ++i) {
239 constraints_[i].offset = Eigen::Quaternion<T>(value.template segment<4>(4 * i)).normalized();
240 }
241 } else if (name == kTargets) {
242 for (size_t i = 0; i < constraints_.size(); ++i) {
243 constraints_[i].target = Eigen::Quaternion<T>(value.template segment<4>(4 * i)).normalized();
244 }
245 } else {
246 MT_THROW(
247 "Unknown input to FullyDifferentiableOrientationErrorFunctionT<T>::getInput: {}", name);
248 }
249}
250
251template <typename T>
252T FullyDifferentiableOrientationErrorFunctionT<T>::calculateOrientationGradient(
253 const SkeletonStateT<T>& state,
254 const OrientationConstraintT<T>& constr,
255 Eigen::VectorX<T>& jGrad) const {
256 const auto& parameterTransform = this->parameterTransform_;
257
258 // calculate orientation error
259 const Eigen::Quaternion<T> rot = state.jointState[constr.parent].rotation() * constr.offset;
260 const Eigen::Matrix3<T> rotDiff = rot.toRotationMatrix() - constr.target.toRotationMatrix();
261 const T wgt = kOrientationWeight * constr.weight;
262
263 // loop over all joints the constraint is attached to and calculate gradient
264 size_t jointIndex = constr.parent;
265 while (jointIndex != kInvalidIndex) {
266 // check for valid index
267 MT_CHECK(jointIndex < this->skeleton_.joints.size());
268
269 const size_t paramIndex = jointIndex * kParametersPerJoint;
270
271 // calculate derivatives based on active joints
272 for (size_t d = 0; d < 3; d++) {
273 if (this->activeJointParams_[paramIndex + 3 + d]) {
274 // calculate joint gradient
275 const Eigen::Vector3<T> axis = state.jointState[jointIndex].rotationAxis.col(d);
276 const auto rotD = crossProductMatrix(axis) * rot;
277 const T val = 2.0f * wgt * rotD.cwiseProduct(rotDiff).sum();
278 // explicitly multiply with the parameter transform to generate parameter space gradients
279 for (auto index = parameterTransform.transform.outerIndexPtr()[paramIndex + 3 + d];
280 index < parameterTransform.transform.outerIndexPtr()[paramIndex + d + 3 + 1];
281 ++index) {
282 jGrad[parameterTransform.transform.innerIndexPtr()[index]] +=
283 val * parameterTransform.transform.valuePtr()[index];
284 }
285 }
286 }
287
288 // go to the next joint
289 jointIndex = this->skeleton_.joints[jointIndex].parent;
290 }
291
292 return rotDiff.squaredNorm() * wgt;
293}
294
295template <typename T>
296template <typename JetType>
297[[nodiscard]] JetType
298FullyDifferentiableOrientationErrorFunctionT<T>::calculateOrientationGradient_dot(
299 const SkeletonStateT<T>& state,
300 const size_t constrParent,
301 const JetType& constrWeight,
302 const Eigen::Quaternion<JetType>& constrOrientationOffset,
303 const Eigen::Quaternion<JetType>& constrOrientationTarget,
304 Eigen::Ref<const Eigen::VectorX<T>> vec) const {
305 JetType result;
306
307 // calculate orientation error
308 const Eigen::Quaternion<JetType> rot =
309 (state.jointState[constrParent].rotation().template cast<JetType>() *
310 constrOrientationOffset);
311 const Eigen::Matrix3<JetType> rotDiff =
312 rot.toRotationMatrix() - constrOrientationTarget.toRotationMatrix();
313 const JetType wgt = this->weight_ * this->kOrientationWeight * constrWeight;
314
315 // loop over all joints the constraint is attached to and calculate gradient
316 size_t jointIndex = constrParent;
317 while (jointIndex != kInvalidIndex) {
318 // check for valid index
319 assert(jointIndex < this->skeleton_.joints.size());
320
321 const size_t paramIndex = jointIndex * kParametersPerJoint;
322
323 // calculate derivatives based on active joints
324 for (size_t d = 0; d < 3; d++) {
325 if (this->activeJointParams_[paramIndex + 3 + d]) {
326 // calculate joint gradient
327 const Eigen::Vector3<T> axis = state.jointState[jointIndex].rotationAxis.col(d);
328 const Eigen::Matrix3<JetType> rotD = crossProductMatrix(axis) * rot;
329 const JetType val = T(2) * wgt * rotD.cwiseProduct(rotDiff).sum();
331 val, paramIndex + 3 + d, this->parameterTransform_, vec);
332 }
333 }
334
335 // go to the next joint
336 jointIndex = this->skeleton_.joints[jointIndex].parent;
337 }
338
339 return result;
340}
341
342template <typename T>
344 const std::string& inputName,
345 const ModelParametersT<T>& /*modelParams*/,
346 const SkeletonStateT<T>& state,
347 Eigen::Ref<const Eigen::VectorX<T>> inputVec) {
348 // Use automatic differentiation on the gradient function:
349 if (inputName == kWeights) {
350 Eigen::VectorX<T> result = Eigen::VectorX<T>::Zero(constraints_.size());
351 using JetType = ceres::Jet<T, 1>;
352 for (size_t iCons = 0; iCons < constraints_.size(); ++iCons) {
353 const auto& cons = constraints_[iCons];
354 result(iCons) = calculateOrientationGradient_dot<JetType>(
355 state,
356 cons.parent,
357 JetType(cons.weight, 0),
358 cons.offset.template cast<JetType>(),
359 cons.target.template cast<JetType>(),
360 inputVec)
361 .v[0];
362 }
363 return result;
364 } else if (inputName == kOffsets) {
365 Eigen::VectorX<T> result = Eigen::VectorX<T>::Zero(4 * constraints_.size());
366 using JetType = ceres::Jet<T, 4>;
367 for (size_t iCons = 0; iCons < constraints_.size(); ++iCons) {
368 const auto& cons = constraints_[iCons];
369 const auto dotProd = calculateOrientationGradient_dot<JetType>(
370 state,
371 cons.parent,
372 JetType(cons.weight),
373 Eigen::Quaternion<JetType>(buildJetVec<T, 4>(cons.offset.coeffs())).normalized(),
374 cons.target.template cast<JetType>(),
375 inputVec);
376 result.template segment<4>(4 * iCons) = dotProd.v;
377 }
378 return result;
379 } else if (inputName == kTargets) {
380 Eigen::VectorX<T> result = Eigen::VectorX<T>::Zero(4 * constraints_.size());
381 using JetType = ceres::Jet<T, 4>;
382 for (size_t iCons = 0; iCons < constraints_.size(); ++iCons) {
383 const auto& cons = constraints_[iCons];
384 const auto dotProd = calculateOrientationGradient_dot<JetType>(
385 state,
386 cons.parent,
387 JetType(cons.weight),
388 cons.offset.template cast<JetType>(),
389 Eigen::Quaternion<JetType>(buildJetVec<T, 4>(cons.target.coeffs())).normalized(),
390 inputVec);
391 result.template segment<4>(4 * iCons) = dotProd.v;
392 }
393 return result;
394 } else {
395 MT_THROW(
396 "Unknown input name in FullyDifferentiableOrientationErrorFunctionT<T>::d_gradient_d_input_dot: {}",
397 inputName);
398 }
399}
400
403
404} // namespace momentum
#define MT_CHECK(condition,...)
Runtime check macros with two interchangeable backends:
Definition checks.h:36
FullyDifferentiableOrientationErrorFunctionT(const Skeleton &skel, const ParameterTransform &pt)
double getGradient(const ModelParametersT< T > &params, const SkeletonStateT< T > &state, const MeshStateT< T > &, Ref< Eigen::VectorX< T > > gradient) final
double getError(const ModelParametersT< T > &params, const SkeletonStateT< T > &state, const MeshStateT< T > &) final
double getJacobian(const ModelParametersT< T > &params, const SkeletonStateT< T > &state, const MeshStateT< T > &, Ref< Eigen::MatrixX< T > > jacobian, Ref< Eigen::VectorX< T > > residual, int &usedRows) final
Eigen::VectorX< T > d_gradient_d_input_dot(const std::string &inputName, const ModelParametersT< T > &params, const SkeletonStateT< T > &state, Eigen::Ref< const Eigen::VectorX< T > > inputVec) final
SkeletonErrorFunctionT(const Skeleton &skel, const ParameterTransform &pt)
const ParameterTransform & parameterTransform_
#define MT_THROW(...)
Throws a std::runtime_error with a formatted message.
Definition exception.h:31
Eigen::Matrix< T, 3, 3 > crossProductMatrix(const Eigen::Vector3< T > &v)
Creates a skew-symmetric matrix for computing cross products.
Definition utility.h:343
SkeletonT< float > Skeleton
Definition fwd.h:263
T times_parameterTransform_times_v(const T &value, const size_t jointParamIdx, const ParameterTransform &parameterTransform, Eigen::Ref< const Eigen::VectorX< T2 > > v)
Eigen::Ref< T > Ref
Definition types.h:43
Eigen::Matrix< ceres::Jet< T, N >, N, 1 > buildJetVec(const Eigen::Matrix< T, N, 1 > &v)
ParameterTransformT< float > ParameterTransform
Definition fwd.h:244
constexpr size_t kParametersPerJoint
Definition types.h:21
constexpr size_t kInvalidIndex
Sentinel value indicating an invalid or unset size_t index.
Definition types.h:182
Eigen::Map< T > Map
Definition types.h:40
decltype(auto) cast(const ContainerType< ObjectType > &originalContainer)
Casts the scalar type of objects in a container that support the cast<>() method.
Definition types.h:466
EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE auto size() const
Definition types.h:87
Represents the complete state of a model's mesh.
Definition mesh_state.h:24
A vector of size numModelParams holding the values of all model parameters for a character.
Definition types.h:99
size_t parent
Parent joint index this constraint is under.
Quaternion< T > target
Target orientation in global space.
Quaternion< T > offset
Constraint rotation offset in local joint space.
Represents the complete state of a skeleton.
JointStateListT< T > jointState
Computed joint states for all joints in the skeleton.