Momentum
A library for solving nonlinear optimization problems related to human body kinematics
Loading...
Searching...
No Matches
fully_differentiable_distance_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
11#include "momentum/common/log.h"
13
14#include <cassert>
15
16namespace momentum {
17
18template <typename T>
23
24template <typename T>
25template <typename JetType>
26JetType FullyDifferentiableDistanceErrorFunctionT<T>::constraintGradient_dot(
27 const momentum::ModelParametersT<T>& /*modelParams*/,
28 const momentum::SkeletonStateT<T>& skelState,
29 const Eigen::Vector3<JetType>& origin_cons,
30 const int parentJointIndex_cons,
31 const Eigen::Vector3<JetType>& offset_cons,
32 const JetType& weight_cons,
33 const JetType& target_cons,
34 Eigen::Ref<const Eigen::VectorX<T>> vec) {
35 JetType result;
36
37 const auto& jsCons = skelState.jointState[parentJointIndex_cons];
38 const Eigen::Vector3<JetType> p_world_cm =
39 jsCons.transform.toAffine3().template cast<T>() * offset_cons;
40
41 const Eigen::Vector3<JetType> diff_vec = p_world_cm - origin_cons;
42 const JetType distance = diff_vec.norm();
43 const Eigen::Vector3<JetType> diff_distance_diff_p_world = diff_vec / distance;
44 const JetType diff = distance - target_cons;
45
46 // Complete weight is the product of the per-constraint weight,
47 // the global error function weight, and the constant-valued distanceWeight.
48 // The 2.0 here is because the error function is (d - d_target)^2 so the
49 // derivative of that brings down a 2 in front.
50 const JetType wgt = (2.0f * kDistanceWeight * this->weight_) * weight_cons;
51
52 // Compute
53 // dError_dModelParams^JetType * v =
54 // (dError/dJointParameter[jFullBodyDOF] *
55 // dJointParameter[jFullBodyDOF]/dModelParams)^JetType * v
56 auto add_gradient_dot = [&](const size_t jFullBodyDOF,
57 const Eigen::Vector3<JetType>& d_p_world_cm) {
58 const JetType diff_p_distance = diff_distance_diff_p_world.dot(d_p_world_cm);
59 const auto gradFull = diff_p_distance * diff;
61 gradFull * wgt, jFullBodyDOF, this->parameterTransform_, vec);
62 };
63
64 // loop over all joints the constraint is attached to and calculate gradient
65 size_t jointIndex = parentJointIndex_cons;
66 while (jointIndex != kInvalidIndex) {
67 // check for valid index
68 assert(jointIndex < skelState.jointState.size());
69
70 const auto& jointState = skelState.jointState[jointIndex];
71 const size_t paramIndex = jointIndex * kParametersPerJoint;
72 const auto posd_cm = (p_world_cm - jointState.translation()).eval();
73
74 // calculate derivatives based on active joints
75 for (size_t d = 0; d < 3; d++) {
76 if (this->activeJointParams_[paramIndex + d]) {
77 add_gradient_dot(
78 paramIndex + d, jointState.getTranslationDerivative(d).template cast<JetType>());
79 }
80 if (this->activeJointParams_[paramIndex + 3 + d]) {
81 add_gradient_dot(
82 paramIndex + 3 + d,
83 getRotationDerivative(jointState, d, posd_cm).template cast<JetType>());
84 }
85 }
86 if (this->activeJointParams_[paramIndex + 6]) {
87 add_gradient_dot(
88 paramIndex + 6, getScaleDerivative(jointState, posd_cm).template cast<JetType>());
89 }
90
91 // go to the next joint
92 jointIndex = this->skeleton_.joints[jointIndex].parent;
93 }
94
95 return result;
96}
97
98template <typename T>
100 const std::string& inputName,
101 const ModelParametersT<T>& modelParams,
102 const SkeletonStateT<T>& state,
103 Eigen::Ref<const Eigen::VectorX<T>> inputVec) {
104 // Use automatic differentiation on the gradient function:
105 const auto nCons = constraints_.size();
106 if (inputName == kWeights) {
107 Eigen::VectorX<T> result = Eigen::VectorX<T>::Zero(nCons);
108 using JetType = ceres::Jet<T, 1>;
109 for (int iCons = 0; iCons < nCons; ++iCons) {
110 const auto dotProd = constraintGradient_dot<JetType>(
111 modelParams,
112 state,
113 constraints_[iCons].origin.template cast<JetType>(),
114 static_cast<int>(constraints_[iCons].parent),
115 constraints_[iCons].offset.template cast<JetType>(),
116 JetType(constraints_[iCons].weight, 0),
117 JetType(constraints_[iCons].target),
118 inputVec);
119 result(iCons) = dotProd.v[0];
120 }
121 return result;
122 } else if (inputName == kOffsets) {
123 Eigen::VectorX<T> result = Eigen::VectorX<T>::Zero(3 * nCons);
124 using JetType = ceres::Jet<T, 3>;
125 for (int iCons = 0; iCons < nCons; ++iCons) {
126 const auto dotProd = constraintGradient_dot<JetType>(
127 modelParams,
128 state,
129 constraints_[iCons].origin.template cast<JetType>(),
130 static_cast<int>(constraints_[iCons].parent),
132 JetType(constraints_[iCons].weight),
133 JetType(constraints_[iCons].target),
134 inputVec);
135 result.template segment<3>(3 * iCons) = dotProd.v;
136 }
137 return result;
138 } else if (inputName == kTargets) {
139 Eigen::VectorX<T> result = Eigen::VectorX<T>::Zero(nCons);
140
141 using JetType = ceres::Jet<T, 1>;
142 for (int iCons = 0; iCons < nCons; ++iCons) {
143 const auto dotProd = constraintGradient_dot<JetType>(
144 modelParams,
145 state,
146 constraints_[iCons].origin.template cast<JetType>(),
147 static_cast<int>(constraints_[iCons].parent),
148 constraints_[iCons].offset.template cast<JetType>(),
149 JetType(constraints_[iCons].weight),
150 JetType(constraints_[iCons].target, 0),
151 inputVec);
152 result(iCons) = dotProd.v[0];
153 }
154 return result;
155 } else if (inputName == kOrigins) {
156 using JetType = ceres::Jet<T, 3>;
157 Eigen::VectorX<T> result = Eigen::VectorX<T>::Zero(3 * nCons);
158 for (int iCons = 0; iCons < nCons; ++iCons) {
159 const auto dotProd = constraintGradient_dot<JetType>(
160 modelParams,
161 state,
162 buildJetVec<T, 3>(constraints_[iCons].origin),
163 static_cast<int>(constraints_[iCons].parent),
164 constraints_[iCons].offset.template cast<JetType>(),
165 JetType(constraints_[iCons].weight),
166 JetType(constraints_[iCons].target),
167 inputVec);
168 result.template segment<3>(3 * iCons) = dotProd.v;
169 }
170 return result;
171 } else {
172 throw std::runtime_error(
173 "Unknown input name in FullyDifferentiablePositionErrorFunction::d_gradient_d_input_dot: " +
174 inputName);
175 }
176}
177
178template <typename T>
181}
182
183template <typename T>
185 const std::string& name) const {
186 if (name == kWeights || name == kTargets) {
187 return constraints_.size();
188 } else if (name == kOffsets || name == kOrigins) {
189 return 3 * constraints_.size();
190 } else {
191 throw std::runtime_error("Unknown input for DistanceErrorFunction: " + name);
192 }
193}
194
195template <typename T>
197 const std::string& name,
198 Eigen::Ref<Eigen::VectorX<T>> result) const {
199 if (name == kWeights) {
200 for (size_t i = 0; i < constraints_.size(); ++i) {
201 result(i) = constraints_[i].weight;
202 }
203 } else if (name == kOffsets) {
204 for (size_t i = 0; i < constraints_.size(); ++i) {
205 result.template segment<3>(3 * i) = constraints_[i].offset;
206 }
207 } else if (name == kTargets) {
208 for (size_t i = 0; i < constraints_.size(); ++i) {
209 result(i) = constraints_[i].target;
210 }
211 } else if (name == kOrigins) {
212 for (size_t i = 0; i < constraints_.size(); ++i) {
213 result.template segment<3>(3 * i) = constraints_[i].origin;
214 }
215 } else {
216 throw std::runtime_error("Unknown input for DistanceErrorFunction: " + name);
217 }
218}
219
220template <typename T>
222 const std::string& name,
223 Eigen::Ref<const Eigen::VectorX<T>> value) {
224 auto checkSize = [&](Eigen::Index expectedSize) {
225 if (value.size() != expectedSize) {
226 throw std::runtime_error(
227 "In DistanceErrorFunction::setInput, " + name + " expects size " +
228 std::to_string(expectedSize) + "; got " + std::to_string(value.size()));
229 }
230 };
231
232 if (name == kWeights) {
233 checkSize(constraints_.size());
234 for (size_t i = 0; i < constraints_.size(); ++i) {
235 constraints_[i].weight = value(i);
236 }
237 } else if (name == kOffsets) {
238 checkSize(3 * constraints_.size());
239 for (size_t i = 0; i < constraints_.size(); ++i) {
240 constraints_[i].offset = value.template segment<3>(3 * i);
241 }
242 } else if (name == kTargets) {
243 checkSize(constraints_.size());
244 for (size_t i = 0; i < constraints_.size(); ++i) {
245 constraints_[i].target = value(i);
246 }
247 } else if (name == kOrigins) {
248 checkSize(3 * constraints_.size());
249 for (size_t i = 0; i < constraints_.size(); ++i) {
250 constraints_[i].origin = value.template segment<3>(3 * i);
251 }
252 } else {
253 throw std::runtime_error("Unknown input for DistanceErrorFunction: " + name);
254 }
255}
256
259
260} // namespace momentum
std::vector< DistanceConstraintDataT< T > > constraints_
DistanceErrorFunctionT(const momentum::Skeleton &skel, const momentum::ParameterTransform &pt)
void setInputImp(const std::string &name, Eigen::Ref< const Eigen::VectorX< T > > value) override
FullyDifferentiableDistanceErrorFunctionT(const momentum::Skeleton &skel, const momentum::ParameterTransform &pt)
Eigen::VectorX< T > d_gradient_d_input_dot(const std::string &inputName, const momentum::ModelParametersT< T > &modelParams, const momentum::SkeletonStateT< T > &state, Eigen::Ref< const Eigen::VectorX< T > > inputVec) override
void getInputImp(const std::string &name, Eigen::Ref< Eigen::VectorX< T > > result) const override
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::Vector3< T > getScaleDerivative(const JointStateT< T2 > &js, const Eigen::Vector3< T > &ref)
Eigen::Matrix< ceres::Jet< T, N >, N, 1 > buildJetVec(const Eigen::Matrix< T, N, 1 > &v)
ParameterTransformT< float > ParameterTransform
Definition fwd.h:244
Eigen::Vector3< T > getRotationDerivative(const JointStateT< T2 > &js, const size_t index, const Eigen::Vector3< T > &ref)
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.