blob: d200aeb82f31b42f9e5a0ef81f63b7ab70958254 [file] [log] [blame]
Keir Mierle8ebb0732012-04-30 23:09:08 -07001// Ceres Solver - A fast non-linear least squares minimizer
2// Copyright 2010, 2011, 2012 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#ifndef CERES_NO_SUITESPARSE
Keir Mierle8ebb0732012-04-30 23:09:08 -070032#include "ceres/suitesparse.h"
33
Sameer Agarwal7a3c43b2012-06-05 23:10:59 -070034#include <vector>
Keir Mierle8ebb0732012-04-30 23:09:08 -070035#include "cholmod.h"
36#include "ceres/compressed_row_sparse_matrix.h"
37#include "ceres/triplet_sparse_matrix.h"
38namespace ceres {
39namespace internal {
Keir Mierle8ebb0732012-04-30 23:09:08 -070040cholmod_sparse* SuiteSparse::CreateSparseMatrix(TripletSparseMatrix* A) {
41 cholmod_triplet triplet;
42
43 triplet.nrow = A->num_rows();
44 triplet.ncol = A->num_cols();
45 triplet.nzmax = A->max_num_nonzeros();
46 triplet.nnz = A->num_nonzeros();
47 triplet.i = reinterpret_cast<void*>(A->mutable_rows());
48 triplet.j = reinterpret_cast<void*>(A->mutable_cols());
49 triplet.x = reinterpret_cast<void*>(A->mutable_values());
50 triplet.stype = 0; // Matrix is not symmetric.
51 triplet.itype = CHOLMOD_INT;
52 triplet.xtype = CHOLMOD_REAL;
53 triplet.dtype = CHOLMOD_DOUBLE;
54
55 return cholmod_triplet_to_sparse(&triplet, triplet.nnz, &cc_);
56}
57
58
59cholmod_sparse* SuiteSparse::CreateSparseMatrixTranspose(
60 TripletSparseMatrix* A) {
61 cholmod_triplet triplet;
62
63 triplet.ncol = A->num_rows(); // swap row and columns
64 triplet.nrow = A->num_cols();
65 triplet.nzmax = A->max_num_nonzeros();
66 triplet.nnz = A->num_nonzeros();
67
68 // swap rows and columns
69 triplet.j = reinterpret_cast<void*>(A->mutable_rows());
70 triplet.i = reinterpret_cast<void*>(A->mutable_cols());
71 triplet.x = reinterpret_cast<void*>(A->mutable_values());
72 triplet.stype = 0; // Matrix is not symmetric.
73 triplet.itype = CHOLMOD_INT;
74 triplet.xtype = CHOLMOD_REAL;
75 triplet.dtype = CHOLMOD_DOUBLE;
76
77 return cholmod_triplet_to_sparse(&triplet, triplet.nnz, &cc_);
78}
79
80cholmod_sparse* SuiteSparse::CreateSparseMatrixTransposeView(
81 CompressedRowSparseMatrix* A) {
82 cholmod_sparse* m = new cholmod_sparse_struct;
83 m->nrow = A->num_cols();
84 m->ncol = A->num_rows();
85 m->nzmax = A->num_nonzeros();
86
87 m->p = reinterpret_cast<void*>(A->mutable_rows());
88 m->i = reinterpret_cast<void*>(A->mutable_cols());
89 m->x = reinterpret_cast<void*>(A->mutable_values());
90
91 m->stype = 0; // Matrix is not symmetric.
92 m->itype = CHOLMOD_INT;
93 m->xtype = CHOLMOD_REAL;
94 m->dtype = CHOLMOD_DOUBLE;
95 m->sorted = 1;
96 m->packed = 1;
97
98 return m;
99}
100
101cholmod_dense* SuiteSparse::CreateDenseVector(const double* x,
102 int in_size,
103 int out_size) {
104 CHECK_LE(in_size, out_size);
105 cholmod_dense* v = cholmod_zeros(out_size, 1, CHOLMOD_REAL, &cc_);
106 if (x != NULL) {
107 memcpy(v->x, x, in_size*sizeof(*x));
108 }
109 return v;
110}
111
112cholmod_factor* SuiteSparse::AnalyzeCholesky(cholmod_sparse* A) {
Sameer Agarwal7a3c43b2012-06-05 23:10:59 -0700113 // Cholmod can try multiple re-ordering strategies to find a fill
114 // reducing ordering. Here we just tell it use AMD with automatic
115 // matrix dependence choice of supernodal versus simplicial
116 // factorization.
117 cc_.nmethods = 1;
118 cc_.method[0].ordering = CHOLMOD_AMD;
119 cc_.supernodal = CHOLMOD_AUTO;
Keir Mierle8ebb0732012-04-30 23:09:08 -0700120 cholmod_factor* factor = cholmod_analyze(A, &cc_);
121 CHECK_EQ(cc_.status, CHOLMOD_OK)
122 << "Cholmod symbolic analysis failed " << cc_.status;
123 CHECK_NOTNULL(factor);
124 return factor;
125}
126
Sameer Agarwal7a3c43b2012-06-05 23:10:59 -0700127cholmod_factor* SuiteSparse::BlockAnalyzeCholesky(
128 cholmod_sparse* A,
129 const vector<int>& row_blocks,
130 const vector<int>& col_blocks) {
131 vector<int> ordering;
132 if (!BlockAMDOrdering(A, row_blocks, col_blocks, &ordering)) {
133 return NULL;
134 }
135 return AnalyzeCholeskyWithUserOrdering(A, ordering);
136}
137
Sameer Agarwal509f68c2013-02-20 01:39:03 -0800138cholmod_factor* SuiteSparse::AnalyzeCholeskyWithUserOrdering(
139 cholmod_sparse* A,
140 const vector<int>& ordering) {
Sameer Agarwal7a3c43b2012-06-05 23:10:59 -0700141 CHECK_EQ(ordering.size(), A->nrow);
Sameer Agarwal509f68c2013-02-20 01:39:03 -0800142 cc_.nmethods = 1;
Sameer Agarwal7a3c43b2012-06-05 23:10:59 -0700143 cc_.method[0].ordering = CHOLMOD_GIVEN;
144 cholmod_factor* factor =
145 cholmod_analyze_p(A, const_cast<int*>(&ordering[0]), NULL, 0, &cc_);
146 CHECK_EQ(cc_.status, CHOLMOD_OK)
147 << "Cholmod symbolic analysis failed " << cc_.status;
148 CHECK_NOTNULL(factor);
149 return factor;
150}
151
152bool SuiteSparse::BlockAMDOrdering(const cholmod_sparse* A,
153 const vector<int>& row_blocks,
154 const vector<int>& col_blocks,
155 vector<int>* ordering) {
156 const int num_row_blocks = row_blocks.size();
157 const int num_col_blocks = col_blocks.size();
158
159 // Arrays storing the compressed column structure of the matrix
160 // incoding the block sparsity of A.
161 vector<int> block_cols;
162 vector<int> block_rows;
163
164 ScalarMatrixToBlockMatrix(A,
165 row_blocks,
166 col_blocks,
167 &block_rows,
168 &block_cols);
169
170 cholmod_sparse_struct block_matrix;
171 block_matrix.nrow = num_row_blocks;
172 block_matrix.ncol = num_col_blocks;
173 block_matrix.nzmax = block_rows.size();
174 block_matrix.p = reinterpret_cast<void*>(&block_cols[0]);
175 block_matrix.i = reinterpret_cast<void*>(&block_rows[0]);
176 block_matrix.x = NULL;
177 block_matrix.stype = A->stype;
178 block_matrix.itype = CHOLMOD_INT;
179 block_matrix.xtype = CHOLMOD_PATTERN;
180 block_matrix.dtype = CHOLMOD_DOUBLE;
181 block_matrix.sorted = 1;
182 block_matrix.packed = 1;
183
184 vector<int> block_ordering(num_row_blocks);
185 if (!cholmod_amd(&block_matrix, NULL, 0, &block_ordering[0], &cc_)) {
186 return false;
187 }
188
189 BlockOrderingToScalarOrdering(row_blocks, block_ordering, ordering);
190 return true;
191}
192
193void SuiteSparse::ScalarMatrixToBlockMatrix(const cholmod_sparse* A,
194 const vector<int>& row_blocks,
195 const vector<int>& col_blocks,
196 vector<int>* block_rows,
197 vector<int>* block_cols) {
198 CHECK_NOTNULL(block_rows)->clear();
199 CHECK_NOTNULL(block_cols)->clear();
200 const int num_row_blocks = row_blocks.size();
201 const int num_col_blocks = col_blocks.size();
202
203 vector<int> row_block_starts(num_row_blocks);
204 for (int i = 0, cursor = 0; i < num_row_blocks; ++i) {
205 row_block_starts[i] = cursor;
206 cursor += row_blocks[i];
207 }
208
209 // The reinterpret_cast is needed here because CHOLMOD stores arrays
210 // as void*.
211 const int* scalar_cols = reinterpret_cast<const int*>(A->p);
212 const int* scalar_rows = reinterpret_cast<const int*>(A->i);
213
214 // This loop extracts the block sparsity of the scalar sparse matrix
215 // A. It does so by iterating over the columns, but only considering
216 // the columns corresponding to the first element of each column
217 // block. Within each column, the inner loop iterates over the rows,
218 // and detects the presence of a row block by checking for the
219 // presence of a non-zero entry corresponding to its first element.
220 block_cols->push_back(0);
221 int c = 0;
222 for (int col_block = 0; col_block < num_col_blocks; ++col_block) {
223 int column_size = 0;
224 for (int idx = scalar_cols[c]; idx < scalar_cols[c + 1]; ++idx) {
225 vector<int>::const_iterator it = lower_bound(row_block_starts.begin(),
226 row_block_starts.end(),
227 scalar_rows[idx]);
Sameer Agarwal32808202012-06-14 13:47:43 -0700228 // Since we are using lower_bound, it will return the row id
229 // where the row block starts. For everything but the first row
230 // of the block, where these values will be the same, we can
231 // skip, as we only need the first row to detect the presence of
232 // the block.
233 //
234 // For rows all but the first row in the last row block,
235 // lower_bound will return row_block_starts.end(), but those can
236 // be skipped like the rows in other row blocks too.
237 if (it == row_block_starts.end() || *it != scalar_rows[idx]) {
Sameer Agarwal7a3c43b2012-06-05 23:10:59 -0700238 continue;
239 }
240
241 block_rows->push_back(it - row_block_starts.begin());
242 ++column_size;
243 }
244 block_cols->push_back(block_cols->back() + column_size);
245 c += col_blocks[col_block];
246 }
247}
248
249void SuiteSparse::BlockOrderingToScalarOrdering(
250 const vector<int>& blocks,
251 const vector<int>& block_ordering,
252 vector<int>* scalar_ordering) {
253 CHECK_EQ(blocks.size(), block_ordering.size());
254 const int num_blocks = blocks.size();
255
256 // block_starts = [0, block1, block1 + block2 ..]
257 vector<int> block_starts(num_blocks);
258 for (int i = 0, cursor = 0; i < num_blocks ; ++i) {
259 block_starts[i] = cursor;
260 cursor += blocks[i];
261 }
262
263 scalar_ordering->resize(block_starts.back() + blocks.back());
264 int cursor = 0;
265 for (int i = 0; i < num_blocks; ++i) {
266 const int block_id = block_ordering[i];
267 const int block_size = blocks[block_id];
268 int block_position = block_starts[block_id];
269 for (int j = 0; j < block_size; ++j) {
270 (*scalar_ordering)[cursor++] = block_position++;
271 }
272 }
273}
274
Keir Mierle8ebb0732012-04-30 23:09:08 -0700275bool SuiteSparse::Cholesky(cholmod_sparse* A, cholmod_factor* L) {
276 CHECK_NOTNULL(A);
277 CHECK_NOTNULL(L);
278
279 cc_.quick_return_if_not_posdef = 1;
280 int status = cholmod_factorize(A, L, &cc_);
281 switch (cc_.status) {
282 case CHOLMOD_NOT_INSTALLED:
283 LOG(WARNING) << "Cholmod failure: method not installed.";
284 return false;
285 case CHOLMOD_OUT_OF_MEMORY:
286 LOG(WARNING) << "Cholmod failure: out of memory.";
287 return false;
288 case CHOLMOD_TOO_LARGE:
289 LOG(WARNING) << "Cholmod failure: integer overflow occured.";
290 return false;
291 case CHOLMOD_INVALID:
292 LOG(WARNING) << "Cholmod failure: invalid input.";
293 return false;
294 case CHOLMOD_NOT_POSDEF:
295 // TODO(sameeragarwal): These two warnings require more
296 // sophisticated handling going forward. For now we will be
297 // strict and treat them as failures.
298 LOG(WARNING) << "Cholmod warning: matrix not positive definite.";
299 return false;
300 case CHOLMOD_DSMALL:
301 LOG(WARNING) << "Cholmod warning: D for LDL' or diag(L) or "
302 << "LL' has tiny absolute value.";
303 return false;
304 case CHOLMOD_OK:
305 if (status != 0) {
306 return true;
307 }
308 LOG(WARNING) << "Cholmod failure: cholmod_factorize returned zero "
309 << "but cholmod_common::status is CHOLMOD_OK."
310 << "Please report this to ceres-solver@googlegroups.com.";
311 return false;
312 default:
313 LOG(WARNING) << "Unknown cholmod return code. "
314 << "Please report this to ceres-solver@googlegroups.com.";
315 return false;
316 }
317 return false;
318}
319
320cholmod_dense* SuiteSparse::Solve(cholmod_factor* L,
321 cholmod_dense* b) {
322 if (cc_.status != CHOLMOD_OK) {
323 LOG(WARNING) << "CHOLMOD status NOT OK";
324 return NULL;
325 }
326
327 return cholmod_solve(CHOLMOD_A, L, b, &cc_);
328}
329
330cholmod_dense* SuiteSparse::SolveCholesky(cholmod_sparse* A,
331 cholmod_factor* L,
332 cholmod_dense* b) {
333 CHECK_NOTNULL(A);
334 CHECK_NOTNULL(L);
335 CHECK_NOTNULL(b);
336
337 if (Cholesky(A, L)) {
338 return Solve(L, b);
339 }
340
341 return NULL;
342}
343
344} // namespace internal
345} // namespace ceres
346
347#endif // CERES_NO_SUITESPARSE