schur_eliminator.h 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630
  1. // Ceres Solver - A fast non-linear least squares minimizer
  2. // Copyright 2019 Google Inc. All rights reserved.
  3. // http://ceres-solver.org/
  4. //
  5. // Redistribution and use in source and binary forms, with or without
  6. // modification, are permitted provided that the following conditions are met:
  7. //
  8. // * Redistributions of source code must retain the above copyright notice,
  9. // this list of conditions and the following disclaimer.
  10. // * Redistributions in binary form must reproduce the above copyright notice,
  11. // this list of conditions and the following disclaimer in the documentation
  12. // and/or other materials provided with the distribution.
  13. // * Neither the name of Google Inc. nor the names of its contributors may be
  14. // used to endorse or promote products derived from this software without
  15. // specific prior written permission.
  16. //
  17. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  18. // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  19. // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  20. // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
  21. // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
  22. // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
  23. // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
  24. // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
  25. // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  26. // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
  27. // POSSIBILITY OF SUCH DAMAGE.
  28. //
  29. // Author: sameeragarwal@google.com (Sameer Agarwal)
  30. #ifndef CERES_INTERNAL_SCHUR_ELIMINATOR_H_
  31. #define CERES_INTERNAL_SCHUR_ELIMINATOR_H_
  32. #include <map>
  33. #include <memory>
  34. #include <mutex>
  35. #include <vector>
  36. #include "Eigen/Dense"
  37. #include "ceres/block_random_access_matrix.h"
  38. #include "ceres/block_sparse_matrix.h"
  39. #include "ceres/block_structure.h"
  40. #include "ceres/internal/config.h"
  41. #include "ceres/internal/disable_warnings.h"
  42. #include "ceres/internal/eigen.h"
  43. #include "ceres/internal/export.h"
  44. #include "ceres/linear_solver.h"
  45. namespace ceres::internal {
  46. // Classes implementing the SchurEliminatorBase interface implement
  47. // variable elimination for linear least squares problems. Assuming
  48. // that the input linear system Ax = b can be partitioned into
  49. //
  50. // E y + F z = b
  51. //
  52. // Where x = [y;z] is a partition of the variables. The partitioning
  53. // of the variables is such that, E'E is a block diagonal matrix. Or
  54. // in other words, the parameter blocks in E form an independent set
  55. // of the graph implied by the block matrix A'A. Then, this class
  56. // provides the functionality to compute the Schur complement system
  57. //
  58. // S z = r
  59. //
  60. // where
  61. //
  62. // S = F'F - F'E (E'E)^{-1} E'F and r = F'b - F'E(E'E)^(-1) E'b
  63. //
  64. // This is the Eliminate operation, i.e., construct the linear system
  65. // obtained by eliminating the variables in E.
  66. //
  67. // The eliminator also provides the reverse functionality, i.e. given
  68. // values for z it can back substitute for the values of y, by solving the
  69. // linear system
  70. //
  71. // Ey = b - F z
  72. //
  73. // which is done by observing that
  74. //
  75. // y = (E'E)^(-1) [E'b - E'F z]
  76. //
  77. // The eliminator has a number of requirements.
  78. //
  79. // The rows of A are ordered so that for every variable block in y,
  80. // all the rows containing that variable block occur as a vertically
  81. // contiguous block. i.e the matrix A looks like
  82. //
  83. // E F chunk
  84. // A = [ y1 0 0 0 | z1 0 0 0 z5] 1
  85. // [ y1 0 0 0 | z1 z2 0 0 0] 1
  86. // [ 0 y2 0 0 | 0 0 z3 0 0] 2
  87. // [ 0 0 y3 0 | z1 z2 z3 z4 z5] 3
  88. // [ 0 0 y3 0 | z1 0 0 0 z5] 3
  89. // [ 0 0 0 y4 | 0 0 0 0 z5] 4
  90. // [ 0 0 0 y4 | 0 z2 0 0 0] 4
  91. // [ 0 0 0 y4 | 0 0 0 0 0] 4
  92. // [ 0 0 0 0 | z1 0 0 0 0] non chunk blocks
  93. // [ 0 0 0 0 | 0 0 z3 z4 z5] non chunk blocks
  94. //
  95. // This structure should be reflected in the corresponding
  96. // CompressedRowBlockStructure object associated with A. The linear
  97. // system Ax = b should either be well posed or the array D below
  98. // should be non-null and the diagonal matrix corresponding to it
  99. // should be non-singular. For simplicity of exposition only the case
  100. // with a null D is described.
  101. //
  102. // The usual way to do the elimination is as follows. Starting with
  103. //
  104. // E y + F z = b
  105. //
  106. // we can form the normal equations,
  107. //
  108. // E'E y + E'F z = E'b
  109. // F'E y + F'F z = F'b
  110. //
  111. // multiplying both sides of the first equation by (E'E)^(-1) and then
  112. // by F'E we get
  113. //
  114. // F'E y + F'E (E'E)^(-1) E'F z = F'E (E'E)^(-1) E'b
  115. // F'E y + F'F z = F'b
  116. //
  117. // now subtracting the two equations we get
  118. //
  119. // [FF' - F'E (E'E)^(-1) E'F] z = F'b - F'E(E'E)^(-1) E'b
  120. //
  121. // Instead of forming the normal equations and operating on them as
  122. // general sparse matrices, the algorithm here deals with one
  123. // parameter block in y at a time. The rows corresponding to a single
  124. // parameter block yi are known as a chunk, and the algorithm operates
  125. // on one chunk at a time. The mathematics remains the same since the
  126. // reduced linear system can be shown to be the sum of the reduced
  127. // linear systems for each chunk. This can be seen by observing two
  128. // things.
  129. //
  130. // 1. E'E is a block diagonal matrix.
  131. //
  132. // 2. When E'F is computed, only the terms within a single chunk
  133. // interact, i.e for y1 column blocks when transposed and multiplied
  134. // with F, the only non-zero contribution comes from the blocks in
  135. // chunk1.
  136. //
  137. // Thus, the reduced linear system
  138. //
  139. // FF' - F'E (E'E)^(-1) E'F
  140. //
  141. // can be re-written as
  142. //
  143. // sum_k F_k F_k' - F_k'E_k (E_k'E_k)^(-1) E_k' F_k
  144. //
  145. // Where the sum is over chunks and E_k'E_k is dense matrix of size y1
  146. // x y1.
  147. //
  148. // Advanced usage. Until now it has been assumed that the user would
  149. // be interested in all of the Schur Complement S. However, it is also
  150. // possible to use this eliminator to obtain an arbitrary submatrix of
  151. // the full Schur complement. When the eliminator is generating the
  152. // blocks of S, it asks the RandomAccessBlockMatrix instance passed to
  153. // it if it has storage for that block. If it does, the eliminator
  154. // computes/updates it, if not it is skipped. This is useful when one
  155. // is interested in constructing a preconditioner based on the Schur
  156. // Complement, e.g., computing the block diagonal of S so that it can
  157. // be used as a preconditioner for an Iterative Substructuring based
  158. // solver [See Agarwal et al, Bundle Adjustment in the Large, ECCV
  159. // 2008 for an example of such use].
  160. //
  161. // Example usage: Please see schur_complement_solver.cc
  162. class CERES_NO_EXPORT SchurEliminatorBase {
  163. public:
  164. virtual ~SchurEliminatorBase();
  165. // Initialize the eliminator. It is the user's responsibility to call
  166. // this function before calling Eliminate or BackSubstitute. It is
  167. // also the caller's responsibility to ensure that the
  168. // CompressedRowBlockStructure object passed to this method is the
  169. // same one (or is equivalent to) the one associated with the
  170. // BlockSparseMatrix objects below.
  171. //
  172. // assume_full_rank_ete controls how the eliminator inverts with the
  173. // diagonal blocks corresponding to e blocks in A'A. If
  174. // assume_full_rank_ete is true, then a Cholesky factorization is
  175. // used to compute the inverse, otherwise a singular value
  176. // decomposition is used to compute the pseudo inverse.
  177. virtual void Init(int num_eliminate_blocks,
  178. bool assume_full_rank_ete,
  179. const CompressedRowBlockStructure* bs) = 0;
  180. // Compute the Schur complement system from the augmented linear
  181. // least squares problem [A;D] x = [b;0]. The left hand side and the
  182. // right hand side of the reduced linear system are returned in lhs
  183. // and rhs respectively.
  184. //
  185. // It is the caller's responsibility to construct and initialize
  186. // lhs. Depending upon the structure of the lhs object passed here,
  187. // the full or a submatrix of the Schur complement will be computed.
  188. //
  189. // Since the Schur complement is a symmetric matrix, only the upper
  190. // triangular part of the Schur complement is computed.
  191. virtual void Eliminate(const BlockSparseMatrixData& A,
  192. const double* b,
  193. const double* D,
  194. BlockRandomAccessMatrix* lhs,
  195. double* rhs) = 0;
  196. // Given values for the variables z in the F block of A, solve for
  197. // the optimal values of the variables y corresponding to the E
  198. // block in A.
  199. virtual void BackSubstitute(const BlockSparseMatrixData& A,
  200. const double* b,
  201. const double* D,
  202. const double* z,
  203. double* y) = 0;
  204. // Factory
  205. static std::unique_ptr<SchurEliminatorBase> Create(
  206. const LinearSolver::Options& options);
  207. };
  208. // Templated implementation of the SchurEliminatorBase interface. The
  209. // templating is on the sizes of the row, e and f blocks sizes in the
  210. // input matrix. In many problems, the sizes of one or more of these
  211. // blocks are constant, in that case, its worth passing these
  212. // parameters as template arguments so that they are visible to the
  213. // compiler and can be used for compile time optimization of the low
  214. // level linear algebra routines.
  215. template <int kRowBlockSize = Eigen::Dynamic,
  216. int kEBlockSize = Eigen::Dynamic,
  217. int kFBlockSize = Eigen::Dynamic>
  218. class CERES_NO_EXPORT SchurEliminator final : public SchurEliminatorBase {
  219. public:
  220. explicit SchurEliminator(const LinearSolver::Options& options)
  221. : num_threads_(options.num_threads), context_(options.context) {
  222. CHECK(context_ != nullptr);
  223. }
  224. // SchurEliminatorBase Interface
  225. ~SchurEliminator() override;
  226. void Init(int num_eliminate_blocks,
  227. bool assume_full_rank_ete,
  228. const CompressedRowBlockStructure* bs) final;
  229. void Eliminate(const BlockSparseMatrixData& A,
  230. const double* b,
  231. const double* D,
  232. BlockRandomAccessMatrix* lhs,
  233. double* rhs) final;
  234. void BackSubstitute(const BlockSparseMatrixData& A,
  235. const double* b,
  236. const double* D,
  237. const double* z,
  238. double* y) final;
  239. private:
  240. // Chunk objects store combinatorial information needed to
  241. // efficiently eliminate a whole chunk out of the least squares
  242. // problem. Consider the first chunk in the example matrix above.
  243. //
  244. // [ y1 0 0 0 | z1 0 0 0 z5]
  245. // [ y1 0 0 0 | z1 z2 0 0 0]
  246. //
  247. // One of the intermediate quantities that needs to be calculated is
  248. // for each row the product of the y block transposed with the
  249. // non-zero z block, and the sum of these blocks across rows. A
  250. // temporary array "buffer_" is used for computing and storing them
  251. // and the buffer_layout maps the indices of the z-blocks to
  252. // position in the buffer_ array. The size of the chunk is the
  253. // number of row blocks/residual blocks for the particular y block
  254. // being considered.
  255. //
  256. // For the example chunk shown above,
  257. //
  258. // size = 2
  259. //
  260. // The entries of buffer_layout will be filled in the following order.
  261. //
  262. // buffer_layout[z1] = 0
  263. // buffer_layout[z5] = y1 * z1
  264. // buffer_layout[z2] = y1 * z1 + y1 * z5
  265. using BufferLayoutType = std::map<int, int>;
  266. struct Chunk {
  267. explicit Chunk(int start) : size(0), start(start) {}
  268. int size;
  269. int start;
  270. BufferLayoutType buffer_layout;
  271. };
  272. void ChunkDiagonalBlockAndGradient(
  273. const Chunk& chunk,
  274. const BlockSparseMatrixData& A,
  275. const double* b,
  276. int row_block_counter,
  277. typename EigenTypes<kEBlockSize, kEBlockSize>::Matrix* eet,
  278. double* g,
  279. double* buffer,
  280. BlockRandomAccessMatrix* lhs);
  281. void UpdateRhs(const Chunk& chunk,
  282. const BlockSparseMatrixData& A,
  283. const double* b,
  284. int row_block_counter,
  285. const double* inverse_ete_g,
  286. double* rhs);
  287. void ChunkOuterProduct(int thread_id,
  288. const CompressedRowBlockStructure* bs,
  289. const Matrix& inverse_eet,
  290. const double* buffer,
  291. const BufferLayoutType& buffer_layout,
  292. BlockRandomAccessMatrix* lhs);
  293. void EBlockRowOuterProduct(const BlockSparseMatrixData& A,
  294. int row_block_index,
  295. BlockRandomAccessMatrix* lhs);
  296. void NoEBlockRowsUpdate(const BlockSparseMatrixData& A,
  297. const double* b,
  298. int row_block_counter,
  299. BlockRandomAccessMatrix* lhs,
  300. double* rhs);
  301. void NoEBlockRowOuterProduct(const BlockSparseMatrixData& A,
  302. int row_block_index,
  303. BlockRandomAccessMatrix* lhs);
  304. int num_threads_;
  305. ContextImpl* context_;
  306. int num_eliminate_blocks_;
  307. bool assume_full_rank_ete_;
  308. // Block layout of the columns of the reduced linear system. Since
  309. // the f blocks can be of varying size, this vector stores the
  310. // position of each f block in the row/col of the reduced linear
  311. // system. Thus lhs_row_layout_[i] is the row/col position of the
  312. // i^th f block.
  313. std::vector<int> lhs_row_layout_;
  314. // Combinatorial structure of the chunks in A. For more information
  315. // see the documentation of the Chunk object above.
  316. std::vector<Chunk> chunks_;
  317. // TODO(sameeragarwal): The following two arrays contain per-thread
  318. // storage. They should be refactored into a per thread struct.
  319. // Buffer to store the products of the y and z blocks generated
  320. // during the elimination phase. buffer_ is of size num_threads *
  321. // buffer_size_. Each thread accesses the chunk
  322. //
  323. // [thread_id * buffer_size_ , (thread_id + 1) * buffer_size_]
  324. //
  325. std::unique_ptr<double[]> buffer_;
  326. // Buffer to store per thread matrix matrix products used by
  327. // ChunkOuterProduct. Like buffer_ it is of size num_threads *
  328. // buffer_size_. Each thread accesses the chunk
  329. //
  330. // [thread_id * buffer_size_ , (thread_id + 1) * buffer_size_ -1]
  331. //
  332. std::unique_ptr<double[]> chunk_outer_product_buffer_;
  333. int buffer_size_;
  334. int uneliminated_row_begins_;
  335. // Locks for the blocks in the right hand side of the reduced linear
  336. // system.
  337. std::vector<std::mutex*> rhs_locks_;
  338. };
  339. // SchurEliminatorForOneFBlock specializes the SchurEliminatorBase interface for
  340. // the case where there is exactly one f-block and all three parameters
  341. // kRowBlockSize, kEBlockSize and KFBlockSize are known at compile time. This is
  342. // the case for some two view bundle adjustment problems which have very
  343. // stringent latency requirements.
  344. //
  345. // Under these assumptions, we can simplify the more general algorithm
  346. // implemented by SchurEliminatorImpl significantly. Two of the major
  347. // contributors to the increased performance are:
  348. //
  349. // 1. Simpler loop structure and less use of dynamic memory. Almost everything
  350. // is on the stack and benefits from aligned memory as well as fixed sized
  351. // vectorization. We are also able to reason about temporaries and control
  352. // their lifetimes better.
  353. // 2. Use of inverse() over llt().solve(Identity).
  354. template <int kRowBlockSize = Eigen::Dynamic,
  355. int kEBlockSize = Eigen::Dynamic,
  356. int kFBlockSize = Eigen::Dynamic>
  357. class CERES_NO_EXPORT SchurEliminatorForOneFBlock final
  358. : public SchurEliminatorBase {
  359. public:
  360. // TODO(sameeragarwal) Find out why "assume_full_rank_ete" is not used here
  361. void Init(int num_eliminate_blocks,
  362. bool /*assume_full_rank_ete*/,
  363. const CompressedRowBlockStructure* bs) override {
  364. CHECK_GT(num_eliminate_blocks, 0)
  365. << "SchurComplementSolver cannot be initialized with "
  366. << "num_eliminate_blocks = 0.";
  367. CHECK_EQ(bs->cols.size() - num_eliminate_blocks, 1);
  368. num_eliminate_blocks_ = num_eliminate_blocks;
  369. const int num_row_blocks = bs->rows.size();
  370. chunks_.clear();
  371. int r = 0;
  372. // Iterate over the row blocks of A, and detect the chunks. The
  373. // matrix should already have been ordered so that all rows
  374. // containing the same y block are vertically contiguous.
  375. while (r < num_row_blocks) {
  376. const int e_block_id = bs->rows[r].cells.front().block_id;
  377. if (e_block_id >= num_eliminate_blocks_) {
  378. break;
  379. }
  380. chunks_.push_back(Chunk());
  381. Chunk& chunk = chunks_.back();
  382. chunk.num_rows = 0;
  383. chunk.start = r;
  384. // Add to the chunk until the first block in the row is
  385. // different than the one in the first row for the chunk.
  386. while (r + chunk.num_rows < num_row_blocks) {
  387. const CompressedRow& row = bs->rows[r + chunk.num_rows];
  388. if (row.cells.front().block_id != e_block_id) {
  389. break;
  390. }
  391. ++chunk.num_rows;
  392. }
  393. r += chunk.num_rows;
  394. }
  395. const Chunk& last_chunk = chunks_.back();
  396. uneliminated_row_begins_ = last_chunk.start + last_chunk.num_rows;
  397. e_t_e_inverse_matrices_.resize(kEBlockSize * kEBlockSize * chunks_.size());
  398. std::fill(
  399. e_t_e_inverse_matrices_.begin(), e_t_e_inverse_matrices_.end(), 0.0);
  400. }
  401. void Eliminate(const BlockSparseMatrixData& A,
  402. const double* b,
  403. const double* D,
  404. BlockRandomAccessMatrix* lhs_bram,
  405. double* rhs_ptr) override {
  406. // Since there is only one f-block, we can call GetCell once, and cache its
  407. // output.
  408. int r, c, row_stride, col_stride;
  409. CellInfo* cell_info =
  410. lhs_bram->GetCell(0, 0, &r, &c, &row_stride, &col_stride);
  411. typename EigenTypes<kFBlockSize, kFBlockSize>::MatrixRef lhs(
  412. cell_info->values, kFBlockSize, kFBlockSize);
  413. typename EigenTypes<kFBlockSize>::VectorRef rhs(rhs_ptr, kFBlockSize);
  414. lhs.setZero();
  415. rhs.setZero();
  416. const CompressedRowBlockStructure* bs = A.block_structure();
  417. const double* values = A.values();
  418. // Add the diagonal to the Schur complement.
  419. if (D != nullptr) {
  420. typename EigenTypes<kFBlockSize>::ConstVectorRef diag(
  421. D + bs->cols[num_eliminate_blocks_].position, kFBlockSize);
  422. lhs.diagonal() = diag.array().square().matrix();
  423. }
  424. Eigen::Matrix<double, kEBlockSize, kFBlockSize> tmp;
  425. Eigen::Matrix<double, kEBlockSize, 1> tmp2;
  426. // The following loop works on a block matrix which looks as follows
  427. // (number of rows can be anything):
  428. //
  429. // [e_1 | f_1] = [b1]
  430. // [e_2 | f_2] = [b2]
  431. // [e_3 | f_3] = [b3]
  432. // [e_4 | f_4] = [b4]
  433. //
  434. // and computes the following
  435. //
  436. // e_t_e = sum_i e_i^T * e_i
  437. // e_t_e_inverse = inverse(e_t_e)
  438. // e_t_f = sum_i e_i^T f_i
  439. // e_t_b = sum_i e_i^T b_i
  440. // f_t_b = sum_i f_i^T b_i
  441. //
  442. // lhs += sum_i f_i^T * f_i - e_t_f^T * e_t_e_inverse * e_t_f
  443. // rhs += f_t_b - e_t_f^T * e_t_e_inverse * e_t_b
  444. for (int i = 0; i < chunks_.size(); ++i) {
  445. const Chunk& chunk = chunks_[i];
  446. const int e_block_id = bs->rows[chunk.start].cells.front().block_id;
  447. // Naming convention, e_t_e = e_block.transpose() * e_block;
  448. Eigen::Matrix<double, kEBlockSize, kEBlockSize> e_t_e;
  449. Eigen::Matrix<double, kEBlockSize, kFBlockSize> e_t_f;
  450. Eigen::Matrix<double, kEBlockSize, 1> e_t_b;
  451. Eigen::Matrix<double, kFBlockSize, 1> f_t_b;
  452. // Add the square of the diagonal to e_t_e.
  453. if (D != nullptr) {
  454. const typename EigenTypes<kEBlockSize>::ConstVectorRef diag(
  455. D + bs->cols[e_block_id].position, kEBlockSize);
  456. e_t_e = diag.array().square().matrix().asDiagonal();
  457. } else {
  458. e_t_e.setZero();
  459. }
  460. e_t_f.setZero();
  461. e_t_b.setZero();
  462. f_t_b.setZero();
  463. for (int j = 0; j < chunk.num_rows; ++j) {
  464. const int row_id = chunk.start + j;
  465. const auto& row = bs->rows[row_id];
  466. const typename EigenTypes<kRowBlockSize, kEBlockSize>::ConstMatrixRef
  467. e_block(values + row.cells[0].position, kRowBlockSize, kEBlockSize);
  468. const typename EigenTypes<kRowBlockSize>::ConstVectorRef b_block(
  469. b + row.block.position, kRowBlockSize);
  470. e_t_e.noalias() += e_block.transpose() * e_block;
  471. e_t_b.noalias() += e_block.transpose() * b_block;
  472. if (row.cells.size() == 1) {
  473. // There is no f block, so there is nothing more to do.
  474. continue;
  475. }
  476. const typename EigenTypes<kRowBlockSize, kFBlockSize>::ConstMatrixRef
  477. f_block(values + row.cells[1].position, kRowBlockSize, kFBlockSize);
  478. e_t_f.noalias() += e_block.transpose() * f_block;
  479. lhs.noalias() += f_block.transpose() * f_block;
  480. f_t_b.noalias() += f_block.transpose() * b_block;
  481. }
  482. // BackSubstitute computes the same inverse, and this is the key workload
  483. // there, so caching these inverses makes BackSubstitute essentially free.
  484. typename EigenTypes<kEBlockSize, kEBlockSize>::MatrixRef e_t_e_inverse(
  485. &e_t_e_inverse_matrices_[kEBlockSize * kEBlockSize * i],
  486. kEBlockSize,
  487. kEBlockSize);
  488. // e_t_e is a symmetric positive definite matrix, so the standard way to
  489. // compute its inverse is via the Cholesky factorization by calling
  490. // e_t_e.llt().solve(Identity()). However, the inverse() method even
  491. // though it is not optimized for symmetric matrices is significantly
  492. // faster for small fixed size (up to 4x4) matrices.
  493. //
  494. // https://eigen.tuxfamily.org/dox/group__TutorialLinearAlgebra.html#title3
  495. e_t_e_inverse.noalias() = e_t_e.inverse();
  496. // The use of these two pre-allocated tmp vectors saves temporaries in the
  497. // expressions for lhs and rhs updates below and has a significant impact
  498. // on the performance of this method.
  499. tmp.noalias() = e_t_e_inverse * e_t_f;
  500. tmp2.noalias() = e_t_e_inverse * e_t_b;
  501. lhs.noalias() -= e_t_f.transpose() * tmp;
  502. rhs.noalias() += f_t_b - e_t_f.transpose() * tmp2;
  503. }
  504. // The rows without any e-blocks can have arbitrary size but only contain
  505. // the f-block.
  506. //
  507. // lhs += f_i^T f_i
  508. // rhs += f_i^T b_i
  509. for (int row_id = uneliminated_row_begins_; row_id < bs->rows.size();
  510. ++row_id) {
  511. const auto& row = bs->rows[row_id];
  512. const auto& cell = row.cells[0];
  513. const typename EigenTypes<Eigen::Dynamic, kFBlockSize>::ConstMatrixRef
  514. f_block(values + cell.position, row.block.size, kFBlockSize);
  515. const typename EigenTypes<Eigen::Dynamic>::ConstVectorRef b_block(
  516. b + row.block.position, row.block.size);
  517. lhs.noalias() += f_block.transpose() * f_block;
  518. rhs.noalias() += f_block.transpose() * b_block;
  519. }
  520. }
  521. // This implementation of BackSubstitute depends on Eliminate being called
  522. // before this. SchurComplementSolver always does this.
  523. //
  524. // y_i = e_t_e_inverse * sum_i e_i^T * (b_i - f_i * z);
  525. void BackSubstitute(const BlockSparseMatrixData& A,
  526. const double* b,
  527. const double* /*D*/,
  528. const double* z_ptr,
  529. double* y) override {
  530. typename EigenTypes<kFBlockSize>::ConstVectorRef z(z_ptr, kFBlockSize);
  531. const CompressedRowBlockStructure* bs = A.block_structure();
  532. const double* values = A.values();
  533. Eigen::Matrix<double, kEBlockSize, 1> tmp;
  534. for (int i = 0; i < chunks_.size(); ++i) {
  535. const Chunk& chunk = chunks_[i];
  536. const int e_block_id = bs->rows[chunk.start].cells.front().block_id;
  537. tmp.setZero();
  538. for (int j = 0; j < chunk.num_rows; ++j) {
  539. const int row_id = chunk.start + j;
  540. const auto& row = bs->rows[row_id];
  541. const typename EigenTypes<kRowBlockSize, kEBlockSize>::ConstMatrixRef
  542. e_block(values + row.cells[0].position, kRowBlockSize, kEBlockSize);
  543. const typename EigenTypes<kRowBlockSize>::ConstVectorRef b_block(
  544. b + row.block.position, kRowBlockSize);
  545. if (row.cells.size() == 1) {
  546. // There is no f block.
  547. tmp += e_block.transpose() * b_block;
  548. } else {
  549. typename EigenTypes<kRowBlockSize, kFBlockSize>::ConstMatrixRef
  550. f_block(
  551. values + row.cells[1].position, kRowBlockSize, kFBlockSize);
  552. tmp += e_block.transpose() * (b_block - f_block * z);
  553. }
  554. }
  555. typename EigenTypes<kEBlockSize, kEBlockSize>::MatrixRef e_t_e_inverse(
  556. &e_t_e_inverse_matrices_[kEBlockSize * kEBlockSize * i],
  557. kEBlockSize,
  558. kEBlockSize);
  559. typename EigenTypes<kEBlockSize>::VectorRef y_block(
  560. y + bs->cols[e_block_id].position, kEBlockSize);
  561. y_block.noalias() = e_t_e_inverse * tmp;
  562. }
  563. }
  564. private:
  565. struct Chunk {
  566. int start = 0;
  567. int num_rows = 0;
  568. };
  569. std::vector<Chunk> chunks_;
  570. int num_eliminate_blocks_;
  571. int uneliminated_row_begins_;
  572. std::vector<double> e_t_e_inverse_matrices_;
  573. };
  574. } // namespace ceres::internal
  575. #include "ceres/internal/reenable_warnings.h"
  576. #endif // CERES_INTERNAL_SCHUR_ELIMINATOR_H_