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 = LAPACKE_dgeqrf(LAPACK_ROW_MAJOR,
25 static_cast<lapack_int>(m),
26 static_cast<lapack_int>(n),
27 R.data(),
28 static_cast<lapack_int>(n), // lda = cols (row-major)
29 tau.data());
30 if (info != 0)
31 throw std::runtime_error("qr (lapack): dgeqrf failed, info="
32 + std::to_string(info));
33
34 // Extract upper triangle as R
35 Matrix Rmat = R;
36 for (idx i = 1; i < m; ++i)
37 for (idx j = 0; j < std::min(i, n); ++j)
38 Rmat(i, j) = 0.0;
39
40 // Build full Q from stored reflectors via dorgqr
41 Matrix Q(m, m, 0.0);
42 for (idx j = 0; j < k; ++j)
43 for (idx i = 0; i < m; ++i)
44 Q(i, j) = R(i, j);
45
46 info = LAPACKE_dorgqr(LAPACK_ROW_MAJOR,
47 static_cast<lapack_int>(m),
48 static_cast<lapack_int>(m),
49 static_cast<lapack_int>(k),
50 Q.data(),
51 static_cast<lapack_int>(m), // lda = cols = m (square)
52 tau.data());
53 if (info != 0)
54 throw std::runtime_error("qr (lapack): dorgqr failed, info="
55 + std::to_string(info));
56
57 return {std::move(Q), std::move(Rmat)};
58#else
59 return seq::qr(A);
60#endif
61}
62
63} // namespace num::backends::lapack
constexpr idx rows() const noexcept
Definition matrix.hpp:87
constexpr idx cols() const noexcept
Definition matrix.hpp:88
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.
QR factorization .
Definition qr.hpp:11