quala 0.0.1a1
Quasi-Newton and other accelerators
limited-memory-qr.hpp
Go to the documentation of this file.
1#include <Eigen/Jacobi>
2#include <cstddef>
4#include <quala/util/vec.hpp>
5#include <type_traits>
6
7namespace quala {
8
9/// Incremental QR factorization using modified Gram-Schmidt with
10/// reorthogonalization.
11///
12/// Computes A = QR while allowing efficient removal of the first
13/// column of A or adding new columns at the end of A.
15 public:
16 LimitedMemoryQR() = default;
17
18 /// @param n
19 /// The size of the vectors, the number of rows of A.
20 /// @param m
21 /// The maximum number of columns of A.
22 ///
23 /// The maximum dimensions of Q are n×m and the maximum dimensions of R are
24 /// m×m.
26
27 length_t n() const { return Q.rows(); }
28 length_t m() const { return Q.cols(); }
29 length_t size() const { return n(); }
30 length_t history() const { return m(); }
31
32 /// Add the given column to the right.
33 template <class VecV>
34 void add_column(const VecV &v) {
35 assert(q_idx < m());
36
37 auto q = Q.col(q_idx);
38 auto r = R.col(r_idx_end);
39
40 // Modified Gram-Schmidt to make q orthogonal to Q
41 q = v;
42 for (index_t i = 0; i < q_idx; ++i) {
43 real_t s = Q.col(i).dot(q);
44 r(i) = s;
45 q -= s * Q.col(i);
46 }
47
48 // Compute the norms of orthogonalized q and original v
49 real_t norm_q = q.norm();
50 real_t norm_v = v.norm();
51
52 // If ‖q‖ is significantly smaller than ‖v‖, perform
53 // reorthogonalization
54 real_t η = 0.7;
55 while (norm_q < η * norm_v) {
57 for (index_t i = 0; i < q_idx; ++i) {
58 real_t s = Q.col(i).dot(q);
59 r(i) += s;
60 q -= s * Q.col(i);
61 }
62 norm_v = norm_q;
63 norm_q = q.norm();
64 }
65
66 // Normalize q such that new matrix (Q q) remains orthogonal (i.e. has
67 // orthonormal columns)
68 r(q_idx) = norm_q;
69 q /= norm_q;
70
71 // Increment indices, add a column to Q and R.
72 ++q_idx;
74 }
75
76 /// Remove the leftmost column.
78 assert(q_idx > 0);
79
80 // After removing the first colomn of the upper triangular matrix R,
81 // it becomes upper Hessenberg. Givens rotations are used to make it
82 // triangular again.
83 Eigen::JacobiRotation<real_t> G;
84 index_t r = 0; // row index of R
85 index_t c = r_succ(r_idx_start); // column index of R in storage
86 while (r < q_idx - 1) {
87 // Compute the Givens rotation that makes the subdiagonal element
88 // of column c or R zero.
89 G.makeGivens(R(r, c), R(r + 1, c), &R(r, c));
90 // Apply it to the remaining columns of R.
91 // Not the current column, because the diagonal element was updated
92 // by the makeGivens function, and the subdiagonal element doesn't
93 // have to be set to zero explicitly, it's implicit.
94 // Also not the previous columns, because they are already
95 // implicitly zero below the diagonal and this rotation wouldn't
96 // have any effect there.
97 // TODO: can this be sped up by applying it in two blocks instead
98 // of column by column?
99 for (index_t cc = r_succ(c); cc != r_idx_end; cc = r_succ(cc))
100 R.col(cc).applyOnTheLeft(r, r + 1, G.adjoint());
101 // Apply the inverse of the Givens rotation to Q.
102 Q.block(0, 0, Q.rows(), q_idx).applyOnTheRight(r, r + 1, G);
103 // Advance indices to next diagonal element of R.
104 ++r;
105 c = r_succ(c);
106 }
107 // Remove rightmost column of Q, since it corresponds to the bottom row
108 // of R, which was set to zero by the Givens rotations
109 --q_idx;
110 // Remove the first column of R.
112 }
113
114 /// Solve the least squares problem Ax = b.
115 template <class VecB, class VecX>
116 void solve_col(const VecB &b, VecX &x) const {
117 // Iterate over the diagonal of R, starting at the bottom right,
118 // this is standard back substitution
119 // (recall that R is stored in a circular buffer, so R.col(i) is
120 // not the mathematical i-th column)
121 auto rev_bgn = ring_reverse_iter().begin();
122 auto rev_end = ring_reverse_iter().end();
123 auto fwd_end = ring_iter().end();
124 for (auto it_d = rev_bgn; it_d != rev_end; ++it_d) {
125 // Row/column index of diagonal element of R
126 auto [rR, cR] = *it_d;
127 // (r is the zero-based mathematical index, c is the index in
128 // the circular buffer)
129 x(rR) = Q.col(rR).transpose() * b; // Compute rhs Qᵀb
130 // In the current row of R, iterate over the elements to the
131 // right of the diagonal
132 // Iterating from left to right seems to give better results
133 for (auto it_c = it_d.forwardit; it_c != fwd_end; ++it_c) {
134 auto [rX2, cR2] = *it_c;
135 x(rR) -= R(rR, cR2) * x(rX2);
136 }
137 x(rR) /= R(rR, cR); // Divide by diagonal element
138 }
139 }
140
141 /// Solve the least squares problem AX = B.
142 template <class MatB, class MatX>
143 void solve(const MatB &B, MatX &X) const {
144 assert(B.cols() <= X.cols());
145 assert(B.rows() >= Q.rows());
146 assert(X.rows() >= Eigen::Index(num_columns()));
147 // Each column of the right hand side is solved as an individual system
148 for (Eigen::Index cB = 0; cB < B.cols(); ++cB) {
149 auto b = B.col(cB);
150 auto x = X.col(cB);
151 solve_col(b, x);
152 }
153 }
154
155 template <class Derived>
156 using solve_ret_t = std::conditional_t<
157 Eigen::internal::traits<Derived>::ColsAtCompileTime == 1, vec, mat>;
158
159 /// Solve the least squares problem AX = B.
160 template <class Derived>
161 solve_ret_t<Derived> solve(const Eigen::DenseBase<Derived> &B) {
162 solve_ret_t<Derived> X(m(), B.cols());
163 solve(B, X);
164 return X;
165 }
166
167 /// Get the full, raw storage for the orthogonal matrix Q.
168 const mat &get_raw_Q() const { return Q; }
169 /// Get the full, raw storage for the upper triangular matrix R.
170 /// The columns of this matrix are permuted because it's stored as a
171 /// circular buffer for efficiently appending columns to the end and
172 /// popping columns from the front.
173 const mat &get_raw_R() const { return R; }
174
175 /// Get the full storage for the upper triangular matrix R but with the
176 /// columns in the correct order.
177 /// @note Meant for tests only, creates a permuted copy.
178 mat get_full_R() const {
179 if (r_idx_start == 0)
180 return R;
181 // Using a permutation matrix here isn't as efficient as rotating the
182 // matrix manually, but this function is only used in tests, so it
183 // shouldn't matter.
184 Eigen::PermutationMatrix<Eigen::Dynamic> P(R.cols());
185 P.setIdentity();
186 std::rotate(P.indices().data(), P.indices().data() + r_idx_start,
187 P.indices().data() + P.size());
188 return R * P;
189 }
190 /// Get the matrix R such that Q times R is the original matrix.
191 /// @note Meant for tests only, creates a permuted copy.
192 mat get_R() const {
193 return get_full_R()
194 .block(0, 0, q_idx, q_idx)
195 .triangularView<Eigen::Upper>();
196 }
197 /// Get the matrix Q such that Q times R is the original matrix.
198 /// @note Meant for tests only, creates a copy.
199 mat get_Q() const { return Q.block(0, 0, n(), q_idx); }
200
201 /// Multiply the matrix R by a scalar.
202 void scale_R(real_t scal) {
203 for (auto [i, r_idx] : ring_iter())
204 R.col(r_idx).topRows(i + 1) *= scal;
205 }
206
207 /// Get the number of MGS reorthogonalizations.
208 unsigned long get_reorth_count() const { return reorth_count; }
209 /// Reset the number of MGS reorthogonalizations.
211
212 /// Reset all indices, clearing the Q and R matrices.
213 void reset() {
214 q_idx = 0;
215 r_idx_start = 0;
216 r_idx_end = 0;
217 reorth_count = 0;
218 }
219
220 /// Re-allocate storage for a problem with a different size. Causes
221 /// a @ref reset.
223 Q.resize(n, m);
224 R.resize(m, m);
225 reset();
226 }
227
228 /// Get the number of columns that are currently stored.
229 length_t num_columns() const { return q_idx; }
230 /// Get the head index of the circular buffer (points to the oldest
231 /// element).
232 index_t ring_head() const { return r_idx_start; }
233 /// Get the tail index of the circular buffer (points to one past the most
234 /// recent element).
235 index_t ring_tail() const { return r_idx_end; }
236 /// Get the next index in the circular buffer.
237 index_t ring_next(index_t i) const { return r_succ(i); }
238 /// Get the previous index in the circular buffer.
239 index_t ring_prev(index_t i) const { return r_pred(i); }
240 /// Get the number of columns currently stored in the buffer.
241 length_t current_history() const { return q_idx; }
242
243 /// Get iterators in the circular buffer.
245 return {q_idx, r_idx_start, r_idx_end, m()};
246 }
247 /// Get reverse iterators in the circular buffer.
249 return ring_iter();
250 }
251
252 private:
253 mat Q; ///< Storage for orthogonal factor Q.
254 mat R; ///< Storage for upper triangular factor R.
255
256 index_t q_idx = 0; ///< Number of columns of Q being stored.
257 index_t r_idx_start = 0; ///< Index of the first column of R.
258 index_t r_idx_end = 0; ///< Index of the one-past-last column of R.
259
260 unsigned long reorth_count = 0; ///< Number of MGS reorthogonalizations.
261
262 /// Get the next index in the circular storage for R.
263 index_t r_succ(index_t i) const { return i + 1 < m() ? i + 1 : 0; }
264 /// Get the previous index in the circular storage for R.
265 index_t r_pred(index_t i) const { return i == 0 ? m() - 1 : i - 1; }
266};
267
268} // namespace quala
Incremental QR factorization using modified Gram-Schmidt with reorthogonalization.
mat R
Storage for upper triangular factor R.
index_t r_idx_start
Index of the first column of R.
CircularRange< index_t > ring_iter() const
Get iterators in the circular buffer.
mat Q
Storage for orthogonal factor Q.
LimitedMemoryQR(length_t n, length_t m)
length_t num_columns() const
Get the number of columns that are currently stored.
mat get_Q() const
Get the matrix Q such that Q times R is the original matrix.
length_t current_history() const
Get the number of columns currently stored in the buffer.
unsigned long reorth_count
Number of MGS reorthogonalizations.
void remove_column()
Remove the leftmost column.
mat get_R() const
Get the matrix R such that Q times R is the original matrix.
index_t q_idx
Number of columns of Q being stored.
index_t r_pred(index_t i) const
Get the previous index in the circular storage for R.
void add_column(const VecV &v)
Add the given column to the right.
solve_ret_t< Derived > solve(const Eigen::DenseBase< Derived > &B)
Solve the least squares problem AX = B.
void solve_col(const VecB &b, VecX &x) const
Solve the least squares problem Ax = b.
void clear_reorth_count()
Reset the number of MGS reorthogonalizations.
index_t ring_tail() const
Get the tail index of the circular buffer (points to one past the most recent element).
void solve(const MatB &B, MatX &X) const
Solve the least squares problem AX = B.
index_t r_succ(index_t i) const
Get the next index in the circular storage for R.
std::conditional_t< Eigen::internal::traits< Derived >::ColsAtCompileTime==1, vec, mat > solve_ret_t
index_t ring_prev(index_t i) const
Get the previous index in the circular buffer.
index_t ring_head() const
Get the head index of the circular buffer (points to the oldest element).
const mat & get_raw_Q() const
Get the full, raw storage for the orthogonal matrix Q.
const mat & get_raw_R() const
Get the full, raw storage for the upper triangular matrix R.
void resize(length_t n, length_t m)
Re-allocate storage for a problem with a different size.
void reset()
Reset all indices, clearing the Q and R matrices.
index_t ring_next(index_t i) const
Get the next index in the circular buffer.
unsigned long get_reorth_count() const
Get the number of MGS reorthogonalizations.
void scale_R(real_t scal)
Multiply the matrix R by a scalar.
ReverseCircularRange< index_t > ring_reverse_iter() const
Get reverse iterators in the circular buffer.
mat get_full_R() const
Get the full storage for the upper triangular matrix R but with the columns in the correct order.
index_t r_idx_end
Index of the one-past-last column of R.
realmat mat
Default type for matrices.
Definition: vec.hpp:20
index_t length_t
Default type for vector sizes.
Definition: vec.hpp:29
realvec vec
Default type for vectors.
Definition: vec.hpp:14
Eigen::Index index_t
Default type for vector indices.
Definition: vec.hpp:27
double real_t
Default floating point type.
Definition: vec.hpp:8