blob: c02d30567abd2f9bd6afd5efeb58b3a500da9779 [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
138cholmod_factor* SuiteSparse::AnalyzeCholeskyWithUserOrdering(cholmod_sparse* A,
139 const vector<int>& ordering) {
140 CHECK_EQ(ordering.size(), A->nrow);
141 cc_.nmethods = 1 ;
142 cc_.method[0].ordering = CHOLMOD_GIVEN;
143 cholmod_factor* factor =
144 cholmod_analyze_p(A, const_cast<int*>(&ordering[0]), NULL, 0, &cc_);
145 CHECK_EQ(cc_.status, CHOLMOD_OK)
146 << "Cholmod symbolic analysis failed " << cc_.status;
147 CHECK_NOTNULL(factor);
148 return factor;
149}
150
151bool SuiteSparse::BlockAMDOrdering(const cholmod_sparse* A,
152 const vector<int>& row_blocks,
153 const vector<int>& col_blocks,
154 vector<int>* ordering) {
155 const int num_row_blocks = row_blocks.size();
156 const int num_col_blocks = col_blocks.size();
157
158 // Arrays storing the compressed column structure of the matrix
159 // incoding the block sparsity of A.
160 vector<int> block_cols;
161 vector<int> block_rows;
162
163 ScalarMatrixToBlockMatrix(A,
164 row_blocks,
165 col_blocks,
166 &block_rows,
167 &block_cols);
168
169 cholmod_sparse_struct block_matrix;
170 block_matrix.nrow = num_row_blocks;
171 block_matrix.ncol = num_col_blocks;
172 block_matrix.nzmax = block_rows.size();
173 block_matrix.p = reinterpret_cast<void*>(&block_cols[0]);
174 block_matrix.i = reinterpret_cast<void*>(&block_rows[0]);
175 block_matrix.x = NULL;
176 block_matrix.stype = A->stype;
177 block_matrix.itype = CHOLMOD_INT;
178 block_matrix.xtype = CHOLMOD_PATTERN;
179 block_matrix.dtype = CHOLMOD_DOUBLE;
180 block_matrix.sorted = 1;
181 block_matrix.packed = 1;
182
183 vector<int> block_ordering(num_row_blocks);
184 if (!cholmod_amd(&block_matrix, NULL, 0, &block_ordering[0], &cc_)) {
185 return false;
186 }
187
188 BlockOrderingToScalarOrdering(row_blocks, block_ordering, ordering);
189 return true;
190}
191
192void SuiteSparse::ScalarMatrixToBlockMatrix(const cholmod_sparse* A,
193 const vector<int>& row_blocks,
194 const vector<int>& col_blocks,
195 vector<int>* block_rows,
196 vector<int>* block_cols) {
197 CHECK_NOTNULL(block_rows)->clear();
198 CHECK_NOTNULL(block_cols)->clear();
199 const int num_row_blocks = row_blocks.size();
200 const int num_col_blocks = col_blocks.size();
201
202 vector<int> row_block_starts(num_row_blocks);
203 for (int i = 0, cursor = 0; i < num_row_blocks; ++i) {
204 row_block_starts[i] = cursor;
205 cursor += row_blocks[i];
206 }
207
208 // The reinterpret_cast is needed here because CHOLMOD stores arrays
209 // as void*.
210 const int* scalar_cols = reinterpret_cast<const int*>(A->p);
211 const int* scalar_rows = reinterpret_cast<const int*>(A->i);
212
213 // This loop extracts the block sparsity of the scalar sparse matrix
214 // A. It does so by iterating over the columns, but only considering
215 // the columns corresponding to the first element of each column
216 // block. Within each column, the inner loop iterates over the rows,
217 // and detects the presence of a row block by checking for the
218 // presence of a non-zero entry corresponding to its first element.
219 block_cols->push_back(0);
220 int c = 0;
221 for (int col_block = 0; col_block < num_col_blocks; ++col_block) {
222 int column_size = 0;
223 for (int idx = scalar_cols[c]; idx < scalar_cols[c + 1]; ++idx) {
224 vector<int>::const_iterator it = lower_bound(row_block_starts.begin(),
225 row_block_starts.end(),
226 scalar_rows[idx]);
227 DCHECK(it != row_block_starts.end());
228 // Only consider the first row of each row block.
229 if (*it != scalar_rows[idx]) {
230 continue;
231 }
232
233 block_rows->push_back(it - row_block_starts.begin());
234 ++column_size;
235 }
236 block_cols->push_back(block_cols->back() + column_size);
237 c += col_blocks[col_block];
238 }
239}
240
241void SuiteSparse::BlockOrderingToScalarOrdering(
242 const vector<int>& blocks,
243 const vector<int>& block_ordering,
244 vector<int>* scalar_ordering) {
245 CHECK_EQ(blocks.size(), block_ordering.size());
246 const int num_blocks = blocks.size();
247
248 // block_starts = [0, block1, block1 + block2 ..]
249 vector<int> block_starts(num_blocks);
250 for (int i = 0, cursor = 0; i < num_blocks ; ++i) {
251 block_starts[i] = cursor;
252 cursor += blocks[i];
253 }
254
255 scalar_ordering->resize(block_starts.back() + blocks.back());
256 int cursor = 0;
257 for (int i = 0; i < num_blocks; ++i) {
258 const int block_id = block_ordering[i];
259 const int block_size = blocks[block_id];
260 int block_position = block_starts[block_id];
261 for (int j = 0; j < block_size; ++j) {
262 (*scalar_ordering)[cursor++] = block_position++;
263 }
264 }
265}
266
Keir Mierle8ebb0732012-04-30 23:09:08 -0700267bool SuiteSparse::Cholesky(cholmod_sparse* A, cholmod_factor* L) {
268 CHECK_NOTNULL(A);
269 CHECK_NOTNULL(L);
270
271 cc_.quick_return_if_not_posdef = 1;
272 int status = cholmod_factorize(A, L, &cc_);
273 switch (cc_.status) {
274 case CHOLMOD_NOT_INSTALLED:
275 LOG(WARNING) << "Cholmod failure: method not installed.";
276 return false;
277 case CHOLMOD_OUT_OF_MEMORY:
278 LOG(WARNING) << "Cholmod failure: out of memory.";
279 return false;
280 case CHOLMOD_TOO_LARGE:
281 LOG(WARNING) << "Cholmod failure: integer overflow occured.";
282 return false;
283 case CHOLMOD_INVALID:
284 LOG(WARNING) << "Cholmod failure: invalid input.";
285 return false;
286 case CHOLMOD_NOT_POSDEF:
287 // TODO(sameeragarwal): These two warnings require more
288 // sophisticated handling going forward. For now we will be
289 // strict and treat them as failures.
290 LOG(WARNING) << "Cholmod warning: matrix not positive definite.";
291 return false;
292 case CHOLMOD_DSMALL:
293 LOG(WARNING) << "Cholmod warning: D for LDL' or diag(L) or "
294 << "LL' has tiny absolute value.";
295 return false;
296 case CHOLMOD_OK:
297 if (status != 0) {
298 return true;
299 }
300 LOG(WARNING) << "Cholmod failure: cholmod_factorize returned zero "
301 << "but cholmod_common::status is CHOLMOD_OK."
302 << "Please report this to ceres-solver@googlegroups.com.";
303 return false;
304 default:
305 LOG(WARNING) << "Unknown cholmod return code. "
306 << "Please report this to ceres-solver@googlegroups.com.";
307 return false;
308 }
309 return false;
310}
311
312cholmod_dense* SuiteSparse::Solve(cholmod_factor* L,
313 cholmod_dense* b) {
314 if (cc_.status != CHOLMOD_OK) {
315 LOG(WARNING) << "CHOLMOD status NOT OK";
316 return NULL;
317 }
318
319 return cholmod_solve(CHOLMOD_A, L, b, &cc_);
320}
321
322cholmod_dense* SuiteSparse::SolveCholesky(cholmod_sparse* A,
323 cholmod_factor* L,
324 cholmod_dense* b) {
325 CHECK_NOTNULL(A);
326 CHECK_NOTNULL(L);
327 CHECK_NOTNULL(b);
328
329 if (Cholesky(A, L)) {
330 return Solve(L, b);
331 }
332
333 return NULL;
334}
335
336} // namespace internal
337} // namespace ceres
338
339#endif // CERES_NO_SUITESPARSE