Momentum
A library for solving nonlinear optimization problems related to human body kinematics
Loading...
Searching...
No Matches
mppca.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
14namespace momentum {
15
16template <typename T>
18 const VectorX<T>& inPi,
19 const MatrixX<T>& mmu,
21 const VectorX<T>& sigma2) {
22 using CovarianceMatrix = LowRankCovarianceMatrixT<T>;
23
24 d = mmu.cols();
25 p = sigma2.rows();
26
27 // Validate input dimensions up front so a mismatch surfaces as a clear error rather than an
28 // out-of-bounds access or silently corrupted output further down.
30 inPi.rows() != static_cast<Eigen::Index>(p),
31 "MppcaT::set: inPi has {} rows, expected {} (p == sigma2.rows())",
32 inPi.rows(),
33 p);
35 mmu.rows() != static_cast<Eigen::Index>(p),
36 "MppcaT::set: mmu has {} rows, expected {} (p == sigma2.rows())",
37 mmu.rows(),
38 p);
40 W.size() != p,
41 "MppcaT::set: W has {} components, expected {} (p == sigma2.rows())",
42 W.size(),
43 p);
44 for (size_t c = 0; c < p; ++c) {
45 // Each W[c] is the (data x latent) PPCA loading matrix; W[c].transpose() is later passed to
46 // LowRankCovarianceMatrix as the factor A with A^T A = W W^T, so the row count must be d.
48 W[c].rows() != static_cast<Eigen::Index>(d),
49 "MppcaT::set: W[{}] has {} rows, expected {} (d == mmu.cols())",
50 c,
51 W[c].rows(),
52 d);
53 }
54
55 Rpre.setZero(p);
56 Cinv.resize(p);
57 L.resize(p);
58
59 CovarianceMatrix covariance;
60
61 // For each mixture component c, PPCA models the data covariance as
62 // C_c = sigma_c^2 * I + W_c * W_c^T,
63 // i.e. low-rank signal (W_c) plus isotropic noise (sigma_c^2). The log of the
64 // Gaussian normalizer used in the per-component log-density is
65 // -0.5 * d * log(2*pi) (the half_d_log_2pi term below).
66 const T half_d_log_2pi = T(0.5) * static_cast<T>(d) * std::log(twopi<T>());
67
68 for (size_t c = 0; c < p; c++) {
69 // LowRankCovarianceMatrix takes A such that C = sigma^2*I + A^T*A; here A = W_c^T,
70 // so A^T*A = W_c * W_c^T as required by the PPCA model. It produces the QR
71 // factorization R with R^T * R = sigma^2*I + W_c * W_c^T = C_c.
72 covariance.reset(std::sqrt(sigma2(c)), W[c].transpose());
73
74 // R is upper-triangular, so back-substituting the identity yields R^{-1}.
75 // L_tmp = R^{-T} (the lower-triangular factor of C^{-1} = R^{-1} * R^{-T}).
76 const Eigen::MatrixX<T> L_tmp = covariance.R()
77 .template triangularView<Eigen::Upper>()
78 .solve(Eigen::MatrixX<T>::Identity(d, d))
79 .transpose();
80 // Cinv = R^{-1} * R^{-T} = (R^T * R)^{-1} = C^{-1}.
81 Cinv[c] = covariance.R().template triangularView<Eigen::Upper>().solve(L_tmp);
82 L[c] = L_tmp;
83
84 const T C_logDeterminant = covariance.logDeterminant();
85
86 // Per-component log responsibility for input x is
87 // log r_c(x) = log pi_c - 0.5*log|C_c| - 0.5*d*log(2*pi) - 0.5*(x-mu_c)^T C_c^{-1}
88 // (x-mu_c).
89 // Rpre stores the data-independent prefactor (everything but the quadratic term),
90 // so callers can add the cached -0.5 * Mahalanobis distance at evaluation time
91 // and apply log-sum-exp across components for a numerically stable mixture log-likelihood.
92 Rpre(c) = std::log(inPi(c)) - T(0.5) * C_logDeterminant - half_d_log_2pi;
93 }
94 mu = mmu;
95
96 // Reset names to the data-space dimension; caller is expected to populate them
97 // afterwards if needed. Note: this discards any names previously set on the model.
98 names = std::vector<std::string>(d);
99}
100
101template <typename T, typename T2>
102std::vector<Eigen::MatrixX<T2>> castMatrices(momentum::span<const Eigen::MatrixX<T>> m_in) {
103 std::vector<Eigen::MatrixX<T2>> result;
104 result.reserve(m_in.size());
105 for (const auto& m : m_in) {
106 result.emplace_back(m.template cast<T2>());
107 }
108 return result;
109}
110
111template <typename T>
112template <typename T2>
114 MppcaT<T2> result;
115 result.d = this->d;
116 result.p = this->p;
117 result.names = this->names;
118
119 result.mu = this->mu.template cast<T2>();
120 result.Cinv = castMatrices<T, T2>(this->Cinv);
121 result.L = castMatrices<T, T2>(this->L);
122 result.Rpre = this->Rpre.template cast<T2>();
123
124 return result;
125}
126
127template <typename T>
128bool MppcaT<T>::isApprox(const MppcaT<T>& mppcaT) const {
129 auto vecIsApprox = [](auto& vL, auto& vR) {
130 if (vL.size() != vR.size()) {
131 return false;
132 }
133 for (size_t i = 0; i < vL.size(); i++) {
134 if (!vL[i].isApprox(vR[i])) {
135 return false;
136 }
137 }
138 return true;
139 };
140 return (
141 (d == mppcaT.d) && (p == mppcaT.p) && (names == mppcaT.names) && mu.isApprox(mppcaT.mu) &&
142 vecIsApprox(Cinv, mppcaT.Cinv) && vecIsApprox(L, mppcaT.L) && Rpre.isApprox(mppcaT.Rpre));
143}
144
145template struct MppcaT<float>;
146template struct MppcaT<double>;
147
148template MppcaT<float> MppcaT<float>::cast() const;
149template MppcaT<float> MppcaT<double>::cast() const;
150template MppcaT<double> MppcaT<float>::cast() const;
151template MppcaT<double> MppcaT<double>::cast() const;
152
153} // namespace momentum
Efficient and numerically stable representation of a low-rank-plus-diagonal Gaussian covariance matri...
#define MT_THROW_IF(Condition,...)
Conditionally throws a std::runtime_error with a formatted message if the condition is true.
Definition exception.h:55
bool isApprox(T l, T r, T eps=Eps< T >(1e-4, 1e-6)) noexcept
Determines if two values are approximately equal within a given tolerance.
Definition utility.h:53
Eigen::Matrix< T, Dynamic, Dynamic > MatrixX
Dynamic-size, column-major dense matrix.
Definition types.h:80
Vector< T, Dynamic > VectorX
Dynamic-size column vector. Common return type for solver residuals and parameter vectors.
Definition types.h:207
std::vector< Eigen::MatrixX< T2 > > castMatrices(momentum::span< const Eigen::MatrixX< T > > m_in)
Definition mppca.cpp:102
gsl::span< T > span
Span type alias using gsl::span (C++17 fallback).
Definition span_compat.h:54
constexpr T twopi() noexcept
Returns 2 * pi.
Definition constants.h:60
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
Mixture of Probabilistic Principal Component Analyzers (MPPCA).
Definition mppca.h:29
size_t d
Dimensionality of the data space x.
Definition mppca.h:31
void set(const VectorX< T > &pi, const MatrixX< T > &mmu, momentum::span< const MatrixX< T > > W, const VectorX< T > &sigma2)
Initializes the model from raw mixture parameters and precomputes Cinv, L, and Rpre for fast log-like...
Definition mppca.cpp:17
std::vector< Eigen::MatrixX< T > > L
Per-component lower-triangular factors derived from the Cholesky-like decomposition of C_c (used as a...
Definition mppca.h:51
std::vector< Eigen::MatrixX< T > > Cinv
Per-component inverse covariance matrices C_c^{-1} of size d x d.
Definition mppca.h:45
bool isApprox(const MppcaT< T > &mppcaT) const
Returns true if every member matches mppcaT exactly (d, p, names) or approximately (mu,...
Definition mppca.cpp:128
MppcaT< T2 > cast() const
Returns a copy of this model with all numeric data converted to scalar type T2.
Definition mppca.cpp:113
Eigen::VectorX< T > Rpre
Per-component constant term of the log-likelihood: Rpre(c) = log(pi_c) - 0.5 * log|C_c| - (d/2) * log...
Definition mppca.h:57
std::vector< std::string > names
Optional human-readable names for each of the d data dimensions.
Definition mppca.h:38
Eigen::MatrixX< T > mu
Per-component mean vectors stored as a p x d matrix; row c is mu_c.
Definition mppca.h:41
size_t p
Number of mixture components.
Definition mppca.h:34