1// Ceres Solver - A fast non-linear least squares minimizer
2// Copyright 2013 Google Inc. All rights reserved.
3// http://code.google.com/p/ceres-solver/
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_crs_matrix.h"
32
33#include <algorithm>
34#include <set>
35#include <utility>
36#include <vector>
37#include "ceres/compressed_row_sparse_matrix.h"
38#include "ceres/internal/port.h"
39#include "ceres/internal/scoped_ptr.h"
40#include "ceres/mutex.h"
41#include "ceres/triplet_sparse_matrix.h"
42#include "ceres/types.h"
43#include "glog/logging.h"
44
45namespace ceres {
46namespace internal {
47
48BlockRandomAccessCRSMatrix::BlockRandomAccessCRSMatrix(
49    const vector<int>& blocks,
50    const set<pair<int, int> >& block_pairs)
51    : kMaxRowBlocks(10 * 1000 * 1000),
52      blocks_(blocks) {
53  CHECK_LT(blocks.size(), kMaxRowBlocks);
54
55  col_layout_.resize(blocks_.size(), 0);
56  row_strides_.resize(blocks_.size(), 0);
57
58  // Build the row/column layout vector and count the number of scalar
59  // rows/columns.
60  int num_cols = 0;
61  for (int i = 0; i < blocks_.size(); ++i) {
62    col_layout_[i] = num_cols;
63    num_cols += blocks_[i];
64  }
65
66  // Walk the sparsity pattern and count the number of non-zeros.
67  int num_nonzeros = 0;
68  for (set<pair<int, int> >::const_iterator it = block_pairs.begin();
69       it != block_pairs.end();
70       ++it) {
71    const int row_block_size = blocks_[it->first];
72    const int col_block_size = blocks_[it->second];
73    num_nonzeros += row_block_size * col_block_size;
74  }
75
76  VLOG(2) << "Matrix Size [" << num_cols
77          << "," << num_cols
78          << "] " << num_nonzeros;
79
80  crsm_.reset(new CompressedRowSparseMatrix(num_cols, num_cols, num_nonzeros));
81  int* rows = crsm_->mutable_rows();
82  int* cols = crsm_->mutable_cols();
83  double* values = crsm_->mutable_values();
84
85  // Iterate over the sparsity pattern and fill the scalar sparsity
86  // pattern of the underlying compressed sparse row matrix. Along the
87  // way also fill out the Layout object which will allow random
88  // access into the CRS Matrix.
89  set<pair<int, int> >::const_iterator it = block_pairs.begin();
90  vector<int> col_blocks;
91  int row_pos = 0;
92  rows[0] = 0;
93  while (it != block_pairs.end()) {
94    // Add entries to layout_ for all the blocks for this row.
95    col_blocks.clear();
96    const int row_block_id = it->first;
97    const int row_block_size = blocks_[row_block_id];
98    int num_cols = 0;
99    while ((it != block_pairs.end()) && (it->first == row_block_id)) {
100      layout_[IntPairToLong(it->first, it->second)] =
101          new CellInfo(values + num_cols);
102      col_blocks.push_back(it->second);
103      num_cols += blocks_[it->second];
104      ++it;
105    };
106
107    // Count the number of non-zeros in the row block.
108    for (int j = 0; j < row_block_size; ++j) {
109      rows[row_pos + j + 1] = rows[row_pos + j] + num_cols;
110    }
111
112    // Fill out the sparsity pattern for each row.
113    int col_pos = 0;
114    for (int j = 0; j < col_blocks.size(); ++j) {
115      const int col_block_id = col_blocks[j];
116      const int col_block_size = blocks_[col_block_id];
117      for (int r = 0; r < row_block_size; ++r) {
118        const int column_block_begin = rows[row_pos + r] + col_pos;
119        for (int c = 0; c < col_block_size; ++c) {
120          cols[column_block_begin + c] = col_layout_[col_block_id] + c;
121        }
122      }
123      col_pos += col_block_size;
124    }
125
126    row_pos += row_block_size;
127    values += row_block_size * num_cols;
128    row_strides_[row_block_id] = num_cols;
129  }
130}
131
132// Assume that the user does not hold any locks on any cell blocks
133// when they are calling SetZero.
134BlockRandomAccessCRSMatrix::~BlockRandomAccessCRSMatrix() {
135  // TODO(sameeragarwal) this should be rationalized going forward and
136  // perhaps moved into BlockRandomAccessMatrix.
137  for (LayoutType::iterator it = layout_.begin();
138       it != layout_.end();
139       ++it) {
140    delete it->second;
141  }
142}
143
144CellInfo* BlockRandomAccessCRSMatrix::GetCell(int row_block_id,
145                                              int col_block_id,
146                                              int* row,
147                                              int* col,
148                                              int* row_stride,
149                                              int* col_stride) {
150  const LayoutType::iterator it  =
151      layout_.find(IntPairToLong(row_block_id, col_block_id));
152  if (it == layout_.end()) {
153    return NULL;
154  }
155
156  *row = 0;
157  *col = 0;
158  *row_stride = blocks_[row_block_id];
159  *col_stride = row_strides_[row_block_id];
160  return it->second;
161}
162
163// Assume that the user does not hold any locks on any cell blocks
164// when they are calling SetZero.
165void BlockRandomAccessCRSMatrix::SetZero() {
166  crsm_->SetZero();
167}
168
169}  // namespace internal
170}  // namespace ceres
171