Austin Schuh | 70cc955 | 2019-01-21 19:46:48 -0800 | [diff] [blame^] | 1 | // Ceres Solver - A fast non-linear least squares minimizer |
| 2 | // Copyright 2015 Google Inc. All rights reserved. |
| 3 | // 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: sameeragarwal@google.com (Sameer Agarwal) |
| 30 | // mierle@gmail.com (Keir Mierle) |
| 31 | |
| 32 | #include "ceres/problem_impl.h" |
| 33 | |
| 34 | #include <algorithm> |
| 35 | #include <cstddef> |
| 36 | #include <cstdint> |
| 37 | #include <iterator> |
| 38 | #include <memory> |
| 39 | #include <set> |
| 40 | #include <string> |
| 41 | #include <utility> |
| 42 | #include <vector> |
| 43 | |
| 44 | #include "ceres/casts.h" |
| 45 | #include "ceres/compressed_row_jacobian_writer.h" |
| 46 | #include "ceres/compressed_row_sparse_matrix.h" |
| 47 | #include "ceres/context_impl.h" |
| 48 | #include "ceres/cost_function.h" |
| 49 | #include "ceres/crs_matrix.h" |
| 50 | #include "ceres/evaluator.h" |
| 51 | #include "ceres/internal/port.h" |
| 52 | #include "ceres/loss_function.h" |
| 53 | #include "ceres/map_util.h" |
| 54 | #include "ceres/parameter_block.h" |
| 55 | #include "ceres/program.h" |
| 56 | #include "ceres/program_evaluator.h" |
| 57 | #include "ceres/residual_block.h" |
| 58 | #include "ceres/scratch_evaluate_preparer.h" |
| 59 | #include "ceres/stl_util.h" |
| 60 | #include "ceres/stringprintf.h" |
| 61 | #include "glog/logging.h" |
| 62 | |
| 63 | namespace ceres { |
| 64 | namespace internal { |
| 65 | |
| 66 | using std::map; |
| 67 | using std::string; |
| 68 | using std::vector; |
| 69 | |
| 70 | namespace { |
| 71 | // Returns true if two regions of memory, a and b, with sizes size_a and size_b |
| 72 | // respectively, overlap. |
| 73 | bool RegionsAlias(const double* a, int size_a, |
| 74 | const double* b, int size_b) { |
| 75 | return (a < b) ? b < (a + size_a) |
| 76 | : a < (b + size_b); |
| 77 | } |
| 78 | |
| 79 | void CheckForNoAliasing(double* existing_block, |
| 80 | int existing_block_size, |
| 81 | double* new_block, |
| 82 | int new_block_size) { |
| 83 | CHECK(!RegionsAlias(existing_block, existing_block_size, |
| 84 | new_block, new_block_size)) |
| 85 | << "Aliasing detected between existing parameter block at memory " |
| 86 | << "location " << existing_block |
| 87 | << " and has size " << existing_block_size << " with new parameter " |
| 88 | << "block that has memory address " << new_block << " and would have " |
| 89 | << "size " << new_block_size << "."; |
| 90 | } |
| 91 | |
| 92 | template <typename KeyType> |
| 93 | void DecrementValueOrDeleteKey(const KeyType key, |
| 94 | std::map<KeyType, int>* container) { |
| 95 | auto it = container->find(key); |
| 96 | if (it->second == 1) { |
| 97 | delete key; |
| 98 | container->erase(it); |
| 99 | } else { |
| 100 | --it->second; |
| 101 | } |
| 102 | } |
| 103 | |
| 104 | template <typename ForwardIterator> |
| 105 | void STLDeleteContainerPairFirstPointers(ForwardIterator begin, |
| 106 | ForwardIterator end) { |
| 107 | while (begin != end) { |
| 108 | delete begin->first; |
| 109 | ++begin; |
| 110 | } |
| 111 | } |
| 112 | |
| 113 | void InitializeContext(Context* context, |
| 114 | ContextImpl** context_impl, |
| 115 | bool* context_impl_owned) { |
| 116 | if (context == NULL) { |
| 117 | *context_impl_owned = true; |
| 118 | *context_impl = new ContextImpl; |
| 119 | } else { |
| 120 | *context_impl_owned = false; |
| 121 | *context_impl = down_cast<ContextImpl*>(context); |
| 122 | } |
| 123 | } |
| 124 | |
| 125 | } // namespace |
| 126 | |
| 127 | ParameterBlock* ProblemImpl::InternalAddParameterBlock(double* values, |
| 128 | int size) { |
| 129 | CHECK(values != NULL) << "Null pointer passed to AddParameterBlock " |
| 130 | << "for a parameter with size " << size; |
| 131 | |
| 132 | // Ignore the request if there is a block for the given pointer already. |
| 133 | ParameterMap::iterator it = parameter_block_map_.find(values); |
| 134 | if (it != parameter_block_map_.end()) { |
| 135 | if (!options_.disable_all_safety_checks) { |
| 136 | int existing_size = it->second->Size(); |
| 137 | CHECK(size == existing_size) |
| 138 | << "Tried adding a parameter block with the same double pointer, " |
| 139 | << values << ", twice, but with different block sizes. Original " |
| 140 | << "size was " << existing_size << " but new size is " |
| 141 | << size; |
| 142 | } |
| 143 | return it->second; |
| 144 | } |
| 145 | |
| 146 | if (!options_.disable_all_safety_checks) { |
| 147 | // Before adding the parameter block, also check that it doesn't alias any |
| 148 | // other parameter blocks. |
| 149 | if (!parameter_block_map_.empty()) { |
| 150 | ParameterMap::iterator lb = parameter_block_map_.lower_bound(values); |
| 151 | |
| 152 | // If lb is not the first block, check the previous block for aliasing. |
| 153 | if (lb != parameter_block_map_.begin()) { |
| 154 | ParameterMap::iterator previous = lb; |
| 155 | --previous; |
| 156 | CheckForNoAliasing(previous->first, |
| 157 | previous->second->Size(), |
| 158 | values, |
| 159 | size); |
| 160 | } |
| 161 | |
| 162 | // If lb is not off the end, check lb for aliasing. |
| 163 | if (lb != parameter_block_map_.end()) { |
| 164 | CheckForNoAliasing(lb->first, |
| 165 | lb->second->Size(), |
| 166 | values, |
| 167 | size); |
| 168 | } |
| 169 | } |
| 170 | } |
| 171 | |
| 172 | // Pass the index of the new parameter block as well to keep the index in |
| 173 | // sync with the position of the parameter in the program's parameter vector. |
| 174 | ParameterBlock* new_parameter_block = |
| 175 | new ParameterBlock(values, size, program_->parameter_blocks_.size()); |
| 176 | |
| 177 | // For dynamic problems, add the list of dependent residual blocks, which is |
| 178 | // empty to start. |
| 179 | if (options_.enable_fast_removal) { |
| 180 | new_parameter_block->EnableResidualBlockDependencies(); |
| 181 | } |
| 182 | parameter_block_map_[values] = new_parameter_block; |
| 183 | program_->parameter_blocks_.push_back(new_parameter_block); |
| 184 | return new_parameter_block; |
| 185 | } |
| 186 | |
| 187 | void ProblemImpl::InternalRemoveResidualBlock(ResidualBlock* residual_block) { |
| 188 | CHECK(residual_block != nullptr); |
| 189 | // Perform no check on the validity of residual_block, that is handled in |
| 190 | // the public method: RemoveResidualBlock(). |
| 191 | |
| 192 | // If needed, remove the parameter dependencies on this residual block. |
| 193 | if (options_.enable_fast_removal) { |
| 194 | const int num_parameter_blocks_for_residual = |
| 195 | residual_block->NumParameterBlocks(); |
| 196 | for (int i = 0; i < num_parameter_blocks_for_residual; ++i) { |
| 197 | residual_block->parameter_blocks()[i] |
| 198 | ->RemoveResidualBlock(residual_block); |
| 199 | } |
| 200 | |
| 201 | ResidualBlockSet::iterator it = residual_block_set_.find(residual_block); |
| 202 | residual_block_set_.erase(it); |
| 203 | } |
| 204 | DeleteBlockInVector(program_->mutable_residual_blocks(), residual_block); |
| 205 | } |
| 206 | |
| 207 | // Deletes the residual block in question, assuming there are no other |
| 208 | // references to it inside the problem (e.g. by another parameter). Referenced |
| 209 | // cost and loss functions are tucked away for future deletion, since it is not |
| 210 | // possible to know whether other parts of the problem depend on them without |
| 211 | // doing a full scan. |
| 212 | void ProblemImpl::DeleteBlock(ResidualBlock* residual_block) { |
| 213 | // The const casts here are legit, since ResidualBlock holds these |
| 214 | // pointers as const pointers but we have ownership of them and |
| 215 | // have the right to destroy them when the destructor is called. |
| 216 | CostFunction* cost_function = |
| 217 | const_cast<CostFunction*>(residual_block->cost_function()); |
| 218 | if (options_.cost_function_ownership == TAKE_OWNERSHIP) { |
| 219 | DecrementValueOrDeleteKey(cost_function, &cost_function_ref_count_); |
| 220 | } |
| 221 | |
| 222 | LossFunction* loss_function = |
| 223 | const_cast<LossFunction*>(residual_block->loss_function()); |
| 224 | if (options_.loss_function_ownership == TAKE_OWNERSHIP && |
| 225 | loss_function != NULL) { |
| 226 | DecrementValueOrDeleteKey(loss_function, &loss_function_ref_count_); |
| 227 | } |
| 228 | |
| 229 | delete residual_block; |
| 230 | } |
| 231 | |
| 232 | // Deletes the parameter block in question, assuming there are no other |
| 233 | // references to it inside the problem (e.g. by any residual blocks). |
| 234 | // Referenced parameterizations are tucked away for future deletion, since it |
| 235 | // is not possible to know whether other parts of the problem depend on them |
| 236 | // without doing a full scan. |
| 237 | void ProblemImpl::DeleteBlock(ParameterBlock* parameter_block) { |
| 238 | if (options_.local_parameterization_ownership == TAKE_OWNERSHIP && |
| 239 | parameter_block->local_parameterization() != NULL) { |
| 240 | local_parameterizations_to_delete_.push_back( |
| 241 | parameter_block->mutable_local_parameterization()); |
| 242 | } |
| 243 | parameter_block_map_.erase(parameter_block->mutable_user_state()); |
| 244 | delete parameter_block; |
| 245 | } |
| 246 | |
| 247 | ProblemImpl::ProblemImpl() |
| 248 | : options_(Problem::Options()), |
| 249 | program_(new internal::Program) { |
| 250 | InitializeContext(options_.context, &context_impl_, &context_impl_owned_); |
| 251 | } |
| 252 | |
| 253 | ProblemImpl::ProblemImpl(const Problem::Options& options) |
| 254 | : options_(options), |
| 255 | program_(new internal::Program) { |
| 256 | InitializeContext(options_.context, &context_impl_, &context_impl_owned_); |
| 257 | } |
| 258 | |
| 259 | ProblemImpl::~ProblemImpl() { |
| 260 | STLDeleteContainerPointers(program_->residual_blocks_.begin(), |
| 261 | program_->residual_blocks_.end()); |
| 262 | |
| 263 | if (options_.cost_function_ownership == TAKE_OWNERSHIP) { |
| 264 | STLDeleteContainerPairFirstPointers(cost_function_ref_count_.begin(), |
| 265 | cost_function_ref_count_.end()); |
| 266 | } |
| 267 | |
| 268 | if (options_.loss_function_ownership == TAKE_OWNERSHIP) { |
| 269 | STLDeleteContainerPairFirstPointers(loss_function_ref_count_.begin(), |
| 270 | loss_function_ref_count_.end()); |
| 271 | } |
| 272 | |
| 273 | // Collect the unique parameterizations and delete the parameters. |
| 274 | for (int i = 0; i < program_->parameter_blocks_.size(); ++i) { |
| 275 | DeleteBlock(program_->parameter_blocks_[i]); |
| 276 | } |
| 277 | |
| 278 | // Delete the owned parameterizations. |
| 279 | STLDeleteUniqueContainerPointers(local_parameterizations_to_delete_.begin(), |
| 280 | local_parameterizations_to_delete_.end()); |
| 281 | |
| 282 | if (context_impl_owned_) { |
| 283 | delete context_impl_; |
| 284 | } |
| 285 | } |
| 286 | |
| 287 | ResidualBlockId ProblemImpl::AddResidualBlock( |
| 288 | CostFunction* cost_function, |
| 289 | LossFunction* loss_function, |
| 290 | double* const* const parameter_blocks, |
| 291 | int num_parameter_blocks) { |
| 292 | CHECK(cost_function != nullptr); |
| 293 | CHECK_EQ(num_parameter_blocks, |
| 294 | cost_function->parameter_block_sizes().size()); |
| 295 | |
| 296 | // Check the sizes match. |
| 297 | const vector<int32_t>& parameter_block_sizes = |
| 298 | cost_function->parameter_block_sizes(); |
| 299 | |
| 300 | if (!options_.disable_all_safety_checks) { |
| 301 | CHECK_EQ(parameter_block_sizes.size(), num_parameter_blocks) |
| 302 | << "Number of blocks input is different than the number of blocks " |
| 303 | << "that the cost function expects."; |
| 304 | |
| 305 | // Check for duplicate parameter blocks. |
| 306 | vector<double*> sorted_parameter_blocks( |
| 307 | parameter_blocks, parameter_blocks + num_parameter_blocks); |
| 308 | sort(sorted_parameter_blocks.begin(), sorted_parameter_blocks.end()); |
| 309 | const bool has_duplicate_items = |
| 310 | (std::adjacent_find(sorted_parameter_blocks.begin(), |
| 311 | sorted_parameter_blocks.end()) |
| 312 | != sorted_parameter_blocks.end()); |
| 313 | if (has_duplicate_items) { |
| 314 | string blocks; |
| 315 | for (int i = 0; i < num_parameter_blocks; ++i) { |
| 316 | blocks += StringPrintf(" %p ", parameter_blocks[i]); |
| 317 | } |
| 318 | |
| 319 | LOG(FATAL) << "Duplicate parameter blocks in a residual parameter " |
| 320 | << "are not allowed. Parameter block pointers: [" |
| 321 | << blocks << "]"; |
| 322 | } |
| 323 | } |
| 324 | |
| 325 | // Add parameter blocks and convert the double*'s to parameter blocks. |
| 326 | vector<ParameterBlock*> parameter_block_ptrs(num_parameter_blocks); |
| 327 | for (int i = 0; i < num_parameter_blocks; ++i) { |
| 328 | parameter_block_ptrs[i] = |
| 329 | InternalAddParameterBlock(parameter_blocks[i], |
| 330 | parameter_block_sizes[i]); |
| 331 | } |
| 332 | |
| 333 | if (!options_.disable_all_safety_checks) { |
| 334 | // Check that the block sizes match the block sizes expected by the |
| 335 | // cost_function. |
| 336 | for (int i = 0; i < parameter_block_ptrs.size(); ++i) { |
| 337 | CHECK_EQ(cost_function->parameter_block_sizes()[i], |
| 338 | parameter_block_ptrs[i]->Size()) |
| 339 | << "The cost function expects parameter block " << i |
| 340 | << " of size " << cost_function->parameter_block_sizes()[i] |
| 341 | << " but was given a block of size " |
| 342 | << parameter_block_ptrs[i]->Size(); |
| 343 | } |
| 344 | } |
| 345 | |
| 346 | ResidualBlock* new_residual_block = |
| 347 | new ResidualBlock(cost_function, |
| 348 | loss_function, |
| 349 | parameter_block_ptrs, |
| 350 | program_->residual_blocks_.size()); |
| 351 | |
| 352 | // Add dependencies on the residual to the parameter blocks. |
| 353 | if (options_.enable_fast_removal) { |
| 354 | for (int i = 0; i < num_parameter_blocks; ++i) { |
| 355 | parameter_block_ptrs[i]->AddResidualBlock(new_residual_block); |
| 356 | } |
| 357 | } |
| 358 | |
| 359 | program_->residual_blocks_.push_back(new_residual_block); |
| 360 | |
| 361 | if (options_.enable_fast_removal) { |
| 362 | residual_block_set_.insert(new_residual_block); |
| 363 | } |
| 364 | |
| 365 | if (options_.cost_function_ownership == TAKE_OWNERSHIP) { |
| 366 | // Increment the reference count, creating an entry in the table if |
| 367 | // needed. Note: C++ maps guarantee that new entries have default |
| 368 | // constructed values; this implies integers are zero initialized. |
| 369 | ++cost_function_ref_count_[cost_function]; |
| 370 | } |
| 371 | |
| 372 | if (options_.loss_function_ownership == TAKE_OWNERSHIP && |
| 373 | loss_function != NULL) { |
| 374 | ++loss_function_ref_count_[loss_function]; |
| 375 | } |
| 376 | |
| 377 | return new_residual_block; |
| 378 | } |
| 379 | |
| 380 | void ProblemImpl::AddParameterBlock(double* values, int size) { |
| 381 | InternalAddParameterBlock(values, size); |
| 382 | } |
| 383 | |
| 384 | void ProblemImpl::AddParameterBlock( |
| 385 | double* values, |
| 386 | int size, |
| 387 | LocalParameterization* local_parameterization) { |
| 388 | ParameterBlock* parameter_block = |
| 389 | InternalAddParameterBlock(values, size); |
| 390 | if (local_parameterization != NULL) { |
| 391 | parameter_block->SetParameterization(local_parameterization); |
| 392 | } |
| 393 | } |
| 394 | |
| 395 | // Delete a block from a vector of blocks, maintaining the indexing invariant. |
| 396 | // This is done in constant time by moving an element from the end of the |
| 397 | // vector over the element to remove, then popping the last element. It |
| 398 | // destroys the ordering in the interest of speed. |
| 399 | template<typename Block> |
| 400 | void ProblemImpl::DeleteBlockInVector(vector<Block*>* mutable_blocks, |
| 401 | Block* block_to_remove) { |
| 402 | CHECK_EQ((*mutable_blocks)[block_to_remove->index()], block_to_remove) |
| 403 | << "You found a Ceres bug! \n" |
| 404 | << "Block requested: " |
| 405 | << block_to_remove->ToString() << "\n" |
| 406 | << "Block present: " |
| 407 | << (*mutable_blocks)[block_to_remove->index()]->ToString(); |
| 408 | |
| 409 | // Prepare the to-be-moved block for the new, lower-in-index position by |
| 410 | // setting the index to the blocks final location. |
| 411 | Block* tmp = mutable_blocks->back(); |
| 412 | tmp->set_index(block_to_remove->index()); |
| 413 | |
| 414 | // Overwrite the to-be-deleted residual block with the one at the end. |
| 415 | (*mutable_blocks)[block_to_remove->index()] = tmp; |
| 416 | |
| 417 | DeleteBlock(block_to_remove); |
| 418 | |
| 419 | // The block is gone so shrink the vector of blocks accordingly. |
| 420 | mutable_blocks->pop_back(); |
| 421 | } |
| 422 | |
| 423 | void ProblemImpl::RemoveResidualBlock(ResidualBlock* residual_block) { |
| 424 | CHECK(residual_block != nullptr); |
| 425 | |
| 426 | // Verify that residual_block identifies a residual in the current problem. |
| 427 | const string residual_not_found_message = |
| 428 | StringPrintf("Residual block to remove: %p not found. This usually means " |
| 429 | "one of three things have happened:\n" |
| 430 | " 1) residual_block is uninitialised and points to a random " |
| 431 | "area in memory.\n" |
| 432 | " 2) residual_block represented a residual that was added to" |
| 433 | " the problem, but referred to a parameter block which has " |
| 434 | "since been removed, which removes all residuals which " |
| 435 | "depend on that parameter block, and was thus removed.\n" |
| 436 | " 3) residual_block referred to a residual that has already " |
| 437 | "been removed from the problem (by the user).", |
| 438 | residual_block); |
| 439 | if (options_.enable_fast_removal) { |
| 440 | CHECK(residual_block_set_.find(residual_block) != |
| 441 | residual_block_set_.end()) |
| 442 | << residual_not_found_message; |
| 443 | } else { |
| 444 | // Perform a full search over all current residuals. |
| 445 | CHECK(std::find(program_->residual_blocks().begin(), |
| 446 | program_->residual_blocks().end(), |
| 447 | residual_block) != program_->residual_blocks().end()) |
| 448 | << residual_not_found_message; |
| 449 | } |
| 450 | |
| 451 | InternalRemoveResidualBlock(residual_block); |
| 452 | } |
| 453 | |
| 454 | void ProblemImpl::RemoveParameterBlock(double* values) { |
| 455 | ParameterBlock* parameter_block = |
| 456 | FindWithDefault(parameter_block_map_, values, NULL); |
| 457 | if (parameter_block == NULL) { |
| 458 | LOG(FATAL) << "Parameter block not found: " << values |
| 459 | << ". You must add the parameter block to the problem before " |
| 460 | << "it can be removed."; |
| 461 | } |
| 462 | |
| 463 | if (options_.enable_fast_removal) { |
| 464 | // Copy the dependent residuals from the parameter block because the set of |
| 465 | // dependents will change after each call to RemoveResidualBlock(). |
| 466 | vector<ResidualBlock*> residual_blocks_to_remove( |
| 467 | parameter_block->mutable_residual_blocks()->begin(), |
| 468 | parameter_block->mutable_residual_blocks()->end()); |
| 469 | for (int i = 0; i < residual_blocks_to_remove.size(); ++i) { |
| 470 | InternalRemoveResidualBlock(residual_blocks_to_remove[i]); |
| 471 | } |
| 472 | } else { |
| 473 | // Scan all the residual blocks to remove ones that depend on the parameter |
| 474 | // block. Do the scan backwards since the vector changes while iterating. |
| 475 | const int num_residual_blocks = NumResidualBlocks(); |
| 476 | for (int i = num_residual_blocks - 1; i >= 0; --i) { |
| 477 | ResidualBlock* residual_block = |
| 478 | (*(program_->mutable_residual_blocks()))[i]; |
| 479 | const int num_parameter_blocks = residual_block->NumParameterBlocks(); |
| 480 | for (int j = 0; j < num_parameter_blocks; ++j) { |
| 481 | if (residual_block->parameter_blocks()[j] == parameter_block) { |
| 482 | InternalRemoveResidualBlock(residual_block); |
| 483 | // The parameter blocks are guaranteed unique. |
| 484 | break; |
| 485 | } |
| 486 | } |
| 487 | } |
| 488 | } |
| 489 | DeleteBlockInVector(program_->mutable_parameter_blocks(), parameter_block); |
| 490 | } |
| 491 | |
| 492 | void ProblemImpl::SetParameterBlockConstant(double* values) { |
| 493 | ParameterBlock* parameter_block = |
| 494 | FindWithDefault(parameter_block_map_, values, NULL); |
| 495 | if (parameter_block == NULL) { |
| 496 | LOG(FATAL) << "Parameter block not found: " << values |
| 497 | << ". You must add the parameter block to the problem before " |
| 498 | << "it can be set constant."; |
| 499 | } |
| 500 | |
| 501 | parameter_block->SetConstant(); |
| 502 | } |
| 503 | |
| 504 | bool ProblemImpl::IsParameterBlockConstant(double* values) const { |
| 505 | const ParameterBlock* parameter_block = |
| 506 | FindWithDefault(parameter_block_map_, values, NULL); |
| 507 | CHECK(parameter_block != NULL) |
| 508 | << "Parameter block not found: " << values << ". You must add the " |
| 509 | << "parameter block to the problem before it can be queried."; |
| 510 | |
| 511 | return parameter_block->IsSetConstantByUser(); |
| 512 | } |
| 513 | |
| 514 | void ProblemImpl::SetParameterBlockVariable(double* values) { |
| 515 | ParameterBlock* parameter_block = |
| 516 | FindWithDefault(parameter_block_map_, values, NULL); |
| 517 | if (parameter_block == NULL) { |
| 518 | LOG(FATAL) << "Parameter block not found: " << values |
| 519 | << ". You must add the parameter block to the problem before " |
| 520 | << "it can be set varying."; |
| 521 | } |
| 522 | |
| 523 | parameter_block->SetVarying(); |
| 524 | } |
| 525 | |
| 526 | void ProblemImpl::SetParameterization( |
| 527 | double* values, |
| 528 | LocalParameterization* local_parameterization) { |
| 529 | ParameterBlock* parameter_block = |
| 530 | FindWithDefault(parameter_block_map_, values, NULL); |
| 531 | if (parameter_block == NULL) { |
| 532 | LOG(FATAL) << "Parameter block not found: " << values |
| 533 | << ". You must add the parameter block to the problem before " |
| 534 | << "you can set its local parameterization."; |
| 535 | } |
| 536 | |
| 537 | parameter_block->SetParameterization(local_parameterization); |
| 538 | } |
| 539 | |
| 540 | const LocalParameterization* ProblemImpl::GetParameterization( |
| 541 | double* values) const { |
| 542 | ParameterBlock* parameter_block = |
| 543 | FindWithDefault(parameter_block_map_, values, NULL); |
| 544 | if (parameter_block == NULL) { |
| 545 | LOG(FATAL) << "Parameter block not found: " << values |
| 546 | << ". You must add the parameter block to the problem before " |
| 547 | << "you can get its local parameterization."; |
| 548 | } |
| 549 | |
| 550 | return parameter_block->local_parameterization(); |
| 551 | } |
| 552 | |
| 553 | void ProblemImpl::SetParameterLowerBound(double* values, |
| 554 | int index, |
| 555 | double lower_bound) { |
| 556 | ParameterBlock* parameter_block = |
| 557 | FindWithDefault(parameter_block_map_, values, NULL); |
| 558 | if (parameter_block == NULL) { |
| 559 | LOG(FATAL) << "Parameter block not found: " << values |
| 560 | << ". You must add the parameter block to the problem before " |
| 561 | << "you can set a lower bound on one of its components."; |
| 562 | } |
| 563 | |
| 564 | parameter_block->SetLowerBound(index, lower_bound); |
| 565 | } |
| 566 | |
| 567 | void ProblemImpl::SetParameterUpperBound(double* values, |
| 568 | int index, |
| 569 | double upper_bound) { |
| 570 | ParameterBlock* parameter_block = |
| 571 | FindWithDefault(parameter_block_map_, values, NULL); |
| 572 | if (parameter_block == NULL) { |
| 573 | LOG(FATAL) << "Parameter block not found: " << values |
| 574 | << ". You must add the parameter block to the problem before " |
| 575 | << "you can set an upper bound on one of its components."; |
| 576 | } |
| 577 | parameter_block->SetUpperBound(index, upper_bound); |
| 578 | } |
| 579 | |
| 580 | double ProblemImpl::GetParameterLowerBound(double* values, int index) const { |
| 581 | ParameterBlock* parameter_block = |
| 582 | FindWithDefault(parameter_block_map_, values, NULL); |
| 583 | if (parameter_block == NULL) { |
| 584 | LOG(FATAL) << "Parameter block not found: " << values |
| 585 | << ". You must add the parameter block to the problem before " |
| 586 | << "you can get the lower bound on one of its components."; |
| 587 | } |
| 588 | return parameter_block->LowerBound(index); |
| 589 | } |
| 590 | |
| 591 | double ProblemImpl::GetParameterUpperBound(double* values, int index) const { |
| 592 | ParameterBlock* parameter_block = |
| 593 | FindWithDefault(parameter_block_map_, values, NULL); |
| 594 | if (parameter_block == NULL) { |
| 595 | LOG(FATAL) << "Parameter block not found: " << values |
| 596 | << ". You must add the parameter block to the problem before " |
| 597 | << "you can set an upper bound on one of its components."; |
| 598 | } |
| 599 | return parameter_block->UpperBound(index); |
| 600 | } |
| 601 | |
| 602 | bool ProblemImpl::Evaluate(const Problem::EvaluateOptions& evaluate_options, |
| 603 | double* cost, |
| 604 | vector<double>* residuals, |
| 605 | vector<double>* gradient, |
| 606 | CRSMatrix* jacobian) { |
| 607 | if (cost == NULL && |
| 608 | residuals == NULL && |
| 609 | gradient == NULL && |
| 610 | jacobian == NULL) { |
| 611 | LOG(INFO) << "Nothing to do."; |
| 612 | return true; |
| 613 | } |
| 614 | |
| 615 | // If the user supplied residual blocks, then use them, otherwise |
| 616 | // take the residual blocks from the underlying program. |
| 617 | Program program; |
| 618 | *program.mutable_residual_blocks() = |
| 619 | ((evaluate_options.residual_blocks.size() > 0) |
| 620 | ? evaluate_options.residual_blocks : program_->residual_blocks()); |
| 621 | |
| 622 | const vector<double*>& parameter_block_ptrs = |
| 623 | evaluate_options.parameter_blocks; |
| 624 | |
| 625 | vector<ParameterBlock*> variable_parameter_blocks; |
| 626 | vector<ParameterBlock*>& parameter_blocks = |
| 627 | *program.mutable_parameter_blocks(); |
| 628 | |
| 629 | if (parameter_block_ptrs.size() == 0) { |
| 630 | // The user did not provide any parameter blocks, so default to |
| 631 | // using all the parameter blocks in the order that they are in |
| 632 | // the underlying program object. |
| 633 | parameter_blocks = program_->parameter_blocks(); |
| 634 | } else { |
| 635 | // The user supplied a vector of parameter blocks. Using this list |
| 636 | // requires a number of steps. |
| 637 | |
| 638 | // 1. Convert double* into ParameterBlock* |
| 639 | parameter_blocks.resize(parameter_block_ptrs.size()); |
| 640 | for (int i = 0; i < parameter_block_ptrs.size(); ++i) { |
| 641 | parameter_blocks[i] = FindWithDefault(parameter_block_map_, |
| 642 | parameter_block_ptrs[i], |
| 643 | NULL); |
| 644 | if (parameter_blocks[i] == NULL) { |
| 645 | LOG(FATAL) << "No known parameter block for " |
| 646 | << "Problem::Evaluate::Options.parameter_blocks[" << i << "]" |
| 647 | << " = " << parameter_block_ptrs[i]; |
| 648 | } |
| 649 | } |
| 650 | |
| 651 | // 2. The user may have only supplied a subset of parameter |
| 652 | // blocks, so identify the ones that are not supplied by the user |
| 653 | // and are NOT constant. These parameter blocks are stored in |
| 654 | // variable_parameter_blocks. |
| 655 | // |
| 656 | // To ensure that the parameter blocks are not included in the |
| 657 | // columns of the jacobian, we need to make sure that they are |
| 658 | // constant during evaluation and then make them variable again |
| 659 | // after we are done. |
| 660 | vector<ParameterBlock*> all_parameter_blocks(program_->parameter_blocks()); |
| 661 | vector<ParameterBlock*> included_parameter_blocks( |
| 662 | program.parameter_blocks()); |
| 663 | |
| 664 | vector<ParameterBlock*> excluded_parameter_blocks; |
| 665 | sort(all_parameter_blocks.begin(), all_parameter_blocks.end()); |
| 666 | sort(included_parameter_blocks.begin(), included_parameter_blocks.end()); |
| 667 | set_difference(all_parameter_blocks.begin(), |
| 668 | all_parameter_blocks.end(), |
| 669 | included_parameter_blocks.begin(), |
| 670 | included_parameter_blocks.end(), |
| 671 | back_inserter(excluded_parameter_blocks)); |
| 672 | |
| 673 | variable_parameter_blocks.reserve(excluded_parameter_blocks.size()); |
| 674 | for (int i = 0; i < excluded_parameter_blocks.size(); ++i) { |
| 675 | ParameterBlock* parameter_block = excluded_parameter_blocks[i]; |
| 676 | if (!parameter_block->IsConstant()) { |
| 677 | variable_parameter_blocks.push_back(parameter_block); |
| 678 | parameter_block->SetConstant(); |
| 679 | } |
| 680 | } |
| 681 | } |
| 682 | |
| 683 | // Setup the Parameter indices and offsets before an evaluator can |
| 684 | // be constructed and used. |
| 685 | program.SetParameterOffsetsAndIndex(); |
| 686 | |
| 687 | Evaluator::Options evaluator_options; |
| 688 | |
| 689 | // Even though using SPARSE_NORMAL_CHOLESKY requires SuiteSparse or |
| 690 | // CXSparse, here it just being used for telling the evaluator to |
| 691 | // use a SparseRowCompressedMatrix for the jacobian. This is because |
| 692 | // the Evaluator decides the storage for the Jacobian based on the |
| 693 | // type of linear solver being used. |
| 694 | evaluator_options.linear_solver_type = SPARSE_NORMAL_CHOLESKY; |
| 695 | #ifdef CERES_NO_THREADS |
| 696 | LOG_IF(WARNING, evaluate_options.num_threads > 1) |
| 697 | << "No threading support is compiled into this binary; " |
| 698 | << "only evaluate_options.num_threads = 1 is supported. Switching " |
| 699 | << "to single threaded mode."; |
| 700 | evaluator_options.num_threads = 1; |
| 701 | #else |
| 702 | evaluator_options.num_threads = evaluate_options.num_threads; |
| 703 | #endif // CERES_NO_THREADS |
| 704 | |
| 705 | // The main thread also does work so we only need to launch num_threads - 1. |
| 706 | context_impl_->EnsureMinimumThreads(evaluator_options.num_threads - 1); |
| 707 | evaluator_options.context = context_impl_; |
| 708 | |
| 709 | std::unique_ptr<Evaluator> evaluator( |
| 710 | new ProgramEvaluator<ScratchEvaluatePreparer, |
| 711 | CompressedRowJacobianWriter>(evaluator_options, |
| 712 | &program)); |
| 713 | |
| 714 | if (residuals !=NULL) { |
| 715 | residuals->resize(evaluator->NumResiduals()); |
| 716 | } |
| 717 | |
| 718 | if (gradient != NULL) { |
| 719 | gradient->resize(evaluator->NumEffectiveParameters()); |
| 720 | } |
| 721 | |
| 722 | std::unique_ptr<CompressedRowSparseMatrix> tmp_jacobian; |
| 723 | if (jacobian != NULL) { |
| 724 | tmp_jacobian.reset( |
| 725 | down_cast<CompressedRowSparseMatrix*>(evaluator->CreateJacobian())); |
| 726 | } |
| 727 | |
| 728 | // Point the state pointers to the user state pointers. This is |
| 729 | // needed so that we can extract a parameter vector which is then |
| 730 | // passed to Evaluator::Evaluate. |
| 731 | program.SetParameterBlockStatePtrsToUserStatePtrs(); |
| 732 | |
| 733 | // Copy the value of the parameter blocks into a vector, since the |
| 734 | // Evaluate::Evaluate method needs its input as such. The previous |
| 735 | // call to SetParameterBlockStatePtrsToUserStatePtrs ensures that |
| 736 | // these values are the ones corresponding to the actual state of |
| 737 | // the parameter blocks, rather than the temporary state pointer |
| 738 | // used for evaluation. |
| 739 | Vector parameters(program.NumParameters()); |
| 740 | program.ParameterBlocksToStateVector(parameters.data()); |
| 741 | |
| 742 | double tmp_cost = 0; |
| 743 | |
| 744 | Evaluator::EvaluateOptions evaluator_evaluate_options; |
| 745 | evaluator_evaluate_options.apply_loss_function = |
| 746 | evaluate_options.apply_loss_function; |
| 747 | bool status = evaluator->Evaluate(evaluator_evaluate_options, |
| 748 | parameters.data(), |
| 749 | &tmp_cost, |
| 750 | residuals != NULL ? &(*residuals)[0] : NULL, |
| 751 | gradient != NULL ? &(*gradient)[0] : NULL, |
| 752 | tmp_jacobian.get()); |
| 753 | |
| 754 | // Make the parameter blocks that were temporarily marked constant, |
| 755 | // variable again. |
| 756 | for (int i = 0; i < variable_parameter_blocks.size(); ++i) { |
| 757 | variable_parameter_blocks[i]->SetVarying(); |
| 758 | } |
| 759 | |
| 760 | if (status) { |
| 761 | if (cost != NULL) { |
| 762 | *cost = tmp_cost; |
| 763 | } |
| 764 | if (jacobian != NULL) { |
| 765 | tmp_jacobian->ToCRSMatrix(jacobian); |
| 766 | } |
| 767 | } |
| 768 | |
| 769 | program_->SetParameterBlockStatePtrsToUserStatePtrs(); |
| 770 | program_->SetParameterOffsetsAndIndex(); |
| 771 | return status; |
| 772 | } |
| 773 | |
| 774 | int ProblemImpl::NumParameterBlocks() const { |
| 775 | return program_->NumParameterBlocks(); |
| 776 | } |
| 777 | |
| 778 | int ProblemImpl::NumParameters() const { |
| 779 | return program_->NumParameters(); |
| 780 | } |
| 781 | |
| 782 | int ProblemImpl::NumResidualBlocks() const { |
| 783 | return program_->NumResidualBlocks(); |
| 784 | } |
| 785 | |
| 786 | int ProblemImpl::NumResiduals() const { |
| 787 | return program_->NumResiduals(); |
| 788 | } |
| 789 | |
| 790 | int ProblemImpl::ParameterBlockSize(const double* values) const { |
| 791 | ParameterBlock* parameter_block = |
| 792 | FindWithDefault(parameter_block_map_, const_cast<double*>(values), NULL); |
| 793 | if (parameter_block == NULL) { |
| 794 | LOG(FATAL) << "Parameter block not found: " << values |
| 795 | << ". You must add the parameter block to the problem before " |
| 796 | << "you can get its size."; |
| 797 | } |
| 798 | |
| 799 | return parameter_block->Size(); |
| 800 | } |
| 801 | |
| 802 | int ProblemImpl::ParameterBlockLocalSize(const double* values) const { |
| 803 | ParameterBlock* parameter_block = |
| 804 | FindWithDefault(parameter_block_map_, const_cast<double*>(values), NULL); |
| 805 | if (parameter_block == NULL) { |
| 806 | LOG(FATAL) << "Parameter block not found: " << values |
| 807 | << ". You must add the parameter block to the problem before " |
| 808 | << "you can get its local size."; |
| 809 | } |
| 810 | |
| 811 | return parameter_block->LocalSize(); |
| 812 | } |
| 813 | |
| 814 | bool ProblemImpl::HasParameterBlock(const double* parameter_block) const { |
| 815 | return (parameter_block_map_.find(const_cast<double*>(parameter_block)) != |
| 816 | parameter_block_map_.end()); |
| 817 | } |
| 818 | |
| 819 | void ProblemImpl::GetParameterBlocks(vector<double*>* parameter_blocks) const { |
| 820 | CHECK(parameter_blocks != nullptr); |
| 821 | parameter_blocks->resize(0); |
| 822 | parameter_blocks->reserve(parameter_block_map_.size()); |
| 823 | for (const auto& entry : parameter_block_map_) { |
| 824 | parameter_blocks->push_back(entry.first); |
| 825 | } |
| 826 | } |
| 827 | |
| 828 | void ProblemImpl::GetResidualBlocks( |
| 829 | vector<ResidualBlockId>* residual_blocks) const { |
| 830 | CHECK(residual_blocks != nullptr); |
| 831 | *residual_blocks = program().residual_blocks(); |
| 832 | } |
| 833 | |
| 834 | void ProblemImpl::GetParameterBlocksForResidualBlock( |
| 835 | const ResidualBlockId residual_block, |
| 836 | vector<double*>* parameter_blocks) const { |
| 837 | int num_parameter_blocks = residual_block->NumParameterBlocks(); |
| 838 | CHECK(parameter_blocks != nullptr); |
| 839 | parameter_blocks->resize(num_parameter_blocks); |
| 840 | for (int i = 0; i < num_parameter_blocks; ++i) { |
| 841 | (*parameter_blocks)[i] = |
| 842 | residual_block->parameter_blocks()[i]->mutable_user_state(); |
| 843 | } |
| 844 | } |
| 845 | |
| 846 | const CostFunction* ProblemImpl::GetCostFunctionForResidualBlock( |
| 847 | const ResidualBlockId residual_block) const { |
| 848 | return residual_block->cost_function(); |
| 849 | } |
| 850 | |
| 851 | const LossFunction* ProblemImpl::GetLossFunctionForResidualBlock( |
| 852 | const ResidualBlockId residual_block) const { |
| 853 | return residual_block->loss_function(); |
| 854 | } |
| 855 | |
| 856 | void ProblemImpl::GetResidualBlocksForParameterBlock( |
| 857 | const double* values, |
| 858 | vector<ResidualBlockId>* residual_blocks) const { |
| 859 | ParameterBlock* parameter_block = |
| 860 | FindWithDefault(parameter_block_map_, const_cast<double*>(values), NULL); |
| 861 | if (parameter_block == NULL) { |
| 862 | LOG(FATAL) << "Parameter block not found: " << values |
| 863 | << ". You must add the parameter block to the problem before " |
| 864 | << "you can get the residual blocks that depend on it."; |
| 865 | } |
| 866 | |
| 867 | if (options_.enable_fast_removal) { |
| 868 | // In this case the residual blocks that depend on the parameter block are |
| 869 | // stored in the parameter block already, so just copy them out. |
| 870 | CHECK(residual_blocks != nullptr); |
| 871 | residual_blocks->resize(parameter_block->mutable_residual_blocks()->size()); |
| 872 | std::copy(parameter_block->mutable_residual_blocks()->begin(), |
| 873 | parameter_block->mutable_residual_blocks()->end(), |
| 874 | residual_blocks->begin()); |
| 875 | return; |
| 876 | } |
| 877 | |
| 878 | // Find residual blocks that depend on the parameter block. |
| 879 | CHECK(residual_blocks != nullptr); |
| 880 | residual_blocks->clear(); |
| 881 | const int num_residual_blocks = NumResidualBlocks(); |
| 882 | for (int i = 0; i < num_residual_blocks; ++i) { |
| 883 | ResidualBlock* residual_block = |
| 884 | (*(program_->mutable_residual_blocks()))[i]; |
| 885 | const int num_parameter_blocks = residual_block->NumParameterBlocks(); |
| 886 | for (int j = 0; j < num_parameter_blocks; ++j) { |
| 887 | if (residual_block->parameter_blocks()[j] == parameter_block) { |
| 888 | residual_blocks->push_back(residual_block); |
| 889 | // The parameter blocks are guaranteed unique. |
| 890 | break; |
| 891 | } |
| 892 | } |
| 893 | } |
| 894 | } |
| 895 | |
| 896 | } // namespace internal |
| 897 | } // namespace ceres |