Momentum
A library for solving nonlinear optimization problems related to human body kinematics
Loading...
Searching...
No Matches
velocity_magnitude_sequence_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
15
16namespace momentum {
17
18template <typename T>
20 const Skeleton& skel,
21 const ParameterTransform& pt)
22 : SequenceErrorFunctionT<T>(skel, pt) {
23 targetWeights_.setOnes(skel.joints.size());
24 targetSpeeds_.setZero(skel.joints.size());
25}
26
27template <typename T>
32
33template <typename T>
35 targetWeights_.setOnes(this->skeleton_.joints.size());
36 targetSpeeds_.setZero(this->skeleton_.joints.size());
37}
38
39template <typename T>
41 const Eigen::VectorX<T>& weights) {
42 MT_CHECK(weights.size() == static_cast<Eigen::Index>(this->skeleton_.joints.size()));
43 targetWeights_ = weights;
44}
45
46template <typename T>
48 targetSpeeds_.setConstant(this->skeleton_.joints.size(), speed);
49}
50
51template <typename T>
53 MT_CHECK(speeds.size() == static_cast<Eigen::Index>(this->skeleton_.joints.size()));
54 targetSpeeds_ = speeds;
55}
56
57template <typename T>
59 std::span<const ModelParametersT<T>> /* modelParameters */,
60 std::span<const SkeletonStateT<T>> skelStates,
61 std::span<const MeshStateT<T>> /* meshStates */) const {
63
64 MT_CHECK(skelStates.size() == 2);
65
66 const auto& prevState = skelStates[0];
67 const auto& nextState = skelStates[1];
68
69 double error = 0.0;
70
71 for (size_t i = 0; i < this->skeleton_.joints.size(); ++i) {
72 if (targetWeights_[i] == 0) {
73 continue;
74 }
75
76 // Compute velocity: v = pos[t+1] - pos[t]
77 const Eigen::Vector3<T> velocity =
78 nextState.jointState[i].translation() - prevState.jointState[i].translation();
79
80 // Compute smooth velocity magnitude: ||v||_smooth = sqrt(||v||^2 + eps^2)
81 // This provides a smooth, differentiable approximation to the velocity magnitude.
82 const T speedSquared = velocity.squaredNorm();
83 const T smoothSpeed =
85
86 // Compute residual: smoothSpeed - targetSpeed
87 const T residual = smoothSpeed - targetSpeeds_[i];
88
89 error += residual * residual * targetWeights_[i];
90 }
91
92 return error * this->weight_;
93}
94
95template <typename T>
97 std::span<const ModelParametersT<T>> /* modelParameters */,
98 std::span<const SkeletonStateT<T>> skelStates,
99 std::span<const MeshStateT<T>> /* meshStates */,
100 Eigen::Ref<Eigen::VectorX<T>> gradient) const {
102
103 MT_CHECK(skelStates.size() == 2);
104
105 const auto& prevState = skelStates[0];
106 const auto& nextState = skelStates[1];
107
108 const Eigen::Index nParam = this->parameterTransform_.numAllModelParameters();
109 MT_CHECK(gradient.size() == 2 * nParam);
110
111 double error = 0.0;
112
113 for (size_t i = 0; i < this->skeleton_.joints.size(); ++i) {
114 if (targetWeights_[i] == 0) {
115 continue;
116 }
117
118 // Compute velocity: v = pos[t+1] - pos[t]
119 const Eigen::Vector3<T> velocity =
120 nextState.jointState[i].translation() - prevState.jointState[i].translation();
121
122 // Compute smooth velocity magnitude: ||v||_smooth = sqrt(||v||^2 + eps^2)
123 const T speedSquared = velocity.squaredNorm();
124 const T smoothSpeed =
126
127 // Compute residual: smoothSpeed - targetSpeed
128 const T residual = smoothSpeed - targetSpeeds_[i];
129
130 const T wgt = targetWeights_[i] * this->weight_;
131 error += residual * residual * wgt;
132
133 // Compute smooth gradient direction: d(||v||_smooth)/d(v) = v / ||v||_smooth
134 // This is always well-defined since ||v||_smooth >= eps > 0
135 const Eigen::Vector3<T> gradDir = velocity / smoothSpeed;
136 // d(error)/d(pos) = 2 * (||v|| - s) * (v / ||v||) * d(v)/d(pos)
137 // d(v)/d(pos0) = -I, d(v)/d(pos1) = I
138 const T gradScale = T(2) * wgt * residual;
139
140 // Gradient for prevState (frame 0) - negative because d(v)/d(pos0) = -I
141 {
142 size_t ancestorJointIndex = i;
143 while (ancestorJointIndex != kInvalidIndex) {
144 MT_CHECK(ancestorJointIndex < this->skeleton_.joints.size());
145
146 const size_t paramIndex = ancestorJointIndex * kParametersPerJoint;
147 const Eigen::Vector3<T> posd = prevState.jointState[i].translation() -
148 prevState.jointState[ancestorJointIndex].translation();
149
150 // Translation parameters (3)
151 for (size_t d = 0; d < 3; d++) {
152 if (this->activeJointParams_[paramIndex + d]) {
153 const T val = -gradScale *
154 gradDir.dot(prevState.jointState[ancestorJointIndex].getTranslationDerivative(d));
156 val, paramIndex + d, this->parameterTransform_, gradient.segment(0, nParam));
157 }
158 }
159
160 // Rotation parameters (3)
161 for (size_t d = 0; d < 3; d++) {
162 if (this->activeJointParams_[paramIndex + 3 + d]) {
163 const T val = -gradScale *
164 gradDir.dot(
165 prevState.jointState[ancestorJointIndex].getRotationDerivative(d, posd));
167 val, paramIndex + 3 + d, this->parameterTransform_, gradient.segment(0, nParam));
168 }
169 }
170
171 // Scale parameter (1)
172 if (this->activeJointParams_[paramIndex + 6]) {
173 const T val = -gradScale *
174 gradDir.dot(prevState.jointState[ancestorJointIndex].getScaleDerivative(posd));
176 val, paramIndex + 6, this->parameterTransform_, gradient.segment(0, nParam));
177 }
178
179 ancestorJointIndex = this->skeleton_.joints[ancestorJointIndex].parent;
180 }
181 }
182
183 // Gradient for nextState (frame 1) - positive because d(v)/d(pos1) = I
184 {
185 size_t ancestorJointIndex = i;
186 while (ancestorJointIndex != kInvalidIndex) {
187 MT_CHECK(ancestorJointIndex < this->skeleton_.joints.size());
188
189 const size_t paramIndex = ancestorJointIndex * kParametersPerJoint;
190 const Eigen::Vector3<T> posd = nextState.jointState[i].translation() -
191 nextState.jointState[ancestorJointIndex].translation();
192
193 // Translation parameters (3)
194 for (size_t d = 0; d < 3; d++) {
195 if (this->activeJointParams_[paramIndex + d]) {
196 const T val = gradScale *
197 gradDir.dot(nextState.jointState[ancestorJointIndex].getTranslationDerivative(d));
199 val, paramIndex + d, this->parameterTransform_, gradient.segment(nParam, nParam));
200 }
201 }
202
203 // Rotation parameters (3)
204 for (size_t d = 0; d < 3; d++) {
205 if (this->activeJointParams_[paramIndex + 3 + d]) {
206 const T val = gradScale *
207 gradDir.dot(
208 nextState.jointState[ancestorJointIndex].getRotationDerivative(d, posd));
210 val,
211 paramIndex + 3 + d,
213 gradient.segment(nParam, nParam));
214 }
215 }
216
217 // Scale parameter (1)
218 if (this->activeJointParams_[paramIndex + 6]) {
219 const T val = gradScale *
220 gradDir.dot(nextState.jointState[ancestorJointIndex].getScaleDerivative(posd));
222 val, paramIndex + 6, this->parameterTransform_, gradient.segment(nParam, nParam));
223 }
224
225 ancestorJointIndex = this->skeleton_.joints[ancestorJointIndex].parent;
226 }
227 }
228 }
229
230 return error;
231}
232
233template <typename T>
235 // 1 row per active joint (scalar speed residual)
236 const auto nActiveJoints = (targetWeights_.array() != 0).count();
237 return nActiveJoints;
238}
239
240template <typename T>
242 std::span<const ModelParametersT<T>> /* modelParameters */,
243 std::span<const SkeletonStateT<T>> skelStates,
244 std::span<const MeshStateT<T>> /* meshStates */,
245 Eigen::Ref<Eigen::MatrixX<T>> jacobian,
246 Eigen::Ref<Eigen::VectorX<T>> residual,
247 int& usedRows) const {
249
250 MT_CHECK(skelStates.size() == 2);
251
252 const auto& prevState = skelStates[0];
253 const auto& nextState = skelStates[1];
254
255 const Eigen::Index nParam = this->parameterTransform_.numAllModelParameters();
256 MT_CHECK(jacobian.cols() == 2 * nParam);
257
258 double error = 0.0;
259 Eigen::Index offset = 0;
260
261 // Helper lambda to accumulate jacobian value for a given joint parameter
262 const auto accumulateJacobian = [&](size_t paramIdx, Eigen::Index colOffset, T jc) {
263 const auto& transform = this->parameterTransform_.transform;
264 for (auto index = transform.outerIndexPtr()[paramIdx];
265 index < transform.outerIndexPtr()[paramIdx + 1];
266 ++index) {
267 jacobian(offset, colOffset + transform.innerIndexPtr()[index]) +=
268 jc * transform.valuePtr()[index];
269 }
270 };
271
272 // Helper lambda to process jacobian contributions for one frame
273 const auto processFrame = [&](const SkeletonStateT<T>& state,
274 size_t jointIdx,
275 Eigen::Index colOffset,
276 T sign,
277 T sqrtWgt,
278 const Eigen::Vector3<T>& gradDir) {
279 size_t ancestorJointIndex = jointIdx;
280 while (ancestorJointIndex != kInvalidIndex) {
281 MT_CHECK(ancestorJointIndex < this->skeleton_.joints.size());
282
283 const auto& jointState = state.jointState[ancestorJointIndex];
284 const size_t paramIndex = ancestorJointIndex * kParametersPerJoint;
285 const Eigen::Vector3<T> posd =
286 state.jointState[jointIdx].translation() - jointState.translation();
287
288 // Translation parameters (3)
289 for (size_t d = 0; d < 3; d++) {
290 if (this->activeJointParams_[paramIndex + d]) {
291 const T jc = sign * sqrtWgt * gradDir.dot(jointState.getTranslationDerivative(d));
292 accumulateJacobian(paramIndex + d, colOffset, jc);
293 }
294 }
295
296 // Rotation parameters (3)
297 for (size_t d = 0; d < 3; d++) {
298 if (this->activeJointParams_[paramIndex + 3 + d]) {
299 const T jc = sign * sqrtWgt * gradDir.dot(jointState.getRotationDerivative(d, posd));
300 accumulateJacobian(paramIndex + 3 + d, colOffset, jc);
301 }
302 }
303
304 // Scale parameter (1)
305 if (this->activeJointParams_[paramIndex + 6]) {
306 const T jc = sign * sqrtWgt * gradDir.dot(jointState.getScaleDerivative(posd));
307 accumulateJacobian(paramIndex + 6, colOffset, jc);
308 }
309
310 ancestorJointIndex = this->skeleton_.joints[ancestorJointIndex].parent;
311 }
312 };
313
314 for (size_t i = 0; i < this->skeleton_.joints.size(); ++i) {
315 if (targetWeights_[i] == 0) {
316 continue;
317 }
318
319 // Compute velocity: v = pos[t+1] - pos[t]
320 const Eigen::Vector3<T> velocity =
321 nextState.jointState[i].translation() - prevState.jointState[i].translation();
322
323 // Compute smooth velocity magnitude: ||v||_smooth = sqrt(||v||^2 + eps^2)
324 const T speedSquared = velocity.squaredNorm();
325 const T smoothSpeed =
327
328 // Compute residual: smoothSpeed - targetSpeed
329 const T res = smoothSpeed - targetSpeeds_[i];
330
331 const T wgt = targetWeights_[i] * this->weight_;
332 const T sqrtWgt = std::sqrt(wgt);
333
334 error += res * res * wgt;
335 residual(offset) = res * sqrtWgt;
336
337 // Compute smooth Jacobian direction: d(||v||_smooth)/d(v) = v / ||v||_smooth
338 // This is always well-defined since ||v||_smooth >= eps > 0
339 const Eigen::Vector3<T> gradDir = velocity / smoothSpeed;
340
341 // Jacobian for prevState (frame 0) - negative because d(v)/d(pos0) = -I
342 processFrame(prevState, i, 0, T(-1), sqrtWgt, gradDir);
343
344 // Jacobian for nextState (frame 1) - positive because d(v)/d(pos1) = I
345 processFrame(nextState, i, nParam, T(1), sqrtWgt, gradDir);
346
347 offset += 1;
348 }
349
350 usedRows = gsl::narrow_cast<int>(offset);
351
352 return error;
353}
354
357
358} // namespace momentum
#define MT_CHECK(condition,...)
Runtime check macros with two interchangeable backends:
Definition checks.h:36
const ParameterTransform & parameterTransform_
SequenceErrorFunctionT(const Skeleton &skel, const ParameterTransform &pt)
Error function that penalizes the deviation of per-joint velocity magnitude from a target speed.
double getError(std::span< const ModelParametersT< T > > modelParameters, std::span< const SkeletonStateT< T > > skelStates, std::span< const MeshStateT< T > > meshStates) const final
VelocityMagnitudeSequenceErrorFunctionT(const Skeleton &skel, const ParameterTransform &pt)
void setTargetSpeed(T speed)
Set a single target speed applied to all joints.
double getJacobian(std::span< const ModelParametersT< T > > modelParameters, std::span< const SkeletonStateT< T > > skelStates, std::span< const MeshStateT< T > > meshStates, Eigen::Ref< Eigen::MatrixX< T > > jacobian, Eigen::Ref< Eigen::VectorX< T > > residual, int &usedRows) const final
double getGradient(std::span< const ModelParametersT< T > > modelParameters, std::span< const SkeletonStateT< T > > skelStates, std::span< const MeshStateT< T > > meshStates, Eigen::Ref< Eigen::VectorX< T > > gradient) const final
void setTargetWeights(const Eigen::VectorX< T > &weights)
Set the per-joint weights for the velocity magnitude error.
void setTargetSpeeds(const Eigen::VectorX< T > &speeds)
Set per-joint target speeds.
void reset()
Reset weights to ones and target speeds to zero.
SkeletonT< float > Skeleton
Definition fwd.h:263
ParameterTransformT< float > ParameterTransform
Definition fwd.h:244
constexpr T kVelocityMagnitudeEpsilon
Epsilon for smooth velocity magnitude approximation: ||v||_smooth = sqrt(||v||^2 + eps^2).
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
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
A character model with skeletal structure, mesh, and optional components.
Definition character.h:32
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.
JointList joints
The list of joints in this skeleton, ordered such that every joint's parent appears earlier in the li...
Definition skeleton.h:25