numerics 0.1.0
Loading...
Searching...
No Matches
qr.cpp
Go to the documentation of this file.
1/// @file linalg/factorization/backends/lapack/qr.cpp
2/// @brief LAPACK QR factorization via LAPACKE_dgeqrf + LAPACKE_dorgqr.
3#include "../seq/impl.hpp"
4#include "impl.hpp"
5#include <algorithm>
6#include <stdexcept>
7#include <string>
8#include <vector>
9
10#if defined(NUMERICS_HAS_LAPACK)
11#include <lapacke.h>
12#endif
13
14namespace num::backends::lapack {
15
16QRResult qr(const Matrix &A) {
17#if defined(NUMERICS_HAS_LAPACK)
18 const idx m = A.rows(), n = A.cols();
19 const idx k = std::min(m, n);
20
21 Matrix R = A;
22 std::vector<double> tau(k);
23
24 int info =
25 LAPACKE_dgeqrf(LAPACK_ROW_MAJOR, static_cast<lapack_int>(m),
26 static_cast<lapack_int>(n), R.data(),
27 static_cast<lapack_int>(n), // lda = cols (row-major)
28 tau.data());
29 if (info != 0)
30 throw std::runtime_error("qr (lapack): dgeqrf failed, info=" +
31 std::to_string(info));
32
33 // Extract upper triangle as R
34 Matrix Rmat = R;
35 for (idx i = 1; i < m; ++i)
36 for (idx j = 0; j < std::min(i, n); ++j)
37 Rmat(i, j) = 0.0;
38
39 // Build full Q from stored reflectors via dorgqr
40 Matrix Q(m, m, 0.0);
41 for (idx j = 0; j < k; ++j)
42 for (idx i = 0; i < m; ++i)
43 Q(i, j) = R(i, j);
44
45 info = LAPACKE_dorgqr(LAPACK_ROW_MAJOR, static_cast<lapack_int>(m),
46 static_cast<lapack_int>(m), static_cast<lapack_int>(k),
47 Q.data(),
48 static_cast<lapack_int>(m), // lda = cols = m (square)
49 tau.data());
50 if (info != 0)
51 throw std::runtime_error("qr (lapack): dorgqr failed, info=" +
52 std::to_string(info));
53
54 return {std::move(Q), std::move(Rmat)};
55#else
56 return seq::qr(A);
57#endif
58}
59
60} // namespace num::backends::lapack
Dense row-major matrix with optional GPU storage.
Definition matrix.hpp:12
real * data()
Definition matrix.hpp:28
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
std::size_t idx
Definition types.hpp:11
std::experimental::simd butterfly for FFT.
Result of a QR factorization: A = Q * R.
Definition qr.hpp:18