blob: 7f2a91185af0ca35cfa48f0951dc1c9c7d03eea2 [file] [log] [blame]
Austin Schuh70cc9552019-01-21 19:46:48 -08001// 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: keir@google.com (Keir Mierle)
30
31#ifndef CERES_INTERNAL_PARAMETER_BLOCK_H_
32#define CERES_INTERNAL_PARAMETER_BLOCK_H_
33
34#include <algorithm>
35#include <cstdint>
36#include <cstdlib>
37#include <limits>
38#include <memory>
39#include <string>
40#include <unordered_set>
41#include "ceres/array_utils.h"
42#include "ceres/internal/eigen.h"
43#include "ceres/internal/port.h"
44#include "ceres/local_parameterization.h"
45#include "ceres/stringprintf.h"
46#include "glog/logging.h"
47
48namespace ceres {
49namespace internal {
50
51class ProblemImpl;
52class ResidualBlock;
53
54// The parameter block encodes the location of the user's original value, and
55// also the "current state" of the parameter. The evaluator uses whatever is in
56// the current state of the parameter when evaluating. This is inlined since the
57// methods are performance sensitive.
58//
59// The class is not thread-safe, unless only const methods are called. The
60// parameter block may also hold a pointer to a local parameterization; the
61// parameter block does not take ownership of this pointer, so the user is
62// responsible for the proper disposal of the local parameterization.
63class ParameterBlock {
64 public:
65 typedef std::unordered_set<ResidualBlock*> ResidualBlockSet;
66
67 // Create a parameter block with the user state, size, and index specified.
68 // The size is the size of the parameter block and the index is the position
69 // of the parameter block inside a Program (if any).
70 ParameterBlock(double* user_state, int size, int index)
71 : user_state_(user_state),
72 state_(user_state),
73 size_(size),
74 index_(index) {}
75
76 ParameterBlock(double* user_state,
77 int size,
78 int index,
79 LocalParameterization* local_parameterization)
80 : user_state_(user_state),
81 state_(user_state),
82 size_(size),
83 index_(index) {
84 if (local_parameterization != nullptr) {
85 SetParameterization(local_parameterization);
86 }
87 }
88
89 // The size of the parameter block.
90 int Size() const { return size_; }
91
92 // Manipulate the parameter state.
93 bool SetState(const double* x) {
94 CHECK(x != nullptr) << "Tried to set the state of constant parameter "
95 << "with user location " << user_state_;
96 CHECK(!IsConstant()) << "Tried to set the state of constant parameter "
97 << "with user location " << user_state_;
98
99 state_ = x;
100 return UpdateLocalParameterizationJacobian();
101 }
102
103 // Copy the current parameter state out to x. This is "GetState()" rather than
104 // simply "state()" since it is actively copying the data into the passed
105 // pointer.
106 void GetState(double* x) const {
107 if (x != state_) {
108 std::copy(state_, state_ + size_, x);
109 }
110 }
111
112 // Direct pointers to the current state.
113 const double* state() const { return state_; }
114 const double* user_state() const { return user_state_; }
115 double* mutable_user_state() { return user_state_; }
116 const LocalParameterization* local_parameterization() const {
117 return local_parameterization_;
118 }
119 LocalParameterization* mutable_local_parameterization() {
120 return local_parameterization_;
121 }
122
123 // Set this parameter block to vary or not.
124 void SetConstant() { is_set_constant_ = true; }
125 void SetVarying() { is_set_constant_ = false; }
126 bool IsSetConstantByUser() const { return is_set_constant_; }
127 bool IsConstant() const { return (is_set_constant_ || LocalSize() == 0); }
128
129 double UpperBound(int index) const {
130 return (upper_bounds_ ? upper_bounds_[index]
131 : std::numeric_limits<double>::max());
132 }
133
134 double LowerBound(int index) const {
135 return (lower_bounds_ ? lower_bounds_[index]
136 : -std::numeric_limits<double>::max());
137 }
138
139 bool IsUpperBounded() const { return (upper_bounds_ == nullptr); }
140 bool IsLowerBounded() const { return (lower_bounds_ == nullptr); }
141
142 // This parameter block's index in an array.
143 int index() const { return index_; }
144 void set_index(int index) { index_ = index; }
145
146 // This parameter offset inside a larger state vector.
147 int state_offset() const { return state_offset_; }
148 void set_state_offset(int state_offset) { state_offset_ = state_offset; }
149
150 // This parameter offset inside a larger delta vector.
151 int delta_offset() const { return delta_offset_; }
152 void set_delta_offset(int delta_offset) { delta_offset_ = delta_offset; }
153
154 // Methods relating to the parameter block's parameterization.
155
156 // The local to global jacobian. Returns nullptr if there is no local
157 // parameterization for this parameter block. The returned matrix is row-major
158 // and has Size() rows and LocalSize() columns.
159 const double* LocalParameterizationJacobian() const {
160 return local_parameterization_jacobian_.get();
161 }
162
163 int LocalSize() const {
164 return (local_parameterization_ == nullptr)
165 ? size_
166 : local_parameterization_->LocalSize();
167 }
168
169 // Set the parameterization. The parameterization can be set exactly once;
170 // multiple calls to set the parameterization to different values will crash.
171 // It is an error to pass nullptr for the parameterization. The parameter
172 // block does not take ownership of the parameterization.
173 void SetParameterization(LocalParameterization* new_parameterization) {
174 CHECK(new_parameterization != nullptr)
175 << "nullptr parameterization invalid.";
176 // Nothing to do if the new parameterization is the same as the
177 // old parameterization.
178 if (new_parameterization == local_parameterization_) {
179 return;
180 }
181
182 CHECK(local_parameterization_ == nullptr)
183 << "Can't re-set the local parameterization; it leads to "
184 << "ambiguous ownership. Current local parameterization is: "
185 << local_parameterization_;
186
187 CHECK(new_parameterization->GlobalSize() == size_)
188 << "Invalid parameterization for parameter block. The parameter block "
189 << "has size " << size_ << " while the parameterization has a global "
190 << "size of " << new_parameterization->GlobalSize() << ". Did you "
191 << "accidentally use the wrong parameter block or parameterization?";
192
193 CHECK_GT(new_parameterization->LocalSize(), 0)
194 << "Invalid parameterization. Parameterizations must have a "
195 << "positive dimensional tangent space.";
196
197 local_parameterization_ = new_parameterization;
198 local_parameterization_jacobian_.reset(
199 new double[local_parameterization_->GlobalSize() *
200 local_parameterization_->LocalSize()]);
201 CHECK(UpdateLocalParameterizationJacobian())
202 << "Local parameterization Jacobian computation failed for x: "
203 << ConstVectorRef(state_, Size()).transpose();
204 }
205
206 void SetUpperBound(int index, double upper_bound) {
207 CHECK_LT(index, size_);
208
209 if (upper_bound >= std::numeric_limits<double>::max() && !upper_bounds_) {
210 return;
211 }
212
213 if (!upper_bounds_) {
214 upper_bounds_.reset(new double[size_]);
215 std::fill(upper_bounds_.get(),
216 upper_bounds_.get() + size_,
217 std::numeric_limits<double>::max());
218 }
219
220 upper_bounds_[index] = upper_bound;
221 }
222
223 void SetLowerBound(int index, double lower_bound) {
224 CHECK_LT(index, size_);
225
226 if (lower_bound <= -std::numeric_limits<double>::max() && !lower_bounds_) {
227 return;
228 }
229
230 if (!lower_bounds_) {
231 lower_bounds_.reset(new double[size_]);
232 std::fill(lower_bounds_.get(),
233 lower_bounds_.get() + size_,
234 -std::numeric_limits<double>::max());
235 }
236
237 lower_bounds_[index] = lower_bound;
238 }
239
240 // Generalization of the addition operation. This is the same as
241 // LocalParameterization::Plus() followed by projection onto the
242 // hyper cube implied by the bounds constraints.
243 bool Plus(const double* x, const double* delta, double* x_plus_delta) {
244 if (local_parameterization_ != nullptr) {
245 if (!local_parameterization_->Plus(x, delta, x_plus_delta)) {
246 return false;
247 }
248 } else {
249 VectorRef(x_plus_delta, size_) =
250 ConstVectorRef(x, size_) + ConstVectorRef(delta, size_);
251 }
252
253 // Project onto the box constraints.
254 if (lower_bounds_.get() != nullptr) {
255 for (int i = 0; i < size_; ++i) {
256 x_plus_delta[i] = std::max(x_plus_delta[i], lower_bounds_[i]);
257 }
258 }
259
260 if (upper_bounds_.get() != nullptr) {
261 for (int i = 0; i < size_; ++i) {
262 x_plus_delta[i] = std::min(x_plus_delta[i], upper_bounds_[i]);
263 }
264 }
265
266 return true;
267 }
268
269 std::string ToString() const {
270 return StringPrintf(
271 "{ this=%p, user_state=%p, state=%p, size=%d, "
272 "constant=%d, index=%d, state_offset=%d, "
273 "delta_offset=%d }",
274 this,
275 user_state_,
276 state_,
277 size_,
278 is_set_constant_,
279 index_,
280 state_offset_,
281 delta_offset_);
282 }
283
284 void EnableResidualBlockDependencies() {
285 CHECK(residual_blocks_.get() == nullptr)
286 << "Ceres bug: There is already a residual block collection "
287 << "for parameter block: " << ToString();
288 residual_blocks_.reset(new ResidualBlockSet);
289 }
290
291 void AddResidualBlock(ResidualBlock* residual_block) {
292 CHECK(residual_blocks_.get() != nullptr)
293 << "Ceres bug: The residual block collection is null for parameter "
294 << "block: " << ToString();
295 residual_blocks_->insert(residual_block);
296 }
297
298 void RemoveResidualBlock(ResidualBlock* residual_block) {
299 CHECK(residual_blocks_.get() != nullptr)
300 << "Ceres bug: The residual block collection is null for parameter "
301 << "block: " << ToString();
302 CHECK(residual_blocks_->find(residual_block) != residual_blocks_->end())
303 << "Ceres bug: Missing residual for parameter block: " << ToString();
304 residual_blocks_->erase(residual_block);
305 }
306
307 // This is only intended for iterating; perhaps this should only expose
308 // .begin() and .end().
309 ResidualBlockSet* mutable_residual_blocks() { return residual_blocks_.get(); }
310
311 double LowerBoundForParameter(int index) const {
312 if (lower_bounds_.get() == nullptr) {
313 return -std::numeric_limits<double>::max();
314 } else {
315 return lower_bounds_[index];
316 }
317 }
318
319 double UpperBoundForParameter(int index) const {
320 if (upper_bounds_.get() == nullptr) {
321 return std::numeric_limits<double>::max();
322 } else {
323 return upper_bounds_[index];
324 }
325 }
326
327 private:
328 bool UpdateLocalParameterizationJacobian() {
329 if (local_parameterization_ == nullptr) {
330 return true;
331 }
332
333 // Update the local to global Jacobian. In some cases this is
334 // wasted effort; if this is a bottleneck, we will find a solution
335 // at that time.
336
337 const int jacobian_size = Size() * LocalSize();
338 InvalidateArray(jacobian_size, local_parameterization_jacobian_.get());
339 if (!local_parameterization_->ComputeJacobian(
340 state_, local_parameterization_jacobian_.get())) {
341 LOG(WARNING) << "Local parameterization Jacobian computation failed"
342 "for x: "
343 << ConstVectorRef(state_, Size()).transpose();
344 return false;
345 }
346
347 if (!IsArrayValid(jacobian_size, local_parameterization_jacobian_.get())) {
348 LOG(WARNING) << "Local parameterization Jacobian computation returned"
349 << "an invalid matrix for x: "
350 << ConstVectorRef(state_, Size()).transpose()
351 << "\n Jacobian matrix : "
352 << ConstMatrixRef(local_parameterization_jacobian_.get(),
353 Size(),
354 LocalSize());
355 return false;
356 }
357 return true;
358 }
359
360 double* user_state_ = nullptr;
361 int size_ = -1;
362 bool is_set_constant_ = false;
363 LocalParameterization* local_parameterization_ = nullptr;
364
365 // The "state" of the parameter. These fields are only needed while the
366 // solver is running. While at first glance using mutable is a bad idea, this
367 // ends up simplifying the internals of Ceres enough to justify the potential
368 // pitfalls of using "mutable."
369 mutable const double* state_ = nullptr;
370 mutable std::unique_ptr<double[]> local_parameterization_jacobian_;
371
372 // The index of the parameter. This is used by various other parts of Ceres to
373 // permit switching from a ParameterBlock* to an index in another array.
374 int32_t index_ = -1;
375
376 // The offset of this parameter block inside a larger state vector.
377 int32_t state_offset_ = -1;
378
379 // The offset of this parameter block inside a larger delta vector.
380 int32_t delta_offset_ = -1;
381
382 // If non-null, contains the residual blocks this parameter block is in.
383 std::unique_ptr<ResidualBlockSet> residual_blocks_;
384
385 // Upper and lower bounds for the parameter block. SetUpperBound
386 // and SetLowerBound lazily initialize the upper_bounds_ and
387 // lower_bounds_ arrays. If they are never called, then memory for
388 // these arrays is never allocated. Thus for problems where there
389 // are no bounds, or only one sided bounds we do not pay the cost of
390 // allocating memory for the inactive bounds constraints.
391 //
392 // Upon initialization these arrays are initialized to
393 // std::numeric_limits<double>::max() and
394 // -std::numeric_limits<double>::max() respectively which correspond
395 // to the parameter block being unconstrained.
396 std::unique_ptr<double[]> upper_bounds_;
397 std::unique_ptr<double[]> lower_bounds_;
398
399 // Necessary so ProblemImpl can clean up the parameterizations.
400 friend class ProblemImpl;
401};
402
403} // namespace internal
404} // namespace ceres
405
406#endif // CERES_INTERNAL_PARAMETER_BLOCK_H_