libena 0.4.18-dev.9021
QE C++ library
Loading...
Searching...
No Matches
generalized_rotation.hpp
Go to the documentation of this file.
1
40#ifndef LIBQE_GENERALIZED_ROTATION_HPP
41#define LIBQE_GENERALIZED_ROTATION_HPP
42
43#include <libqe/linalg_fallback.hpp> // qe::linalg::eig_sym (works w/o LAPACK)
44#include <libqe/lasso.hpp> // lasso_x1_contribution
45#include "rotation.hpp" // ena_svd, complete_rotation, RotationResult
46
47#include <armadillo>
48#include <stdexcept>
49#include <string>
50#include <vector>
51
52namespace qe {
53
56
71inline arma::mat between_group_scatter(
72 const arma::mat& V,
73 const arma::uvec& labels,
74 arma::uword n_groups
75) {
76 const arma::uword p = V.n_cols;
77 arma::rowvec mu = arma::mean(V, 0);
78 arma::mat SB(p, p, arma::fill::zeros);
79
80 for (arma::uword g = 0; g < n_groups; ++g) {
81 arma::uvec idx = arma::find(labels == g);
82 if (idx.is_empty()) continue;
83 arma::vec diff = (arma::mean(V.rows(idx), 0) - mu).t();
84 SB += static_cast<double>(idx.n_elem) * diff * diff.t();
85 }
86 return SB;
87}
88
90
93
123inline arma::vec gmr_direction(
124 const arma::mat& Vx, // n×q covariate-adjusted contribution
125 const arma::vec& target, // n×1 (numeric float, or 0-based int codes)
126 bool categorical,
127 arma::uword n_groups = 0
128) {
129 arma::vec r;
130
131 if (categorical) {
132 if (n_groups < 2)
133 throw std::runtime_error(
134 "gmr_direction: x_n_groups must be >= 2 for categorical target");
135 arma::uvec labels = arma::conv_to<arma::uvec>::from(target);
136 arma::mat SB = between_group_scatter(Vx, labels, n_groups);
137
138 arma::vec eigval; arma::mat eigvec;
139 qe::linalg::eig_sym(eigval, eigvec, SB); // ascending order
140 r = eigvec.col(eigvec.n_cols - 1); // largest eigenvalue → last col
141 } else {
142 // Centre target to get the OLS slope (mirrors R's lm() intercept handling)
143 arma::vec tc = target - arma::mean(target);
144 double tTt = arma::dot(tc, tc);
145 if (tTt < 1e-12)
146 throw std::runtime_error(
147 "gmr_direction: target has zero variance after centering");
148 arma::rowvec beta = (tc.t() * Vx) / tTt; // 1×q slope vector
149 r = beta.t();
150 }
151
152 double norm = arma::norm(r);
153 if (norm < 1e-12)
154 throw std::runtime_error("gmr_direction: resulting direction has zero norm");
155 return r / norm;
156}
157
159
164 arma::vec direction;
165};
166
169
202 const arma::mat& V,
203 const arma::mat& X_model,
204 const arma::vec& target,
205 const arma::uvec& x1_cols,
206 bool categorical,
207 arma::uword n_groups,
208 const arma::uvec& subset,
209 int n_lambda = 50,
210 int k_folds = 5,
211 double lasso_eps = 0.01
212) {
213 const arma::uword n = V.n_rows;
214 const arma::uword p = X_model.n_cols;
215
216 // ── Select rows ──────────────────────────────────────────────────────────
217 arma::uvec rows = subset.is_empty()
218 ? arma::regspace<arma::uvec>(0, n - 1)
219 : subset;
220
221 const arma::mat V_sub = V.rows(rows);
222 const arma::mat X_sub = X_model.rows(rows);
223 const arma::vec t_sub = target.rows(rows);
224
225 // ── Lasso-adjusted contribution Vx ───────────────────────────────────────
226 arma::mat Vx_sub;
227 if (x1_cols.n_elem >= p) {
228 // All columns are target columns (no penalized covariates):
229 // fall back to simple OLS projection (Vx = fitted values from lm(V~t))
230 arma::vec tc = t_sub - arma::mean(t_sub);
231 double tTt = arma::dot(tc, tc);
232 if (tTt > 1e-12) {
233 arma::rowvec b1 = (tc.t() * V_sub) / tTt;
234 Vx_sub = tc * b1;
235 } else {
236 Vx_sub.zeros(V_sub.n_rows, V_sub.n_cols);
237 }
238 } else {
239 arma::vec pf(p, arma::fill::ones);
240 for (arma::uword j : x1_cols) pf(j) = 0.0;
241
242 Vx_sub = lasso_x1_contribution(
243 X_sub, V_sub, x1_cols, pf, n_lambda, k_folds, lasso_eps);
244 }
245
246 // ── Rotation direction ───────────────────────────────────────────────────
247 arma::vec direction = gmr_direction(Vx_sub, t_sub, categorical, n_groups);
248
249 return {direction};
250}
251
253
265 arma::mat x_model_matrix;
266 arma::vec x_target;
267 arma::uvec x1_cols;
268 bool x_categorical = false;
269 arma::uword x_n_groups = 0;
270 arma::uvec x_subset;
272
276 bool has_y = false;
277 arma::mat y_model_matrix;
278 arma::vec y_target;
279 arma::uvec y1_cols;
280 bool y_categorical = false;
281 arma::uword y_n_groups = 0;
284
287 int n_lambda = 50;
288 int k_folds = 5;
289 double lasso_eps = 0.01;
291};
292
295
341 const arma::mat& V,
342 const GeneralizedRotationParams& params
343) {
344 // ── Step 1: X axis via GMR ────────────────────────────────────────────
345 GMRStepResult x_gmr = gmr_step(
346 V,
347 params.x_model_matrix,
348 params.x_target,
349 params.x1_cols,
350 params.x_categorical,
351 params.x_n_groups,
352 params.x_subset,
353 params.n_lambda,
354 params.k_folds,
355 params.lasso_eps);
356
357 const arma::vec x_vector = x_gmr.direction;
358
359 // ── Step 2: Deflate V by x_vector ─────────────────────────────────────
360 // defA is used only for y_vector computation; x1 uses original V.
361 const arma::mat defA = V - V * x_vector * x_vector.t();
362
363 // ── Step 3: Secondary axis x1 ─────────────────────────────────────────
364 // Mirrors R: x1 = normalize(mean(V[group0]) - mean(V[group1])).
365 //
366 // Key points matching the authoritative R:
367 // - Uses original V (not defA)
368 // - Uses the full-length target (all n rows), not just the subset
369 // - Groups are always 0 (first) and 1 (second) in 0-based encoding
370 // - NO fallback: x1 stays empty when categorical/2-group condition fails
371 // - x1 does NOT deflate defA; it is only used to orthogonalise y_vector
372 arma::vec x1;
373
374 if (params.x_categorical && params.x_n_groups >= 2) {
375 arma::uvec labels = arma::conv_to<arma::uvec>::from(params.x_target);
376 arma::uvec g0 = arma::find(labels == 0);
377 arma::uvec g1 = arma::find(labels == 1);
378
379 if (!g0.is_empty() && !g1.is_empty()) {
380 arma::rowvec m0 = arma::mean(V.rows(g0), 0); // original V, not defA
381 arma::rowvec m1 = arma::mean(V.rows(g1), 0);
382 arma::vec diff = (m0 - m1).t();
383 double dlen = arma::norm(diff);
384 if (dlen > 1e-10) x1 = diff / dlen;
385 }
386 }
387
388 // ── Step 4: Y axis ────────────────────────────────────────────────────
389 // GMR on defA (deflated by x_vector only), or SVD of defA.
390 arma::vec y_vector;
391 std::string y_name = "SVD2";
392
393 if (params.has_y) {
394 GMRStepResult y_gmr = gmr_step(
395 defA,
396 params.y_model_matrix,
397 params.y_target,
398 params.y1_cols,
399 params.y_categorical,
400 params.y_n_groups,
401 {}, // no row subset for y axis
402 params.n_lambda,
403 params.k_folds,
404 params.lasso_eps);
405 y_vector = y_gmr.direction;
406 y_name = "GMR2";
407 } else {
408 RotationResult svd_r = ena_svd(defA);
409 y_vector = svd_r.rotation.col(0);
410 }
411
412 // ── Step 5: Orthogonalise y_vector ────────────────────────────────────
413 // Mirrors R (authoritative commit):
414 // y_vector <- y_vector - (t(y_vector) %*% x_vector) * x_vector
415 // if (!is.null(x1)) y_vector <- y_vector - (t(y_vector) %*% x1) * x1
416 // y_vector <- safe_normalize(y_vector)
417 y_vector -= arma::dot(y_vector, x_vector) * x_vector;
418 if (!x1.is_empty())
419 y_vector -= arma::dot(y_vector, x1) * x1;
420
421 double yn = arma::norm(y_vector);
422 if (yn < 1e-12)
423 throw std::runtime_error(
424 "generalized_means_rotation: y_vector has zero norm after orthogonalization");
425 y_vector /= yn;
426
427 // ── Step 6: Combine and complete with SVD ─────────────────────────────
428 // Double-deflate the original data (mirrors R):
429 // defA <- A - A %*% x %*% t(x) - A %*% y %*% t(y)
430 // then pass to prcomp (equivalent: SVD of defA_final).
431 arma::mat defA_final = V
432 - V * x_vector * x_vector.t()
433 - V * y_vector * y_vector.t();
434
435 arma::mat named_axes = arma::join_rows(x_vector, y_vector);
436 return complete_rotation(defA_final, named_axes, {"GMR1", y_name});
437}
438
440
441} // namespace qe
442#endif // LIBQE_GENERALIZED_ROTATION_HPP
Definition cxxwrap.hpp:36
RotationResult generalized_means_rotation(const arma::mat &V, const GeneralizedRotationParams &params)
Full Generalized Means Rotation (GMR) producing a complete q×q rotation matrix.
Definition generalized_rotation.hpp:340
arma::mat between_group_scatter(const arma::mat &V, const arma::uvec &labels, arma::uword n_groups)
Compute the between-group scatter matrix S_B.
Definition generalized_rotation.hpp:71
RotationResult ena_svd(const arma::mat &points)
Compute a full SVD rotation of a (pre-centered) points matrix.
Definition rotation.hpp:79
arma::vec gmr_direction(const arma::mat &Vx, const arma::vec &target, bool categorical, arma::uword n_groups=0)
Compute the unit rotation direction from a covariate-adjusted contribution matrix.
Definition generalized_rotation.hpp:123
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
GMRStepResult gmr_step(const arma::mat &V, const arma::mat &X_model, const arma::vec &target, const arma::uvec &x1_cols, bool categorical, arma::uword n_groups, const arma::uvec &subset, int n_lambda=50, int k_folds=5, double lasso_eps=0.01)
Compute the rotation direction for one axis of the Generalized Means Rotation.
Definition generalized_rotation.hpp:201
Rotation routines for Epistemic Network Analysis (ENA): SVD, deflation, orthogonal-SVD,...
Result of one GMR axis step.
Definition generalized_rotation.hpp:163
arma::vec direction
Unit vector in connection space (p×1).
Definition generalized_rotation.hpp:164
Parameters for generalized_means_rotation().
Definition generalized_rotation.hpp:262
arma::uword y_n_groups
Definition generalized_rotation.hpp:281
int n_lambda
Length of the lambda path.
Definition generalized_rotation.hpp:287
arma::uvec x_subset
Optional row subset (0-based); empty means use all rows.
Definition generalized_rotation.hpp:270
bool x_categorical
true if the X target is categorical.
Definition generalized_rotation.hpp:268
arma::mat y_model_matrix
n×p model matrix for the Y axis.
Definition generalized_rotation.hpp:277
bool y_categorical
true if the Y target is categorical.
Definition generalized_rotation.hpp:280
arma::uvec y1_cols
0-based target column indices in y_model_matrix.
Definition generalized_rotation.hpp:279
double lasso_eps
lambda_min = lasso_eps * lambda_max.
Definition generalized_rotation.hpp:289
bool has_y
true if a Y-axis GMR target is provided.
Definition generalized_rotation.hpp:276
arma::mat x_model_matrix
n×p model matrix for the X axis.
Definition generalized_rotation.hpp:265
arma::vec y_target
n×1 target variable for the Y axis.
Definition generalized_rotation.hpp:278
arma::uword x_n_groups
Number of distinct groups (used when x_categorical is true).
Definition generalized_rotation.hpp:269
arma::uvec x1_cols
0-based target column indices in x_model_matrix.
Definition generalized_rotation.hpp:267
arma::vec x_target
n×1 target variable (raw float or 0-based integer codes).
Definition generalized_rotation.hpp:266
int k_folds
Number of cross-validation folds.
Definition generalized_rotation.hpp:288
Aggregated result returned by every rotation routine.
Definition rotation.hpp:33
arma::mat rotation
p x p orthogonal matrix; column j is rotation axis j.
Definition rotation.hpp:34