1 // Ceres Solver - A fast non-linear least squares minimizer
2 // Copyright 2015 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 
31 #include "ceres/block_random_access_sparse_matrix.h"
32 
33 #include <algorithm>
34 #include <memory>
35 #include <set>
36 #include <utility>
37 #include <vector>
38 
39 #include "ceres/internal/port.h"
40 #include "ceres/triplet_sparse_matrix.h"
41 #include "ceres/types.h"
42 #include "glog/logging.h"
43 
44 namespace ceres {
45 namespace internal {
46 
47 using std::make_pair;
48 using std::pair;
49 using std::set;
50 using std::vector;
51 
BlockRandomAccessSparseMatrix(const vector<int> & blocks,const set<pair<int,int>> & block_pairs)52 BlockRandomAccessSparseMatrix::BlockRandomAccessSparseMatrix(
53     const vector<int>& blocks, const set<pair<int, int>>& block_pairs)
54     : kMaxRowBlocks(10 * 1000 * 1000), blocks_(blocks) {
55   CHECK_LT(blocks.size(), kMaxRowBlocks);
56 
57   // Build the row/column layout vector and count the number of scalar
58   // rows/columns.
59   int num_cols = 0;
60   block_positions_.reserve(blocks_.size());
61   for (int i = 0; i < blocks_.size(); ++i) {
62     block_positions_.push_back(num_cols);
63     num_cols += blocks_[i];
64   }
65 
66   // Count the number of scalar non-zero entries and build the layout
67   // object for looking into the values array of the
68   // TripletSparseMatrix.
69   int num_nonzeros = 0;
70   for (const auto& block_pair : block_pairs) {
71     const int row_block_size = blocks_[block_pair.first];
72     const int col_block_size = blocks_[block_pair.second];
73     num_nonzeros += row_block_size * col_block_size;
74   }
75 
76   VLOG(1) << "Matrix Size [" << num_cols << "," << num_cols << "] "
77           << num_nonzeros;
78 
79   tsm_.reset(new TripletSparseMatrix(num_cols, num_cols, num_nonzeros));
80   tsm_->set_num_nonzeros(num_nonzeros);
81   int* rows = tsm_->mutable_rows();
82   int* cols = tsm_->mutable_cols();
83   double* values = tsm_->mutable_values();
84 
85   int pos = 0;
86   for (const auto& block_pair : block_pairs) {
87     const int row_block_size = blocks_[block_pair.first];
88     const int col_block_size = blocks_[block_pair.second];
89     cell_values_.push_back(make_pair(block_pair, values + pos));
90     layout_[IntPairToLong(block_pair.first, block_pair.second)] =
91         new CellInfo(values + pos);
92     pos += row_block_size * col_block_size;
93   }
94 
95   // Fill the sparsity pattern of the underlying matrix.
96   for (const auto& block_pair : block_pairs) {
97     const int row_block_id = block_pair.first;
98     const int col_block_id = block_pair.second;
99     const int row_block_size = blocks_[row_block_id];
100     const int col_block_size = blocks_[col_block_id];
101     int pos =
102         layout_[IntPairToLong(row_block_id, col_block_id)]->values - values;
103     for (int r = 0; r < row_block_size; ++r) {
104       for (int c = 0; c < col_block_size; ++c, ++pos) {
105         rows[pos] = block_positions_[row_block_id] + r;
106         cols[pos] = block_positions_[col_block_id] + c;
107         values[pos] = 1.0;
108         DCHECK_LT(rows[pos], tsm_->num_rows());
109         DCHECK_LT(cols[pos], tsm_->num_rows());
110       }
111     }
112   }
113 }
114 
115 // Assume that the user does not hold any locks on any cell blocks
116 // when they are calling SetZero.
~BlockRandomAccessSparseMatrix()117 BlockRandomAccessSparseMatrix::~BlockRandomAccessSparseMatrix() {
118   for (const auto& entry : layout_) {
119     delete entry.second;
120   }
121 }
122 
GetCell(int row_block_id,int col_block_id,int * row,int * col,int * row_stride,int * col_stride)123 CellInfo* BlockRandomAccessSparseMatrix::GetCell(int row_block_id,
124                                                  int col_block_id,
125                                                  int* row,
126                                                  int* col,
127                                                  int* row_stride,
128                                                  int* col_stride) {
129   const LayoutType::iterator it =
130       layout_.find(IntPairToLong(row_block_id, col_block_id));
131   if (it == layout_.end()) {
132     return NULL;
133   }
134 
135   // Each cell is stored contiguously as its own little dense matrix.
136   *row = 0;
137   *col = 0;
138   *row_stride = blocks_[row_block_id];
139   *col_stride = blocks_[col_block_id];
140   return it->second;
141 }
142 
143 // Assume that the user does not hold any locks on any cell blocks
144 // when they are calling SetZero.
SetZero()145 void BlockRandomAccessSparseMatrix::SetZero() {
146   if (tsm_->num_nonzeros()) {
147     VectorRef(tsm_->mutable_values(), tsm_->num_nonzeros()).setZero();
148   }
149 }
150 
SymmetricRightMultiply(const double * x,double * y) const151 void BlockRandomAccessSparseMatrix::SymmetricRightMultiply(const double* x,
152                                                            double* y) const {
153   for (const auto& cell_position_and_data : cell_values_) {
154     const int row = cell_position_and_data.first.first;
155     const int row_block_size = blocks_[row];
156     const int row_block_pos = block_positions_[row];
157 
158     const int col = cell_position_and_data.first.second;
159     const int col_block_size = blocks_[col];
160     const int col_block_pos = block_positions_[col];
161 
162     MatrixVectorMultiply<Eigen::Dynamic, Eigen::Dynamic, 1>(
163         cell_position_and_data.second,
164         row_block_size,
165         col_block_size,
166         x + col_block_pos,
167         y + row_block_pos);
168 
169     // Since the matrix is symmetric, but only the upper triangular
170     // part is stored, if the block being accessed is not a diagonal
171     // block, then use the same block to do the corresponding lower
172     // triangular multiply also.
173     if (row != col) {
174       MatrixTransposeVectorMultiply<Eigen::Dynamic, Eigen::Dynamic, 1>(
175           cell_position_and_data.second,
176           row_block_size,
177           col_block_size,
178           x + row_block_pos,
179           y + col_block_pos);
180     }
181   }
182 }
183 
184 }  // namespace internal
185 }  // namespace ceres
186