Momentum
A library for solving nonlinear optimization problems related to human body kinematics
Loading...
Searching...
No Matches
limit_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
16
17namespace momentum {
18
19namespace {
20
21constexpr float kPositionWeight = 1e-4f;
22
23// Each constraint contributes `w * loss(s)` where `s` is the raw squared residual and `w` is the
24// product of the weighting terms. The helpers below are templated on whether the loss is a plain
25// L2 loss:
26// - IsL2 == true: the squared error is used directly. `invC2` (the loss scale, 1 for the default
27// c = 1) is folded into the surrounding weight by the caller, so these helpers do no
28// loss-function calls at all and match the original hand-optimized quadratic penalty.
29// - IsL2 == false: the squared error is transformed by GeneralizedLossT::value/deriv.
30
31template <typename T, bool IsL2>
32T computeMinMaxError(
33 const LimitMinMax& data,
34 const ModelParametersT<T>& params,
35 T limitWeight,
36 const GeneralizedLossT<T>& loss,
37 const ParameterSet& enabledParameters) {
38 if (!enabledParameters.test(data.parameterIndex)) {
39 return T(0);
40 }
41 T error = T(0);
42 if (params(data.parameterIndex) < data.limits[0]) {
43 const T val = data.limits[0] - params(data.parameterIndex);
44 const T sqrError = val * val;
45 if constexpr (IsL2) {
46 error = limitWeight * sqrError;
47 } else {
48 error = limitWeight * loss.value(sqrError);
49 }
50 }
51 if (params(data.parameterIndex) > data.limits[1]) {
52 const T val = data.limits[1] - params(data.parameterIndex);
53 const T sqrError = val * val;
54 if constexpr (IsL2) {
55 error = limitWeight * sqrError;
56 } else {
57 error = limitWeight * loss.value(sqrError);
58 }
59 }
60 return error;
61}
62
63template <typename T, bool IsL2>
64T computeMinMaxJointError(
65 const LimitMinMaxJoint& data,
66 const SkeletonStateT<T>& state,
67 T limitWeight,
68 const GeneralizedLossT<T>& loss,
69 const Eigen::VectorX<bool>& activeJointParams) {
70 const size_t parameterIndex = data.jointIndex * kParametersPerJoint + data.jointParameter;
71 MT_CHECK(parameterIndex < static_cast<size_t>(state.jointParameters.size()));
72 if (!activeJointParams[parameterIndex]) {
73 return T(0);
74 }
75 T error = T(0);
76 if (state.jointParameters(parameterIndex) < data.limits[0]) {
77 const T val = data.limits[0] - state.jointParameters[parameterIndex];
78 const T sqrError = val * val;
79 if constexpr (IsL2) {
80 error = limitWeight * sqrError;
81 } else {
82 error = limitWeight * loss.value(sqrError);
83 }
84 }
85 if (state.jointParameters(parameterIndex) > data.limits[1]) {
86 const T val = data.limits[1] - state.jointParameters[parameterIndex];
87 const T sqrError = val * val;
88 if constexpr (IsL2) {
89 error = limitWeight * sqrError;
90 } else {
91 error = limitWeight * loss.value(sqrError);
92 }
93 }
94 return error;
95}
96
97template <typename T, bool IsL2>
98T computeLinearError(
99 const LimitLinear& data,
100 const ModelParametersT<T>& params,
101 T limitWeight,
102 const GeneralizedLossT<T>& loss,
103 const ParameterSet& enabledParameters) {
104 MT_CHECK(data.referenceIndex < static_cast<size_t>(params.size()));
105 MT_CHECK(data.targetIndex < static_cast<size_t>(params.size()));
106 if ((!enabledParameters.test(data.targetIndex) && !enabledParameters.test(data.referenceIndex)) ||
107 !isInRange(data, params(data.targetIndex))) {
108 return T(0);
109 }
110 const T residual =
111 params(data.targetIndex) * data.scale - data.offset - params(data.referenceIndex);
112 const T sqrError = residual * residual;
113 if constexpr (IsL2) {
114 return limitWeight * sqrError;
115 } else {
116 return limitWeight * loss.value(sqrError);
117 }
118}
119
120template <typename T, bool IsL2>
121T computeLinearJointError(
122 const LimitLinearJoint& data,
123 const SkeletonStateT<T>& state,
124 T limitWeight,
125 const GeneralizedLossT<T>& loss,
126 const Eigen::VectorX<bool>& activeJointParams) {
127 const size_t referenceParameterIndex =
128 data.referenceJointIndex * kParametersPerJoint + data.referenceJointParameter;
129 const size_t targetParameterIndex =
130 data.targetJointIndex * kParametersPerJoint + data.targetJointParameter;
131 MT_CHECK(referenceParameterIndex < static_cast<size_t>(state.jointParameters.size()));
132 MT_CHECK(targetParameterIndex < static_cast<size_t>(state.jointParameters.size()));
133 if ((!activeJointParams[referenceParameterIndex] && !activeJointParams[targetParameterIndex]) ||
134 !isInRange(data, state.jointParameters[targetParameterIndex])) {
135 return T(0);
136 }
137 const T residual = state.jointParameters(targetParameterIndex) * data.scale - data.offset -
138 state.jointParameters(referenceParameterIndex);
139 const T sqrError = residual * residual;
140 if constexpr (IsL2) {
141 return limitWeight * sqrError;
142 } else {
143 return limitWeight * loss.value(sqrError);
144 }
145}
146
147template <typename T, bool IsL2>
148T computeHalfPlaneError(
149 const LimitHalfPlane& data,
150 const ModelParametersT<T>& params,
151 T limitWeight,
152 const GeneralizedLossT<T>& loss,
153 const ParameterSet& enabledParameters) {
154 MT_CHECK(data.param1 < static_cast<size_t>(params.size()));
155 MT_CHECK(data.param2 < static_cast<size_t>(params.size()));
156 if (!enabledParameters.test(data.param1) && !enabledParameters.test(data.param2)) {
157 return T(0);
158 }
159 const Eigen::Vector2<T> p(params(data.param1), params(data.param2));
160 const T residual = p.dot(data.normal.template cast<T>()) - data.offset;
161 if (residual < 0) {
162 const T sqrError = residual * residual;
163 if constexpr (IsL2) {
164 return limitWeight * sqrError;
165 } else {
166 return limitWeight * loss.value(sqrError);
167 }
168 }
169 return T(0);
170}
171
172template <typename T, bool IsL2>
173T computeEllipsoidError(
174 const LimitEllipsoid& ct,
175 const SkeletonStateT<T>& state,
176 T limitWeight,
177 const GeneralizedLossT<T>& loss) {
178 const Eigen::Vector3<T> position =
179 state.jointState[ct.parent].transform * ct.offset.template cast<T>();
180 const Eigen::Vector3<T> localPosition =
181 state.jointState[ct.ellipsoidParent].transform.inverse() * position;
182 const Eigen::Vector3<T> ellipsoidPosition = ct.ellipsoidInv.template cast<T>() * localPosition;
183 const Eigen::Vector3<T> normalizedPosition = ellipsoidPosition.normalized();
184 const Eigen::Vector3<T> projectedPosition = ct.ellipsoid.template cast<T>() * normalizedPosition;
185 const Eigen::Vector3<T> diff =
186 position - state.jointState[ct.ellipsoidParent].transform * projectedPosition;
187 const T sqrError = diff.squaredNorm();
188 if constexpr (IsL2) {
189 return T(kPositionWeight) * limitWeight * sqrError;
190 } else {
191 return T(kPositionWeight) * limitWeight * loss.value(sqrError);
192 }
193}
194
195template <typename T, bool IsL2>
196T computeMinMaxGradient(
197 const LimitMinMax& data,
198 const ModelParametersT<T>& params,
199 T tWeight,
200 T limitWeight,
201 const GeneralizedLossT<T>& loss,
202 const ParameterSet& enabledParameters,
203 Ref<Eigen::VectorX<T>> gradient) {
204 if (!enabledParameters.test(data.parameterIndex)) {
205 return T(0);
206 }
207 T error = T(0);
208 if (params(data.parameterIndex) < data.limits[0]) {
209 const T val = params(data.parameterIndex) - data.limits[0];
210 const T sqrError = val * val;
211 if constexpr (IsL2) {
212 error = tWeight * limitWeight * sqrError;
213 gradient[data.parameterIndex] += T(2) * val * tWeight * limitWeight;
214 } else {
215 error = tWeight * limitWeight * loss.value(sqrError);
216 gradient[data.parameterIndex] += T(2) * val * tWeight * limitWeight * loss.deriv(sqrError);
217 }
218 }
219 if (params(data.parameterIndex) > data.limits[1]) {
220 const T val = params(data.parameterIndex) - data.limits[1];
221 const T sqrError = val * val;
222 if constexpr (IsL2) {
223 error = tWeight * limitWeight * sqrError;
224 gradient[data.parameterIndex] += T(2) * val * tWeight * limitWeight;
225 } else {
226 error = tWeight * limitWeight * loss.value(sqrError);
227 gradient[data.parameterIndex] += T(2) * val * tWeight * limitWeight * loss.deriv(sqrError);
228 }
229 }
230 return error;
231}
232
233template <typename T, bool IsL2>
234T computeMinMaxJointGradient(
235 const LimitMinMaxJoint& data,
236 const SkeletonStateT<T>& state,
237 T tWeight,
238 T limitWeight,
239 const GeneralizedLossT<T>& loss,
240 const Eigen::VectorX<bool>& activeJointParams,
241 const ParameterTransform& parameterTransform,
242 Ref<Eigen::VectorX<T>> gradient) {
243 const size_t parameterIndex = data.jointIndex * kParametersPerJoint + data.jointParameter;
244 MT_CHECK(parameterIndex < static_cast<size_t>(state.jointParameters.size()));
245 if (!activeJointParams[parameterIndex]) {
246 return T(0);
247 }
248
249 T error = T(0);
250 if (state.jointParameters(parameterIndex) < data.limits[0]) {
251 const T val = state.jointParameters[parameterIndex] - data.limits[0];
252 const T sqrError = val * val;
253 T jGrad;
254 if constexpr (IsL2) {
255 error = tWeight * limitWeight * sqrError;
256 jGrad = T(2) * val * tWeight * limitWeight;
257 } else {
258 error = tWeight * limitWeight * loss.value(sqrError);
259 jGrad = T(2) * val * tWeight * limitWeight * loss.deriv(sqrError);
260 }
261 gradient_jointParams_to_modelParams(jGrad, parameterIndex, parameterTransform, gradient);
262 }
263 if (state.jointParameters(parameterIndex) > data.limits[1]) {
264 const T val = state.jointParameters[parameterIndex] - data.limits[1];
265 const T sqrError = val * val;
266 T jGrad;
267 if constexpr (IsL2) {
268 error = tWeight * limitWeight * sqrError;
269 jGrad = T(2) * val * tWeight * limitWeight;
270 } else {
271 error = tWeight * limitWeight * loss.value(sqrError);
272 jGrad = T(2) * val * tWeight * limitWeight * loss.deriv(sqrError);
273 }
274 gradient_jointParams_to_modelParams(jGrad, parameterIndex, parameterTransform, gradient);
275 }
276 return error;
277}
278
279template <typename T, bool IsL2>
280T computeLinearGradient(
281 const LimitLinear& data,
282 const ModelParametersT<T>& params,
283 T tWeight,
284 T limitWeight,
285 const GeneralizedLossT<T>& loss,
286 const ParameterSet& enabledParameters,
287 Ref<Eigen::VectorX<T>> gradient) {
288 MT_CHECK(data.referenceIndex < static_cast<size_t>(params.size()));
289 MT_CHECK(data.targetIndex < static_cast<size_t>(params.size()));
290 if (!isInRange(data, params(data.targetIndex))) {
291 return T(0);
292 }
293 const T residual =
294 params(data.targetIndex) * data.scale - data.offset - params(data.referenceIndex);
295 const T sqrError = residual * residual;
296 T error;
297 T gradScale;
298 if constexpr (IsL2) {
299 error = limitWeight * tWeight * sqrError;
300 gradScale = T(2) * residual * limitWeight * tWeight;
301 } else {
302 error = limitWeight * tWeight * loss.value(sqrError);
303 gradScale = T(2) * residual * limitWeight * tWeight * loss.deriv(sqrError);
304 }
305 if (enabledParameters.test(data.targetIndex)) {
306 gradient[data.targetIndex] += gradScale * T(data.scale);
307 }
308 if (enabledParameters.test(data.referenceIndex)) {
309 gradient[data.referenceIndex] -= gradScale;
310 }
311 return error;
312}
313
314template <typename T, bool IsL2>
315T computeLinearJointGradient(
316 const LimitLinearJoint& data,
317 const SkeletonStateT<T>& state,
318 T tWeight,
319 T limitWeight,
320 const GeneralizedLossT<T>& loss,
321 const Eigen::VectorX<bool>& activeJointParams,
322 const ParameterTransform& parameterTransform,
323 Ref<Eigen::VectorX<T>> gradient) {
324 const size_t referenceParameterIndex =
325 data.referenceJointIndex * kParametersPerJoint + data.referenceJointParameter;
326 const size_t targetParameterIndex =
327 data.targetJointIndex * kParametersPerJoint + data.targetJointParameter;
328 MT_CHECK(referenceParameterIndex < static_cast<size_t>(state.jointParameters.size()));
329 MT_CHECK(targetParameterIndex < static_cast<size_t>(state.jointParameters.size()));
330
331 if ((!activeJointParams[referenceParameterIndex] && !activeJointParams[targetParameterIndex]) ||
332 !isInRange(data, state.jointParameters[targetParameterIndex])) {
333 return T(0);
334 }
335
336 const T residual = state.jointParameters(targetParameterIndex) * data.scale - data.offset -
337 state.jointParameters(referenceParameterIndex);
338 const T sqrError = residual * residual;
339 T error;
340 T gradScale;
341 if constexpr (IsL2) {
342 error = limitWeight * tWeight * sqrError;
343 gradScale = T(2) * residual * limitWeight * tWeight;
344 } else {
345 error = limitWeight * tWeight * loss.value(sqrError);
346 gradScale = T(2) * residual * limitWeight * tWeight * loss.deriv(sqrError);
347 }
348
349 const T targetGrad = gradScale * T(data.scale);
351 targetGrad, targetParameterIndex, parameterTransform, gradient);
352
353 const T referenceGrad = -gradScale;
355 referenceGrad, referenceParameterIndex, parameterTransform, gradient);
356
357 return error;
358}
359
360template <typename T, bool IsL2>
361T computeHalfPlaneGradient(
362 const LimitHalfPlane& data,
363 const ModelParametersT<T>& params,
364 T tWeight,
365 T limitWeight,
366 const GeneralizedLossT<T>& loss,
367 const ParameterSet& enabledParameters,
368 Ref<Eigen::VectorX<T>> gradient) {
369 if (!enabledParameters.test(data.param1) && !enabledParameters.test(data.param2)) {
370 return T(0);
371 }
372 const Eigen::Vector2<T> p(params(data.param1), params(data.param2));
373 const T residual = p.dot(data.normal.template cast<T>()) - data.offset;
374 if (residual >= T(0)) {
375 return T(0);
376 }
377 const T sqrError = residual * residual;
378 T error;
379 T gradScale;
380 if constexpr (IsL2) {
381 error = limitWeight * tWeight * sqrError;
382 gradScale = T(2) * residual * limitWeight * tWeight;
383 } else {
384 error = limitWeight * tWeight * loss.value(sqrError);
385 gradScale = T(2) * residual * limitWeight * tWeight * loss.deriv(sqrError);
386 }
387 if (enabledParameters.test(data.param1)) {
388 gradient[data.param1] += gradScale * T(data.normal[0]);
389 }
390 if (enabledParameters.test(data.param2)) {
391 gradient[data.param2] += gradScale * T(data.normal[1]);
392 }
393 return error;
394}
395
396template <typename T, bool IsL2>
397T computeEllipsoidGradient(
398 const LimitEllipsoid& ct,
399 const SkeletonStateT<T>& state,
400 T tWeight,
401 T limitWeight,
402 const GeneralizedLossT<T>& loss,
403 const Eigen::VectorX<bool>& activeJointParams,
404 const Skeleton& skeleton,
405 const ParameterTransform& parameterTransform,
406 Ref<Eigen::VectorX<T>> gradient) {
407 const Eigen::Vector3<T> position =
408 state.jointState[ct.parent].transform * ct.offset.template cast<T>();
409 const Eigen::Vector3<T> localPosition =
410 state.jointState[ct.ellipsoidParent].transform.inverse() * position;
411 const Eigen::Vector3<T> ellipsoidPosition = ct.ellipsoidInv.template cast<T>() * localPosition;
412 const Eigen::Vector3<T> normalizedPosition = ellipsoidPosition.normalized();
413 const Eigen::Vector3<T> projectedPosition = ct.ellipsoid.template cast<T>() * normalizedPosition;
414 const Eigen::Vector3<T> diff =
415 position - state.jointState[ct.ellipsoidParent].transform * projectedPosition;
416 const T sqrError = diff.squaredNorm();
417
418 // wgt is the gradient scale: d(w * loss(s))/dq has the factor 2 * w * loss'(s), with
419 // w = kPositionWeight * limitWeight * tWeight. For L2, loss'(s) is folded into tWeight by the
420 // caller.
421 T wgt;
422 if constexpr (IsL2) {
423 wgt = T(2) * T(kPositionWeight) * limitWeight * tWeight;
424 } else {
425 wgt = T(2) * T(kPositionWeight) * limitWeight * tWeight * loss.deriv(sqrError);
426 }
427
428 size_t jointIndex = ct.parent;
429 while (jointIndex != ct.ellipsoidParent && jointIndex != kInvalidIndex) {
430 MT_CHECK(jointIndex < skeleton.joints.size());
431 const auto& jointState = state.jointState[jointIndex];
432 const size_t paramIndex = jointIndex * kParametersPerJoint;
433 const Eigen::Vector3<T> posd = position - jointState.translation();
434
435 for (size_t d = 0; d < 3; d++) {
436 if (activeJointParams[paramIndex + d]) {
437 const T val = diff.dot(jointState.getTranslationDerivative(d)) * wgt;
438 gradient_jointParams_to_modelParams(val, paramIndex + d, parameterTransform, gradient);
439 }
440 if (activeJointParams[paramIndex + 3 + d]) {
441 const T val = diff.dot(jointState.getRotationDerivative(d, posd)) * wgt;
442 gradient_jointParams_to_modelParams(val, paramIndex + 3 + d, parameterTransform, gradient);
443 }
444 }
445 if (activeJointParams[paramIndex + 6]) {
446 const T val = diff.dot(jointState.getScaleDerivative(posd)) * wgt;
447 gradient_jointParams_to_modelParams(val, paramIndex + 6, parameterTransform, gradient);
448 }
449 jointIndex = skeleton.joints[jointIndex].parent;
450 }
451
452 if constexpr (IsL2) {
453 return T(kPositionWeight) * limitWeight * tWeight * sqrError;
454 } else {
455 return T(kPositionWeight) * limitWeight * tWeight * loss.value(sqrError);
456 }
457}
458
459template <typename T, bool IsL2>
460T computeMinMaxJacobian(
461 const LimitMinMax& data,
462 const ModelParametersT<T>& params,
463 T tWeight,
464 T limitWeight,
465 T wgt,
466 const GeneralizedLossT<T>& loss,
467 const ParameterSet& enabledParameters,
468 Ref<Eigen::MatrixX<T>> jacobian,
469 Ref<Eigen::VectorX<T>> residual,
470 int row) {
471 if (!enabledParameters.test(data.parameterIndex)) {
472 return T(0);
473 }
474 if (params(data.parameterIndex) < data.limits[0]) {
475 const T val = params(data.parameterIndex) - data.limits[0];
476 const T sqrError = val * val;
477 if constexpr (IsL2) {
478 jacobian(row, data.parameterIndex) = wgt;
479 residual(row) = val * wgt;
480 return tWeight * limitWeight * sqrError;
481 } else {
482 const T wgtLoss = std::sqrt(tWeight * limitWeight * loss.deriv(sqrError));
483 jacobian(row, data.parameterIndex) = wgtLoss;
484 residual(row) = val * wgtLoss;
485 return tWeight * limitWeight * loss.value(sqrError);
486 }
487 }
488 if (params(data.parameterIndex) > data.limits[1]) {
489 const T val = params(data.parameterIndex) - data.limits[1];
490 const T sqrError = val * val;
491 if constexpr (IsL2) {
492 jacobian(row, data.parameterIndex) = wgt;
493 residual(row) = val * wgt;
494 return tWeight * limitWeight * sqrError;
495 } else {
496 const T wgtLoss = std::sqrt(tWeight * limitWeight * loss.deriv(sqrError));
497 jacobian(row, data.parameterIndex) = wgtLoss;
498 residual(row) = val * wgtLoss;
499 return tWeight * limitWeight * loss.value(sqrError);
500 }
501 }
502 return T(0);
503}
504
505template <typename T, bool IsL2>
506T computeMinMaxJointJacobian(
507 const LimitMinMaxJoint& data,
508 const SkeletonStateT<T>& state,
509 T tWeight,
510 T limitWeight,
511 T wgt,
512 const GeneralizedLossT<T>& loss,
513 const Eigen::VectorX<bool>& activeJointParams,
514 const ParameterTransform& parameterTransform,
515 Ref<Eigen::MatrixX<T>> jacobian,
516 Ref<Eigen::VectorX<T>> residual,
517 int row) {
518 const size_t jointIndex = data.jointIndex * kParametersPerJoint + data.jointParameter;
519 MT_CHECK(jointIndex < static_cast<size_t>(state.jointParameters.size()));
520 if (!activeJointParams[jointIndex]) {
521 return T(0);
522 }
523 if (state.jointParameters(jointIndex) < data.limits[0]) {
524 const T val = state.jointParameters[jointIndex] - data.limits[0];
525 const T sqrError = val * val;
526 T wgtLoss;
527 T error;
528 if constexpr (IsL2) {
529 wgtLoss = wgt;
530 error = tWeight * limitWeight * sqrError;
531 } else {
532 wgtLoss = std::sqrt(tWeight * limitWeight * loss.deriv(sqrError));
533 error = tWeight * limitWeight * loss.value(sqrError);
534 }
536 wgtLoss, Eigen::Index(jointIndex), Eigen::Index(row), parameterTransform, jacobian);
537 residual(row) = val * wgtLoss;
538 return error;
539 }
540 if (state.jointParameters(jointIndex) > data.limits[1]) {
541 const T val = state.jointParameters[jointIndex] - data.limits[1];
542 const T sqrError = val * val;
543 T wgtLoss;
544 T error;
545 if constexpr (IsL2) {
546 wgtLoss = wgt;
547 error = tWeight * limitWeight * sqrError;
548 } else {
549 wgtLoss = std::sqrt(tWeight * limitWeight * loss.deriv(sqrError));
550 error = tWeight * limitWeight * loss.value(sqrError);
551 }
553 wgtLoss, Eigen::Index(jointIndex), Eigen::Index(row), parameterTransform, jacobian);
554 residual(row) = val * wgtLoss;
555 return error;
556 }
557 return T(0);
558}
559
560template <typename T, bool IsL2>
561T computeLinearJacobian(
562 const LimitLinear& data,
563 const ModelParametersT<T>& params,
564 T tWeight,
565 T limitWeight,
566 T wgt,
567 const GeneralizedLossT<T>& loss,
568 const ParameterSet& enabledParameters,
569 Ref<Eigen::MatrixX<T>> jacobian,
570 Ref<Eigen::VectorX<T>> residual,
571 int row) {
572 MT_CHECK(data.referenceIndex < static_cast<size_t>(params.size()));
573 MT_CHECK(data.targetIndex < static_cast<size_t>(params.size()));
574
575 if ((!enabledParameters.test(data.targetIndex) && !enabledParameters.test(data.referenceIndex)) ||
576 !isInRange(data, params(data.targetIndex))) {
577 return T(0);
578 }
579 const T res = params(data.targetIndex) * data.scale - data.offset - params(data.referenceIndex);
580 const T sqrError = res * res;
581 T wgtLoss;
582 T error;
583 if constexpr (IsL2) {
584 wgtLoss = wgt;
585 error = tWeight * limitWeight * sqrError;
586 } else {
587 wgtLoss = std::sqrt(tWeight * limitWeight * loss.deriv(sqrError));
588 error = tWeight * limitWeight * loss.value(sqrError);
589 }
590 residual(row) = res * wgtLoss;
591 if (enabledParameters.test(data.targetIndex)) {
592 jacobian(row, data.targetIndex) = T(data.scale) * wgtLoss;
593 }
594 if (enabledParameters.test(data.referenceIndex)) {
595 jacobian(row, data.referenceIndex) = -wgtLoss;
596 }
597 return error;
598}
599
600template <typename T, bool IsL2>
601T computeLinearJointJacobian(
602 const LimitLinearJoint& data,
603 const SkeletonStateT<T>& state,
604 T tWeight,
605 T limitWeight,
606 T wgt,
607 const GeneralizedLossT<T>& loss,
608 const Eigen::VectorX<bool>& activeJointParams,
609 const ParameterTransform& parameterTransform,
610 Ref<Eigen::MatrixX<T>> jacobian,
611 Ref<Eigen::VectorX<T>> residual,
612 int row) {
613 const size_t referenceParameterIndex =
614 data.referenceJointIndex * kParametersPerJoint + data.referenceJointParameter;
615 const size_t targetParameterIndex =
616 data.targetJointIndex * kParametersPerJoint + data.targetJointParameter;
617 MT_CHECK(referenceParameterIndex < static_cast<size_t>(state.jointParameters.size()));
618 MT_CHECK(targetParameterIndex < static_cast<size_t>(state.jointParameters.size()));
619
620 if ((!activeJointParams[referenceParameterIndex] && !activeJointParams[targetParameterIndex]) ||
621 !isInRange(data, state.jointParameters(targetParameterIndex))) {
622 return T(0);
623 }
624
625 const T res = state.jointParameters(targetParameterIndex) * data.scale - data.offset -
626 state.jointParameters(referenceParameterIndex);
627 const T sqrError = res * res;
628 T wgtLoss;
629 T error;
630 if constexpr (IsL2) {
631 wgtLoss = wgt;
632 error = tWeight * limitWeight * sqrError;
633 } else {
634 wgtLoss = std::sqrt(tWeight * limitWeight * loss.deriv(sqrError));
635 error = tWeight * limitWeight * loss.value(sqrError);
636 }
637 residual(row) = res * wgtLoss;
638
639 if (activeJointParams[targetParameterIndex]) {
641 T(data.scale) * wgtLoss,
642 Eigen::Index(targetParameterIndex),
643 Eigen::Index(row),
644 parameterTransform,
645 jacobian);
646 }
647 if (activeJointParams[referenceParameterIndex]) {
649 -wgtLoss,
650 Eigen::Index(referenceParameterIndex),
651 Eigen::Index(row),
652 parameterTransform,
653 jacobian);
654 }
655 return error;
656}
657
658template <typename T, bool IsL2>
659T computeHalfPlaneJacobian(
660 const LimitHalfPlane& data,
661 const ModelParametersT<T>& params,
662 T tWeight,
663 T limitWeight,
664 T wgt,
665 const GeneralizedLossT<T>& loss,
666 const ParameterSet& enabledParameters,
667 Ref<Eigen::MatrixX<T>> jacobian,
668 Ref<Eigen::VectorX<T>> residual,
669 int row) {
670 MT_CHECK(data.param1 < static_cast<size_t>(params.size()));
671 MT_CHECK(data.param2 < static_cast<size_t>(params.size()));
672
673 if (!enabledParameters.test(data.param1) && !enabledParameters.test(data.param2)) {
674 return T(0);
675 }
676 const Eigen::Vector2<T> p(params(data.param1), params(data.param2));
677 const T res = p.dot(data.normal.template cast<T>()) - data.offset;
678 if (res >= T(0)) {
679 return T(0);
680 }
681 const T sqrError = res * res;
682 T wgtLoss;
683 T error;
684 if constexpr (IsL2) {
685 wgtLoss = wgt;
686 error = tWeight * limitWeight * sqrError;
687 } else {
688 wgtLoss = std::sqrt(tWeight * limitWeight * loss.deriv(sqrError));
689 error = tWeight * limitWeight * loss.value(sqrError);
690 }
691 residual(row) = res * wgtLoss;
692 if (enabledParameters.test(data.param1)) {
693 jacobian(row, data.param1) = T(data.normal[0]) * wgtLoss;
694 }
695 if (enabledParameters.test(data.param2)) {
696 jacobian(row, data.param2) = T(data.normal[1]) * wgtLoss;
697 }
698 return error;
699}
700
701template <typename T, bool IsL2>
702T computeEllipsoidJacobian(
703 const LimitEllipsoid& ct,
704 const ModelParametersT<T>& params,
705 const SkeletonStateT<T>& state,
706 T totalWeight,
707 T limitWeight,
708 const GeneralizedLossT<T>& loss,
709 const Eigen::VectorX<bool>& activeJointParams,
710 const Skeleton& skeleton,
711 const ParameterTransform& parameterTransform,
712 Ref<Eigen::MatrixX<T>> jacobian,
713 Ref<Eigen::VectorX<T>> residual,
714 int row) {
715 const Eigen::Vector3<T> position =
716 state.jointState[ct.parent].transform * ct.offset.template cast<T>();
717 const Eigen::Vector3<T> localPosition =
718 state.jointState[ct.ellipsoidParent].transform.inverse() * position;
719 const Eigen::Vector3<T> ellipsoidPosition = ct.ellipsoidInv.template cast<T>() * localPosition;
720 const Eigen::Vector3<T> normalizedPosition = ellipsoidPosition.normalized();
721 const Eigen::Vector3<T> projectedPosition = ct.ellipsoid.template cast<T>() * normalizedPosition;
722 const Eigen::Vector3<T> diff =
723 position - state.jointState[ct.ellipsoidParent].transform * projectedPosition;
724 const T sqrError = diff.squaredNorm();
725
726 Eigen::Ref<Eigen::MatrixX<T>> jac = jacobian.block(row, 0, 3, params.size());
727 Eigen::Ref<Eigen::VectorX<T>> res = residual.middleRows(row, 3);
728 MT_CHECK(jac.cols() == static_cast<Eigen::Index>(parameterTransform.transform.cols()));
729 MT_CHECK(jac.rows() == 3);
730
731 // jwgt is the residual/Jacobian scale sqrt(w * loss'(s)), with w = totalWeight * kPositionWeight
732 // * limitWeight. For L2, loss'(s) is folded into totalWeight by the caller.
733 T jwgt;
734 if constexpr (IsL2) {
735 jwgt = std::sqrt(totalWeight * T(kPositionWeight) * limitWeight);
736 } else {
737 jwgt = std::sqrt(totalWeight * T(kPositionWeight) * limitWeight * loss.deriv(sqrError));
738 }
739
740 size_t jointIndex = ct.parent;
741 while (jointIndex != ct.ellipsoidParent && jointIndex != kInvalidIndex) {
742 MT_CHECK(jointIndex < skeleton.joints.size());
743 const auto& jointState = state.jointState[jointIndex];
744 const size_t paramIndex = jointIndex * kParametersPerJoint;
745 const Eigen::Vector3<T> posd = position - jointState.translation();
746
747 for (size_t d = 0; d < 3; d++) {
748 if (activeJointParams[paramIndex + d]) {
749 const Eigen::Vector3<T> jc = jointState.getTranslationDerivative(d) * jwgt;
750 for (auto index = parameterTransform.transform.outerIndexPtr()[paramIndex + d];
751 index < parameterTransform.transform.outerIndexPtr()[paramIndex + d + 1];
752 ++index) {
753 jac.col(parameterTransform.transform.innerIndexPtr()[index]) +=
754 jc * parameterTransform.transform.valuePtr()[index];
755 }
756 }
757 if (activeJointParams[paramIndex + 3 + d]) {
758 const Eigen::Vector3<T> jc = jointState.getRotationDerivative(d, posd) * jwgt;
759 for (auto index = parameterTransform.transform.outerIndexPtr()[paramIndex + 3 + d];
760 index < parameterTransform.transform.outerIndexPtr()[paramIndex + 3 + d + 1];
761 ++index) {
762 jac.col(parameterTransform.transform.innerIndexPtr()[index]) +=
763 jc * parameterTransform.transform.valuePtr()[index];
764 }
765 }
766 }
767 if (activeJointParams[paramIndex + 6]) {
768 const Eigen::Vector3<T> jc = jointState.getScaleDerivative(posd) * jwgt;
769 for (auto index = parameterTransform.transform.outerIndexPtr()[paramIndex + 6];
770 index < parameterTransform.transform.outerIndexPtr()[paramIndex + 6 + 1];
771 ++index) {
772 jac.col(parameterTransform.transform.innerIndexPtr()[index]) +=
773 jc * parameterTransform.transform.valuePtr()[index];
774 }
775 }
776 jointIndex = skeleton.joints[jointIndex].parent;
777 }
778
779 res = diff * jwgt;
780 if constexpr (IsL2) {
781 return totalWeight * T(kPositionWeight) * limitWeight * sqrError;
782 } else {
783 return totalWeight * T(kPositionWeight) * limitWeight * loss.value(sqrError);
784 }
785}
786
787} // namespace
788
789template <typename T>
791 const Skeleton& skel,
792 const ParameterTransform& pt,
793 const ParameterLimits& pl,
794 const T& lossAlpha,
795 const T& lossC)
796 : SkeletonErrorFunctionT<T>(skel, pt), limits_(pl), loss_(lossAlpha, lossC) {}
797
798template <typename T>
800 const Character& character,
801 const T& lossAlpha,
802 const T& lossC)
804 character.skeleton,
805 character.parameterTransform,
806 character.parameterLimits,
807 lossAlpha,
808 lossC) {}
809
810template <typename T>
812 const Character& character,
813 const ParameterLimits& pl,
814 const T& lossAlpha,
815 const T& lossC)
816 : LimitErrorFunctionT(character.skeleton, character.parameterTransform, pl, lossAlpha, lossC) {}
817
818template <typename T>
819template <bool IsL2>
820[[nodiscard]] double LimitErrorFunctionT<T>::getErrorImpl(
821 const ModelParametersT<T>& params,
822 const SkeletonStateT<T>& state) const {
823 double error = 0.0;
824
825 for (const auto& limit : limits_) {
826 const T limitWeight = T(limit.weight);
827 switch (limit.type) {
828 case MinMax:
829 error += computeMinMaxError<T, IsL2>(
830 limit.data.minMax, params, limitWeight, loss_, this->enabledParameters_);
831 break;
832 case MinMaxJoint:
833 error += computeMinMaxJointError<T, IsL2>(
834 limit.data.minMaxJoint, state, limitWeight, loss_, this->activeJointParams_);
835 break;
837 break;
838 case Linear:
839 error += computeLinearError<T, IsL2>(
840 limit.data.linear, params, limitWeight, loss_, this->enabledParameters_);
841 break;
842 case LinearJoint:
843 error += computeLinearJointError<T, IsL2>(
844 limit.data.linearJoint, state, limitWeight, loss_, this->activeJointParams_);
845 break;
846 case HalfPlane:
847 error += computeHalfPlaneError<T, IsL2>(
848 limit.data.halfPlane, params, limitWeight, loss_, this->enabledParameters_);
849 break;
850 case Ellipsoid:
851 error += computeEllipsoidError<T, IsL2>(limit.data.ellipsoid, state, limitWeight, loss_);
852 break;
853 case LimitTypeCount:
854 default:
855 MT_THROW("Unknown parameter type for joint limit");
856 break;
857 }
858 }
859
860 // For an L2 loss the per-limit terms above are raw squared residuals; the loss scale 1/c^2 is
861 // applied once here. For a non-L2 loss it is already baked into loss_.value().
862 if constexpr (IsL2) {
863 return error * kLimitWeight * this->weight_ * loss_.invC2();
864 } else {
865 return error * kLimitWeight * this->weight_;
866 }
867}
868
869template <typename T>
871 const ModelParametersT<T>& params,
872 const SkeletonStateT<T>& state,
873 const MeshStateT<T>& /* meshState */) {
875
876 MT_CHECK(
877 state.jointParameters.size() ==
878 gsl::narrow<Eigen::Index>(this->skeleton_.joints.size() * kParametersPerJoint));
879
880 return loss_.isL2() ? getErrorImpl<true>(params, state) : getErrorImpl<false>(params, state);
881}
882
883template <typename T>
884template <bool IsL2>
885[[nodiscard]] double LimitErrorFunctionT<T>::getGradientImpl(
886 const ModelParametersT<T>& params,
887 const SkeletonStateT<T>& state,
888 Ref<Eigen::VectorX<T>> gradient) const {
889 const auto& parameterTransform = this->parameterTransform_;
890 double error = 0.0;
891
892 // tWeight folds in the loss scale 1/c^2 for the L2 path so the per-constraint code below needs no
893 // loss-function calls.
894 T tWeight = kLimitWeight * this->weight_;
895 if constexpr (IsL2) {
896 tWeight *= loss_.invC2();
897 }
898
899 for (const auto& limit : limits_) {
900 const T limitWeight = T(limit.weight);
901 switch (limit.type) {
902 case MinMax:
903 error += computeMinMaxGradient<T, IsL2>(
904 limit.data.minMax,
905 params,
906 tWeight,
907 limitWeight,
908 loss_,
909 this->enabledParameters_,
910 gradient);
911 break;
912 case MinMaxJoint:
913 error += computeMinMaxJointGradient<T, IsL2>(
914 limit.data.minMaxJoint,
915 state,
916 tWeight,
917 limitWeight,
918 loss_,
919 this->activeJointParams_,
920 parameterTransform,
921 gradient);
922 break;
924 break;
925 case Linear:
926 error += computeLinearGradient<T, IsL2>(
927 limit.data.linear,
928 params,
929 tWeight,
930 limitWeight,
931 loss_,
932 this->enabledParameters_,
933 gradient);
934 break;
935 case LinearJoint:
936 error += computeLinearJointGradient<T, IsL2>(
937 limit.data.linearJoint,
938 state,
939 tWeight,
940 limitWeight,
941 loss_,
942 this->activeJointParams_,
943 parameterTransform,
944 gradient);
945 break;
946 case HalfPlane:
947 error += computeHalfPlaneGradient<T, IsL2>(
948 limit.data.halfPlane,
949 params,
950 tWeight,
951 limitWeight,
952 loss_,
953 this->enabledParameters_,
954 gradient);
955 break;
956 case Ellipsoid:
957 error += computeEllipsoidGradient<T, IsL2>(
958 limit.data.ellipsoid,
959 state,
960 tWeight,
961 limitWeight,
962 loss_,
963 this->activeJointParams_,
964 this->skeleton_,
965 parameterTransform,
966 gradient);
967 break;
968 case LimitTypeCount:
969 default:
970 MT_THROW("Unknown parameter type for joint limit");
971 break;
972 }
973 }
974
975 return error;
976}
977
978template <typename T>
980 const ModelParametersT<T>& params,
981 const SkeletonStateT<T>& state,
982 const MeshStateT<T>& /* meshState */,
983 Ref<Eigen::VectorX<T>> gradient) {
985
986 return loss_.isL2() ? getGradientImpl<true>(params, state, gradient)
987 : getGradientImpl<false>(params, state, gradient);
988}
989
990template <typename T>
991template <bool IsL2>
992double LimitErrorFunctionT<T>::getJacobianImpl(
993 const ModelParametersT<T>& params,
994 const SkeletonStateT<T>& state,
995 Ref<Eigen::MatrixX<T>> jacobian,
996 Ref<Eigen::VectorX<T>> residual,
997 int& usedRows) const {
998 const auto& parameterTransform = this->parameterTransform_;
999 double error = 0.0;
1000
1001 // tWeight folds in the loss scale 1/c^2 for the L2 path. The Jacobian weight sqrt(tWeight *
1002 // limitWeight) is then a constant per limit (it does not depend on the residual), so it is
1003 // computed once here rather than inside the per-constraint helpers. This matches the original
1004 // L2-only implementation; the non-L2 path cannot do this because its weight depends on the
1005 // per-constraint residual via loss'(s).
1006 T tWeight = kLimitWeight * this->weight_;
1007 if constexpr (IsL2) {
1008 tWeight *= loss_.invC2();
1009 }
1010
1011 jacobian.setZero();
1012 residual.setZero();
1013
1014 int count = 0;
1015 for (const auto& limit : limits_) {
1016 const T limitWeight = T(limit.weight);
1017 T wgt = T(0);
1018 if constexpr (IsL2) {
1019 wgt = std::sqrt(tWeight * limitWeight);
1020 }
1021 switch (limit.type) {
1022 case MinMax:
1023 error += computeMinMaxJacobian<T, IsL2>(
1024 limit.data.minMax,
1025 params,
1026 tWeight,
1027 limitWeight,
1028 wgt,
1029 loss_,
1030 this->enabledParameters_,
1031 jacobian,
1032 residual,
1033 count);
1034 count++;
1035 break;
1036 case MinMaxJoint:
1037 error += computeMinMaxJointJacobian<T, IsL2>(
1038 limit.data.minMaxJoint,
1039 state,
1040 tWeight,
1041 limitWeight,
1042 wgt,
1043 loss_,
1044 this->activeJointParams_,
1045 parameterTransform,
1046 jacobian,
1047 residual,
1048 count);
1049 count++;
1050 break;
1051 case MinMaxJointPassive:
1052 break;
1053 case Linear:
1054 error += computeLinearJacobian<T, IsL2>(
1055 limit.data.linear,
1056 params,
1057 tWeight,
1058 limitWeight,
1059 wgt,
1060 loss_,
1061 this->enabledParameters_,
1062 jacobian,
1063 residual,
1064 count);
1065 count++;
1066 break;
1067 case LinearJoint:
1068 error += computeLinearJointJacobian<T, IsL2>(
1069 limit.data.linearJoint,
1070 state,
1071 tWeight,
1072 limitWeight,
1073 wgt,
1074 loss_,
1075 this->activeJointParams_,
1076 parameterTransform,
1077 jacobian,
1078 residual,
1079 count);
1080 count++;
1081 break;
1082 case HalfPlane:
1083 error += computeHalfPlaneJacobian<T, IsL2>(
1084 limit.data.halfPlane,
1085 params,
1086 tWeight,
1087 limitWeight,
1088 wgt,
1089 loss_,
1090 this->enabledParameters_,
1091 jacobian,
1092 residual,
1093 count);
1094 count++;
1095 break;
1096 case Ellipsoid:
1097 error += computeEllipsoidJacobian<T, IsL2>(
1098 limit.data.ellipsoid,
1099 params,
1100 state,
1101 tWeight,
1102 limitWeight,
1103 loss_,
1104 this->activeJointParams_,
1105 this->skeleton_,
1106 parameterTransform,
1107 jacobian,
1108 residual,
1109 count);
1110 count += 3;
1111 break;
1112 case LimitTypeCount:
1113 default:
1114 MT_THROW("Unknown parameter type for joint limit");
1115 break;
1116 }
1117 }
1118
1119 usedRows = count;
1120 return error;
1121}
1122
1123template <typename T>
1125 const ModelParametersT<T>& params,
1126 const SkeletonStateT<T>& state,
1127 const MeshStateT<T>& /* meshState */,
1128 Ref<Eigen::MatrixX<T>> jacobian,
1129 Ref<Eigen::VectorX<T>> residual,
1130 int& usedRows) {
1132
1133 return loss_.isL2() ? getJacobianImpl<true>(params, state, jacobian, residual, usedRows)
1134 : getJacobianImpl<false>(params, state, jacobian, residual, usedRows);
1135}
1136
1137template <typename T>
1139 size_t count = 0;
1140 for (const auto& limit : limits_) {
1141 switch (limit.type) {
1142 case MinMax:
1143 case MinMaxJoint:
1144 case Linear:
1145 case LinearJoint:
1146 case HalfPlane:
1147 count++;
1148 break;
1149 case MinMaxJointPassive:
1150 break;
1151 case Ellipsoid:
1152 count += 3;
1153 break;
1154 case LimitTypeCount:
1155 default:
1156 MT_THROW("Unknown parameter type for joint limit");
1157 break;
1158 }
1159 }
1160 return count;
1161}
1162
1163template <typename T>
1165 limits_ = lm;
1166}
1167
1168template <typename T>
1170 limits_ = character.parameterLimits;
1171}
1172
1173template class LimitErrorFunctionT<float>;
1174template class LimitErrorFunctionT<double>;
1175
1176} // namespace momentum
#define MT_CHECK(condition,...)
Runtime check macros with two interchangeable backends:
Definition checks.h:36
Implementation of "A General and Adaptive Robust Loss Function" (https://arxiv.org/abs/1701....
Penalizes model/joint parameters that violate their configured limits.
double getJacobian(const ModelParametersT< T > &params, const SkeletonStateT< T > &state, const MeshStateT< T > &meshState, Ref< Eigen::MatrixX< T > > jacobian, Ref< Eigen::VectorX< T > > residual, int &usedRows) final
void setLimits(const ParameterLimits &lm)
LimitErrorFunctionT(const Skeleton &skel, const ParameterTransform &pt, const ParameterLimits &pl=ParameterLimits(), const T &lossAlpha=GeneralizedLossT< T >::kL2, const T &lossC=T(1))
Constructor.
double getGradient(const ModelParametersT< T > &params, const SkeletonStateT< T > &state, const MeshStateT< T > &meshState, Ref< Eigen::VectorX< T > > gradient) final
double getError(const ModelParametersT< T > &params, const SkeletonStateT< T > &state, const MeshStateT< T > &meshState) final
SkeletonErrorFunctionT(const Skeleton &skel, const ParameterTransform &pt)
#define MT_THROW(...)
Throws a std::runtime_error with a formatted message.
Definition exception.h:31
SkeletonT< float > Skeleton
Definition fwd.h:263
void jacobian_jointParams_to_modelParams(const Eigen::Ref< const Eigen::VectorX< T > > &jacobian_jointParams, const Eigen::Index iJointParam, const ParameterTransform &parameterTransform, Eigen::Ref< Eigen::MatrixX< T > > jacobian)
Eigen::Ref< T > Ref
Definition types.h:43
std::vector< ParameterLimit > ParameterLimits
ParameterTransformT< float > ParameterTransform
Definition fwd.h:244
void gradient_jointParams_to_modelParams(const T &grad_jointParams, const Eigen::Index iJointParam, const ParameterTransform &parameterTransform, Eigen::Ref< Eigen::VectorX< T > > gradient)
constexpr size_t kParametersPerJoint
Definition types.h:21
bool isInRange(const LimitLinear &limit, float value)
If rangeMin and rangeMax are both 0, the limit applies to all values.
constexpr size_t kInvalidIndex
Sentinel value indicating an invalid or unset size_t index.
Definition types.h:182
std::bitset< kMaxModelParams > ParameterSet
Bitset for model parameter enablement.
Definition types.h:430
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
Profiling macros that dispatch to one of three backends, selected at compile time:
#define MT_PROFILE_FUNCTION()
Definition profile.h:110
A character model with skeletal structure, mesh, and optional components.
Definition character.h:32
ParameterLimits parameterLimits
Constraints on model parameters.
Definition character.h:46
Constrains a point (offset in parent joint's frame) to lie on the surface of an ellipsoid defined in ...
Constraint: (p1, p2) ยท (normal) - offset >= 0.
Linear relationship between parameters: p_0 = s * p_1 - o.
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.
JointParametersT< T > jointParameters
Joint parameters for all joints in the skeleton.