Momentum
A library for solving nonlinear optimization problems related to human body kinematics
Loading...
Searching...
No Matches
vertex_position_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
13
14#include <dispenso/parallel_for.h>
15
16#include <numeric>
17
18namespace momentum {
19
20template <typename T>
22 const Character& character,
23 const ParameterTransform& parameterTransform,
24 const T& lossAlpha,
25 const T& lossC)
27 character,
28 parameterTransform,
29 lossAlpha,
30 lossC) {
31 this->legacyWeight_ = this->kLegacyWeight;
32}
33
34template <typename T>
36 size_t constrIndex,
37 const SkeletonStateT<T>& /*state*/,
38 const MeshStateT<T>& /*meshState*/,
39 std::span<const Eigen::Vector3<T>> worldVecs,
40 FuncType& f,
41 std::span<DfdvType> dfdv) const {
42 MT_CHECK(constrIndex < this->constraints_.size(), "Constraint index out of range");
43 MT_CHECK(worldVecs.size() == 1, "Expected exactly one world vector for vertex position");
44
45 const auto& constraint = this->constraints_[constrIndex];
46
47 // Residual: f = vertexPosition - target
48 f = worldVecs[0] - constraint.target;
49
50 // Derivative: df/dv = I (identity matrix)
51 if (!dfdv.empty()) {
52 MT_CHECK(dfdv.size() == 1, "Expected exactly one dfdv for vertex position");
53 dfdv[0] = Eigen::Matrix<T, 3, 3>::Identity();
54 }
55}
56
57template <typename T>
59 const ModelParametersT<T>& /*params*/,
60 const SkeletonStateT<T>& state,
61 const MeshStateT<T>& meshState,
62 Eigen::Ref<Eigen::VectorX<T>> gradient) {
63 const auto& constraints = this->constraints_;
64 const size_t numConstraints = constraints.size();
65 if (numConstraints == 0) {
66 return 0.0;
67 }
69
70 auto dispensoOptions = dispenso::ParForOptions();
71 dispensoOptions.maxThreads = static_cast<uint32_t>(this->maxThreads_);
72 const SkeletonDerivativeT<T> skeletonDerivative(
73 this->skeleton_,
76 this->enabledParameters_);
77
78 const bool isL2 = this->loss_.isL2();
79 const T lossInvC2 = this->loss_.invC2();
80
81 std::vector<std::tuple<double, VectorX<T>>> errorGradThread;
82 dispenso::parallel_for(
83 errorGradThread,
84 [&]() -> std::tuple<double, VectorX<T>> {
85 return {0.0, VectorX<T>::Zero(this->parameterTransform_.numAllModelParameters())};
86 },
87 size_t(0),
88 numConstraints,
89 [&](std::tuple<double, VectorX<T>>& errorGradLocal, const size_t i) {
90 double& errorLocal = std::get<0>(errorGradLocal);
91 auto& gradLocal = std::get<1>(errorGradLocal);
92
93 const T constrWeight = static_cast<T>(constraints[i].weight);
94 if (constrWeight == T(0)) {
95 return;
96 }
97
98 const size_t vertexIndex = constraints[i].vertexIndex;
99 const Eigen::Vector3<T> worldPos =
100 meshState.posedMesh_->vertices[vertexIndex].template cast<T>();
101
102 // Inline the position residual: f = worldPos - target (no virtual call)
103 const Eigen::Vector3<T> f = worldPos - constraints[i].target;
104
105 if (f.isZero()) {
106 return;
107 }
108
109 const T sqrError = f.squaredNorm();
110 const T w = constrWeight * this->weight_ * this->legacyWeight_;
111
112 Eigen::Vector3<T> weightedResidual;
113 if (isL2) {
114 errorLocal += w * sqrError * lossInvC2;
115 weightedResidual = T(2) * w * lossInvC2 * f;
116 } else {
117 errorLocal += w * this->loss_.value(sqrError);
118 weightedResidual = T(2) * w * this->loss_.deriv(sqrError) * f;
119 }
120
121 // Use IdentityDfdv specialization — eliminates dfdv*derivative matrix multiply
122 skeletonDerivative.accumulateVertexGradientIdentityDfdv(
123 vertexIndex, weightedResidual, state, meshState, this->character_, gradLocal);
124 },
125 dispensoOptions);
126
127 if (!errorGradThread.empty()) {
128 errorGradThread[0] = std::accumulate(
129 errorGradThread.begin() + 1,
130 errorGradThread.end(),
131 errorGradThread[0],
132 [](const auto& a, const auto& b) -> std::tuple<double, VectorX<T>> {
133 return {std::get<0>(a) + std::get<0>(b), std::get<1>(a) + std::get<1>(b)};
134 });
135
136 gradient += std::get<1>(errorGradThread[0]);
137 return std::get<0>(errorGradThread[0]);
138 }
139
140 return 0.0;
141}
142
143template <typename T>
145 const ModelParametersT<T>& /*params*/,
146 const SkeletonStateT<T>& state,
147 const MeshStateT<T>& meshState,
148 Eigen::Ref<Eigen::MatrixX<T>> jacobian,
149 Eigen::Ref<Eigen::VectorX<T>> residual,
150 int& usedRows) {
151 const auto& constraints = this->constraints_;
152 const size_t numConstraints = constraints.size();
153 usedRows = 0;
154 if (numConstraints == 0) {
155 return 0.0;
156 }
157 MT_CHECK_NOTNULL(meshState.posedMesh_);
158
159 auto dispensoOptions = dispenso::ParForOptions();
160 dispensoOptions.maxThreads = static_cast<uint32_t>(this->maxThreads_);
161 const SkeletonDerivativeT<T> skeletonDerivative(
162 this->skeleton_,
164 this->activeJointParams_,
165 this->enabledParameters_);
166
167 constexpr size_t FuncDim = 3;
168 const bool isL2 = this->loss_.isL2();
169 const T lossInvC2 = this->loss_.invC2();
170
171 std::vector<double> errorThread;
172 dispenso::parallel_for(
173 errorThread,
174 [&]() -> double { return 0.0; },
175 size_t(0),
176 numConstraints,
177 [&](double& errorLocal, const size_t i) {
178 const T constrWeight = static_cast<T>(constraints[i].weight);
179 if (constrWeight == T(0)) {
180 return;
181 }
182
183 const size_t vertexIndex = constraints[i].vertexIndex;
184 const Eigen::Vector3<T> worldPos =
185 meshState.posedMesh_->vertices[vertexIndex].template cast<T>();
186
187 const size_t rowIndex = i * FuncDim;
188
189 // Inline the position residual: f = worldPos - target (no virtual call)
190 const Eigen::Vector3<T> f = worldPos - constraints[i].target;
191
192 const T sqrError = f.squaredNorm();
193 const T w = constrWeight * this->weight_ * this->legacyWeight_;
194
195 T deriv;
196 if (isL2) {
197 errorLocal += w * sqrError * lossInvC2;
198 deriv = std::sqrt(w * lossInvC2);
199 } else {
200 errorLocal += w * this->loss_.value(sqrError);
201 deriv = std::sqrt(w * this->loss_.deriv(sqrError));
202 }
203
204 residual.template segment<FuncDim>(rowIndex).noalias() = deriv * f;
205
206 if (deriv == T(0)) {
207 return;
208 }
209
210 // Use IdentityDfdv specialization — eliminates dfdv*derivative matrix multiply
211 skeletonDerivative.accumulateVertexJacobianIdentityDfdv(
212 vertexIndex, deriv, state, meshState, this->character_, jacobian, rowIndex);
213 },
214 dispensoOptions);
215
216 usedRows = static_cast<int>(numConstraints * FuncDim);
217
218 if (!errorThread.empty()) {
219 return std::accumulate(errorThread.begin() + 1, errorThread.end(), errorThread[0]);
220 }
221
222 return 0.0;
223}
224
225// Explicit template instantiations
228
229} // namespace momentum
#define MT_CHECK_NOTNULL(ptr,...)
Asserts that ptr is not null; on failure, throws std::runtime_error with the optional fmt-style messa...
Definition checks.h:45
#define MT_CHECK(condition,...)
Runtime check macros with two interchangeable backends:
Definition checks.h:36
Shared utility for derivative computation in error functions.
void accumulateVertexJacobianIdentityDfdv(size_t vertexIndex, T scale, const SkeletonStateT< T > &skeletonState, const MeshStateT< T > &meshState, const Character &character, Eigen::Ref< Eigen::MatrixX< T > > jacobian, size_t rowIndex) const
Specialized vertex Jacobian for identity dfdv (FuncDim=3, dfdv=I).
void accumulateVertexGradientIdentityDfdv(size_t vertexIndex, const Eigen::Vector3< T > &weightedResidual, const SkeletonStateT< T > &skeletonState, const MeshStateT< T > &meshState, const Character &character, Eigen::Ref< Eigen::VectorX< T > > gradient) const
Specialized vertex gradient for identity dfdv (FuncDim=3, dfdv=I).
const ParameterTransform & parameterTransform_
VertexErrorFunctionT(const Character &character, const ParameterTransform &parameterTransform, const T &lossAlpha=GeneralizedLossT< T >::kL2, const T &lossC=T(1))
Error function that constrains mesh vertices to target positions.
void evalFunction(size_t constrIndex, const SkeletonStateT< T > &state, const MeshStateT< T > &meshState, std::span< const Eigen::Vector3< T > > worldVecs, FuncType &f, std::span< DfdvType > dfdv) const final
Computes the residual and derivatives.
double getGradient(const ModelParametersT< T > &params, const SkeletonStateT< T > &state, const MeshStateT< T > &meshState, Eigen::Ref< Eigen::VectorX< T > > gradient) override
Specialized getGradient that avoids the dfdv*derivative matrix multiply.
VertexPositionErrorFunctionT(const Character &character, const ParameterTransform &parameterTransform, const T &lossAlpha=GeneralizedLossT< T >::kL2, const T &lossC=T(1))
double getJacobian(const ModelParametersT< T > &params, const SkeletonStateT< T > &state, const MeshStateT< T > &meshState, Eigen::Ref< Eigen::MatrixX< T > > jacobian, Eigen::Ref< Eigen::VectorX< T > > residual, int &usedRows) override
Specialized getJacobian with the same dfdv=Identity optimization.
ParameterTransformT< float > ParameterTransform
Definition fwd.h:244
Vector< T, Dynamic > VectorX
Dynamic-size column vector. Common return type for solver residuals and parameter vectors.
Definition types.h:207
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 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
std::unique_ptr< MeshT< T > > posedMesh_
Posed mesh after the skeleton transforms have been applied.
Definition mesh_state.h:32
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.
Constraint data for a vertex position target.