Momentum
A library for solving nonlinear optimization problems related to human body kinematics
Loading...
Searching...
No Matches
joint_error_function-inl.h
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
8#pragma once
9
11
16
17namespace momentum {
18
19template <typename T, class Data, size_t FuncDim, size_t NumVec, size_t NumPos>
21 const Skeleton& skel,
22 const ParameterTransform& pt,
23 const T& lossAlpha,
24 const T& lossC)
25 : SkeletonErrorFunctionT<T>(skel, pt),
26 loss_(lossAlpha, lossC),
27 jointGrad_(pt.numAllModelParameters()) {
28 static_assert(FuncDim > 0, "The error function cannot be empty.");
29 static_assert(NumVec > 0, "At least one vector is required in the constraint.");
30 static_assert(
31 NumVec >= NumPos, "The number of points cannot be more than the total number of vectors.");
32}
33
34template <typename T, class Data, size_t FuncDim, size_t NumVec, size_t NumPos>
36 const ModelParametersT<T>& /* params */,
37 const SkeletonStateT<T>& state,
38 const MeshStateT<T>& /* meshState */) {
40
41 FuncType f;
42 std::array<VType, NumVec> v;
43 std::array<DfdvType, NumVec> dfdv;
44 double error = 0.0;
45 for (size_t iConstr = 0; iConstr < constraints_.size(); ++iConstr) {
46 const Data& constr = constraints_[iConstr];
47 if (constr.weight == 0) {
48 continue;
49 }
50 evalFunction(iConstr, state.jointState.at(constr.parent), f, v, dfdv);
51 error += constr.weight * loss_.value(f.squaredNorm());
52 }
53 return this->weight_ * error;
54}
55
56template <typename T, class Data, size_t FuncDim, size_t NumVec, size_t NumPos>
58 const ModelParametersT<T>& /*unused*/,
59 const SkeletonStateT<T>& state,
60 const MeshStateT<T>& /* meshState */,
61 Ref<Eigen::VectorX<T>> gradient) {
63
64 // Initialize joint gradients storage
65 jointGrad_.setZero();
66
67 // Shorthands for parameter transform
68 const auto outerIndexPtr = this->parameterTransform_.transform.outerIndexPtr();
69 const auto innerIndexPtr = this->parameterTransform_.transform.innerIndexPtr();
70 const auto valuePtr = this->parameterTransform_.transform.valuePtr();
72 double error = 0.0;
73 for (size_t iConstr = 0; iConstr < this->constraints_.size(); ++iConstr) {
74 const Data& constr = constraints_[iConstr];
75 if (constr.weight == 0) {
76 continue;
77 }
78
79 FuncType f;
80 std::array<VType, NumVec> v;
81 std::array<DfdvType, NumVec> dfdv;
82 evalFunction(iConstr, state.jointState.at(constr.parent), f, v, dfdv);
83
84 if (f.isZero()) {
85 continue;
86 }
87
88 const T sqrError = f.squaredNorm();
89 const T w = constr.weight * this->weight_;
90 error += w * loss_.value(sqrError);
91 const FuncType deriv = T(2) * w * loss_.deriv(sqrError) * f;
92
93 // Precompute wR[jVec] = dfdv[jVec]^T * deriv once per constraint.
94 // Converts per-DOF cost from FuncDim x 3 matmul + FuncDim dot to 3-element dot.
95 std::array<Eigen::Vector3<T>, NumVec> wR;
96 for (size_t jVec = 0; jVec < NumVec; ++jVec) {
97 if (dfdv[jVec].isZero()) {
98 wR[jVec].setZero();
99 } else {
100 wR[jVec].noalias() = dfdv[jVec].transpose() * deriv;
101 }
102 }
103
104 // Inline hierarchy walk: walk from parent joint to root
105 size_t jntIndex = constr.parent;
106 while (jntIndex != kInvalidIndex) {
107 MT_CHECK(jntIndex < this->skeleton_.joints.size());
108
109 const auto& jntState = state.jointState[jntIndex];
110 const size_t jntParamIndex = jntIndex * kParametersPerJoint;
111
112 for (size_t jVec = 0; jVec < NumVec; ++jVec) {
113 if (wR[jVec].isZero()) {
114 continue;
115 }
116
117 Eigen::Vector3<T> offset;
118 if (jVec < NumPos) {
119 offset.noalias() = v[jVec] - jntState.translation();
120 } else {
121 offset = v[jVec];
122 }
123
124 // Translational dofs -- only affect POINT
125 if (jVec < NumPos) {
126 for (size_t d = 0; d < 3; d++) {
127 if (!this->activeJointParams_[jntParamIndex + d]) {
128 continue;
129 }
130 const T val = wR[jVec].dot(jntState.getTranslationDerivative(d));
131 for (auto index = outerIndexPtr[jntParamIndex + d];
132 index < outerIndexPtr[jntParamIndex + d + 1];
133 ++index) {
134 if (this->enabledParameters_.test(innerIndexPtr[index])) {
135 jointGrad_[innerIndexPtr[index]] += val * valuePtr[index];
136 }
137 }
139 }
140
141 // Rotational dofs -- affect both POINT and AXIS
142 for (size_t d = 0; d < 3; d++) {
143 if (!this->activeJointParams_[jntParamIndex + 3 + d]) {
144 continue;
145 }
146 const T val = wR[jVec].dot(jntState.getRotationDerivative(d, offset));
147 for (auto index = outerIndexPtr[jntParamIndex + 3 + d];
148 index < outerIndexPtr[jntParamIndex + 3 + d + 1];
149 ++index) {
150 if (this->enabledParameters_.test(innerIndexPtr[index])) {
151 jointGrad_[innerIndexPtr[index]] += val * valuePtr[index];
152 }
153 }
154 }
155
156 // Scale dof -- only affect POINT
157 if (jVec < NumPos) {
158 if (this->activeJointParams_[jntParamIndex + 6]) {
159 const T val = wR[jVec].dot(jntState.getScaleDerivative(offset));
160 for (auto index = outerIndexPtr[jntParamIndex + 6];
161 index < outerIndexPtr[jntParamIndex + 6 + 1];
162 ++index) {
163 if (this->enabledParameters_.test(innerIndexPtr[index])) {
164 jointGrad_[innerIndexPtr[index]] += val * valuePtr[index];
165 }
166 }
167 }
168 }
169 }
170 jntIndex = this->skeleton_.joints[jntIndex].parent;
171 }
172 }
173
174 gradient += jointGrad_;
175 return error;
176}
177
178template <typename T, class Data, size_t FuncDim, size_t NumVec, size_t NumPos>
180 const ModelParametersT<T>& /*params*/,
181 const SkeletonStateT<T>& state,
182 const MeshStateT<T>& /* meshState */,
183 Ref<Eigen::MatrixX<T>> jacobian,
184 Ref<Eigen::VectorX<T>> residual,
185 int& usedRows) {
187 usedRows = static_cast<int>(getJacobianSize());
188
189 // Shorthands for parameter transform
190 const auto outerIndexPtr = this->parameterTransform_.transform.outerIndexPtr();
191 const auto innerIndexPtr = this->parameterTransform_.transform.innerIndexPtr();
192 const auto valuePtr = this->parameterTransform_.transform.valuePtr();
193
194 double error = 0.0;
195 for (size_t iConstr = 0; iConstr < this->constraints_.size(); ++iConstr) {
196 const Data& constr = constraints_[iConstr];
197 if (constr.weight == 0) {
198 continue;
199 }
200
201 FuncType f;
202 std::array<VType, NumVec> v;
203 std::array<DfdvType, NumVec> dfdv;
204 evalFunction(iConstr, state.jointState.at(constr.parent), f, v, dfdv);
205
206 const T sqrError = f.squaredNorm();
207 const T w = constr.weight * this->weight_;
208 error += w * this->loss_.value(sqrError);
209 const T derivScale = std::sqrt(w * this->loss_.deriv(sqrError));
210
211 // Write scaled residual
212 const size_t rowIndex = FuncDim * iConstr;
213 residual.template middleRows<FuncDim>(rowIndex).noalias() = derivScale * f;
214
215 // Early termination
216 if (isApprox<T>(derivScale, T(0), Eps<T>(1e-9, 1e-16))) {
217 continue;
218 }
219 const bool zeroDfdv =
220 !std::any_of(dfdv.begin(), dfdv.end(), [](const auto& m) { return !m.isZero(); });
221 if (zeroDfdv) {
222 continue;
223 }
224
225 auto&& jac = jacobian.template middleRows<FuncDim>(rowIndex);
226
227 // Inline hierarchy walk: walk from parent joint to root
228 size_t jntIndex = constr.parent;
229 while (jntIndex != kInvalidIndex) {
230 MT_CHECK(jntIndex < this->skeleton_.joints.size());
231
232 const auto& jntState = state.jointState[jntIndex];
233 const size_t jntParamIndex = jntIndex * kParametersPerJoint;
234
235 for (size_t jVec = 0; jVec < NumVec; ++jVec) {
236 if (dfdv[jVec].isZero()) {
237 continue;
238 }
239
240 Eigen::Vector3<T> offset;
241 if (jVec < NumPos) {
242 offset.noalias() = v[jVec] - jntState.translation();
243 } else {
244 offset = v[jVec];
245 }
246
247 // Translational dofs -- only affect POINT
248 if (jVec < NumPos) {
249 for (size_t d = 0; d < 3; ++d) {
250 if (!this->activeJointParams_[jntParamIndex + d]) {
251 continue;
252 }
253 const FuncType jc = derivScale * dfdv[jVec] * jntState.getTranslationDerivative(d);
254 for (auto index = outerIndexPtr[jntParamIndex + d];
255 index < outerIndexPtr[jntParamIndex + d + 1];
256 ++index) {
257 if (this->enabledParameters_.test(innerIndexPtr[index])) {
258 jac.col(innerIndexPtr[index]).noalias() += jc * valuePtr[index];
259 }
260 }
261 }
262 }
263
264 // Rotational dofs -- affect both POINT and AXIS
265 for (size_t d = 0; d < 3; ++d) {
266 if (!this->activeJointParams_[jntParamIndex + 3 + d]) {
267 continue;
268 }
269 const FuncType jc = derivScale * dfdv[jVec] * jntState.getRotationDerivative(d, offset);
270 for (auto index = outerIndexPtr[jntParamIndex + 3 + d];
271 index < outerIndexPtr[jntParamIndex + 3 + d + 1];
272 ++index) {
273 if (this->enabledParameters_.test(innerIndexPtr[index])) {
274 jac.col(innerIndexPtr[index]).noalias() += jc * valuePtr[index];
275 }
276 }
277 }
278
279 // Scale dof -- only affect POINT
280 if (jVec < NumPos) {
281 if (this->activeJointParams_[jntParamIndex + 6]) {
282 const FuncType jc = derivScale * dfdv[jVec] * jntState.getScaleDerivative(offset);
283 for (auto index = outerIndexPtr[jntParamIndex + 6];
284 index < outerIndexPtr[jntParamIndex + 6 + 1];
285 ++index) {
286 if (this->enabledParameters_.test(innerIndexPtr[index])) {
287 jac.col(innerIndexPtr[index]).noalias() += jc * valuePtr[index];
288 }
289 }
290 }
291 }
292 }
293 jntIndex = this->skeleton_.joints[jntIndex].parent;
294 }
295 }
296 return error;
297}
298
299template <typename T, class Data, size_t FuncDim, size_t NumVec, size_t NumPos>
303
304} // namespace momentum
#define MT_CHECK(condition,...)
Runtime check macros with two interchangeable backends:
Definition checks.h:36
virtual void evalFunction(size_t constrIndex, const JointStateT< T > &state, FuncType &f, std::array< VType, NumVec > &v, std::array< DfdvType, NumVec > &dfdv) const =0
Evaluate the constraint residual and derivatives for a single constraint.
JointErrorFunctionT(const Skeleton &skel, const ParameterTransform &pt, const T &lossAlpha=GeneralizedLossT< T >::kL2, const T &lossC=T(1))
Constructor.
size_t getJacobianSize() const final
The number of rows in the jacobian is the dimension of f, FuncDim, times the number of constraints.
double getGradient(const ModelParametersT< T > &params, const SkeletonStateT< T > &state, const MeshStateT< T > &meshState, Ref< VectorX< T > > gradient) final
The gradient of the error function: dl/dq = dl/d[f^2] * 2f * df/dv * dv/dq.
std::vector< Data > constraints_
List of constraints.
const GeneralizedLossT< T > loss_
The generalized loss function that transforms f^2.
double getError(const ModelParametersT< T > &params, const SkeletonStateT< T > &state, const MeshStateT< T > &meshState) final
Computes the error function value l = w * loss(f^2).
VectorX< T > jointGrad_
Intermediate storage of the gradient from this error function.
double getJacobian(const ModelParametersT< T > &params, const SkeletonStateT< T > &state, const MeshStateT< T > &meshState, Ref< MatrixX< T > > jacobian, Ref< VectorX< T > > residual, int &usedRows) final
For least-square problems, we assume l is the square of a vector function F.
SkeletonErrorFunctionT(const Skeleton &skel, const ParameterTransform &pt)
const ParameterTransform & parameterTransform_
constexpr T Eps(T FloatEps=T(1e-7), T DoubleEps=T(1e-16))
Returns a type-appropriate tolerance/epsilon value.
Definition constants.h:30
SkeletonT< float > Skeleton
Definition fwd.h:263
Eigen::Ref< T > Ref
Definition types.h:43
ParameterTransformT< float > ParameterTransform
Definition fwd.h:244
bool isApprox(T l, T r, T eps=Eps< T >(1e-4, 1e-6)) noexcept
Determines if two values are approximately equal within a given tolerance.
Definition utility.h:53
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
Profiling macros that dispatch to one of three backends, selected at compile time:
#define MT_PROFILE_FUNCTION()
Definition profile.h:110
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
Represents the complete state of a skeleton.
JointStateListT< T > jointState
Computed joint states for all joints in the skeleton.