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