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