libqe 0.2.5
QE C++ library
Loading...
Searching...
No Matches
linalg_fallback.hpp
Go to the documentation of this file.
1
21#ifndef LIBQE_LINALG_FALLBACK_HPP
22#define LIBQE_LINALG_FALLBACK_HPP
23
24#include <armadillo>
25#include <cmath>
26#include <limits>
27
28namespace qe {
29namespace linalg {
30
32// ── helpers ───────────────────────────────────────────────────────────────────
33
34namespace detail {
35
43inline void mgs(arma::mat& Q) {
44 const arma::uword p = Q.n_cols;
45 for (arma::uword j = 0; j < p; ++j) {
46 for (arma::uword i = 0; i < j; ++i)
47 Q.col(j) -= arma::dot(Q.col(i), Q.col(j)) * Q.col(i);
48 double n = arma::norm(Q.col(j));
49 if (n > 1e-14) Q.col(j) /= n;
50 }
51}
52
69inline void jacobi_sweep(arma::mat& A, arma::mat& V) {
70 const arma::uword p = A.n_rows;
71 for (arma::uword q = 0; q < p - 1; ++q) {
72 for (arma::uword r = q + 1; r < p; ++r) {
73 double aqq = A(q, q), arr = A(r, r), aqr = A(q, r);
74 if (std::abs(aqr) <= 1e-14 * (std::abs(aqq) + std::abs(arr)))
75 continue;
76 double theta = (arr - aqq) / (2.0 * aqr);
77 double t = (theta >= 0.0)
78 ? 1.0 / (theta + std::sqrt(1.0 + theta * theta))
79 : 1.0 / (theta - std::sqrt(1.0 + theta * theta));
80 double c = 1.0 / std::sqrt(1.0 + t * t);
81 double s = t * c;
82 // Apply Jacobi rotation to A (symmetric update)
83 double new_qq = aqq - t * aqr;
84 double new_rr = arr + t * aqr;
85 A(q, q) = new_qq; A(r, r) = new_rr; A(q, r) = A(r, q) = 0.0;
86 for (arma::uword k = 0; k < p; ++k) {
87 if (k == q || k == r) continue;
88 double akq = A(k, q), akr = A(k, r);
89 A(k, q) = A(q, k) = c * akq - s * akr;
90 A(k, r) = A(r, k) = s * akq + c * akr;
91 }
92 // Accumulate rotation in V
93 for (arma::uword k = 0; k < p; ++k) {
94 double vkq = V(k, q), vkr = V(k, r);
95 V(k, q) = c * vkq - s * vkr;
96 V(k, r) = s * vkq + c * vkr;
97 }
98 }
99 }
100}
101
102} // namespace detail
103
105
108
109// ── eig_sym ───────────────────────────────────────────────────────────────────
110
129inline void eig_sym(arma::vec& eigval, arma::mat& eigvec, const arma::mat& S) {
130#if defined(ARMA_USE_LAPACK)
131 arma::eig_sym(eigval, eigvec, S);
132#else
133 const arma::uword p = S.n_rows;
134 arma::mat A = S;
135 eigvec.eye(p, p);
136
137 for (int sweep = 0; sweep < 50 * static_cast<int>(p); ++sweep) {
138 // Check off-diagonal convergence
139 double off = 0.0;
140 for (arma::uword q = 0; q < p - 1; ++q)
141 for (arma::uword r = q + 1; r < p; ++r)
142 off += A(q, r) * A(q, r);
143 if (std::sqrt(off) < 1e-13) break;
144 detail::jacobi_sweep(A, eigvec);
145 }
146 eigval = A.diag();
147
148 // Sort ascending
149 arma::uvec idx = arma::sort_index(eigval);
150 eigval = eigval(idx);
151 eigvec = eigvec.cols(idx);
152#endif
153}
154
156
159
160// ── qr_full ───────────────────────────────────────────────────────────────────
161
180inline void qr_full(arma::mat& Q, arma::mat& R, const arma::mat& A) {
181#if defined(ARMA_USE_LAPACK)
182 arma::qr(Q, R, A);
183#else
184 // Build a full n×n orthogonal matrix.
185 // Step 1: thin QR via modified Gram-Schmidt (gives first k=A.n_cols columns).
186 // Step 2: extend to a full ONB using random vectors + re-orthogonalisation.
187 const arma::uword n = A.n_rows, p = A.n_cols;
188
189 // Start with all n columns of A padded with random vectors if n > p.
190 arma::mat Qfull(n, n, arma::fill::zeros);
191 // Copy A's columns first
192 for (arma::uword j = 0; j < p && j < n; ++j)
193 Qfull.col(j) = A.col(j);
194 // Fill remaining columns with standard basis vectors (or random fallback)
195 for (arma::uword j = p; j < n; ++j) {
196 Qfull(j, j) = 1.0;
197 }
198 // Full MGS orthonormalization
199 detail::mgs(Qfull);
200 Q = Qfull;
201
202 // R is n×p (upper trapezoidal); only first p rows are non-zero
203 R = Q.t() * A;
204 // Zero the strictly lower-triangular part of R[0:p, 0:p]
205 for (arma::uword j = 0; j < p; ++j)
206 for (arma::uword i = j + 1; i < n; ++i)
207 R(i, j) = 0.0;
208#endif
209}
210
212
215
216// ── svd ───────────────────────────────────────────────────────────────────────
217
237inline void svd(arma::mat& U, arma::vec& s, arma::mat& V, const arma::mat& A) {
238#if defined(ARMA_USE_LAPACK)
239 arma::svd(U, s, V, A);
240#else
241 // One-sided Jacobi on A^T:
242 // We work with B = A^T (p×n). The right singular vectors of A are the
243 // left singular vectors of B (= columns of U_B after Jacobi on B^T B).
244 // We use the eigendecomposition of A^T * A to get V and s.
245 const arma::uword n = A.n_rows, p = A.n_cols;
246 const arma::uword k = std::min(n, p);
247
248 arma::mat AtA = A.t() * A;
249 arma::vec eigval;
250 arma::mat eigvec;
251 eig_sym(eigval, eigvec, AtA);
252
253 // Eigenvalues from eig_sym are ascending; we want descending.
254 arma::uvec idx = arma::sort_index(eigval, "descend");
255 eigval = eigval(idx);
256 eigvec = eigvec.cols(idx);
257
258 // Singular values (non-negative square roots)
259 s.set_size(k);
260 for (arma::uword j = 0; j < k; ++j)
261 s(j) = std::sqrt(std::max(0.0, eigval(j)));
262
263 // V = eigvec (right singular vectors of A are eigvectors of A^T*A)
264 V = eigvec;
265
266 // U = A * V / s (left singular vectors, only first k columns needed)
267 U.set_size(n, k);
268 for (arma::uword j = 0; j < k; ++j) {
269 if (s(j) > 1e-14)
270 U.col(j) = A * V.col(j) / s(j);
271 else
272 U.col(j).zeros();
273 }
274#endif
275}
276
277// ── svd_right ─────────────────────────────────────────────────────────────────
278
291inline void svd_right(arma::vec& s, arma::mat& V, const arma::mat& A) {
292#if defined(ARMA_USE_LAPACK)
293 arma::mat U;
294 arma::svd(U, s, V, A);
295#else
296 arma::mat U_unused;
297 svd(U_unused, s, V, A);
298#endif
299}
300
302
305
306// ── solve_spd ─────────────────────────────────────────────────────────────────
307
330inline arma::mat solve_spd(const arma::mat& A, const arma::mat& b,
331 double tol = 1e-12) {
332#if defined(ARMA_USE_LAPACK)
333 return arma::solve(A, b, arma::solve_opts::fast);
334#else
335 arma::vec eigval;
336 arma::mat eigvec;
337 eig_sym(eigval, eigvec, A);
338
339 const double thresh = tol * std::abs(eigval.max());
340 arma::vec inv_eigval(eigval.n_elem, arma::fill::zeros);
341 for (arma::uword i = 0; i < eigval.n_elem; ++i)
342 if (std::abs(eigval(i)) > thresh)
343 inv_eigval(i) = 1.0 / eigval(i);
344
345 // x = eigvec * diag(inv_eigval) * eigvec^T * b
346 return eigvec * arma::diagmat(inv_eigval) * eigvec.t() * b;
347#endif
348}
349
350// ── inv_sym ───────────────────────────────────────────────────────────────────
351
364inline arma::mat inv_sym(const arma::mat& A, double tol = 1e-12) {
365#if defined(ARMA_USE_LAPACK)
366 arma::mat out;
367 if (!arma::inv(out, A))
368 out = arma::pinv(A);
369 return out;
370#else
371 return solve_spd(A, arma::eye(A.n_rows, A.n_rows), tol);
372#endif
373}
374
376
377} // namespace linalg
378} // namespace qe
379
380#endif // LIBQE_LINALG_FALLBACK_HPP
void svd(arma::mat &U, arma::vec &s, arma::mat &V, const arma::mat &A)
Full SVD: A ≈ U * diag(s) * V', singular values descending.
Definition linalg_fallback.hpp:237
arma::mat solve_spd(const arma::mat &A, const arma::mat &b, double tol=1e-12)
Solve A*x = b for symmetric positive (semi-)definite A.
Definition linalg_fallback.hpp:330
arma::mat inv_sym(const arma::mat &A, double tol=1e-12)
Inverse of a symmetric positive (semi-)definite matrix, falling back to the pseudo-inverse when it is...
Definition linalg_fallback.hpp:364
void eig_sym(arma::vec &eigval, arma::mat &eigvec, const arma::mat &S)
Eigendecomposition of a real symmetric matrix.
Definition linalg_fallback.hpp:129
void qr_full(arma::mat &Q, arma::mat &R, const arma::mat &A)
Full (square) QR factorization of an n×p matrix.
Definition linalg_fallback.hpp:180
void svd_right(arma::vec &s, arma::mat &V, const arma::mat &A)
Singular values and right singular vectors only (left vectors skipped).
Definition linalg_fallback.hpp:291
Definition adjacency.hpp:16