Momentum
A library for solving nonlinear optimization problems related to human body kinematics
Loading...
Searching...
No Matches
online_householder_qr.cpp
Go to the documentation of this file.
1/*
2 * Copyright (c) Meta Platforms, Inc. and affiliates.
3 *
4 * This source code is licensed under the MIT license found in the
5 * LICENSE file in the root directory of this source tree.
6 */
7
9
11
12namespace momentum {
13
14namespace {
15
16template <typename T>
17T sqr(T val) {
18 return val * val;
19}
20
21// Apply the Householder transformation H*y, where
22// H = (I - beta*v*v^T)
23// We use v_2m and y_2m to indicate that these vectors contain the
24// 2...m entries of the vector.
25//
26// Thus, the y vector is divided up:
27// y = [ y_1 y_2m... ]^T
28// and v is implicitly assumed to have 1 stored in its first entry,
29// v = [ 1 v_2m ]^T
30// Splitting v_1=1 out of storage saves one multiply per dot product and lets
31// computeHouseholderVec reuse the input column to store v_2m in place.
32template <typename T>
33void applyHouseholderTransformation(
34 T beta,
35 const Eigen::Ref<const Eigen::Matrix<T, Eigen::Dynamic, 1>>& v_2m,
36 T& y_1,
37 Eigen::Ref<Eigen::Matrix<T, Eigen::Dynamic, 1>> y_2m) {
38 MT_CHECK(v_2m.size() == y_2m.size());
39
40 // dotProd = v^T * y, exploiting v_1 = 1 implicitly.
41 const T dotProd = y_1 + v_2m.dot(y_2m);
42 const T scalar = dotProd * beta;
43
44 // y <- y - beta * v * (v^T * y)
45 y_1 -= scalar;
46 y_2m.noalias() -= scalar * v_2m;
47}
48
49// Apply the Householder transformation to columns [colStart, colEnd) of a
50// ColumnIndexedMatrix. Y_1 holds the leading row entries (full width); Y_2m
51// holds the trailing rows used to form v_2m.
52//
53// TODO: this currently only iterates column-by-column. The "Block" name and
54// the loop structure suggest that a true blocked variant (e.g. WY-form
55// updates) was intended but never implemented.
56template <typename T, typename MatrixType, typename RowType>
57void applyHouseholderTransformationBlock(
58 T beta,
59 const Eigen::Ref<const Eigen::Matrix<T, Eigen::Dynamic, 1>>& v_2m,
60 RowType Y_1,
62 Eigen::Index colStart,
63 Eigen::Index colEnd) {
64 [[maybe_unused]] const auto nCols = Y_2m.cols();
65 MT_CHECK(v_2m.rows() == Y_2m.rows());
66 MT_CHECK(colStart <= colEnd);
67 MT_CHECK(colEnd <= nCols);
68 MT_CHECK(Y_1.cols() == nCols);
69
70 [[maybe_unused]] const auto colIndices = Y_2m.columnIndices();
71 MT_CHECK(colIndices.empty() || colIndices.size() >= colEnd);
72 auto jCol = colStart;
73
74 while (jCol < colEnd) {
75 applyHouseholderTransformation<T>(beta, v_2m, Y_1(jCol), Y_2m.col(jCol));
76 ++jCol;
77 }
78}
79
80// Computes the Householder reflection vector for the column [x1 x2...xm]^T
81// (x1 is passed in separately because it comes from the R matrix rather than A).
82// Uses the stable algorithm from Golub and van Loan, "Matrix Computations" 4e,
83// Algorithm 5.1.1.
84// The result of applying the Householder transform (I - beta*v*v^T) is a vector of the form
85// [mu 0 0 0 ... 0]^T
86// Returns the pair [beta, mu]. Side effect: `vec` is overwritten in place with
87// v_2m (the implicit v_1 = 1 is not stored). Caller must treat `vec` as the
88// reflector vector after this call, not the original column data.
89//
90// Numerical-stability notes:
91// - When x1 > 0, computing v1 = x1 - mu would suffer cancellation
92// (mu ~ |x1| when sigma is small), so we use the algebraically-equivalent
93// -sigma / (x1 + mu) form. The x1 <= 0 branch is already cancellation-free.
94// - sigma == 0 means the trailing entries are exactly zero, so x1 already
95// sits in the [mu 0 ... 0] form; we return beta = 0 to signal "skip".
96// Callers must check beta == 0 before applying the transform; otherwise
97// `vec` would be divided by an undefined v1.
98// - mu has the sign opposite to v1 by construction, so the diagonal entry of
99// R may be negative. This is standard and downstream solves only depend on
100// R^T R, so the sign is irrelevant.
101template <typename T>
102std::pair<T, T> computeHouseholderVec(
103 T x1,
104 Eigen::Ref<Eigen::Matrix<T, Eigen::Dynamic, 1>>
105 vec) // NOLINT(facebook-hte-ConstantArgumentPassByValue)
106{
107 const T sigma = vec.squaredNorm();
108 if (sigma == 0) {
109 return {T(0), x1};
110 }
111
112 const T mu = std::sqrt(sqr(x1) + sigma);
113 const T v1 = (x1 <= 0) ? (x1 - mu) : (-sigma / (x1 + mu));
114 const T beta = T(2) * sqr(v1) / (sigma + sqr(v1));
115 vec /= v1;
116
117 return std::make_pair(beta, mu);
118}
119
120} // namespace
121
122template <typename T>
123OnlineHouseholderQR<T>::OnlineHouseholderQR(const Eigen::Index n, T lambda) {
124 reset(n, lambda);
125}
126
127template <typename T>
129 reset(R_.cols());
130}
131
132template <typename T>
133void OnlineHouseholderQR<T>::reset(const Eigen::Index n, T lambda) {
134 R_.resize(n, n);
135 R_.setZero();
136 if (lambda != 0) {
137 // Seed the diagonal with `lambda` so the first add() effectively appends
138 // a Tikhonov regularizer block (lambda*I, 0) to (A, b).
139 R_.diagonal().setConstant(lambda);
140 }
141
142 y_.resize(n);
143 y_.setZero();
144}
145
146// Definition of the public helper declared in online_householder_qr.h; called from
147// `ColumnIndexedMatrix`'s constructor and from a small number of tests.
148void validateColumnIndices(momentum::span<const Eigen::Index> colIndices, Eigen::Index maxEntry) {
149#ifndef NDEBUG
150 {
151 for (const auto& idx : colIndices) {
152 MT_CHECK(idx < maxEntry);
153 }
154
155 std::vector<Eigen::Index> colsCheckDups(std::begin(colIndices), std::end(colIndices));
156 std::sort(colsCheckDups.begin(), colsCheckDups.end());
157 MT_CHECK(std::unique(colsCheckDups.begin(), colsCheckDups.end()) == colsCheckDups.end());
158 }
159#else
160 (void)colIndices;
161 (void)maxEntry;
162#endif
163}
164
165template <typename T>
169
170template <typename T>
173 Eigen::Ref<VectorType> b) {
175
176 // Conceptually we form the stacked matrix [R; A] and reduce it back to upper
177 // triangular by sweeping a Householder reflector down each column. R already
178 // satisfies the upper-triangular invariant from prior calls, so for column
179 // iCol we only need to zero the new rows in A.col(iCol) below R_(iCol, iCol).
180 // Side effect: A and b are overwritten in place — A.col(iCol) is replaced
181 // with v_2m (the reflector for column iCol), and rhs entries are mixed into
182 // y_. Caller must not reuse A/b after this call.
183 const Eigen::Index n = R_.rows();
184 MT_CHECK(A.rows() == b.rows());
185 MT_CHECK(A.cols() == n);
186 for (Eigen::Index iCol = 0; iCol < n; ++iCol) {
187 // At this point, we have zeroed out all the columns to the
188 // left of iCol. The current matrix looks like this.
189 // iCol
190 // \|/
191 // [ r r r r ]
192 // [ 0 r r r ]
193 // [ 0 0 r r ]
194 // [ 0 0 0 r ]
195 // [ 0 0 0 0 ]
196 // [ ... ]
197 // [ 0 0 a a ]
198 // [ 0 0 a a ]
199 // We will apply a Householder reflection (I - beta*v*v^T) * A
200 // This will zero out the ith column.
201 const auto [beta, mu] = computeHouseholderVec<T>(R_(iCol, iCol), A.col(iCol));
202 if (beta == 0) {
203 // A.col(iCol) was already zero below R_(iCol,iCol); R is unchanged for
204 // this column and nothing needs to be applied to the trailing columns.
205 continue;
206 }
207
208 // computeHouseholderVec guarantees that applying the transform to iCol
209 // results in a vector [mu 0 ... 0].
210 R_(iCol, iCol) = mu;
211
212 // v2m aliases A.col(iCol), which now stores the reflector tail (see
213 // computeHouseholderVec side effect).
214 const auto& v2m = A.col(iCol);
215 for (Eigen::Index jCol = iCol + 1; jCol < n; ++jCol) {
216 applyHouseholderTransformation<T>(beta, v2m, R_(iCol, jCol), A.col(jCol));
217 }
218
219 applyHouseholderTransformation<T>(beta, v2m, y_(iCol), b);
220 }
221}
222
223template <typename T>
225 // We defined R and y as
226 // R = Q*A y = Q*b
227 // Therefore
228 // R^T*y = (Q*A)^T*(Q*b)
229 // = A^T * Q^T * Q * b =
230 // = A^T*b
231 return R_.transpose() * y_;
232}
233
234template <typename T>
236 // Note on rank deficiency: when `lambda == 0` and a column never received any contribution
237 // from `add()`, the corresponding diagonal of R is zero. The triangular back-substitution
238 // below then produces 0/0 for that row's update, which Eigen's TriangularView solver returns
239 // as 0 (rather than NaN) — this matches the documented "empty QR returns zero" behavior the
240 // existing tests rely on. Callers that need a meaningful solution under rank deficiency
241 // should construct with a non-zero `lambda` to add Tikhonov damping on the diagonal.
242 return R_.template triangularView<Eigen::Upper>().solve(y_);
243}
244
245template class OnlineHouseholderQR<float>;
246template class OnlineHouseholderQR<double>;
247
248template <typename T>
249OnlineBlockHouseholderQR<T>::OnlineBlockHouseholderQR(const Eigen::Index n_common, T lambda)
250 : lambda_(lambda),
251 R_nn_(MatrixType::Zero(n_common, n_common)),
252 y_n_(VectorType::Zero(n_common)) {
253 R_nn_.diagonal().setConstant(lambda);
254}
255
256template <typename T>
258 size_t iBlock,
261 Eigen::Ref<VectorType> b) {
262 const Eigen::Index n_diag = A_diag.cols();
263 const Eigen::Index n_common = R_nn_.cols();
264 MT_CHECK(A_diag.rows() == b.rows());
265 MT_CHECK(A_common.rows() == b.rows());
266 MT_CHECK(A_common.cols() == n_common);
267
268 while (R_ii_.size() <= iBlock) {
269 R_ii_.push_back(MatrixType());
270 }
271 while (y_i_.size() <= iBlock) {
272 y_i_.push_back(VectorType());
273 }
274 while (R_in_.size() <= iBlock) {
275 R_in_.push_back(MatrixType());
276 }
277
278 if (R_ii_[iBlock].rows() == 0) {
279 R_ii_[iBlock] = MatrixType::Zero(n_diag, n_diag);
280 R_ii_[iBlock].diagonal().setConstant(lambda_);
281
282 y_i_[iBlock] = VectorType::Zero(n_diag);
283
284 R_in_[iBlock] = MatrixType::Zero(n_diag, n_common);
285 } else {
286 MT_CHECK(R_ii_[iBlock].cols() == A_diag.cols());
287 MT_CHECK(y_i_[iBlock].rows() == A_diag.cols());
288 }
289
290 auto& R_ii = R_ii_[iBlock];
291 auto& y_i = y_i_[iBlock];
292 auto& R_in = R_in_[iBlock];
293 auto& R_nn = R_nn_;
294
295 // Phase 1: zero out the per-block diagonal columns A_diag. Each reflector
296 // also touches A_common (cross-block fill) so that the running R has the
297 // arrowhead structure [R_ii R_in; 0 R_nn].
298 for (Eigen::Index iCol = 0; iCol < n_diag; ++iCol) {
299 if (A_diag.col(iCol).isZero()) {
300 // Fast skip for empty Jacobian columns. Note that this is stricter than
301 // the beta == 0 check below: a column whose squared norm underflows to 0
302 // would be caught there too, but isZero() avoids the squaredNorm() cost.
303 continue;
304 }
305
306 // At this point, we have zeroed out all the columns to the
307 // left of iCol. The current matrix looks like this.
308 // iCol
309 // \|/
310 // [ r r r r ]
311 // [ 0 r r r ]
312 // [ 0 0 r r ]
313 // [ 0 0 0 r ]
314 // [ 0 0 0 0 ]
315 // [ ... ]
316 // [ 0 0 a a ]
317 // [ 0 0 a a ]
318 // We will apply a Householder reflection (I - beta*v*v^T) * A
319 // This will zero out the ith column.
320 const auto [beta, mu] = computeHouseholderVec<T>(R_ii(iCol, iCol), A_diag.col(iCol));
321 if (beta == 0) {
322 continue;
323 }
324
325 // computeHouseholderVec guarantees that applying the transform to iCol
326 // results in a vector [mu 0 ... 0].
327 R_ii(iCol, iCol) = mu;
328
329 const auto& v2m = A_diag.col(iCol);
330 if (iCol + 1 < n_diag) {
331 applyHouseholderTransformationBlock<T>(beta, v2m, R_ii.row(iCol), A_diag, iCol + 1, n_diag);
332 }
333
334 if (n_common > 0) {
335 // Couple the per-block rotation into the common columns; this is what
336 // lets the block solve later subtract R_in * x_n.
337 applyHouseholderTransformationBlock<T>(beta, v2m, R_in.row(iCol), A_common, 0, n_common);
338 }
339
340 applyHouseholderTransformation<T>(beta, v2m, y_i(iCol), b);
341 }
342
343 // Phase 2: with A_diag now zero in this block, fold the residual A_common
344 // and b into the shared (R_nn, y_n) tail. This is the same algorithm as
345 // OnlineHouseholderQR::addMutating but operating on the bottom-right block.
346 for (Eigen::Index iCol = 0; iCol < n_common; ++iCol) {
347 const auto [beta, mu] = computeHouseholderVec<T>(R_nn(iCol, iCol), A_common.col(iCol));
348 if (beta == 0) {
349 continue;
350 }
351
352 R_nn(iCol, iCol) = mu;
353
354 const auto& v2m = A_common.col(iCol);
355 for (Eigen::Index jCol_common = iCol + 1; jCol_common < n_common; ++jCol_common) {
356 applyHouseholderTransformation<T>(
357 beta, v2m, R_nn_(iCol, jCol_common), A_common.col(jCol_common));
358 }
359
360 applyHouseholderTransformation<T>(beta, v2m, y_n_(iCol), b);
361 }
362}
363
364template <typename T>
366 const auto nCol_common = R_nn_.cols();
367
368 Eigen::Index nCol_diag = 0;
369 for (const auto& R_ii : R_ii_) {
370 nCol_diag += R_ii.cols();
371 }
372
373 const Eigen::Index nCol_total = nCol_diag + nCol_common;
374
375 MatrixType result = MatrixType::Zero(nCol_total, nCol_total);
376 auto offset_cur = 0;
377 for (size_t iBlock = 0; iBlock < R_ii_.size(); ++iBlock) {
378 const auto& R_ii = R_ii_[iBlock];
379 const auto& R_in = R_in_[iBlock];
380 MT_CHECK(R_ii.rows() == R_in.rows());
381 MT_CHECK(R_in.cols() == nCol_common);
382 result.block(offset_cur, offset_cur, R_ii.rows(), R_ii.cols()) = R_ii;
383 result.block(offset_cur, nCol_diag, R_in.rows(), nCol_common) = R_in;
384 offset_cur += R_ii.rows();
385 }
386 result.block(offset_cur, offset_cur, nCol_common, nCol_common) = R_nn_;
387 return result;
388}
389
390template <typename T>
392 const auto nRow_common = y_n_.rows();
393
394 Eigen::Index nRow_diag = 0;
395 for (const auto& y_i : y_i_) {
396 nRow_diag += y_i.rows();
397 }
398
399 const Eigen::Index nRow_total = nRow_diag + nRow_common;
400
401 auto offset_cur = 0;
402 VectorType result = VectorType::Zero(nRow_total);
403 for (size_t iBlock = 0; iBlock < R_ii_.size(); ++iBlock) {
404 const auto& y_i = y_i_[iBlock];
405 result.segment(offset_cur, y_i.rows()) = y_i;
406 offset_cur += y_i.rows();
407 }
408
409 result.segment(offset_cur, nRow_common) = y_n_;
410 return result;
411}
412
413template <typename T>
415 // Solve the arrowhead system in two stages, exploiting that R has structure
416 // [R_ii R_in] [x_i] [y_i]
417 // [ 0 R_nn] [x_n] = [y_n]
418 // 1) Back-solve R_nn * x_n = y_n once for the shared parameters.
419 // 2) For each block: back-solve R_ii * x_i = y_i - R_in * x_n.
420 const auto nBlocks = R_ii_.size();
421 Eigen::Index nRows_diag = 0;
422 for (const auto& block : R_ii_) {
423 nRows_diag += block.cols();
424 }
425 const Eigen::Index nRows_common = R_nn_.cols();
426 const Eigen::Index nRows_total = nRows_diag + nRows_common;
427
428 VectorType result(nRows_total);
429 result.segment(nRows_diag, nRows_common) =
430 R_nn_.template triangularView<Eigen::Upper>().solve(y_n_);
431
432 const auto& x_n = result.segment(nRows_diag, nRows_common);
433 Eigen::Index offset = 0;
434 for (size_t i = 0; i < nBlocks; ++i) {
435 const auto nRows_cur = R_ii_[i].cols();
436 result.segment(offset, nRows_cur) =
437 R_ii_[i].template triangularView<Eigen::Upper>().solve(y_i_[i] - R_in_[i] * x_n);
438 offset += nRows_cur;
439 }
440
441 return result;
442}
443
444template <typename T>
446 return R_nn_.template triangularView<Eigen::Upper>().solve(y_n_);
447}
448
449template <typename T>
451 size_t iBlock) const {
452 return R_ii_[iBlock].template triangularView<Eigen::Upper>().solve(
453 y_i_[iBlock] - R_in_[iBlock] * (R_nn_.template triangularView<Eigen::Upper>().solve(y_n_)));
454}
455
456template <typename T>
458 size_t iBlock) const {
459 // A^T*b = R^T*y because Q is orthonormal (see OnlineHouseholderQR::At_times_b
460 // for the derivation). For block i this restricts to R_ii^T*y_i since R_ii
461 // is the only block that interacts with the per-block parameters.
462 return R_ii_[iBlock].transpose() * y_i_[iBlock];
463}
464
465template <typename T>
467 // For the common parameters every block contributes via its R_in coupling
468 // term, so we sum R_in_[i]^T * y_i_[i] across blocks alongside R_nn^T * y_n.
469 VectorType result = R_nn_.transpose() * y_n_;
470 for (size_t iBlock = 0; iBlock < R_ii_.size(); ++iBlock) {
471 result.noalias() += R_in_[iBlock].transpose() * y_i_[iBlock];
472 }
473 return result;
474}
475
476template <typename T>
478 const {
479 Eigen::Index nRows_total = y_n_.rows();
480 for (const auto& y_i : y_i_) {
481 nRows_total += y_i.rows();
482 }
483
484 VectorType result(nRows_total);
485 Eigen::Index offset = 0;
486 for (size_t iBlock = 0; iBlock < R_ii_.size(); ++iBlock) {
487 const auto nRows_cur = y_i_[iBlock].rows();
488 result.segment(offset, nRows_cur).noalias() = R_ii_[iBlock].transpose() * y_i_[iBlock];
489 offset += nRows_cur;
490 }
491
492 result.segment(offset, y_n_.rows()).noalias() = R_nn_.transpose() * y_n_;
493 for (size_t iBlock = 0; iBlock < R_ii_.size(); ++iBlock) {
494 result.segment(offset, y_n_.rows()).noalias() += R_in_[iBlock].transpose() * y_i_[iBlock];
495 }
496
497 return result;
498}
499
500template <typename T>
501T OnlineBlockHouseholderQR<T>::At_times_b_dot(Eigen::Ref<const VectorType> rhs) const {
502 return At_times_b_dense().dot(rhs);
503}
504
505template <typename T>
507 R_ii_.clear();
508 R_in_.clear();
509 y_i_.clear();
510
511 R_nn_.setZero();
512 R_nn_.diagonal().setConstant(lambda_);
513 y_n_.setZero();
514}
515
518
519template <typename T>
521 const Eigen::Index n_band,
522 Eigen::Index n_common,
523 const Eigen::Index bandwidth,
524 T lambda)
525 : lambda_(lambda),
526 R_common_{Eigen::MatrixX<T>::Zero(n_band + n_common, n_common)},
527 R_band_{Eigen::MatrixX<T>::Zero(bandwidth, n_band)},
528 y_{Eigen::VectorX<T>::Zero(n_band + n_common)} {
529 // R_band_ uses a packed banded layout: R_band_(i, j) stores the (i, j+k)
530 // entry of the dense R for some shift k determined by R_band_entry. Rows of
531 // the storage matrix correspond to diagonals (the last row is the main
532 // diagonal), columns correspond to the global column index.
533 //
534 // Bandwidth is only allowed to be zero if there are no parameters in the banded part,
535 // in which case it falls back to behaving the same as a regular Householder QR (for
536 // the common part).
537 MT_CHECK(n_band == 0 || bandwidth > 0);
538
539 initializeDiagonal();
540}
541
542template <typename T>
543void OnlineBandedHouseholderQR<T>::initializeDiagonal() {
544 // Seeds the Tikhonov regularizer lambda*I on R's diagonal in both storage
545 // layouts: the bottom-right square of R_common_ (regular dense storage), and
546 // the bottom row of R_band_ (which holds the main diagonal in banded
547 // storage).
548 const auto n_common = R_common_.cols();
549
550 if (n_common != 0) {
551 R_common_.bottomRightCorner(n_common, n_common).diagonal().setConstant(lambda_);
552 }
553
554 if (R_band_.rows() > 0 && R_band_.cols() > 0) {
555 R_band_.template bottomRows<1>().setConstant(lambda_);
556 }
557}
558
559template <typename T>
561 R_common_.setZero();
562 R_band_.setZero();
563 y_.setZero();
564
565 initializeDiagonal();
566}
567
568template <typename T>
570 const Eigen::Index iCol_offset,
573 Eigen::Ref<VectorType> b) {
574 zeroBandedPart(iCol_offset, A_band, A_common, b);
575 addMutating(A_common, b);
576}
577
578template <typename T>
580 const Eigen::Index iCol_offset,
583 Eigen::Ref<VectorType> b) {
584 const auto n_common = R_common_.cols();
585
586 // A_band.cols() bounds bandwidth because each new column can only fill in
587 // rows up to (bandwidth - 1) above its diagonal entry.
588 MT_CHECK(A_band.cols() <= R_band_.rows());
589 MT_CHECK(iCol_offset + A_band.cols() <= R_band_.cols());
590
591 MT_CHECK(A_band.rows() == b.rows());
592 MT_CHECK(A_common.rows() == b.rows());
593 MT_CHECK(A_common.cols() == n_common);
594
595 for (Eigen::Index iCol_local = 0; iCol_local < A_band.cols(); ++iCol_local) {
596 const Eigen::Index iCol_global = iCol_local + iCol_offset;
597
598 // At this point, we have zeroed out all the columns to the
599 // left of iCol. The current matrix looks like this.
600 // iCol
601 // \|/
602 // [ r r r r ]
603 // [ 0 r r r ]
604 // [ 0 0 r r ]
605 // [ 0 0 0 r ]
606 // [ 0 0 0 0 ]
607 // [ ... ]
608 // [ 0 0 a a ]
609 // [ 0 0 a a ]
610 // We will apply a Householder reflection (I - beta*v*v^T) * A
611 // This will zero out the ith column.
612 const auto [beta, mu] =
613 computeHouseholderVec<T>(R_band_entry(iCol_global, iCol_global), A_band.col(iCol_local));
614 if (beta == 0) {
615 continue;
616 }
617
618 // computeHouseholderVec guarantees that applying the transform to iCol
619 // results in a vector [mu 0 ... 0].
620 R_band_entry(iCol_global, iCol_global) = mu;
621
622 const auto& v2m = A_band.col(iCol_local);
623
624 // R_band_ uses packed banded storage, so its row(iCol_global) cannot be
625 // expressed as a contiguous Eigen row expression — we must address each
626 // (iCol_global, jCol_global) entry individually via R_band_entry.
627 for (Eigen::Index jCol_local = iCol_local + 1; jCol_local < A_band.cols(); ++jCol_local) {
628 const auto jCol_global = jCol_local + iCol_offset;
629 applyHouseholderTransformation<T>(
630 beta, v2m, R_band_entry(iCol_global, jCol_global), A_band.col(jCol_local));
631 }
632
633 // R_common_ is a dense matrix, so the block-friendly helper applies.
634 if (n_common > 0) {
635 applyHouseholderTransformationBlock<T>(
636 beta, v2m, R_common_.row(iCol_global), A_common, 0, n_common);
637 }
638
639 applyHouseholderTransformation<T>(beta, v2m, y_(iCol_global), b);
640 }
641}
642
643template <typename T>
646 Eigen::Ref<VectorType> b) {
647 // Reduce A_common into the bottom-right (n_common x n_common) block of
648 // R_common_. R_common_ stores the common columns of R as a dense matrix
649 // whose top n_band rows hold the cross-coupling against the banded part;
650 // the diagonal of R_common itself begins at row n_band, which is why every
651 // row index below is shifted by n_band.
652 const auto n_common = R_common_.cols();
653 const auto n_band = R_band_.cols();
654
655 MT_CHECK(A_common.rows() == b.rows());
656 MT_CHECK(A_common.cols() == n_common);
657
658 for (Eigen::Index iCol = 0; iCol < n_common; ++iCol) {
659 const auto [beta, mu] =
660 computeHouseholderVec<T>(R_common_(iCol + n_band, iCol), A_common.col(iCol));
661 if (beta == 0) {
662 continue;
663 }
664
665 R_common_(iCol + n_band, iCol) = mu;
666
667 const auto& v2m = A_common.col(iCol);
668 for (Eigen::Index jCol_common = iCol + 1; jCol_common < n_common; ++jCol_common) {
669 applyHouseholderTransformation<T>(
670 beta, v2m, R_common_(iCol + n_band, jCol_common), A_common.col(jCol_common));
671 }
672
673 applyHouseholderTransformation<T>(beta, v2m, y_(n_band + iCol), b);
674 }
675}
676
677template <typename T>
679 // Unpack the banded + common storage into a single dense upper-triangular
680 // matrix. Row of the dense result corresponds to a row of R; the banded
681 // block occupies rows/cols [0, n_band) and the common block occupies
682 // [n_band, n_band+n_common).
683 const auto n_common = R_common_.cols();
684 const auto n_band = R_band_.cols();
685 const auto bandwidth = R_band_.rows();
686
687 const auto n_total = n_band + n_common;
688
689 MatrixType result = MatrixType::Zero(n_total, n_total);
690
691 // Walk each banded column upward at most `bandwidth` rows; rows above are
692 // structurally zero in band storage.
693 for (Eigen::Index iCol_band = 0; iCol_band < n_band; ++iCol_band) {
694 for (Eigen::Index jRow = iCol_band; (iCol_band - jRow) < bandwidth && jRow >= 0; --jRow) {
695 result(jRow, iCol_band) = R_band_entry(jRow, iCol_band);
696 }
697 }
698
699 for (Eigen::Index jRow = 0; jRow < n_total; ++jRow) {
700 for (Eigen::Index iCol_common = 0; iCol_common < n_common; ++iCol_common) {
701 result(jRow, n_band + iCol_common) = R_common_(jRow, iCol_common);
702 }
703 }
704
705 return result;
706}
707
708template <typename T>
710 // Two-stage back-substitution analogous to OnlineBlockHouseholderQR::x_dense:
711 // 1) Solve the dense common block first to obtain x_n.
712 // 2) Sweep the banded block from bottom to top, subtracting R_in coupling
713 // via R_common_.row(iRow).dot(x_n) and the in-band tail via R_band_entry.
714 // The inner loop's bandwidth_cur clamp avoids reading past the rightmost
715 // banded column (n_band - 1).
716 VectorType result = VectorType::Zero(R_band_.cols() + R_common_.cols());
717
718 const auto n_common = R_common_.cols();
719 const auto n_band = R_band_.cols();
720 const auto bandwidth = R_band_.rows();
721
722 if (n_common > 0) {
723 result.tail(n_common) =
724 R_common_.bottomRows(n_common).template triangularView<Eigen::Upper>().solve(
725 y_.tail(n_common));
726 }
727
728 if (n_band > 0) {
729 // Note on rank deficiency: when `lambda == 0` and a column never received any contribution,
730 // the corresponding banded diagonal entry is zero. We pin that row's result to 0 instead of
731 // dividing — the same observable behavior as the dense `OnlineHouseholderQR::result` path,
732 // and what the existing edge-case tests rely on (an empty / zero-bandwidth solver returns
733 // a zero vector). Callers wanting a meaningful damped solution under genuine rank
734 // deficiency should construct with a non-zero `lambda`.
735 for (Eigen::Index iRow = n_band - 1; iRow >= 0; --iRow) {
736 const T diag = R_band_entry(iRow, iRow);
737 if (diag == T(0)) {
738 result(iRow) = T(0);
739 continue;
740 }
741
742 T dotProd = n_common > 0 ? R_common_.row(iRow).dot(result.tail(n_common)) : T(0);
743
744 const Eigen::Index bandwidth_cur = std::min(bandwidth, n_band - iRow);
745 for (Eigen::Index jColOffset = 1; jColOffset < bandwidth_cur; ++jColOffset) {
746 dotProd += R_band_entry(iRow, iRow + jColOffset) * result(iRow + jColOffset);
747 }
748 result(iRow) = (y_(iRow) - dotProd) / diag;
749 }
750 }
751
752 return result;
753}
754
755template <typename T>
757 // A^T*b = R^T*y (Q is orthonormal). Computed by accumulating column sums:
758 // each row iRow of R contributes R(iRow, jCol)*y(iRow) into result(jCol).
759 // The banded loop walks only the in-band entries; the common columns are
760 // dense and folded in by the final R_common_.transpose() * y_.
761 VectorType result = VectorType::Zero(R_band_.cols() + R_common_.cols());
762
763 const auto n_common = R_common_.cols();
764 const auto n_band = R_band_.cols();
765 const auto bandwidth = R_band_.rows();
766
767 for (Eigen::Index iRow = 0; iRow < n_band; ++iRow) {
768 const Eigen::Index bandwidth_cur = std::min(bandwidth, n_band - iRow);
769 for (Eigen::Index jColOffset = 0; jColOffset < bandwidth_cur; ++jColOffset) {
770 const Eigen::Index jCol = iRow + jColOffset;
771 result(jCol) += R_band_entry(iRow, jCol) * y_(iRow);
772 }
773 }
774
775 result.tail(n_common).noalias() = R_common_.transpose() * y_;
776
777 return result;
778}
779
782
783} // namespace momentum
#define MT_CHECK(condition,...)
Runtime check macros with two interchangeable backends:
Definition checks.h:36
View over a matrix that exposes a (possibly reordered) subset of its columns.
auto col(Eigen::Index colIdx)
Online Householder QR solver for band-plus-arrowhead matrices.
Eigen::Matrix< T, Eigen::Dynamic, 1 > VectorType
VectorType x_dense() const
Retrieves the full dense result vector of length n_band() + n_common().
Eigen::Matrix< T, Eigen::Dynamic, Eigen::Dynamic > MatrixType
void zeroBandedPart(Eigen::Index iCol_offset, ColumnIndexedMatrix< MatrixType > A_band, ColumnIndexedMatrix< MatrixType > A_common, Eigen::Ref< VectorType > b)
Zeros out just the banded part of A_band by applying Householder rotations.
void addMutating(const Eigen::Index iCol_offset, Eigen::Ref< MatrixType > A_band, Eigen::Ref< MatrixType > A_common, Eigen::Ref< VectorType > b)
In-place addition; convenience wrapper that wraps the matrices in ColumnIndexedMatrix views without r...
void reset()
Discards accumulated state, keeping the existing dimensions and damping.
OnlineBandedHouseholderQR(Eigen::Index n_band, Eigen::Index n_common, Eigen::Index bandwidth, T lambda=T(0))
Constructs a banded solver.
Online Householder QR solver for least-squares problems with block-arrowhead structure.
VectorType x_i(size_t iBlock) const
Retrieves the answer for a single diagonal block iBlock.
VectorType x_n() const
Retrieves the answer for just the final "common" rows.
OnlineBlockHouseholderQR(Eigen::Index n_common, T lambda=T(0))
Constructs a solver for problems with n_common shared unknowns.
const MatrixType & R_ii(size_t iBlock) const
VectorType x_dense() const
Retrieves the full dense result [x_0; x_1; ...; x_{B-1}; x_n].
T At_times_b_dot(Eigen::Ref< const VectorType > rhs) const
void addMutating(size_t iBlock, Eigen::Ref< MatrixType > A_diag, Eigen::Ref< MatrixType > A_common, Eigen::Ref< VectorType > b)
In-place addition; convenience wrapper that wraps the matrices in ColumnIndexedMatrix views without r...
const VectorType & y_i(size_t iBlock) const
Eigen::Matrix< T, Eigen::Dynamic, 1 > VectorType
Eigen::Matrix< T, Eigen::Dynamic, Eigen::Dynamic > MatrixType
VectorType At_times_b_i(size_t iBlock) const
Online (incremental) Householder QR solver for tall, column-sparse least-squares problems.
void reset()
Discards accumulated state, keeping the existing n and lambda.
Eigen::Matrix< T, Eigen::Dynamic, 1 > VectorType
Eigen::Matrix< T, Eigen::Dynamic, Eigen::Dynamic > MatrixType
void add(MatrixType A, VectorType b)
Copying overload of addMutating().
OnlineHouseholderQR(Eigen::Index n, T lambda=T(0))
Constructs a solver for problems with n unknowns.
VectorType result() const
Solves R * x = y by back-substitution using the currently accumulated state and returns x.
void addMutating(Eigen::Ref< MatrixType > A, Eigen::Ref< VectorType > b)
In-place overload: factorizes A and b directly, mutating both buffers.
Definition types.h:28
void validateColumnIndices(momentum::span< const Eigen::Index > colIndices, Eigen::Index maxEntry)
Validates that every entry in colIndices is in [0, maxEntry); throws otherwise.
Eigen::Matrix< T, Dynamic, Dynamic > MatrixX
Dynamic-size, column-major dense matrix.
Definition types.h:80
Vector< T, Dynamic > VectorX
Dynamic-size column vector. Common return type for solver residuals and parameter vectors.
Definition types.h:207
T sqr(const T &x)
Computes the square of a value.
Definition utility.h:47
gsl::span< T > span
Span type alias using gsl::span (C++17 fallback).
Definition span_compat.h:54
Profiling macros that dispatch to one of three backends, selected at compile time:
#define MT_PROFILE_FUNCTION()
Definition profile.h:110