blob: 007346dba13acfece742f77db60a87e8ca22334f [file] [log] [blame]
Austin Schuh70cc9552019-01-21 19:46:48 -08001// Ceres Solver - A fast non-linear least squares minimizer
Austin Schuh3de38b02024-06-25 18:25:10 -07002// Copyright 2023 Google Inc. All rights reserved.
Austin Schuh70cc9552019-01-21 19:46:48 -08003// 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: keir@google.com (Keir Mierle)
30
31#include "ceres/compressed_row_jacobian_writer.h"
32
Austin Schuh3de38b02024-06-25 18:25:10 -070033#include <algorithm>
Austin Schuh70cc9552019-01-21 19:46:48 -080034#include <iterator>
Austin Schuh3de38b02024-06-25 18:25:10 -070035#include <memory>
36#include <string>
Austin Schuh70cc9552019-01-21 19:46:48 -080037#include <utility>
38#include <vector>
39
40#include "ceres/casts.h"
41#include "ceres/compressed_row_sparse_matrix.h"
42#include "ceres/parameter_block.h"
43#include "ceres/program.h"
44#include "ceres/residual_block.h"
45#include "ceres/scratch_evaluate_preparer.h"
46
Austin Schuh3de38b02024-06-25 18:25:10 -070047namespace ceres::internal {
Austin Schuh70cc9552019-01-21 19:46:48 -080048void CompressedRowJacobianWriter::PopulateJacobianRowAndColumnBlockVectors(
49 const Program* program, CompressedRowSparseMatrix* jacobian) {
Austin Schuh3de38b02024-06-25 18:25:10 -070050 const auto& parameter_blocks = program->parameter_blocks();
51 auto& col_blocks = *(jacobian->mutable_col_blocks());
Austin Schuh70cc9552019-01-21 19:46:48 -080052 col_blocks.resize(parameter_blocks.size());
Austin Schuh3de38b02024-06-25 18:25:10 -070053 int col_pos = 0;
Austin Schuh70cc9552019-01-21 19:46:48 -080054 for (int i = 0; i < parameter_blocks.size(); ++i) {
Austin Schuh3de38b02024-06-25 18:25:10 -070055 col_blocks[i].size = parameter_blocks[i]->TangentSize();
56 col_blocks[i].position = col_pos;
57 col_pos += col_blocks[i].size;
Austin Schuh70cc9552019-01-21 19:46:48 -080058 }
59
Austin Schuh3de38b02024-06-25 18:25:10 -070060 const auto& residual_blocks = program->residual_blocks();
61 auto& row_blocks = *(jacobian->mutable_row_blocks());
Austin Schuh70cc9552019-01-21 19:46:48 -080062 row_blocks.resize(residual_blocks.size());
Austin Schuh3de38b02024-06-25 18:25:10 -070063 int row_pos = 0;
Austin Schuh70cc9552019-01-21 19:46:48 -080064 for (int i = 0; i < residual_blocks.size(); ++i) {
Austin Schuh3de38b02024-06-25 18:25:10 -070065 row_blocks[i].size = residual_blocks[i]->NumResiduals();
66 row_blocks[i].position = row_pos;
67 row_pos += row_blocks[i].size;
Austin Schuh70cc9552019-01-21 19:46:48 -080068 }
69}
70
71void CompressedRowJacobianWriter::GetOrderedParameterBlocks(
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080072 const Program* program,
73 int residual_id,
Austin Schuh3de38b02024-06-25 18:25:10 -070074 std::vector<std::pair<int, int>>* evaluated_jacobian_blocks) {
75 auto residual_block = program->residual_blocks()[residual_id];
Austin Schuh70cc9552019-01-21 19:46:48 -080076 const int num_parameter_blocks = residual_block->NumParameterBlocks();
77
78 for (int j = 0; j < num_parameter_blocks; ++j) {
Austin Schuh3de38b02024-06-25 18:25:10 -070079 auto parameter_block = residual_block->parameter_blocks()[j];
Austin Schuh70cc9552019-01-21 19:46:48 -080080 if (!parameter_block->IsConstant()) {
81 evaluated_jacobian_blocks->push_back(
Austin Schuh3de38b02024-06-25 18:25:10 -070082 std::make_pair(parameter_block->index(), j));
Austin Schuh70cc9552019-01-21 19:46:48 -080083 }
84 }
Austin Schuh3de38b02024-06-25 18:25:10 -070085 std::sort(evaluated_jacobian_blocks->begin(),
86 evaluated_jacobian_blocks->end());
Austin Schuh70cc9552019-01-21 19:46:48 -080087}
88
Austin Schuh3de38b02024-06-25 18:25:10 -070089std::unique_ptr<SparseMatrix> CompressedRowJacobianWriter::CreateJacobian()
90 const {
91 const auto& residual_blocks = program_->residual_blocks();
Austin Schuh70cc9552019-01-21 19:46:48 -080092
Austin Schuh3de38b02024-06-25 18:25:10 -070093 const int total_num_residuals = program_->NumResiduals();
94 const int total_num_effective_parameters = program_->NumEffectiveParameters();
Austin Schuh70cc9552019-01-21 19:46:48 -080095
96 // Count the number of jacobian nonzeros.
Austin Schuh3de38b02024-06-25 18:25:10 -070097 //
98 // We used an unsigned int here, so that we can compare it INT_MAX without
99 // triggering overflow behaviour.
100 unsigned int num_jacobian_nonzeros = total_num_effective_parameters;
101 for (auto* residual_block : residual_blocks) {
Austin Schuh70cc9552019-01-21 19:46:48 -0800102 const int num_residuals = residual_block->NumResiduals();
103 const int num_parameter_blocks = residual_block->NumParameterBlocks();
104 for (int j = 0; j < num_parameter_blocks; ++j) {
Austin Schuh3de38b02024-06-25 18:25:10 -0700105 auto parameter_block = residual_block->parameter_blocks()[j];
Austin Schuh70cc9552019-01-21 19:46:48 -0800106 if (!parameter_block->IsConstant()) {
Austin Schuh3de38b02024-06-25 18:25:10 -0700107 num_jacobian_nonzeros += num_residuals * parameter_block->TangentSize();
108 if (num_jacobian_nonzeros > std::numeric_limits<int>::max()) {
109 LOG(ERROR) << "Unable to create Jacobian matrix: Too many entries in "
110 "the Jacobian matrix. num_jacobian_nonzeros = "
111 << num_jacobian_nonzeros;
112 return nullptr;
113 }
Austin Schuh70cc9552019-01-21 19:46:48 -0800114 }
115 }
116 }
117
118 // Allocate storage for the jacobian with some extra space at the end.
119 // Allocate more space than needed to store the jacobian so that when the LM
120 // algorithm adds the diagonal, no reallocation is necessary. This reduces
121 // peak memory usage significantly.
Austin Schuh3de38b02024-06-25 18:25:10 -0700122 auto jacobian = std::make_unique<CompressedRowSparseMatrix>(
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800123 total_num_residuals,
124 total_num_effective_parameters,
Austin Schuh3de38b02024-06-25 18:25:10 -0700125 static_cast<int>(num_jacobian_nonzeros));
Austin Schuh70cc9552019-01-21 19:46:48 -0800126
Austin Schuh3de38b02024-06-25 18:25:10 -0700127 // At this stage, the CompressedRowSparseMatrix is an invalid state. But
128 // this seems to be the only way to construct it without doing a memory
129 // copy.
Austin Schuh70cc9552019-01-21 19:46:48 -0800130 int* rows = jacobian->mutable_rows();
131 int* cols = jacobian->mutable_cols();
132
133 int row_pos = 0;
134 rows[0] = 0;
Austin Schuh3de38b02024-06-25 18:25:10 -0700135 for (auto* residual_block : residual_blocks) {
Austin Schuh70cc9552019-01-21 19:46:48 -0800136 const int num_parameter_blocks = residual_block->NumParameterBlocks();
137
138 // Count the number of derivatives for a row of this residual block and
139 // build a list of active parameter block indices.
140 int num_derivatives = 0;
Austin Schuh3de38b02024-06-25 18:25:10 -0700141 std::vector<int> parameter_indices;
Austin Schuh70cc9552019-01-21 19:46:48 -0800142 for (int j = 0; j < num_parameter_blocks; ++j) {
Austin Schuh3de38b02024-06-25 18:25:10 -0700143 auto parameter_block = residual_block->parameter_blocks()[j];
Austin Schuh70cc9552019-01-21 19:46:48 -0800144 if (!parameter_block->IsConstant()) {
145 parameter_indices.push_back(parameter_block->index());
Austin Schuh3de38b02024-06-25 18:25:10 -0700146 num_derivatives += parameter_block->TangentSize();
Austin Schuh70cc9552019-01-21 19:46:48 -0800147 }
148 }
149
150 // Sort the parameters by their position in the state vector.
Austin Schuh3de38b02024-06-25 18:25:10 -0700151 std::sort(parameter_indices.begin(), parameter_indices.end());
Austin Schuh70cc9552019-01-21 19:46:48 -0800152 if (adjacent_find(parameter_indices.begin(), parameter_indices.end()) !=
153 parameter_indices.end()) {
154 std::string parameter_block_description;
155 for (int j = 0; j < num_parameter_blocks; ++j) {
Austin Schuh3de38b02024-06-25 18:25:10 -0700156 auto parameter_block = residual_block->parameter_blocks()[j];
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800157 parameter_block_description += parameter_block->ToString() + "\n";
Austin Schuh70cc9552019-01-21 19:46:48 -0800158 }
159 LOG(FATAL) << "Ceres internal error: "
160 << "Duplicate parameter blocks detected in a cost function. "
161 << "This should never happen. Please report this to "
162 << "the Ceres developers.\n"
163 << "Residual Block: " << residual_block->ToString() << "\n"
164 << "Parameter Blocks: " << parameter_block_description;
165 }
166
167 // Update the row indices.
168 const int num_residuals = residual_block->NumResiduals();
169 for (int j = 0; j < num_residuals; ++j) {
170 rows[row_pos + j + 1] = rows[row_pos + j] + num_derivatives;
171 }
172
173 // Iterate over parameter blocks in the order which they occur in the
174 // parameter vector. This code mirrors that in Write(), where jacobian
175 // values are updated.
176 int col_pos = 0;
Austin Schuh3de38b02024-06-25 18:25:10 -0700177 for (int parameter_index : parameter_indices) {
178 auto parameter_block = program_->parameter_blocks()[parameter_index];
179 const int parameter_block_size = parameter_block->TangentSize();
Austin Schuh70cc9552019-01-21 19:46:48 -0800180
181 for (int r = 0; r < num_residuals; ++r) {
182 // This is the position in the values array of the jacobian where this
183 // row of the jacobian block should go.
184 const int column_block_begin = rows[row_pos + r] + col_pos;
Austin Schuh70cc9552019-01-21 19:46:48 -0800185 for (int c = 0; c < parameter_block_size; ++c) {
186 cols[column_block_begin + c] = parameter_block->delta_offset() + c;
187 }
188 }
189 col_pos += parameter_block_size;
190 }
191 row_pos += num_residuals;
192 }
Austin Schuh3de38b02024-06-25 18:25:10 -0700193 CHECK_EQ(num_jacobian_nonzeros - total_num_effective_parameters,
194 rows[total_num_residuals]);
Austin Schuh70cc9552019-01-21 19:46:48 -0800195
Austin Schuh3de38b02024-06-25 18:25:10 -0700196 PopulateJacobianRowAndColumnBlockVectors(program_, jacobian.get());
Austin Schuh70cc9552019-01-21 19:46:48 -0800197
198 return jacobian;
199}
200
201void CompressedRowJacobianWriter::Write(int residual_id,
202 int residual_offset,
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800203 double** jacobians,
Austin Schuh70cc9552019-01-21 19:46:48 -0800204 SparseMatrix* base_jacobian) {
Austin Schuh3de38b02024-06-25 18:25:10 -0700205 auto* jacobian = down_cast<CompressedRowSparseMatrix*>(base_jacobian);
Austin Schuh70cc9552019-01-21 19:46:48 -0800206
207 double* jacobian_values = jacobian->mutable_values();
208 const int* jacobian_rows = jacobian->rows();
209
Austin Schuh3de38b02024-06-25 18:25:10 -0700210 auto residual_block = program_->residual_blocks()[residual_id];
Austin Schuh70cc9552019-01-21 19:46:48 -0800211 const int num_residuals = residual_block->NumResiduals();
212
Austin Schuh3de38b02024-06-25 18:25:10 -0700213 std::vector<std::pair<int, int>> evaluated_jacobian_blocks;
Austin Schuh70cc9552019-01-21 19:46:48 -0800214 GetOrderedParameterBlocks(program_, residual_id, &evaluated_jacobian_blocks);
215
216 // Where in the current row does the jacobian for a parameter block begin.
217 int col_pos = 0;
218
219 // Iterate over the jacobian blocks in increasing order of their
220 // positions in the reduced parameter vector.
Austin Schuh3de38b02024-06-25 18:25:10 -0700221 for (auto& evaluated_jacobian_block : evaluated_jacobian_blocks) {
222 auto parameter_block =
223 program_->parameter_blocks()[evaluated_jacobian_block.first];
224 const int argument = evaluated_jacobian_block.second;
225 const int parameter_block_size = parameter_block->TangentSize();
Austin Schuh70cc9552019-01-21 19:46:48 -0800226
227 // Copy one row of the jacobian block at a time.
228 for (int r = 0; r < num_residuals; ++r) {
229 // Position of the r^th row of the current jacobian block.
230 const double* block_row_begin =
231 jacobians[argument] + r * parameter_block_size;
232
233 // Position in the values array of the jacobian where this
234 // row of the jacobian block should go.
235 double* column_block_begin =
236 jacobian_values + jacobian_rows[residual_offset + r] + col_pos;
237
238 std::copy(block_row_begin,
239 block_row_begin + parameter_block_size,
240 column_block_begin);
241 }
242 col_pos += parameter_block_size;
243 }
244}
245
Austin Schuh3de38b02024-06-25 18:25:10 -0700246} // namespace ceres::internal