1 // Ceres Solver - A fast non-linear least squares minimizer
2 // Copyright 2017 Google Inc. All rights reserved.
3 // http://ceres-solver.org/
5 // Redistribution and use in source and binary forms, with or without
6 // modification, are permitted provided that the following conditions are met:
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.
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.
29 // Author: sameeragarwal@google.com (Sameer Agarwal)
31 #include "ceres/compressed_row_sparse_matrix.h"
36 #include "ceres/crs_matrix.h"
37 #include "ceres/internal/port.h"
38 #include "ceres/random.h"
39 #include "ceres/triplet_sparse_matrix.h"
40 #include "glog/logging.h"
49 // Helper functor used by the constructor for reordering the contents
50 // of a TripletSparseMatrix. This comparator assumes thay there are no
51 // duplicates in the pair of arrays rows and cols, i.e., there is no
52 // indices i and j (not equal to each other) s.t.
54 // rows[i] == rows[j] && cols[i] == cols[j]
56 // If this is the case, this functor will not be a StrictWeakOrdering.
57 struct RowColLessThan {
58 RowColLessThan(const int* rows, const int* cols) : rows(rows), cols(cols) {}
60 bool operator()(const int x, const int y) const {
61 if (rows[x] == rows[y]) {
62 return (cols[x] < cols[y]);
64 return (rows[x] < rows[y]);
71 void TransposeForCompressedRowSparseStructure(const int num_rows,
73 const int num_nonzeros,
79 double* transpose_values) {
80 // Explicitly zero out transpose_rows.
81 std::fill(transpose_rows, transpose_rows + num_cols + 1, 0);
83 // Count the number of entries in each column of the original matrix
84 // and assign to transpose_rows[col + 1].
85 for (int idx = 0; idx < num_nonzeros; ++idx) {
86 ++transpose_rows[cols[idx] + 1];
89 // Compute the starting position for each row in the transpose by
90 // computing the cumulative sum of the entries of transpose_rows.
91 for (int i = 1; i < num_cols + 1; ++i) {
92 transpose_rows[i] += transpose_rows[i - 1];
95 // Populate transpose_cols and (optionally) transpose_values by
96 // walking the entries of the source matrices. For each entry that
97 // is added, the value of transpose_row is incremented allowing us
98 // to keep track of where the next entry for that row should go.
100 // As a result transpose_row is shifted to the left by one entry.
101 for (int r = 0; r < num_rows; ++r) {
102 for (int idx = rows[r]; idx < rows[r + 1]; ++idx) {
103 const int c = cols[idx];
104 const int transpose_idx = transpose_rows[c]++;
105 transpose_cols[transpose_idx] = r;
106 if (values != NULL && transpose_values != NULL) {
107 transpose_values[transpose_idx] = values[idx];
112 // This loop undoes the left shift to transpose_rows introduced by
113 // the previous loop.
114 for (int i = num_cols - 1; i > 0; --i) {
115 transpose_rows[i] = transpose_rows[i - 1];
117 transpose_rows[0] = 0;
120 void AddRandomBlock(const int num_rows,
122 const int row_block_begin,
123 const int col_block_begin,
124 std::vector<int>* rows,
125 std::vector<int>* cols,
126 std::vector<double>* values) {
127 for (int r = 0; r < num_rows; ++r) {
128 for (int c = 0; c < num_cols; ++c) {
129 rows->push_back(row_block_begin + r);
130 cols->push_back(col_block_begin + c);
131 values->push_back(RandNormal());
138 // This constructor gives you a semi-initialized CompressedRowSparseMatrix.
139 CompressedRowSparseMatrix::CompressedRowSparseMatrix(int num_rows,
141 int max_num_nonzeros) {
142 num_rows_ = num_rows;
143 num_cols_ = num_cols;
144 storage_type_ = UNSYMMETRIC;
145 rows_.resize(num_rows + 1, 0);
146 cols_.resize(max_num_nonzeros, 0);
147 values_.resize(max_num_nonzeros, 0.0);
149 VLOG(1) << "# of rows: " << num_rows_ << " # of columns: " << num_cols_
150 << " max_num_nonzeros: " << cols_.size() << ". Allocating "
151 << (num_rows_ + 1) * sizeof(int) + // NOLINT
152 cols_.size() * sizeof(int) + // NOLINT
153 cols_.size() * sizeof(double); // NOLINT
156 CompressedRowSparseMatrix* CompressedRowSparseMatrix::FromTripletSparseMatrix(
157 const TripletSparseMatrix& input) {
158 return CompressedRowSparseMatrix::FromTripletSparseMatrix(input, false);
161 CompressedRowSparseMatrix*
162 CompressedRowSparseMatrix::FromTripletSparseMatrixTransposed(
163 const TripletSparseMatrix& input) {
164 return CompressedRowSparseMatrix::FromTripletSparseMatrix(input, true);
167 CompressedRowSparseMatrix* CompressedRowSparseMatrix::FromTripletSparseMatrix(
168 const TripletSparseMatrix& input, bool transpose) {
169 int num_rows = input.num_rows();
170 int num_cols = input.num_cols();
171 const int* rows = input.rows();
172 const int* cols = input.cols();
173 const double* values = input.values();
176 std::swap(num_rows, num_cols);
177 std::swap(rows, cols);
180 // index is the list of indices into the TripletSparseMatrix input.
181 vector<int> index(input.num_nonzeros(), 0);
182 for (int i = 0; i < input.num_nonzeros(); ++i) {
186 // Sort index such that the entries of m are ordered by row and ties
187 // are broken by column.
188 std::sort(index.begin(), index.end(), RowColLessThan(rows, cols));
190 VLOG(1) << "# of rows: " << num_rows << " # of columns: " << num_cols
191 << " num_nonzeros: " << input.num_nonzeros() << ". Allocating "
192 << ((num_rows + 1) * sizeof(int) + // NOLINT
193 input.num_nonzeros() * sizeof(int) + // NOLINT
194 input.num_nonzeros() * sizeof(double)); // NOLINT
196 CompressedRowSparseMatrix* output =
197 new CompressedRowSparseMatrix(num_rows, num_cols, input.num_nonzeros());
199 // Copy the contents of the cols and values array in the order given
200 // by index and count the number of entries in each row.
201 int* output_rows = output->mutable_rows();
202 int* output_cols = output->mutable_cols();
203 double* output_values = output->mutable_values();
206 for (int i = 0; i < index.size(); ++i) {
207 const int idx = index[i];
208 ++output_rows[rows[idx] + 1];
209 output_cols[i] = cols[idx];
210 output_values[i] = values[idx];
213 // Find the cumulative sum of the row counts.
214 for (int i = 1; i < num_rows + 1; ++i) {
215 output_rows[i] += output_rows[i - 1];
218 CHECK_EQ(output->num_nonzeros(), input.num_nonzeros());
222 CompressedRowSparseMatrix::CompressedRowSparseMatrix(const double* diagonal,
224 CHECK_NOTNULL(diagonal);
226 num_rows_ = num_rows;
227 num_cols_ = num_rows;
228 storage_type_ = UNSYMMETRIC;
229 rows_.resize(num_rows + 1);
230 cols_.resize(num_rows);
231 values_.resize(num_rows);
234 for (int i = 0; i < num_rows_; ++i) {
236 values_[i] = diagonal[i];
237 rows_[i + 1] = i + 1;
240 CHECK_EQ(num_nonzeros(), num_rows);
243 CompressedRowSparseMatrix::~CompressedRowSparseMatrix() {}
245 void CompressedRowSparseMatrix::SetZero() {
246 std::fill(values_.begin(), values_.end(), 0);
249 void CompressedRowSparseMatrix::RightMultiply(const double* x,
254 for (int r = 0; r < num_rows_; ++r) {
255 for (int idx = rows_[r]; idx < rows_[r + 1]; ++idx) {
256 y[r] += values_[idx] * x[cols_[idx]];
261 void CompressedRowSparseMatrix::LeftMultiply(const double* x, double* y) const {
265 for (int r = 0; r < num_rows_; ++r) {
266 for (int idx = rows_[r]; idx < rows_[r + 1]; ++idx) {
267 y[cols_[idx]] += values_[idx] * x[r];
272 void CompressedRowSparseMatrix::SquaredColumnNorm(double* x) const {
275 std::fill(x, x + num_cols_, 0.0);
276 for (int idx = 0; idx < rows_[num_rows_]; ++idx) {
277 x[cols_[idx]] += values_[idx] * values_[idx];
281 void CompressedRowSparseMatrix::ScaleColumns(const double* scale) {
282 CHECK_NOTNULL(scale);
284 for (int idx = 0; idx < rows_[num_rows_]; ++idx) {
285 values_[idx] *= scale[cols_[idx]];
289 void CompressedRowSparseMatrix::ToDenseMatrix(Matrix* dense_matrix) const {
290 CHECK_NOTNULL(dense_matrix);
291 dense_matrix->resize(num_rows_, num_cols_);
292 dense_matrix->setZero();
294 for (int r = 0; r < num_rows_; ++r) {
295 for (int idx = rows_[r]; idx < rows_[r + 1]; ++idx) {
296 (*dense_matrix)(r, cols_[idx]) = values_[idx];
301 void CompressedRowSparseMatrix::DeleteRows(int delta_rows) {
302 CHECK_GE(delta_rows, 0);
303 CHECK_LE(delta_rows, num_rows_);
305 num_rows_ -= delta_rows;
306 rows_.resize(num_rows_ + 1);
308 // The rest of the code updates the block information. Immediately
309 // return in case of no block information.
310 if (row_blocks_.empty()) {
314 // Walk the list of row blocks until we reach the new number of rows
315 // and the drop the rest of the row blocks.
316 int num_row_blocks = 0;
318 while (num_row_blocks < row_blocks_.size() && num_rows < num_rows_) {
319 num_rows += row_blocks_[num_row_blocks];
323 row_blocks_.resize(num_row_blocks);
326 void CompressedRowSparseMatrix::AppendRows(const CompressedRowSparseMatrix& m) {
327 CHECK_EQ(m.num_cols(), num_cols_);
329 CHECK((row_blocks_.empty() && m.row_blocks().empty()) ||
330 (!row_blocks_.empty() && !m.row_blocks().empty()))
331 << "Cannot append a matrix with row blocks to one without and vice versa."
332 << "This matrix has : " << row_blocks_.size() << " row blocks."
333 << "The matrix being appended has: " << m.row_blocks().size()
336 if (m.num_rows() == 0) {
340 if (cols_.size() < num_nonzeros() + m.num_nonzeros()) {
341 cols_.resize(num_nonzeros() + m.num_nonzeros());
342 values_.resize(num_nonzeros() + m.num_nonzeros());
345 // Copy the contents of m into this matrix.
346 DCHECK_LT(num_nonzeros(), cols_.size());
347 if (m.num_nonzeros() > 0) {
348 std::copy(m.cols(), m.cols() + m.num_nonzeros(), &cols_[num_nonzeros()]);
350 m.values(), m.values() + m.num_nonzeros(), &values_[num_nonzeros()]);
353 rows_.resize(num_rows_ + m.num_rows() + 1);
354 // new_rows = [rows_, m.row() + rows_[num_rows_]]
355 std::fill(rows_.begin() + num_rows_,
356 rows_.begin() + num_rows_ + m.num_rows() + 1,
359 for (int r = 0; r < m.num_rows() + 1; ++r) {
360 rows_[num_rows_ + r] += m.rows()[r];
363 num_rows_ += m.num_rows();
365 // The rest of the code updates the block information. Immediately
366 // return in case of no block information.
367 if (row_blocks_.empty()) {
372 row_blocks_.end(), m.row_blocks().begin(), m.row_blocks().end());
375 void CompressedRowSparseMatrix::ToTextFile(FILE* file) const {
377 for (int r = 0; r < num_rows_; ++r) {
378 for (int idx = rows_[r]; idx < rows_[r + 1]; ++idx) {
379 fprintf(file, "% 10d % 10d %17f\n", r, cols_[idx], values_[idx]);
384 void CompressedRowSparseMatrix::ToCRSMatrix(CRSMatrix* matrix) const {
385 matrix->num_rows = num_rows_;
386 matrix->num_cols = num_cols_;
387 matrix->rows = rows_;
388 matrix->cols = cols_;
389 matrix->values = values_;
392 matrix->rows.resize(matrix->num_rows + 1);
393 matrix->cols.resize(matrix->rows[matrix->num_rows]);
394 matrix->values.resize(matrix->rows[matrix->num_rows]);
397 void CompressedRowSparseMatrix::SetMaxNumNonZeros(int num_nonzeros) {
398 CHECK_GE(num_nonzeros, 0);
400 cols_.resize(num_nonzeros);
401 values_.resize(num_nonzeros);
404 CompressedRowSparseMatrix* CompressedRowSparseMatrix::CreateBlockDiagonalMatrix(
405 const double* diagonal, const vector<int>& blocks) {
407 int num_nonzeros = 0;
408 for (int i = 0; i < blocks.size(); ++i) {
409 num_rows += blocks[i];
410 num_nonzeros += blocks[i] * blocks[i];
413 CompressedRowSparseMatrix* matrix =
414 new CompressedRowSparseMatrix(num_rows, num_rows, num_nonzeros);
416 int* rows = matrix->mutable_rows();
417 int* cols = matrix->mutable_cols();
418 double* values = matrix->mutable_values();
419 std::fill(values, values + num_nonzeros, 0.0);
423 for (int i = 0; i < blocks.size(); ++i) {
424 const int block_size = blocks[i];
425 for (int r = 0; r < block_size; ++r) {
426 *(rows++) = idx_cursor;
427 values[idx_cursor + r] = diagonal[col_cursor + r];
428 for (int c = 0; c < block_size; ++c, ++idx_cursor) {
429 *(cols++) = col_cursor + c;
432 col_cursor += block_size;
436 *matrix->mutable_row_blocks() = blocks;
437 *matrix->mutable_col_blocks() = blocks;
439 CHECK_EQ(idx_cursor, num_nonzeros);
440 CHECK_EQ(col_cursor, num_rows);
444 CompressedRowSparseMatrix* CompressedRowSparseMatrix::Transpose() const {
445 CompressedRowSparseMatrix* transpose =
446 new CompressedRowSparseMatrix(num_cols_, num_rows_, num_nonzeros());
448 switch (storage_type_) {
450 transpose->set_storage_type(UNSYMMETRIC);
452 case LOWER_TRIANGULAR:
453 transpose->set_storage_type(UPPER_TRIANGULAR);
455 case UPPER_TRIANGULAR:
456 transpose->set_storage_type(LOWER_TRIANGULAR);
459 LOG(FATAL) << "Unknown storage type: " << storage_type_;
462 TransposeForCompressedRowSparseStructure(num_rows(),
468 transpose->mutable_rows(),
469 transpose->mutable_cols(),
470 transpose->mutable_values());
472 // The rest of the code updates the block information. Immediately
473 // return in case of no block information.
474 if (row_blocks_.empty()) {
478 *(transpose->mutable_row_blocks()) = col_blocks_;
479 *(transpose->mutable_col_blocks()) = row_blocks_;
483 CompressedRowSparseMatrix* CompressedRowSparseMatrix::CreateRandomMatrix(
484 const CompressedRowSparseMatrix::RandomMatrixOptions& options) {
485 CHECK_GT(options.num_row_blocks, 0);
486 CHECK_GT(options.min_row_block_size, 0);
487 CHECK_GT(options.max_row_block_size, 0);
488 CHECK_LE(options.min_row_block_size, options.max_row_block_size);
489 CHECK_GT(options.num_col_blocks, 0);
490 CHECK_GT(options.min_col_block_size, 0);
491 CHECK_GT(options.max_col_block_size, 0);
492 CHECK_LE(options.min_col_block_size, options.max_col_block_size);
493 CHECK_GT(options.block_density, 0.0);
494 CHECK_LE(options.block_density, 1.0);
496 vector<int> row_blocks;
497 vector<int> col_blocks;
499 // Generate the row block structure.
500 for (int i = 0; i < options.num_row_blocks; ++i) {
501 // Generate a random integer in [min_row_block_size, max_row_block_size]
502 const int delta_block_size =
503 Uniform(options.max_row_block_size - options.min_row_block_size);
504 row_blocks.push_back(options.min_row_block_size + delta_block_size);
507 // Generate the col block structure.
508 for (int i = 0; i < options.num_col_blocks; ++i) {
509 // Generate a random integer in [min_col_block_size, max_col_block_size]
510 const int delta_block_size =
511 Uniform(options.max_col_block_size - options.min_col_block_size);
512 col_blocks.push_back(options.min_col_block_size + delta_block_size);
515 vector<int> tsm_rows;
516 vector<int> tsm_cols;
517 vector<double> tsm_values;
519 // For ease of construction, we are going to generate the
520 // CompressedRowSparseMatrix by generating it as a
521 // TripletSparseMatrix and then converting it to a
522 // CompressedRowSparseMatrix.
524 // It is possible that the random matrix is empty which is likely
525 // not what the user wants, so do the matrix generation till we have
526 // at least one non-zero entry.
527 while (tsm_values.empty()) {
532 int row_block_begin = 0;
533 for (int r = 0; r < options.num_row_blocks; ++r) {
534 int col_block_begin = 0;
535 for (int c = 0; c < options.num_col_blocks; ++c) {
536 // Randomly determine if this block is present or not.
537 if (RandDouble() <= options.block_density) {
538 AddRandomBlock(row_blocks[r],
546 col_block_begin += col_blocks[c];
548 row_block_begin += row_blocks[r];
552 const int num_rows = std::accumulate(row_blocks.begin(), row_blocks.end(), 0);
553 const int num_cols = std::accumulate(col_blocks.begin(), col_blocks.end(), 0);
554 const bool kDoNotTranspose = false;
555 CompressedRowSparseMatrix* matrix =
556 CompressedRowSparseMatrix::FromTripletSparseMatrix(
558 num_rows, num_cols, tsm_rows, tsm_cols, tsm_values),
560 (*matrix->mutable_row_blocks()) = row_blocks;
561 (*matrix->mutable_col_blocks()) = col_blocks;
562 matrix->set_storage_type(CompressedRowSparseMatrix::UNSYMMETRIC);
566 } // namespace internal