numerics 0.1.0
Loading...
Searching...
No Matches
qr.cpp
Go to the documentation of this file.
1/// @file linalg/factorization/qr.cpp
2/// @brief QR dispatcher + qr_solve.
3///
4/// Backend routing:
5/// Backend::lapack -> backends::lapack::qr (dgeqrf + dorgqr, blocked
6/// BLAS-3) everything else -> backends::seq::qr (Householder
7/// reflections)
8
10#include "backends/seq/impl.hpp"
11#include "backends/lapack/impl.hpp"
12
13namespace num {
14
15QRResult qr(const Matrix& A, Backend backend) {
16 switch (backend) {
17 case Backend::lapack:
18 return backends::lapack::qr(A);
19 default:
20 return backends::seq::qr(A);
21 }
22}
23
24// qr_solve() -- least-squares via Q^T multiply + back-substitution
25
26void qr_solve(const QRResult& f, const Vector& b, Vector& x) {
27 const idx m = f.Q.rows();
28 const idx n = f.R.cols();
29
30 Vector y(m, real(0));
31 for (idx i = 0; i < m; ++i)
32 for (idx j = 0; j < m; ++j)
33 y[i] += f.Q(j, i) * b[j];
34
35 Vector xv(n, real(0));
36 for (idx i = n; i-- > 0;) {
37 xv[i] = y[i];
38 for (idx j = i + 1; j < n; ++j)
39 xv[i] -= f.R(i, j) * xv[j];
40 xv[i] /= f.R(i, i);
41 }
42
43 x = std::move(xv);
44}
45
46} // namespace num
Dense row-major matrix with optional GPU storage.
Definition matrix.hpp:12
constexpr idx rows() const noexcept
Definition matrix.hpp:24
constexpr idx cols() const noexcept
Definition matrix.hpp:25
QRResult qr(const Matrix &A)
Definition qr.cpp:16
QRResult qr(const Matrix &A)
Definition qr.cpp:11
double real
Definition types.hpp:10
void qr_solve(const QRResult &f, const Vector &b, Vector &x)
Solve the least-squares problem min ||A*x - b||_2.
Definition qr.cpp:26
Backend
Selects which backend handles a linalg operation.
Definition policy.hpp:19
@ lapack
LAPACKE – industry-standard factorizations, SVD, eigen.
QRResult qr(const Matrix &A, Backend backend=lapack_backend)
QR factorization of an mxn matrix A (m >= n) via Householder reflections.
Definition qr.cpp:15
std::size_t idx
Definition types.hpp:11
QR factorization via Householder reflections.
Result of a QR factorization: A = Q * R.
Definition qr.hpp:18
Matrix R
mxn upper triangular
Definition qr.hpp:20
Matrix Q
mxm orthogonal
Definition qr.hpp:19