Momentum
A library for solving nonlinear optimization problems related to human body kinematics
Loading...
Searching...
No Matches
mppca_io.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
11#include "momentum/common/log.h"
12#include "momentum/math/mppca.h"
13
14#include <fstream>
15#include <limits>
16
17namespace momentum {
18
19std::shared_ptr<const Mppca> loadMppca(const std::span<const unsigned char> posePriorDataRaw) {
20 // Load from passed file data
21 std::stringstream instream;
22 std::copy(
23 posePriorDataRaw.begin(),
24 posePriorDataRaw.end(),
25 std::ostream_iterator<unsigned char>(instream));
26
27 return loadMppca(instream);
28}
29
30std::shared_ptr<const Mppca> loadMppca(const std::string& name) {
31 std::ifstream data(name, std::ios::in | std::ios::binary);
32 MT_THROW_IF(!data.good(), "Error loading Mppca model: could not open file '{}'.", name);
33
34 return loadMppca(data);
35}
36
37std::shared_ptr<const Mppca> loadMppca(std::istream& inputStream) {
38 auto result = std::make_shared<Mppca>();
39
40 // try to load file
41 try {
42 MT_THROW_IF(!inputStream, "Error loading Mppca model: empty input stream.");
43
44 // load dimensions
45 uint64_t od = 0;
46 uint64_t op = 0;
47 inputStream.read((char*)&od, sizeof(od));
48 inputStream.read((char*)&op, sizeof(op));
49
50 MT_THROW_IF(!inputStream.good(), "Error loading Mppca model: failed to read dimensions.");
51
52 // Validate sizes to prevent excessive allocation from malformed files
53 constexpr uint64_t kMaxDimension = 10'000'000;
54 constexpr uint64_t kMaxStringLength = 10'000;
56 od > kMaxDimension || op > kMaxDimension,
57 "Error loading Mppca model: unreasonable dimensions od={}, op={}.",
58 od,
59 op);
60
61 // Guard against integer overflow in od * od (used for Cinv matrices)
63 od != 0 && od > std::numeric_limits<uint64_t>::max() / od,
64 "Error loading Mppca model: integer overflow in Cinv size calculation.");
65
66 // Guard against integer overflow in op * od (used for mu matrix)
68 op != 0 && od != 0 && op > std::numeric_limits<uint64_t>::max() / od,
69 "Error loading Mppca model: integer overflow in mu size calculation.");
70
71 // set data on result
72 result->d = od;
73 result->p = op;
74
75 // load names
76 result->names.resize(od);
77 for (size_t i = 0; i < od; i++) {
78 uint64_t count = 0;
79 inputStream.read((char*)&count, sizeof(uint64_t));
81 !inputStream.good() || count > kMaxStringLength,
82 "Error loading Mppca model: invalid name length.");
83 result->names[i].resize(count);
84 inputStream.read((char*)result->names[i].data(), count);
85 MT_THROW_IF(!inputStream.good(), "Error loading Mppca model: failed to read name data.");
86 }
87
88 // prepare data structures
89 result->Rpre = VectorXf(op);
90 result->Cinv.resize(op);
91 result->L.resize(op);
92 result->mu.resize(op, od);
93
94 // load Rpre, Cinv, and mu
95 inputStream.read((char*)result->Rpre.data(), sizeof(float) * op);
96 MT_THROW_IF(!inputStream.good(), "Error loading Mppca model: failed to read Rpre data.");
97 for (size_t i = 0; i < op; i++) {
98 result->Cinv[i] = MatrixXf(od, od);
99 inputStream.read((char*)result->Cinv[i].data(), sizeof(float) * od * od);
100 MT_THROW_IF(!inputStream.good(), "Error loading Mppca model: failed to read Cinv data.");
101 result->L[i] = result->Cinv[i].llt().matrixL().transpose();
102 }
103 inputStream.read((char*)result->mu.data(), sizeof(float) * op * od);
104 MT_THROW_IF(!inputStream.good(), "Error loading Mppca model: failed to read mu data.");
105
106 return result;
107 } catch (std::exception& e) {
108 MT_THROW("Error loading Mppca model: {}", e.what());
109 }
110}
111
112void saveMppca(const Mppca& mppca, const std::string& name) {
113 // write output file
114 std::ofstream data(name, std::ios::out | std::ios::binary);
115 if (!data.is_open()) {
116 return;
117 }
118
119 // write dimensions
120 const auto od = gsl::narrow<uint64_t>(mppca.d);
121 const auto op = gsl::narrow<uint64_t>(mppca.p);
122 data.write((char*)&od, sizeof(od));
123 data.write((char*)&op, sizeof(op));
124
125 // write out names
126 MT_CHECK(mppca.names.size() >= od);
127 for (size_t i = 0; i < od; i++) {
128 // NOLINTNEXTLINE(facebook-hte-ParameterUncheckedArrayBounds)
129 const std::string& nm = mppca.names[i];
130 const uint64_t ln = nm.size();
131 data.write((const char*)&ln, sizeof(uint64_t));
132 data.write((const char*)nm.data(), ln);
133 }
134
135 // write pi, mu, W, sigma2
136 data.write((char*)mppca.Rpre.data(), sizeof(float) * op);
137 for (const auto& Cinv : mppca.Cinv) {
138 data.write((char*)Cinv.data(), sizeof(float) * od * od);
139 }
140 data.write((char*)mppca.mu.data(), sizeof(float) * op * od);
141
142 // close file
143 data.close();
144}
145
146} // namespace momentum
#define MT_CHECK(condition,...)
Runtime check macros with two interchangeable backends:
Definition checks.h:36
#define MT_THROW(...)
Throws a std::runtime_error with a formatted message.
Definition exception.h:31
#define MT_THROW_IF(Condition,...)
Conditionally throws a std::runtime_error with a formatted message if the condition is true.
Definition exception.h:55
std::shared_ptr< const Mppca > loadMppca(const std::span< const unsigned char > posePriorDataRaw)
Definition mppca_io.cpp:19
MppcaT< float > Mppca
Definition fwd.h:39
void saveMppca(const Mppca &mppca, const std::string &name)
Definition mppca_io.cpp:112
VectorX< float > VectorXf
Definition types.h:209
MatrixX< float > MatrixXf
Definition types.h:82
size_t d
Dimensionality of the data space x.
Definition mppca.h:31
std::vector< Eigen::MatrixX< T > > Cinv
Per-component inverse covariance matrices C_c^{-1} of size d x d.
Definition mppca.h:45
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