1 // 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: keir@google.com (Keir Mierle)
30
31 #include "ceres/compressed_row_jacobian_writer.h"
32
33 #include "ceres/casts.h"
34 #include "ceres/compressed_row_sparse_matrix.h"
35 #include "ceres/parameter_block.h"
36 #include "ceres/program.h"
37 #include "ceres/residual_block.h"
38 #include "ceres/scratch_evaluate_preparer.h"
39
40 namespace ceres {
41 namespace internal {
42
PopulateJacobianRowAndColumnBlockVectors(const Program * program,CompressedRowSparseMatrix * jacobian)43 void CompressedRowJacobianWriter::PopulateJacobianRowAndColumnBlockVectors(
44 const Program* program, CompressedRowSparseMatrix* jacobian) {
45 const vector<ParameterBlock*>& parameter_blocks =
46 program->parameter_blocks();
47 vector<int>& col_blocks = *(jacobian->mutable_col_blocks());
48 col_blocks.resize(parameter_blocks.size());
49 for (int i = 0; i < parameter_blocks.size(); ++i) {
50 col_blocks[i] = parameter_blocks[i]->LocalSize();
51 }
52
53 const vector<ResidualBlock*>& residual_blocks =
54 program->residual_blocks();
55 vector<int>& row_blocks = *(jacobian->mutable_row_blocks());
56 row_blocks.resize(residual_blocks.size());
57 for (int i = 0; i < residual_blocks.size(); ++i) {
58 row_blocks[i] = residual_blocks[i]->NumResiduals();
59 }
60 }
61
GetOrderedParameterBlocks(const Program * program,int residual_id,vector<pair<int,int>> * evaluated_jacobian_blocks)62 void CompressedRowJacobianWriter::GetOrderedParameterBlocks(
63 const Program* program,
64 int residual_id,
65 vector<pair<int, int> >* evaluated_jacobian_blocks) {
66 const ResidualBlock* residual_block =
67 program->residual_blocks()[residual_id];
68 const int num_parameter_blocks = residual_block->NumParameterBlocks();
69
70 for (int j = 0; j < num_parameter_blocks; ++j) {
71 const ParameterBlock* parameter_block =
72 residual_block->parameter_blocks()[j];
73 if (!parameter_block->IsConstant()) {
74 evaluated_jacobian_blocks->push_back(
75 make_pair(parameter_block->index(), j));
76 }
77 }
78 sort(evaluated_jacobian_blocks->begin(), evaluated_jacobian_blocks->end());
79 }
80
CreateJacobian() const81 SparseMatrix* CompressedRowJacobianWriter::CreateJacobian() const {
82 const vector<ResidualBlock*>& residual_blocks =
83 program_->residual_blocks();
84
85 int total_num_residuals = program_->NumResiduals();
86 int total_num_effective_parameters = program_->NumEffectiveParameters();
87
88 // Count the number of jacobian nonzeros.
89 int num_jacobian_nonzeros = 0;
90 for (int i = 0; i < residual_blocks.size(); ++i) {
91 ResidualBlock* residual_block = residual_blocks[i];
92 const int num_residuals = residual_block->NumResiduals();
93 const int num_parameter_blocks = residual_block->NumParameterBlocks();
94 for (int j = 0; j < num_parameter_blocks; ++j) {
95 ParameterBlock* parameter_block = residual_block->parameter_blocks()[j];
96 if (!parameter_block->IsConstant()) {
97 num_jacobian_nonzeros += num_residuals * parameter_block->LocalSize();
98 }
99 }
100 }
101
102 // Allocate storage for the jacobian with some extra space at the end.
103 // Allocate more space than needed to store the jacobian so that when the LM
104 // algorithm adds the diagonal, no reallocation is necessary. This reduces
105 // peak memory usage significantly.
106 CompressedRowSparseMatrix* jacobian =
107 new CompressedRowSparseMatrix(
108 total_num_residuals,
109 total_num_effective_parameters,
110 num_jacobian_nonzeros + total_num_effective_parameters);
111
112 // At this stage, the CompressedRowSparseMatrix is an invalid state. But this
113 // seems to be the only way to construct it without doing a memory copy.
114 int* rows = jacobian->mutable_rows();
115 int* cols = jacobian->mutable_cols();
116 int row_pos = 0;
117 rows[0] = 0;
118 for (int i = 0; i < residual_blocks.size(); ++i) {
119 const ResidualBlock* residual_block = residual_blocks[i];
120 const int num_parameter_blocks = residual_block->NumParameterBlocks();
121
122 // Count the number of derivatives for a row of this residual block and
123 // build a list of active parameter block indices.
124 int num_derivatives = 0;
125 vector<int> parameter_indices;
126 for (int j = 0; j < num_parameter_blocks; ++j) {
127 ParameterBlock* parameter_block = residual_block->parameter_blocks()[j];
128 if (!parameter_block->IsConstant()) {
129 parameter_indices.push_back(parameter_block->index());
130 num_derivatives += parameter_block->LocalSize();
131 }
132 }
133
134 // Sort the parameters by their position in the state vector.
135 sort(parameter_indices.begin(), parameter_indices.end());
136 CHECK(unique(parameter_indices.begin(), parameter_indices.end()) ==
137 parameter_indices.end())
138 << "Ceres internal error: "
139 << "Duplicate parameter blocks detected in a cost function. "
140 << "This should never happen. Please report this to "
141 << "the Ceres developers.";
142
143 // Update the row indices.
144 const int num_residuals = residual_block->NumResiduals();
145 for (int j = 0; j < num_residuals; ++j) {
146 rows[row_pos + j + 1] = rows[row_pos + j] + num_derivatives;
147 }
148
149 // Iterate over parameter blocks in the order which they occur in the
150 // parameter vector. This code mirrors that in Write(), where jacobian
151 // values are updated.
152 int col_pos = 0;
153 for (int j = 0; j < parameter_indices.size(); ++j) {
154 ParameterBlock* parameter_block =
155 program_->parameter_blocks()[parameter_indices[j]];
156 const int parameter_block_size = parameter_block->LocalSize();
157
158 for (int r = 0; r < num_residuals; ++r) {
159 // This is the position in the values array of the jacobian where this
160 // row of the jacobian block should go.
161 const int column_block_begin = rows[row_pos + r] + col_pos;
162
163 for (int c = 0; c < parameter_block_size; ++c) {
164 cols[column_block_begin + c] = parameter_block->delta_offset() + c;
165 }
166 }
167 col_pos += parameter_block_size;
168 }
169 row_pos += num_residuals;
170 }
171 CHECK_EQ(num_jacobian_nonzeros, rows[total_num_residuals]);
172
173 PopulateJacobianRowAndColumnBlockVectors(program_, jacobian);
174
175 return jacobian;
176 }
177
Write(int residual_id,int residual_offset,double ** jacobians,SparseMatrix * base_jacobian)178 void CompressedRowJacobianWriter::Write(int residual_id,
179 int residual_offset,
180 double **jacobians,
181 SparseMatrix* base_jacobian) {
182 CompressedRowSparseMatrix* jacobian =
183 down_cast<CompressedRowSparseMatrix*>(base_jacobian);
184
185 double* jacobian_values = jacobian->mutable_values();
186 const int* jacobian_rows = jacobian->rows();
187
188 const ResidualBlock* residual_block =
189 program_->residual_blocks()[residual_id];
190 const int num_residuals = residual_block->NumResiduals();
191
192 vector<pair<int, int> > evaluated_jacobian_blocks;
193 GetOrderedParameterBlocks(program_, residual_id, &evaluated_jacobian_blocks);
194
195 // Where in the current row does the jacobian for a parameter block begin.
196 int col_pos = 0;
197
198 // Iterate over the jacobian blocks in increasing order of their
199 // positions in the reduced parameter vector.
200 for (int i = 0; i < evaluated_jacobian_blocks.size(); ++i) {
201 const ParameterBlock* parameter_block =
202 program_->parameter_blocks()[evaluated_jacobian_blocks[i].first];
203 const int argument = evaluated_jacobian_blocks[i].second;
204 const int parameter_block_size = parameter_block->LocalSize();
205
206 // Copy one row of the jacobian block at a time.
207 for (int r = 0; r < num_residuals; ++r) {
208 // Position of the r^th row of the current jacobian block.
209 const double* block_row_begin =
210 jacobians[argument] + r * parameter_block_size;
211
212 // Position in the values array of the jacobian where this
213 // row of the jacobian block should go.
214 double* column_block_begin =
215 jacobian_values + jacobian_rows[residual_offset + r] + col_pos;
216
217 copy(block_row_begin,
218 block_row_begin + parameter_block_size,
219 column_block_begin);
220 }
221 col_pos += parameter_block_size;
222 }
223 }
224
225 } // namespace internal
226 } // namespace ceres
227