Momentum
A library for solving nonlinear optimization problems related to human body kinematics
Loading...
Searching...
No Matches
vertex_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
14
15#include <dispenso/parallel_for.h>
16
17#include <numeric>
18
19namespace momentum {
20
21template <typename T, class Data, size_t FuncDim>
23 const Character& character,
24 const ParameterTransform& parameterTransform,
25 const T& lossAlpha,
26 const T& lossC)
27 : SkeletonErrorFunctionT<T>(character.skeleton, parameterTransform),
28 character_(character),
29 loss_(lossAlpha, lossC) {}
30
31template <typename T, class Data, size_t FuncDim>
35
36template <typename T, class Data, size_t FuncDim>
38 return true;
39}
40
41template <typename T, class Data, size_t FuncDim>
43 MT_CHECK(constraint.vertexIndex != kInvalidIndex, "Constraint must have a valid vertex index");
44 constraints_.push_back(constraint);
45}
46
47template <typename T, class Data, size_t FuncDim>
48void VertexErrorFunctionT<T, Data, FuncDim>::setConstraints(std::span<const Data> constraints) {
49 constraints_.assign(constraints.begin(), constraints.end());
50}
51
52template <typename T, class Data, size_t FuncDim>
56
57template <typename T, class Data, size_t FuncDim>
59 return constraints_;
60}
61
62template <typename T, class Data, size_t FuncDim>
64 const ModelParametersT<T>& /*params*/,
65 const SkeletonStateT<T>& state,
66 const MeshStateT<T>& meshState) {
67 const size_t numConstraints = constraints_.size();
68 if (numConstraints == 0) {
69 return 0.0;
70 }
72
73 double error = 0.0;
74 for (size_t i = 0; i < numConstraints; ++i) {
75 const T constrWeight = static_cast<T>(constraints_[i].weight);
76 if (constrWeight == T(0)) {
77 continue;
78 }
79
80 const size_t vertexIndex = constraints_[i].vertexIndex;
81 const Eigen::Vector3<T> worldVec =
82 meshState.posedMesh_->vertices[vertexIndex].template cast<T>();
83
84 FuncType f;
85 std::span<DfdvType> emptyDfdv;
87 i, state, meshState, std::span<const Eigen::Vector3<T>>(&worldVec, 1), f, emptyDfdv);
88
89 const T sqrError = f.squaredNorm();
90 error += constrWeight * loss_.value(sqrError);
91 }
92 return this->weight_ * legacyWeight_ * error;
93}
94
95template <typename T, class Data, size_t FuncDim>
97 const ModelParametersT<T>& /*params*/,
98 const SkeletonStateT<T>& state,
99 const MeshStateT<T>& meshState,
100 Eigen::Ref<Eigen::VectorX<T>> gradient) {
101 const size_t numConstraints = constraints_.size();
102 if (numConstraints == 0) {
103 return 0.0;
104 }
105 MT_CHECK_NOTNULL(meshState.posedMesh_);
106
107 auto dispensoOptions = dispenso::ParForOptions();
108 dispensoOptions.maxThreads = static_cast<uint32_t>(maxThreads_);
109
110 const SkeletonDerivativeT<T> skeletonDerivative(
111 this->skeleton_,
113 this->activeJointParams_,
114 this->enabledParameters_);
115
116 const bool isL2 = loss_.isL2();
117 const T lossInvC2 = loss_.invC2();
118
119 std::vector<std::tuple<double, VectorX<T>>> errorGradThread;
120 dispenso::parallel_for(
121 errorGradThread,
122 [&]() -> std::tuple<double, VectorX<T>> {
123 return {0.0, VectorX<T>::Zero(this->parameterTransform_.numAllModelParameters())};
124 },
125 size_t(0),
126 numConstraints,
127 [&](std::tuple<double, VectorX<T>>& errorGradLocal, const size_t i) {
128 double& errorLocal = std::get<0>(errorGradLocal);
129 auto& gradLocal = std::get<1>(errorGradLocal);
130
131 const T constrWeight = static_cast<T>(constraints_[i].weight);
132 if (constrWeight == T(0)) {
133 return;
134 }
135
136 const size_t vertexIndex = constraints_[i].vertexIndex;
137 const Eigen::Vector3<T> worldVec =
138 meshState.posedMesh_->vertices[vertexIndex].template cast<T>();
139
140 FuncType f;
141 DfdvType dfdv;
142 dfdv.setZero();
143
145 i,
146 state,
147 meshState,
148 std::span<const Eigen::Vector3<T>>(&worldVec, 1),
149 f,
150 std::span<DfdvType>(&dfdv, 1));
151
152 if (f.isZero()) {
153 return;
154 }
155
156 const T sqrError = f.squaredNorm();
157 const T w = constrWeight * this->weight_ * legacyWeight_;
158
159 FuncType weightedResidual;
160 if (isL2) {
161 errorLocal += w * sqrError * lossInvC2;
162 weightedResidual = T(2) * w * lossInvC2 * f;
163 } else {
164 errorLocal += w * loss_.value(sqrError);
165 weightedResidual = T(2) * w * loss_.deriv(sqrError) * f;
166 }
167
168 skeletonDerivative.template accumulateVertexGradient<FuncDim>(
169 vertexIndex, worldVec, dfdv, weightedResidual, state, meshState, character_, gradLocal);
170 },
171 dispensoOptions);
172
173 if (!errorGradThread.empty()) {
174 errorGradThread[0] = std::accumulate(
175 errorGradThread.begin() + 1,
176 errorGradThread.end(),
177 errorGradThread[0],
178 [](const auto& a, const auto& b) -> std::tuple<double, VectorX<T>> {
179 return {std::get<0>(a) + std::get<0>(b), std::get<1>(a) + std::get<1>(b)};
180 });
181
182 gradient += std::get<1>(errorGradThread[0]);
183 return std::get<0>(errorGradThread[0]);
184 }
185
186 return 0.0;
187}
188
189template <typename T, class Data, size_t FuncDim>
191 const ModelParametersT<T>& /*params*/,
192 const SkeletonStateT<T>& state,
193 const MeshStateT<T>& meshState,
194 Eigen::Ref<Eigen::MatrixX<T>> jacobian,
195 Eigen::Ref<Eigen::VectorX<T>> residual,
196 int& usedRows) {
197 const size_t numConstraints = constraints_.size();
198 usedRows = 0;
199 if (numConstraints == 0) {
200 return 0.0;
201 }
202 MT_CHECK_NOTNULL(meshState.posedMesh_);
203
204 auto dispensoOptions = dispenso::ParForOptions();
205 dispensoOptions.maxThreads = static_cast<uint32_t>(maxThreads_);
206
207 const SkeletonDerivativeT<T> skeletonDerivative(
208 this->skeleton_,
210 this->activeJointParams_,
211 this->enabledParameters_);
212
213 const bool isL2Jac = loss_.isL2();
214 const T lossInvC2Jac = loss_.invC2();
215
216 std::vector<double> errorThread;
217 dispenso::parallel_for(
218 errorThread,
219 [&]() -> double { return 0.0; },
220 size_t(0),
221 numConstraints,
222 [&](double& errorLocal, const size_t i) {
223 const T constrWeight = static_cast<T>(constraints_[i].weight);
224 if (constrWeight == T(0)) {
225 return;
226 }
227
228 const size_t vertexIndex = constraints_[i].vertexIndex;
229 const Eigen::Vector3<T> worldVec =
230 meshState.posedMesh_->vertices[vertexIndex].template cast<T>();
231
232 const size_t rowIndex = i * FuncDim;
233 FuncType f;
234 DfdvType dfdv;
235 dfdv.setZero();
236
238 i,
239 state,
240 meshState,
241 std::span<const Eigen::Vector3<T>>(&worldVec, 1),
242 f,
243 std::span<DfdvType>(&dfdv, 1));
244
245 const T sqrError = f.squaredNorm();
246 const T w = constrWeight * this->weight_ * legacyWeight_;
247
248 T deriv;
249 if (isL2Jac) {
250 errorLocal += w * sqrError * lossInvC2Jac;
251 deriv = std::sqrt(w * lossInvC2Jac);
252 } else {
253 errorLocal += w * loss_.value(sqrError);
254 deriv = std::sqrt(w * loss_.deriv(sqrError));
255 }
256
257 residual.template segment<FuncDim>(rowIndex).noalias() = deriv * f;
258
259 if (deriv == T(0)) {
260 return;
261 }
262
263 skeletonDerivative.template accumulateVertexJacobian<FuncDim>(
264 vertexIndex, worldVec, dfdv, deriv, state, meshState, character_, jacobian, rowIndex);
265 },
266 dispensoOptions);
267
268 usedRows = static_cast<int>(numConstraints * FuncDim);
269
270 if (!errorThread.empty()) {
271 return std::accumulate(errorThread.begin() + 1, errorThread.end(), errorThread[0]);
272 }
273
274 return 0.0;
275}
276
277// Explicit instantiations for common constraint types
284
285} // namespace momentum
286
287// Include leaf class headers for explicit instantiations
292
293namespace momentum {
294
295template class VertexErrorFunctionT<float, VertexPositionDataT<float>, 3>;
296template class VertexErrorFunctionT<double, VertexPositionDataT<double>, 3>;
297
298template class VertexErrorFunctionT<float, VertexNormalDataT<float>, 1>;
299template class VertexErrorFunctionT<double, VertexNormalDataT<double>, 1>;
300
301template class VertexErrorFunctionT<float, VertexPlaneDataT<float>, 1>;
302template class VertexErrorFunctionT<double, VertexPlaneDataT<double>, 1>;
303
304template class VertexErrorFunctionT<float, VertexProjectionDataT<float>, 2>;
305template class VertexErrorFunctionT<double, VertexProjectionDataT<double>, 2>;
306
307} // 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.
SkeletonErrorFunctionT(const Skeleton &skel, const ParameterTransform &pt)
const ParameterTransform & parameterTransform_
Mid-level adapter for single-vertex constraints.
bool needsMesh() const final
Returns true (vertex constraints always need mesh).
double getError(const ModelParametersT< T > &params, const SkeletonStateT< T > &state, const MeshStateT< T > &meshState) override
Computes the error.
virtual 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 =0
Computes the residual and derivatives.
VertexErrorFunctionT(const Character &character, const ParameterTransform &parameterTransform, const T &lossAlpha=GeneralizedLossT< T >::kL2, const T &lossC=T(1))
Constructor.
const std::vector< Data > & getConstraints() const
Returns the current constraints.
T legacyWeight_
Legacy weight multiplied into error/gradient/Jacobian for backwards compatibility.
Eigen::Matrix< T, FuncDim, 1 > FuncType
double getGradient(const ModelParametersT< T > &params, const SkeletonStateT< T > &state, const MeshStateT< T > &meshState, Eigen::Ref< Eigen::VectorX< T > > gradient) override
Computes the gradient.
void setConstraints(std::span< const Data > constraints)
Sets all constraints, replacing existing ones.
Eigen::Matrix< T, FuncDim, 3 > DfdvType
void addConstraint(const Data &constraint)
Adds a constraint.
void clearConstraints()
Clears all constraints.
const Character * getCharacter() const final
Returns the character (needed for mesh-based computations).
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
Computes the Jacobian.
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
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 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.