libena 0.4.18-dev.9021
QE C++ library
Loading...
Searching...
No Matches
rotation.hpp
Go to the documentation of this file.
1
9#ifndef LIBQE_ROTATION_HPP
10#define LIBQE_ROTATION_HPP
11
12#include <libqe/linalg_fallback.hpp>
13#include <armadillo>
14#include <stdexcept>
15#include <string>
16#include <utility>
17#include <vector>
18
19namespace qe {
20
23
34 arma::mat rotation;
35 arma::vec eigenvalues;
36 std::vector<std::string> column_names;
37};
38
46struct GroupPair {
47 arma::uvec a;
48 arma::uvec b;
49};
50
52
55
79inline RotationResult ena_svd(const arma::mat& points) {
80 if (!points.is_finite())
81 throw std::invalid_argument("ena_svd: input matrix must not contain NaN or Inf");
82 arma::mat U, V;
83 arma::vec s;
84 qe::linalg::svd(U, s, V, points);
85
86 const arma::uword p = points.n_cols;
87 const double denom = points.n_rows > 1
88 ? static_cast<double>(points.n_rows - 1)
89 : 1.0;
90
91 arma::vec eigenvalues(p, arma::fill::zeros);
92 const arma::uword k = std::min<arma::uword>(s.n_elem, p);
93 for (arma::uword j = 0; j < k; ++j) {
94 eigenvalues(j) = (s(j) * s(j)) / denom;
95 }
96
97 std::vector<std::string> labels(p);
98 for (arma::uword j = 0; j < p; ++j) {
99 labels[j] = "SVD" + std::to_string(j + 1);
100 }
101 return {V, eigenvalues, std::move(labels)};
102}
103
105
108
122inline arma::mat deflate(const arma::mat& data, const arma::vec& axis) {
123 return data - (data * axis) * axis.t();
124}
125
127
130
168 const arma::mat& data,
169 const arma::mat& weights,
170 const std::vector<std::string>& named_labels) {
171 const arma::uword p = weights.n_rows;
172 const arma::uword k = weights.n_cols;
173 if (data.n_cols != p) {
174 throw std::runtime_error(
175 "orthogonal_svd: data.n_cols must equal weights.n_rows");
176 }
177 if (named_labels.size() != k) {
178 throw std::runtime_error(
179 "orthogonal_svd: named_labels.size() must equal weights.n_cols");
180 }
181 if (k == 0) {
182 return ena_svd(data);
183 }
184
185 arma::mat Q, R;
186 qe::linalg::qr_full(Q, R, weights); // Q is p x p
187
188 arma::mat rotation(p, p);
189 arma::vec eigenvalues(p, arma::fill::zeros);
190 rotation.cols(0, k - 1) = Q.cols(0, k - 1);
191
192 if (k < p) {
193 arma::mat Q_comp = Q.cols(k, p - 1); // p x (p - k)
194 arma::mat X_bar = data * Q_comp; // n x (p - k)
195 RotationResult inner = ena_svd(X_bar);
196 rotation.cols(k, p - 1) = Q_comp * inner.rotation;
197 for (arma::uword j = 0; j < (p - k); ++j) {
198 eigenvalues(k + j) = inner.eigenvalues(j);
199 }
200 }
201
202 std::vector<std::string> labels(p);
203 for (arma::uword j = 0; j < k; ++j) labels[j] = named_labels[j];
204 for (arma::uword j = k; j < p; ++j) {
205 labels[j] = "SVD" + std::to_string(j + 1);
206 }
207 return {rotation, eigenvalues, std::move(labels)};
208}
209
211
214
257 const arma::mat& data,
258 const arma::mat& named_axes,
259 const std::vector<std::string>& named_labels) {
260 const arma::uword p = named_axes.n_rows;
261 const arma::uword k = named_axes.n_cols;
262 if (data.n_cols != p) {
263 throw std::runtime_error(
264 "complete_rotation: data.n_cols must equal named_axes.n_rows");
265 }
266 if (named_labels.size() != k) {
267 throw std::runtime_error(
268 "complete_rotation: named_labels.size() must equal named_axes.n_cols");
269 }
270 if (k == 0) {
271 return ena_svd(data);
272 }
273
274 arma::mat defA = data - data * named_axes * named_axes.t();
275 RotationResult inner = ena_svd(defA);
276
277 arma::mat rotation(p, p);
278 arma::vec eigenvalues(p, arma::fill::zeros);
279 rotation.cols(0, k - 1) = named_axes;
280 if (k < p) {
281 // The SVD columns with non-zero singular values are taken as they are
282 // (rENA's pattern; with orthonormal named axes they lie in defA's row
283 // space, orthogonal to the axes). When the data are rank-deficient --
284 // e.g. an all-zero connection column from a code mask, or fewer units
285 // than connections -- the trailing columns come from defA's null
286 // space, which contains the named axes themselves, so the SVD can
287 // return one that nearly duplicates a named axis (|cos| ~ 0.99): the
288 // rotation is no longer orthonormal and that axis's variance is
289 // counted twice. Null-space columns are therefore orthogonalised
290 // against the named axes and the axes already chosen (Gram-Schmidt),
291 // skipping any with nothing left. Full-rank data are unaffected.
292 arma::mat basis(p, p, arma::fill::zeros); // orthonormal span so far
293 arma::uword nb = 0;
294 auto add_to_basis = [&](arma::vec v) {
295 for (int pass = 0; pass < 2; ++pass)
296 if (nb > 0) v -= basis.cols(0, nb - 1) * (basis.cols(0, nb - 1).t() * v);
297 const double len = arma::norm(v);
298 if (len > 1e-10 && nb < p) basis.col(nb++) = v / len;
299 };
300 for (arma::uword j = 0; j < k; ++j) add_to_basis(named_axes.col(j));
301
302 // A singular value below 1e-7 of the largest is numerically zero.
303 const double max_eig = inner.eigenvalues.is_empty() ? 0.0 : inner.eigenvalues.max();
304 const double null_eig = 1e-14 * max_eig;
305 arma::uword filled = 0;
306 auto take = [&](arma::vec v, double eigenvalue, bool in_null_space) {
307 if (filled >= p - k) return;
308 if (in_null_space) {
309 for (int pass = 0; pass < 2; ++pass)
310 if (nb > 0) v -= basis.cols(0, nb - 1) * (basis.cols(0, nb - 1).t() * v);
311 const double len = arma::norm(v);
312 if (len < 1e-8) return; // nothing left: skip the candidate
313 v /= len;
314 }
315 rotation.col(k + filled) = v;
316 eigenvalues(k + filled) = eigenvalue;
317 ++filled;
318 add_to_basis(v);
319 };
320 for (arma::uword j = 0; j < inner.rotation.n_cols && filled < p - k; ++j)
321 take(inner.rotation.col(j), inner.eigenvalues(j), inner.eigenvalues(j) <= null_eig);
322 // The SVD columns span R^p, so this only runs on degenerate input.
323 for (arma::uword i = 0; i < p && filled < p - k; ++i) {
324 arma::vec e(p, arma::fill::zeros);
325 e(i) = 1.0;
326 take(e, 0.0, true);
327 }
328 }
329
330 std::vector<std::string> labels(p);
331 for (arma::uword j = 0; j < k; ++j) labels[j] = named_labels[j];
332 for (arma::uword j = k; j < p; ++j) {
333 labels[j] = "SVD" + std::to_string(j + 1);
334 }
335 return {rotation, eigenvalues, std::move(labels)};
336}
337
339
342
371inline RotationResult means_rotation(const arma::mat& points,
372 const std::vector<GroupPair>& pairs) {
373 if (pairs.empty()) {
374 throw std::runtime_error("Unable to rotate without 2 groups.");
375 }
376
377 arma::mat data = points.each_row() - arma::mean(points, 0);
378 arma::mat deflated = data;
379 arma::mat weights(data.n_cols, pairs.size(), arma::fill::zeros);
380 std::vector<std::string> labels;
381 labels.reserve(pairs.size());
382
383 for (std::size_t i = 0; i < pairs.size(); ++i) {
384 const arma::rowvec mean_a = arma::mean(deflated.rows(pairs[i].a), 0);
385 const arma::rowvec mean_b = arma::mean(deflated.rows(pairs[i].b), 0);
386 const arma::vec diff = (mean_a - mean_b).t();
387 const double norm = std::sqrt(arma::accu(diff % diff));
388 const arma::vec axis = diff / norm; // no zero-norm guard
389
390 deflated = deflate(deflated, axis);
391 weights.col(i) = axis;
392 labels.push_back("MR" + std::to_string(i + 1));
393 }
394
395 return orthogonal_svd(deflated, weights, labels);
396}
397
399
400} // namespace qe
401
402#endif // LIBQE_ROTATION_HPP
Definition cxxwrap.hpp:36
arma::mat deflate(const arma::mat &data, const arma::vec &axis)
Project a data matrix onto the hyperplane orthogonal to a given axis.
Definition rotation.hpp:122
RotationResult means_rotation(const arma::mat &points, const std::vector< GroupPair > &pairs)
Compute a means rotation from one or more group pairs.
Definition rotation.hpp:371
RotationResult ena_svd(const arma::mat &points)
Compute a full SVD rotation of a (pre-centered) points matrix.
Definition rotation.hpp:79
RotationResult complete_rotation(const arma::mat &data, const arma::mat &named_axes, const std::vector< std::string > &named_labels)
Keep named axes verbatim and fill remaining axes from an SVD of the data after parallel deflation by ...
Definition rotation.hpp:256
RotationResult orthogonal_svd(const arma::mat &data, const arma::mat &weights, const std::vector< std::string > &named_labels)
Orthonormalize named axes via QR, then complete the rotation with an SVD of the data projected onto t...
Definition rotation.hpp:167
A pair of 0-based row-index vectors identifying two groups within a points matrix.
Definition rotation.hpp:46
arma::uvec a
Row indices of group A (0-based).
Definition rotation.hpp:47
arma::uvec b
Row indices of group B (0-based).
Definition rotation.hpp:48
Aggregated result returned by every rotation routine.
Definition rotation.hpp:33
arma::vec eigenvalues
Length-p vector of sdev^2 values, matching rENA's convention.
Definition rotation.hpp:35
std::vector< std::string > column_names
Axis labels, e.g. "MR1", "SVD2", "GMR1".
Definition rotation.hpp:36
arma::mat rotation
p x p orthogonal matrix; column j is rotation axis j.
Definition rotation.hpp:34