gtsam 4.1.1
gtsam
CameraSet.h
Go to the documentation of this file.
1/* ----------------------------------------------------------------------------
2
3 * GTSAM Copyright 2010, Georgia Tech Research Corporation,
4 * Atlanta, Georgia 30332-0415
5 * All Rights Reserved
6 * Authors: Frank Dellaert, et al. (see THANKS for the full author list)
7
8 * See LICENSE for the license information
9
10 * -------------------------------------------------------------------------- */
11
19#pragma once
20
22#include <gtsam/geometry/CalibratedCamera.h> // for Cheirality exception
23#include <gtsam/base/Testable.h>
25#include <gtsam/base/FastMap.h>
26#include <gtsam/inference/Key.h>
27#include <vector>
28
29namespace gtsam {
30
34template<class CAMERA>
35class CameraSet : public std::vector<CAMERA, Eigen::aligned_allocator<CAMERA> > {
36
37protected:
38
43 typedef typename CAMERA::Measurement Z;
44 typedef typename CAMERA::MeasurementVector ZVector;
45
46 static const int D = traits<CAMERA>::dimension;
47 static const int ZDim = traits<Z>::dimension;
48
50 static Vector ErrorVector(const ZVector& predicted,
51 const ZVector& measured) {
52
53 // Check size
54 size_t m = predicted.size();
55 if (measured.size() != m)
56 throw std::runtime_error("CameraSet::errors: size mismatch");
57
58 // Project and fill error vector
59 Vector b(ZDim * m);
60 for (size_t i = 0, row = 0; i < m; i++, row += ZDim) {
61 Vector bi = traits<Z>::Local(measured[i], predicted[i]);
62 if(ZDim==3 && std::isnan(bi(1))){ // if it is a stereo point and the right pixel is missing (nan)
63 bi(1) = 0;
64 }
65 b.segment<ZDim>(row) = bi;
66 }
67 return b;
68 }
69
70public:
71
73 virtual ~CameraSet() = default;
74
76 using MatrixZD = Eigen::Matrix<double, ZDim, D>;
77 using FBlocks = std::vector<MatrixZD, Eigen::aligned_allocator<MatrixZD>>;
78
84 virtual void print(const std::string& s = "") const {
85 std::cout << s << "CameraSet, cameras = \n";
86 for (size_t k = 0; k < this->size(); ++k)
87 this->at(k).print(s);
88 }
89
91 bool equals(const CameraSet& p, double tol = 1e-9) const {
92 if (this->size() != p.size())
93 return false;
94 bool camerasAreEqual = true;
95 for (size_t i = 0; i < this->size(); i++) {
96 if (this->at(i).equals(p.at(i), tol) == false)
97 camerasAreEqual = false;
98 break;
99 }
100 return camerasAreEqual;
101 }
102
109 template<class POINT>
110 ZVector project2(const POINT& point, //
111 boost::optional<FBlocks&> Fs = boost::none, //
112 boost::optional<Matrix&> E = boost::none) const {
113
114 static const int N = FixedDimension<POINT>::value;
115
116 // Allocate result
117 size_t m = this->size();
118 ZVector z;
119 z.reserve(m);
120
121 // Allocate derivatives
122 if (E) E->resize(ZDim * m, N);
123 if (Fs) Fs->resize(m);
124
125 // Project and fill derivatives
126 for (size_t i = 0; i < m; i++) {
127 MatrixZD Fi;
128 Eigen::Matrix<double, ZDim, N> Ei;
129 z.emplace_back(this->at(i).project2(point, Fs ? &Fi : 0, E ? &Ei : 0));
130 if (Fs) (*Fs)[i] = Fi;
131 if (E) E->block<ZDim, N>(ZDim * i, 0) = Ei;
132 }
133
134 return z;
135 }
136
138 template<class POINT>
139 Vector reprojectionError(const POINT& point, const ZVector& measured,
140 boost::optional<FBlocks&> Fs = boost::none, //
141 boost::optional<Matrix&> E = boost::none) const {
142 return ErrorVector(project2(point, Fs, E), measured);
143 }
144
151 template <int N,
152 int ND> // N = 2 or 3 (point dimension), ND is the camera dimension
154 const std::vector<
155 Eigen::Matrix<double, ZDim, ND>,
156 Eigen::aligned_allocator<Eigen::Matrix<double, ZDim, ND>>>& Fs,
157 const Matrix& E, const Eigen::Matrix<double, N, N>& P, const Vector& b) {
158 // a single point is observed in m cameras
159 size_t m = Fs.size();
160
161 // Create a SymmetricBlockMatrix (augmented hessian, with extra row/column with info vector)
162 size_t M1 = ND * m + 1;
163 std::vector<DenseIndex> dims(m + 1); // this also includes the b term
164 std::fill(dims.begin(), dims.end() - 1, ND);
165 dims.back() = 1;
166 SymmetricBlockMatrix augmentedHessian(dims, Matrix::Zero(M1, M1));
167
168 // Blockwise Schur complement
169 for (size_t i = 0; i < m; i++) { // for each camera
170
171 const Eigen::Matrix<double, ZDim, ND>& Fi = Fs[i];
172 const auto FiT = Fi.transpose();
173 const Eigen::Matrix<double, ZDim, N> Ei_P = //
174 E.block(ZDim * i, 0, ZDim, N) * P;
175
176 // D = (Dx2) * ZDim
177 augmentedHessian.setOffDiagonalBlock(i, m, FiT * b.segment<ZDim>(ZDim * i) // F' * b
178 - FiT * (Ei_P * (E.transpose() * b))); // D = (DxZDim) * (ZDimx3) * (N*ZDimm) * (ZDimm x 1)
179
180 // (DxD) = (DxZDim) * ( (ZDimxD) - (ZDimx3) * (3xZDim) * (ZDimxD) )
181 augmentedHessian.setDiagonalBlock(i, FiT
182 * (Fi - Ei_P * E.block(ZDim * i, 0, ZDim, N).transpose() * Fi));
183
184 // upper triangular part of the hessian
185 for (size_t j = i + 1; j < m; j++) { // for each camera
186 const Eigen::Matrix<double, ZDim, ND>& Fj = Fs[j];
187
188 // (DxD) = (Dx2) * ( (2x2) * (2xD) )
189 augmentedHessian.setOffDiagonalBlock(i, j, -FiT
190 * (Ei_P * E.block(ZDim * j, 0, ZDim, N).transpose() * Fj));
191 }
192 } // end of for over cameras
193
194 augmentedHessian.diagonalBlock(m)(0, 0) += b.squaredNorm();
195 return augmentedHessian;
196 }
197
211 template <int N, int ND, int NDD>
213 const std::vector<
214 Eigen::Matrix<double, ZDim, ND>,
215 Eigen::aligned_allocator<Eigen::Matrix<double, ZDim, ND>>>& Fs,
216 const Matrix& E, const Eigen::Matrix<double, N, N>& P, const Vector& b,
217 const KeyVector& jacobianKeys, const KeyVector& hessianKeys) {
218 size_t nrNonuniqueKeys = jacobianKeys.size();
219 size_t nrUniqueKeys = hessianKeys.size();
220
221 // Marginalize point: note - we reuse the standard SchurComplement function.
222 SymmetricBlockMatrix augmentedHessian = SchurComplement<N, ND>(Fs, E, P, b);
223
224 // Pack into an Hessian factor, allow space for b term.
225 std::vector<DenseIndex> dims(nrUniqueKeys + 1);
226 std::fill(dims.begin(), dims.end() - 1, NDD);
227 dims.back() = 1;
228 SymmetricBlockMatrix augmentedHessianUniqueKeys;
229
230 // Deal with the fact that some blocks may share the same keys.
231 if (nrUniqueKeys == nrNonuniqueKeys) {
232 // Case when there is 1 calibration key per camera:
233 augmentedHessianUniqueKeys = SymmetricBlockMatrix(
234 dims, Matrix(augmentedHessian.selfadjointView()));
235 } else {
236 // When multiple cameras share a calibration we have to rearrange
237 // the results of the Schur complement matrix.
238 std::vector<DenseIndex> nonuniqueDims(nrNonuniqueKeys + 1); // includes b
239 std::fill(nonuniqueDims.begin(), nonuniqueDims.end() - 1, NDD);
240 nonuniqueDims.back() = 1;
241 augmentedHessian = SymmetricBlockMatrix(
242 nonuniqueDims, Matrix(augmentedHessian.selfadjointView()));
243
244 // Get map from key to location in the new augmented Hessian matrix (the
245 // one including only unique keys).
246 std::map<Key, size_t> keyToSlotMap;
247 for (size_t k = 0; k < nrUniqueKeys; k++) {
248 keyToSlotMap[hessianKeys[k]] = k;
249 }
250
251 // Initialize matrix to zero.
252 augmentedHessianUniqueKeys = SymmetricBlockMatrix(
253 dims, Matrix::Zero(NDD * nrUniqueKeys + 1, NDD * nrUniqueKeys + 1));
254
255 // Add contributions for each key: note this loops over the hessian with
256 // nonUnique keys (augmentedHessian) and populates an Hessian that only
257 // includes the unique keys (that is what we want to return).
258 for (size_t i = 0; i < nrNonuniqueKeys; i++) { // rows
259 Key key_i = jacobianKeys.at(i);
260
261 // Update information vector.
262 augmentedHessianUniqueKeys.updateOffDiagonalBlock(
263 keyToSlotMap[key_i], nrUniqueKeys,
264 augmentedHessian.aboveDiagonalBlock(i, nrNonuniqueKeys));
265
266 // Update blocks.
267 for (size_t j = i; j < nrNonuniqueKeys; j++) { // cols
268 Key key_j = jacobianKeys.at(j);
269 if (i == j) {
270 augmentedHessianUniqueKeys.updateDiagonalBlock(
271 keyToSlotMap[key_i], augmentedHessian.diagonalBlock(i));
272 } else { // (i < j)
273 if (keyToSlotMap[key_i] != keyToSlotMap[key_j]) {
274 augmentedHessianUniqueKeys.updateOffDiagonalBlock(
275 keyToSlotMap[key_i], keyToSlotMap[key_j],
276 augmentedHessian.aboveDiagonalBlock(i, j));
277 } else {
278 augmentedHessianUniqueKeys.updateDiagonalBlock(
279 keyToSlotMap[key_i],
280 augmentedHessian.aboveDiagonalBlock(i, j) +
281 augmentedHessian.aboveDiagonalBlock(i, j).transpose());
282 }
283 }
284 }
285 }
286
287 // Update bottom right element of the matrix.
288 augmentedHessianUniqueKeys.updateDiagonalBlock(
289 nrUniqueKeys, augmentedHessian.diagonalBlock(nrNonuniqueKeys));
290 }
291 return augmentedHessianUniqueKeys;
292 }
293
300 template<int N> // N = 2 or 3
301 static SymmetricBlockMatrix SchurComplement(const FBlocks& Fs,
302 const Matrix& E, const Eigen::Matrix<double, N, N>& P, const Vector& b) {
303 return SchurComplement<N,D>(Fs, E, P, b);
304 }
305
307 template<int N> // N = 2 or 3 (point dimension)
308 static void ComputePointCovariance(Eigen::Matrix<double, N, N>& P,
309 const Matrix& E, double lambda, bool diagonalDamping = false) {
310
311 Matrix EtE = E.transpose() * E;
312
313 if (diagonalDamping) { // diagonal of the hessian
314 EtE.diagonal() += lambda * EtE.diagonal();
315 } else {
316 DenseIndex n = E.cols();
317 EtE += lambda * Eigen::MatrixXd::Identity(n, n);
318 }
319
320 P = (EtE).inverse();
321 }
322
324 static Matrix PointCov(const Matrix& E, const double lambda = 0.0,
325 bool diagonalDamping = false) {
326 if (E.cols() == 2) {
327 Matrix2 P2;
328 ComputePointCovariance<2>(P2, E, lambda, diagonalDamping);
329 return P2;
330 } else {
331 Matrix3 P3;
332 ComputePointCovariance<3>(P3, E, lambda, diagonalDamping);
333 return P3;
334 }
335 }
336
341 static SymmetricBlockMatrix SchurComplement(const FBlocks& Fblocks,
342 const Matrix& E, const Vector& b, const double lambda = 0.0,
343 bool diagonalDamping = false) {
344 if (E.cols() == 2) {
345 Matrix2 P;
346 ComputePointCovariance<2>(P, E, lambda, diagonalDamping);
347 return SchurComplement<2>(Fblocks, E, P, b);
348 } else {
349 Matrix3 P;
350 ComputePointCovariance<3>(P, E, lambda, diagonalDamping);
351 return SchurComplement<3>(Fblocks, E, P, b);
352 }
353 }
354
359 template<int N> // N = 2 or 3 (point dimension)
360 static void UpdateSchurComplement(const FBlocks& Fs, const Matrix& E,
361 const Eigen::Matrix<double, N, N>& P, const Vector& b,
362 const KeyVector& allKeys, const KeyVector& keys,
363 /*output ->*/SymmetricBlockMatrix& augmentedHessian) {
364
365 assert(keys.size()==Fs.size());
366 assert(keys.size()<=allKeys.size());
367
368 FastMap<Key, size_t> KeySlotMap;
369 for (size_t slot = 0; slot < allKeys.size(); slot++)
370 KeySlotMap.insert(std::make_pair(allKeys[slot], slot));
371
372 // Schur complement trick
373 // G = F' * F - F' * E * P * E' * F
374 // g = F' * (b - E * P * E' * b)
375
376 // a single point is observed in m cameras
377 size_t m = Fs.size(); // cameras observing current point
378 size_t M = (augmentedHessian.rows() - 1) / D; // all cameras in the group
379 assert(allKeys.size()==M);
380
381 // Blockwise Schur complement
382 for (size_t i = 0; i < m; i++) { // for each camera in the current factor
383
384 const MatrixZD& Fi = Fs[i];
385 const auto FiT = Fi.transpose();
386 const Eigen::Matrix<double, 2, N> Ei_P = E.template block<ZDim, N>(
387 ZDim * i, 0) * P;
388
389 // D = (DxZDim) * (ZDim)
390 // allKeys are the list of all camera keys in the group, e.g, (1,3,4,5,7)
391 // we should map those to a slot in the local (grouped) hessian (0,1,2,3,4)
392 // Key cameraKey_i = this->keys_[i];
393 DenseIndex aug_i = KeySlotMap.at(keys[i]);
394
395 // information vector - store previous vector
396 // vectorBlock = augmentedHessian(aug_i, aug_m).knownOffDiagonal();
397 // add contribution of current factor
398 augmentedHessian.updateOffDiagonalBlock(aug_i, M,
399 FiT * b.segment<ZDim>(ZDim * i) // F' * b
400 - FiT * (Ei_P * (E.transpose() * b))); // D = (DxZDim) * (ZDimx3) * (N*ZDimm) * (ZDimm x 1)
401
402 // (DxD) += (DxZDim) * ( (ZDimxD) - (ZDimx3) * (3xZDim) * (ZDimxD) )
403 // add contribution of current factor
404 // TODO(gareth): Eigen doesn't let us pass the expression. Call eval() for now...
405 augmentedHessian.updateDiagonalBlock(aug_i,
406 ((FiT * (Fi - Ei_P * E.template block<ZDim, N>(ZDim * i, 0).transpose() * Fi))).eval());
407
408 // upper triangular part of the hessian
409 for (size_t j = i + 1; j < m; j++) { // for each camera
410 const MatrixZD& Fj = Fs[j];
411
412 DenseIndex aug_j = KeySlotMap.at(keys[j]);
413
414 // (DxD) = (DxZDim) * ( (ZDimxZDim) * (ZDimxD) )
415 // off diagonal block - store previous block
416 // matrixBlock = augmentedHessian(aug_i, aug_j).knownOffDiagonal();
417 // add contribution of current factor
418 augmentedHessian.updateOffDiagonalBlock(aug_i, aug_j,
419 -FiT * (Ei_P * E.template block<ZDim, N>(ZDim * j, 0).transpose() * Fj));
420 }
421 } // end of for over cameras
422
423 augmentedHessian.diagonalBlock(M)(0, 0) += b.squaredNorm();
424 }
425
426private:
427
430 template<class ARCHIVE>
431 void serialize(ARCHIVE & ar, const unsigned int /*version*/) {
432 ar & (*this);
433 }
434
435public:
437};
438
439template<class CAMERA>
440const int CameraSet<CAMERA>::D;
441
442template<class CAMERA>
444
445template<class CAMERA>
446struct traits<CameraSet<CAMERA> > : public Testable<CameraSet<CAMERA> > {
447};
448
449template<class CAMERA>
450struct traits<const CameraSet<CAMERA> > : public Testable<CameraSet<CAMERA> > {
451};
452
453} // \ namespace gtsam
#define GTSAM_MAKE_ALIGNED_OPERATOR_NEW
This marks a GTSAM object to require alignment.
Definition: types.h:277
A thin wrapper around std::map that uses boost's fast_pool_allocator.
Access to matrices via blocks of pre-defined sizes.
Concept check for values that can be used in unit tests.
Calibrated camera for which only pose is unknown.
3D Point
Global functions in a separate testing namespace.
Definition: chartTesting.h:28
FastVector< Key > KeyVector
Define collection type once and for all - also used in wrappers.
Definition: Key.h:86
ptrdiff_t DenseIndex
The index type for Eigen objects.
Definition: types.h:75
const MATRIX::ConstRowXpr row(const MATRIX &A, size_t j)
Extracts a row view from a matrix that avoids a copy.
Definition: Matrix.h:225
std::uint64_t Key
Integer nonlinear key type.
Definition: types.h:69
A manifold defines a space in which there is a notion of a linear tangent space that can be centered ...
Definition: concepts.h:30
Give fixed size dimension of a type, fails at compile time if dynamic.
Definition: Manifold.h:164
Definition: SymmetricBlockMatrix.h:52
void setDiagonalBlock(DenseIndex I, const XprType &xpr)
Set a diagonal block. Only the upper triangular portion of xpr is evaluated.
Definition: SymmetricBlockMatrix.h:200
void setOffDiagonalBlock(DenseIndex I, DenseIndex J, const XprType &xpr)
Set an off-diagonal block. Only the upper triangular portion of xpr is evaluated.
Definition: SymmetricBlockMatrix.h:206
constBlock aboveDiagonalBlock(DenseIndex I, DenseIndex J) const
Get block above the diagonal (I, J).
Definition: SymmetricBlockMatrix.h:155
DenseIndex rows() const
Row size.
Definition: SymmetricBlockMatrix.h:119
void updateOffDiagonalBlock(DenseIndex I, DenseIndex J, const XprType &xpr)
Update an off diagonal block.
Definition: SymmetricBlockMatrix.h:233
Eigen::SelfAdjointView< Block, Eigen::Upper > diagonalBlock(DenseIndex J)
Return the J'th diagonal block as a self adjoint view.
Definition: SymmetricBlockMatrix.h:140
void updateDiagonalBlock(DenseIndex I, const XprType &xpr)
Increment the diagonal block by the values in xpr. Only reads the upper triangular part of xpr.
Definition: SymmetricBlockMatrix.h:217
Eigen::SelfAdjointView< constBlock, Eigen::Upper > selfadjointView(DenseIndex I, DenseIndex J) const
Return the square sub-matrix that contains blocks(i:j, i:j).
Definition: SymmetricBlockMatrix.h:161
A helper that implements the traits interface for GTSAM types.
Definition: Testable.h:151
A set of cameras, all with their own calibration.
Definition: CameraSet.h:35
Vector reprojectionError(const POINT &point, const ZVector &measured, boost::optional< FBlocks & > Fs=boost::none, boost::optional< Matrix & > E=boost::none) const
Calculate vector [project2(point)-z] of re-projection errors.
Definition: CameraSet.h:139
virtual void print(const std::string &s="") const
print
Definition: CameraSet.h:84
static void ComputePointCovariance(Eigen::Matrix< double, N, N > &P, const Matrix &E, double lambda, bool diagonalDamping=false)
Computes Point Covariance P, with lambda parameter.
Definition: CameraSet.h:308
static SymmetricBlockMatrix SchurComplement(const FBlocks &Fblocks, const Matrix &E, const Vector &b, const double lambda=0.0, bool diagonalDamping=false)
Do Schur complement, given Jacobian as Fs,E,P, return SymmetricBlockMatrix Dynamic version.
Definition: CameraSet.h:341
CAMERA::Measurement Z
2D measurement and noise model for each of the m views The order is kept the same as the keys that we...
Definition: CameraSet.h:43
virtual ~CameraSet()=default
Destructor.
bool equals(const CameraSet &p, double tol=1e-9) const
equals
Definition: CameraSet.h:91
static Matrix PointCov(const Matrix &E, const double lambda=0.0, bool diagonalDamping=false)
Computes Point Covariance P, with lambda parameter, dynamic version.
Definition: CameraSet.h:324
static Vector ErrorVector(const ZVector &predicted, const ZVector &measured)
Make a vector of re-projection errors.
Definition: CameraSet.h:50
static void UpdateSchurComplement(const FBlocks &Fs, const Matrix &E, const Eigen::Matrix< double, N, N > &P, const Vector &b, const KeyVector &allKeys, const KeyVector &keys, SymmetricBlockMatrix &augmentedHessian)
Applies Schur complement (exploiting block structure) to get a smart factor on cameras,...
Definition: CameraSet.h:360
static SymmetricBlockMatrix SchurComplementAndRearrangeBlocks(const std::vector< Eigen::Matrix< double, ZDim, ND >, Eigen::aligned_allocator< Eigen::Matrix< double, ZDim, ND > > > &Fs, const Matrix &E, const Eigen::Matrix< double, N, N > &P, const Vector &b, const KeyVector &jacobianKeys, const KeyVector &hessianKeys)
Do Schur complement, given Jacobian as Fs,E,P, return SymmetricBlockMatrix G = F' * F - F' * E * P * ...
Definition: CameraSet.h:212
static SymmetricBlockMatrix SchurComplement(const std::vector< Eigen::Matrix< double, ZDim, ND >, Eigen::aligned_allocator< Eigen::Matrix< double, ZDim, ND > > > &Fs, const Matrix &E, const Eigen::Matrix< double, N, N > &P, const Vector &b)
Do Schur complement, given Jacobian as Fs,E,P, return SymmetricBlockMatrix G = F' * F - F' * E * P * ...
Definition: CameraSet.h:153
static const int ZDim
Measurement dimension.
Definition: CameraSet.h:47
static SymmetricBlockMatrix SchurComplement(const FBlocks &Fs, const Matrix &E, const Eigen::Matrix< double, N, N > &P, const Vector &b)
Do Schur complement, given Jacobian as Fs,E,P, return SymmetricBlockMatrix G = F' * F - F' * E * P * ...
Definition: CameraSet.h:301
static const int D
Camera dimension.
Definition: CameraSet.h:46
friend class boost::serialization::access
Serialization function.
Definition: CameraSet.h:429
Eigen::Matrix< double, ZDim, D > MatrixZD
Definitions for blocks of F.
Definition: CameraSet.h:76
ZVector project2(const POINT &point, boost::optional< FBlocks & > Fs=boost::none, boost::optional< Matrix & > E=boost::none) const
Project a point (possibly Unit3 at infinity), with derivatives Note that F is a sparse block-diagonal...
Definition: CameraSet.h:110