Momentum
A library for solving nonlinear optimization problems related to human body kinematics
Loading...
Searching...
No Matches
fully_differentiable_projection_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
10
15
16#include <cassert>
17
18namespace momentum {
19
20template <typename T>
26
27template <typename T>
28template <typename JetType>
30 const momentum::ModelParametersT<T>& /*modelParams*/,
31 const momentum::SkeletonStateT<T>& skelState,
32 const int parentJointIndex_cons,
33 const Eigen::Vector3<JetType>& offset_cons,
34 const JetType& weight_cons,
35 const Eigen::Matrix<JetType, 3, 4>& projection_cons,
36 const Eigen::Vector2<JetType>& target_cons,
37 Eigen::Ref<const Eigen::VectorX<T>> vec) const {
38 auto result = JetType();
39
40 const auto& jsCons = skelState.jointState[parentJointIndex_cons];
41 const Eigen::Vector3<JetType> p_world_cm =
42 (jsCons.transform.toAffine3().template cast<T>() * offset_cons).eval();
43 const Eigen::Vector3<JetType> p_projected_cm =
44 (projection_cons * p_world_cm.homogeneous()).eval();
45
46 // Behind camera:
47 if (p_projected_cm.z().a < _nearClip) {
48 return result;
49 }
50
51 const Eigen::Vector2<JetType> p_res = p_projected_cm.hnormalized() - target_cons;
52
53 const JetType wgt = T(2) * weight_cons * kProjectionWeight * this->weight_;
54
55 const JetType& z = p_projected_cm(2);
56 const JetType zSqr = z * z;
57 const JetType x_zz = p_projected_cm(0) / zSqr;
58 const JetType y_zz = p_projected_cm(1) / zSqr;
59
60 // Add dError_dModelParametersT<T>^JetType * v =
61 // (dError/dJointParameter[jFullBodyDOF] *
62 // dJointParameter[jFullBodyDOF]/dModelParametersT<T>)^JetType * v
63 auto add_gradient_dot = [&](const size_t jFullBodyDOF,
64 const Eigen::Vector3<JetType>& d_p_world_cm) {
65 const Eigen::Vector3<JetType> d_p_projected =
66 (projection_cons.template topLeftCorner<3, 3>() * d_p_world_cm).eval();
67 const JetType& dx = d_p_projected(0);
68 const JetType& dy = d_p_projected(1);
69 const JetType& dz = d_p_projected(2);
70
71 const Eigen::Vector2<JetType> d_p_res(dx / z - x_zz * dz, dy / z - y_zz * dz);
72
73 // Error is E = w * (p_projected.xy / p_projected.z)^2
74 // Gradient of error is:
75 // dE/dJointParameter[jFullBodyDOF] = 2w*(p_window - p_target) *
76 // d(p_window)/ddJointParameter[jFullBodyDOF].
77 const JetType gradFull = d_p_res.dot(p_res);
78
79 // Multiply by the parameter transform, take the dot product with v, and add to the result:
81 gradFull * wgt, jFullBodyDOF, this->parameterTransform_, vec);
82 };
83
84 // loop over all joints the constraint is attached to and calculate gradient
85 size_t jointIndex = parentJointIndex_cons;
86 while (jointIndex != kInvalidIndex) {
87 // check for valid index
88 assert(jointIndex < this->skeleton_.joints.size());
89
90 const auto& jointState = skelState.jointState[jointIndex];
91 const size_t paramIndex = jointIndex * 7;
92 const Eigen::Vector3<JetType> posd_cm = p_world_cm - jointState.translation();
93
94 // calculate derivatives based on active joints
95 for (size_t d = 0; d < 3; d++) {
96 if (this->activeJointParams_[paramIndex + d]) {
97 add_gradient_dot(
98 paramIndex + d, jointState.getTranslationDerivative(d).template cast<JetType>());
99 }
100 if (this->activeJointParams_[paramIndex + 3 + d]) {
101 add_gradient_dot(
102 paramIndex + 3 + d,
103 getRotationDerivative(jointState, d, posd_cm).template cast<JetType>());
104 }
105 }
106 if (this->activeJointParams_[paramIndex + 6]) {
107 add_gradient_dot(
108 paramIndex + 6, getScaleDerivative(jointState, posd_cm).template cast<JetType>());
109 }
110
111 // go to the next joint
112 jointIndex = this->skeleton_.joints[jointIndex].parent;
113 }
114
115 return result;
116}
117
118template <typename T>
120 const std::string& inputName,
121 const ModelParametersT<T>& modelParams,
122 const SkeletonStateT<T>& state,
123 Eigen::Ref<const Eigen::VectorX<T>> inputVec) {
124 // Use automatic differentiation on the gradient function:
125 const auto nCons = this->constraints_.size();
126 if (inputName == kWeights) {
127 Eigen::VectorX<T> result = Eigen::VectorX<T>::Zero(nCons);
128 using JetType = ceres::Jet<T, 1>;
129 for (int iCons = 0; iCons < nCons; ++iCons) {
130 const auto dotProd = constraintGradient_dot<JetType>(
131 modelParams,
132 state,
133 static_cast<int>(this->constraints_[iCons].parent),
134 this->constraints_[iCons].offset.template cast<JetType>(),
135 JetType(this->constraints_[iCons].weight, 0),
136 this->constraints_[iCons].projection.template cast<JetType>(),
137 this->constraints_[iCons].target.template cast<JetType>(),
138 inputVec);
139 result(iCons) = dotProd.v[0];
140 }
141 return result;
142 } else if (inputName == kOffsets) {
143 Eigen::VectorX<T> result = Eigen::VectorX<T>::Zero(3 * nCons);
144
145 using JetType = ceres::Jet<T, 3>;
146 for (int iCons = 0; iCons < nCons; ++iCons) {
147 const auto dotProd = constraintGradient_dot<JetType>(
148 modelParams,
149 state,
150 static_cast<int>(this->constraints_[iCons].parent),
151 momentum::buildJetVec<T, 3>(this->constraints_[iCons].offset),
152 JetType(this->constraints_[iCons].weight),
153 this->constraints_[iCons].projection.template cast<JetType>(),
154 this->constraints_[iCons].target.template cast<JetType>(),
155 inputVec);
156 result.template segment<3>(3 * iCons) = dotProd.v;
157 }
158 return result;
159 } else if (inputName == kTargets) {
160 Eigen::VectorX<T> result = Eigen::VectorX<T>::Zero(2 * nCons);
161 using JetType = ceres::Jet<T, 2>;
162 for (int iCons = 0; iCons < nCons; ++iCons) {
163 const auto dotProd = constraintGradient_dot<JetType>(
164 modelParams,
165 state,
166 static_cast<int>(this->constraints_[iCons].parent),
167 this->constraints_[iCons].offset.template cast<JetType>(),
168 JetType(this->constraints_[iCons].weight),
169 this->constraints_[iCons].projection.template cast<JetType>(),
170 buildJetVec<T, 2>(this->constraints_[iCons].target),
171 inputVec);
172 result.template segment<2>(2 * iCons) = dotProd.v;
173 }
174 return result;
175 } else if (inputName == kProjections) {
176 Eigen::VectorX<T> result = Eigen::VectorX<T>::Zero(12 * nCons);
177 using JetType = ceres::Jet<T, 12>;
178 for (int iCons = 0; iCons < nCons; ++iCons) {
179 const auto dotProd = constraintGradient_dot<JetType>(
180 modelParams,
181 state,
182 static_cast<int>(this->constraints_[iCons].parent),
183 this->constraints_[iCons].offset.template cast<JetType>(),
184 JetType(this->constraints_[iCons].weight),
185 momentum::buildJetMat<T, 3, 4>(this->constraints_[iCons].projection),
186 this->constraints_[iCons].target.template cast<JetType>(),
187 inputVec);
188 result.template segment<12>(12 * iCons) = dotProd.v;
189 }
190 return result;
191 } else {
192 throw std::runtime_error(
193 "Unknown input name in FullyDifferentiablePositionErrorFunction::d_gradient_d_input_dot: " +
194 inputName);
195 }
196} // namespace momentum
197
198template <typename T>
200 // offsets not currently supported because we can't differentiate through
201 // the camera without a lot of trouble.
203}
204
205template <typename T>
207 const std::string& name) const {
208 if (name == kWeights) {
209 return this->constraints_.size();
210 } else if (name == kOffsets) {
211 return 3 * this->constraints_.size();
212 } else if (name == kTargets) {
213 return 2 * this->constraints_.size();
214 } else if (name == kProjections) {
215 return 3 * 4 * this->constraints_.size();
216 } else {
217 throw std::runtime_error("Unknown input for ProjectionErrorFunction: " + name);
218 }
219}
220
221template <typename T>
223 const std::string& name,
224 Eigen::Ref<Eigen::VectorX<T>> result) const {
225 if (name == kWeights) {
226 for (size_t i = 0; i < this->constraints_.size(); ++i) {
227 result(i) = this->constraints_[i].weight;
228 }
229 } else if (name == kOffsets) {
230 for (size_t i = 0; i < this->constraints_.size(); ++i) {
231 result.template segment<3>(3 * i) = this->constraints_[i].offset;
232 }
233 } else if (name == kTargets) {
234 for (size_t i = 0; i < this->constraints_.size(); ++i) {
235 result.template segment<2>(2 * i) = this->constraints_[i].target;
236 }
237 } else if (name == kProjections) {
238 for (size_t i = 0; i < this->constraints_.size(); ++i) {
239 const auto& proj = this->constraints_[i].projection;
240
241 // Ensure row-major for compatibility with Torch:
242 for (int jRow = 0; jRow < 3; ++jRow) {
243 for (int kCol = 0; kCol < 4; ++kCol) {
244 result(12 * i + 4 * jRow + kCol) = proj(jRow, kCol);
245 }
246 }
247 }
248 } else {
249 throw std::runtime_error("Unknown input for ProjectionErrorFunction: " + name);
250 }
251}
252
253template <typename T>
255 const std::string& name,
256 Eigen::Ref<const Eigen::VectorX<T>> value) {
257 if (name == kWeights) {
258 for (size_t i = 0; i < this->constraints_.size(); ++i) {
259 this->constraints_[i].weight = value(i);
260 }
261 } else if (name == kOffsets) {
262 for (size_t i = 0; i < this->constraints_.size(); ++i) {
263 this->constraints_[i].offset = value.template segment<3>(3 * i);
264 }
265 } else if (name == kTargets) {
266 for (size_t i = 0; i < this->constraints_.size(); ++i) {
267 const Eigen::Vector2<T> target = value.template segment<2>(2 * i);
268 this->constraints_[i].target = target;
269 }
270 } else if (name == kProjections) {
271 for (size_t i = 0; i < this->constraints_.size(); ++i) {
272 auto& proj = this->constraints_[i].projection;
273
274 // Ensure row-major for compatibility with Torch:
275 for (int jRow = 0; jRow < 3; ++jRow) {
276 for (int kCol = 0; kCol < 4; ++kCol) {
277 proj(jRow, kCol) = value(12 * i + 4 * jRow + kCol);
278 }
279 }
280 }
281 } else {
282 throw std::runtime_error("Unknown input for ProjectionErrorFunction: " + name);
283 }
284}
285
288
289} // namespace momentum
FullyDifferentiableProjectionErrorFunctionT(const momentum::Skeleton &skel, const momentum::ParameterTransform &pt, T nearClip=T(1))
JetType constraintGradient_dot(const momentum::ModelParametersT< T > &modelParams, const momentum::SkeletonStateT< T > &skelState, int parentJointIndex_cons, const Eigen::Vector3< JetType > &offset_cons, const JetType &weight_cons, const Eigen::Matrix< JetType, 3, 4 > &projection_cons, const Eigen::Vector2< JetType > &target_cons, Eigen::Ref< const Eigen::VectorX< T > > inputVec) const
void getInputImp(const std::string &name, Eigen::Ref< Eigen::VectorX< T > > result) const override
void setInputImp(const std::string &name, Eigen::Ref< const Eigen::VectorX< T > > value) override
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
ProjectionErrorFunctionT(const momentum::Skeleton &skel, const momentum::ParameterTransform &pt, T nearClip=T(1))
std::vector< ProjectionConstraintDataT< T > > constraints_
const ParameterTransform & parameterTransform_
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::Matrix< ceres::Jet< T, Cols *Rows >, Rows, Cols > buildJetMat(const Eigen::Matrix< T, Rows, Cols > &m)
Eigen::Vector3< T > getRotationDerivative(const JointStateT< T2 > &js, const size_t index, const Eigen::Vector3< T > &ref)
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.