Momentum
A library for solving nonlinear optimization problems related to human body kinematics
Loading...
Searching...
No Matches
fully_differentiable_state_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
11
15
16#include <algorithm>
17
18namespace momentum {
19
20template <typename T>
25
26template <typename T>
28
29template <typename T>
30std::vector<std::string> FullyDifferentiableStateErrorFunctionT<T>::inputs() const {
31 return {"targetPositionWeights", "targetRotationWeights", "targetState"};
32}
33
34template <typename T>
36 const std::string& name) const {
37 if (name == "targetPositionWeights" || name == "targetRotationWeights") {
38 return this->skeleton_.joints.size();
39 } else if (name == "targetState") {
40 return 8 * this->skeleton_.joints.size();
41 } else {
42 MT_THROW("Unknown input to FullyDifferentiableMotionErrorFunctionT: {}", name);
43 }
44}
45
46template <typename T>
48 const std::string& name,
49 Eigen::Ref<Eigen::VectorX<T>> value) const {
50 if (name == "targetPositionWeights") {
51 value = this->getPositionWeights();
52 } else if (name == "targetRotationWeights") {
53 value = this->getRotationWeights();
54 } else if (name == "targetState") {
55 const TransformListT<T>& targetState = this->getTargetState();
56
57 for (size_t iJoint = 0; iJoint < this->skeleton_.joints.size(); ++iJoint) {
58 value.template segment<3>(8 * iJoint + 0) = targetState[iJoint].translation;
59 value.template segment<4>(8 * iJoint + 3) =
60 targetState[iJoint].rotation.normalized().coeffs();
61 value(8 * iJoint + 7) = targetState[iJoint].scale;
62 }
63 } else {
64 MT_THROW("Unknown input to FullyDifferentiableMotionErrorFunctionT: {}", name);
65 }
66}
67
68template <typename T>
70 const std::string& name,
71 Eigen::Ref<const Eigen::VectorX<T>> value) {
72 if (name == "targetPositionWeights") {
73 this->setTargetWeights(value, this->getRotationWeights());
74 } else if (name == "targetRotationWeights") {
75 this->setTargetWeights(this->getPositionWeights(), value);
76 } else if (name == "targetState") {
77 TransformListT<T> transforms(this->skeleton_.joints.size());
78 for (size_t iJoint = 0; iJoint < this->skeleton_.joints.size(); ++iJoint) {
79 const Eigen::Vector3<T> pos = value.template segment<3>(8 * iJoint + 0);
80 const Eigen::Quaternion<T> rot =
81 Eigen::Quaternion<T>(value.template segment<4>(8 * iJoint + 3)).normalized();
82 const T scale = value(8 * iJoint + 7);
83 transforms[iJoint] = TransformT<T>(pos, rot, scale);
84 }
85 this->setTargetState(transforms);
86 } else {
87 MT_THROW("Unknown input to FullyDifferentiableMotionErrorFunctionT: {}", name);
88 }
89}
90
91template <typename T>
92template <typename JetType>
93JetType FullyDifferentiableStateErrorFunctionT<T>::calculateGradient_dot(
94 const SkeletonStateT<T>& state,
95 size_t iJoint,
96 const Eigen::Vector3<JetType>& targetTranslation,
97 const Eigen::Quaternion<JetType>& targetRotation,
98 const JetType& targetPositionWeight,
99 const JetType& targetRotationWeight,
100 Eigen::Ref<const Eigen::VectorX<T>> vec) {
101 // check all is valid
102 Expects(state.jointState.size() == gsl::narrow<Eigen::Index>(this->skeleton_.joints.size()));
103
104 JetType result;
105
106 // calculate orientation gradient
107 const Eigen::Quaternion<T>& rot = state.jointState[iJoint].rotation();
108 const Eigen::Matrix3<JetType> rotDiff =
109 rot.toRotationMatrix() - targetRotation.toRotationMatrix();
110 const JetType rwgt = StateErrorFunctionT<T>::kOrientationWeight * this->getRotationWeight() *
111 this->weight_ * targetRotationWeight;
112
113 // calculate position gradient
114 const Eigen::Vector3<JetType> diff = state.jointState[iJoint].translation() - targetTranslation;
115 const JetType pwgt = StateErrorFunctionT<T>::kPositionWeight * this->getPositionWeight() *
116 this->weight_ * targetPositionWeight;
117
118 // loop over all joints the constraint is attached to and calculate gradient
119 size_t jointIndex = iJoint;
120 while (jointIndex != kInvalidIndex) {
121 // check for valid index
122 Ensures(jointIndex < this->skeleton_.joints.size());
123
124 const size_t paramIndex = jointIndex * kParametersPerJoint;
125
126 // precalculate some more data for position gradient
127 const Eigen::Vector3<T> posd =
128 state.jointState[iJoint].translation() - state.jointState[jointIndex].translation();
129
130 for (size_t d = 0; d < 3; d++) {
131 // position gradient
132 if (this->activeJointParams_[paramIndex + d]) {
134 T(2) * diff.dot(state.jointState[jointIndex].getTranslationDerivative(d)) * pwgt,
135 paramIndex + d,
136 this->parameterTransform_,
137 vec);
138 }
139 if (this->activeJointParams_[paramIndex + 3 + d]) {
140 // calculate joint gradient consisting of position gradient and orientation gradient
141 const Eigen::Vector3<T> axis = state.jointState[jointIndex].rotationAxis.col(d);
142 const auto rotD = crossProductMatrix(axis) * rot;
143 const JetType val =
144 T(2) * diff.dot(state.jointState[jointIndex].getRotationDerivative(d, posd)) * pwgt +
145 T(2) * rwgt * rotD.cwiseProduct(rotDiff).sum();
147 val, paramIndex + 3 + d, this->parameterTransform_, vec);
148 }
149 }
150 if (this->activeJointParams_[paramIndex + 6]) {
151 // calculate joint gradient
152 const JetType val =
153 T(2) * diff.dot(state.jointState[jointIndex].getScaleDerivative(posd)) * pwgt;
154 result +=
155 times_parameterTransform_times_v(val, paramIndex + 6, this->parameterTransform_, vec);
156 }
157
158 // go to the next joint
159 jointIndex = this->skeleton_.joints[jointIndex].parent;
160 }
161
162 // return error
163 return result;
164}
165
166template <typename T>
168 const std::string& inputName,
169 const ModelParametersT<T>& /* params */,
170 const SkeletonStateT<T>& state,
171 Eigen::Ref<const Eigen::VectorX<T>> inputVec) {
172 const auto& targetState = this->getTargetState();
173 const auto& targetPositionWeights = this->getPositionWeights();
174 const auto& targetRotationWeights = this->getRotationWeights();
175
176 if (targetState.empty()) {
177 return Eigen::VectorX<T>::Zero(getInputSize(inputName));
178 }
179
180 // Use automatic differentiation on the gradient function:
181 if (inputName == "targetPositionWeights") {
182 Eigen::VectorX<T> result = Eigen::VectorX<T>::Zero(this->skeleton_.joints.size());
183 using JetType = ceres::Jet<T, 1>;
184 for (size_t iJoint = 0; iJoint < this->skeleton_.joints.size(); ++iJoint) {
185 result(iJoint) = calculateGradient_dot<JetType>(
186 state,
187 iJoint,
188 targetState[iJoint].translation.template cast<JetType>(),
189 targetState[iJoint].rotation.normalized().template cast<JetType>(),
190 JetType(targetPositionWeights[iJoint], 0),
191 JetType(targetRotationWeights[iJoint]),
192 inputVec)
193 .v[0];
194 }
195 return result;
196 } else if (inputName == "targetRotationWeights") {
197 Eigen::VectorX<T> result = Eigen::VectorX<T>::Zero(this->skeleton_.joints.size());
198 using JetType = ceres::Jet<T, 1>;
199 for (size_t iJoint = 0; iJoint < this->skeleton_.joints.size(); ++iJoint) {
200 result(iJoint) = calculateGradient_dot<JetType>(
201 state,
202 iJoint,
203 targetState[iJoint].translation.template cast<JetType>(),
204 targetState[iJoint].rotation.normalized().template cast<JetType>(),
205 JetType(targetPositionWeights[iJoint]),
206 JetType(targetRotationWeights[iJoint], 0),
207 inputVec)
208 .v[0];
209 }
210 return result;
211 } else if (inputName == "targetState") {
212 Eigen::VectorX<T> result = Eigen::VectorX<T>::Zero(8 * this->skeleton_.joints.size());
213 for (size_t iJoint = 0; iJoint < this->skeleton_.joints.size(); ++iJoint) {
214 {
215 using JetType = ceres::Jet<T, 3>;
216 result.template segment<3>(8 * iJoint + 0) =
217 calculateGradient_dot<JetType>(
218 state,
219 iJoint,
220 buildJetVec<T, 3>(targetState[iJoint].translation),
221 targetState[iJoint].rotation.normalized().template cast<JetType>(),
222 JetType(targetPositionWeights[iJoint]),
223 JetType(targetRotationWeights[iJoint]),
224 inputVec)
225 .v;
226 }
227 {
228 using JetType = ceres::Jet<T, 4>;
229 result.template segment<4>(8 * iJoint + 3) =
230 calculateGradient_dot<JetType>(
231 state,
232 iJoint,
233 targetState[iJoint].translation.template cast<JetType>(),
234 Eigen::Quaternion<JetType>(
235 buildJetVec<T, 4>(targetState[iJoint].rotation.normalized().coeffs()))
236 .normalized(),
237 JetType(targetPositionWeights[iJoint]),
238 JetType(targetRotationWeights[iJoint]),
239 inputVec)
240 .v;
241 }
242 }
243 return result;
244 } else {
245 MT_THROW("Unknown input to FullyDifferentiableMotionErrorFunctionT: {}", inputName);
246 }
247}
248
251
252} // namespace momentum
void getInputImp(const std::string &name, Eigen::Ref< Eigen::VectorX< T > > value) const final
FullyDifferentiableStateErrorFunctionT(const Skeleton &skel, const ParameterTransform &pt)
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
void setInputImp(const std::string &name, Eigen::Ref< const Eigen::VectorX< T > > value) final
void setTargetWeights(const Eigen::VectorX< T > &posWeight, const Eigen::VectorX< T > &rotWeight)
const TransformListT< T > & getTargetState() const
void setTargetState(const SkeletonStateT< T > *target)
StateErrorFunctionT(const Skeleton &skel, const ParameterTransform &pt, RotationErrorType rotationErrorType=RotationErrorType::RotationMatrixDifference)
const Eigen::VectorX< T > & getRotationWeights() const
const Eigen::VectorX< T > & getPositionWeights() const
#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
std::vector< TransformT< T > > TransformListT
Per-joint transform list describing the state of all joints in a skeleton (one entry per joint,...
Definition transform.h:228
T times_parameterTransform_times_v(const T &value, const size_t jointParamIdx, const ParameterTransform &parameterTransform, Eigen::Ref< const Eigen::VectorX< T2 > > v)
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
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
A vector of size numModelParams holding the values of all model parameters for a character.
Definition types.h:99
Represents the complete state of a skeleton.
JointStateListT< T > jointState
Computed joint states for all joints in the skeleton.
Lightweight transform with separate rotation, translation, and uniform scaling.
Definition transform.h:36