gtsam  4.0.0
gtsam
ExpressionFactor.h
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 
20 #pragma once
21 
24 #include <gtsam/base/Testable.h>
25 #include <numeric>
26 
27 namespace gtsam {
28 
33 template<typename T>
34 class ExpressionFactor: public NoiseModelFactor {
35  BOOST_CONCEPT_ASSERT((IsTestable<T>));
36 
37 protected:
38 
39  typedef ExpressionFactor<T> This;
40  static const int Dim = traits<T>::dimension;
41 
45 
46 
47  public:
48  typedef boost::shared_ptr<ExpressionFactor<T> > shared_ptr;
49 
52  const T& measurement, const Expression<T>& expression)
53  : NoiseModelFactor(noiseModel), measured_(measurement) {
54  initialize(expression);
55  }
56 
58  virtual ~ExpressionFactor() {}
59 
61  const T& measured() const { return measured_; }
62 
64  void print(const std::string& s = "",
65  const KeyFormatter& keyFormatter = DefaultKeyFormatter) const {
66  NoiseModelFactor::print(s, keyFormatter);
67  traits<T>::Print(measured_, "ExpressionFactor with measurement: ");
68  }
69 
71  bool equals(const NonlinearFactor& f, double tol) const {
72  const ExpressionFactor* p = dynamic_cast<const ExpressionFactor*>(&f);
73  return p && NoiseModelFactor::equals(f, tol) &&
74  traits<T>::Equals(measured_, p->measured_, tol) &&
75  dims_ == p->dims_;
76  }
77 
83  virtual Vector unwhitenedError(const Values& x,
84  boost::optional<std::vector<Matrix>&> H = boost::none) const {
85  if (H) {
86  const T value = expression_.valueAndDerivatives(x, keys_, dims_, *H);
87  // NOTE(hayk): Doing the reverse, AKA Local(measured_, value) is not correct here
88  // because it would use the tangent space of the measurement instead of the value.
89  return -traits<T>::Local(value, measured_);
90  } else {
91  const T value = expression_.value(x);
92  return -traits<T>::Local(value, measured_);
93  }
94  }
95 
96  virtual boost::shared_ptr<GaussianFactor> linearize(const Values& x) const {
97  // Only linearize if the factor is active
98  if (!active(x))
99  return boost::shared_ptr<JacobianFactor>();
100 
101  // In case noise model is constrained, we need to provide a noise model
102  SharedDiagonal noiseModel;
103  if (noiseModel_ && noiseModel_->isConstrained()) {
104  noiseModel = boost::static_pointer_cast<noiseModel::Constrained>(
105  noiseModel_)->unit();
106  }
107 
108  // Create a writeable JacobianFactor in advance
109  boost::shared_ptr<JacobianFactor> factor(
110  new JacobianFactor(keys_, dims_, Dim, noiseModel));
111 
112  // Wrap keys and VerticalBlockMatrix into structure passed to expression_
113  VerticalBlockMatrix& Ab = factor->matrixObject();
114  internal::JacobianMap jacobianMap(keys_, Ab);
115 
116  // Zero out Jacobian so we can simply add to it
117  Ab.matrix().setZero();
118 
119  // Get value and Jacobians, writing directly into JacobianFactor
120  T value = expression_.valueAndJacobianMap(x, jacobianMap); // <<< Reverse AD happens here !
121 
122  // Evaluate error and set RHS vector b
123  Ab(size()).col(0) = traits<T>::Local(value, measured_);
124 
125  // Whiten the corresponding system, Ab already contains RHS
126  if (noiseModel_) {
127  Vector b = Ab(size()).col(0); // need b to be valid for Robust noise models
128  noiseModel_->WhitenSystem(Ab.matrix(), b);
129  }
130 
131  return factor;
132  }
133 
135  virtual gtsam::NonlinearFactor::shared_ptr clone() const {
136  return boost::static_pointer_cast<gtsam::NonlinearFactor>(
137  gtsam::NonlinearFactor::shared_ptr(new This(*this)));
138  }
139 
140 protected:
141  ExpressionFactor() {}
143 
145  ExpressionFactor(const SharedNoiseModel& noiseModel, const T& measurement)
146  : NoiseModelFactor(noiseModel), measured_(measurement) {
147  // Not properly initialized yet, need to call initialize
148  }
149 
152  if (!noiseModel_)
153  throw std::invalid_argument("ExpressionFactor: no NoiseModel.");
154  if (noiseModel_->dim() != Dim)
155  throw std::invalid_argument(
156  "ExpressionFactor was created with a NoiseModel of incorrect dimension.");
157  expression_ = expression;
158 
159  // Get keys and dimensions for Jacobian matrices
160  // An Expression is assumed unmutable, so we do this now
161  boost::tie(keys_, dims_) = expression_.keysAndDims();
162  }
163 
166  virtual Expression<T> expression() const {
167  throw std::runtime_error("ExpressionFactor::expression not provided: cannot deserialize.");
168  }
169 
170 private:
172  template <class Archive>
173  void save(Archive& ar, const unsigned int /*version*/) const {
174  ar << BOOST_SERIALIZATION_BASE_OBJECT_NVP(NoiseModelFactor);
175  ar << boost::serialization::make_nvp("measured_", this->measured_);
176  }
177 
180  template <class Archive>
181  void load(Archive& ar, const unsigned int /*version*/) {
182  ar >> BOOST_SERIALIZATION_BASE_OBJECT_NVP(NoiseModelFactor);
183  ar >> boost::serialization::make_nvp("measured_", this->measured_);
184  this->initialize(expression());
185  }
186 
187  // Indicate that we implement save/load separately, and be friendly to boost
188  BOOST_SERIALIZATION_SPLIT_MEMBER()
189 
190  friend class boost::serialization::access;
191 };
192 // ExpressionFactor
193 
195 template <typename T>
196 struct traits<ExpressionFactor<T> > : public Testable<ExpressionFactor<T> > {};
197 
203 template <typename T, typename A1, typename A2>
205  public:
207  virtual ~ExpressionFactor2() {}
208 
210  Vector evaluateError(const A1& a1, const A2& a2,
211  boost::optional<Matrix&> H1 = boost::none,
212  boost::optional<Matrix&> H2 = boost::none) const {
213  Values values;
214  values.insert(this->keys_[0], a1);
215  values.insert(this->keys_[1], a2);
216  std::vector<Matrix> H(2);
217  Vector error = this->unwhitenedError(values, H);
218  if (H1) (*H1) = H[0];
219  if (H2) (*H2) = H[1];
220  return error;
221  }
222 
225  virtual Expression<T> expression(Key key1, Key key2) const {
226  throw std::runtime_error("ExpressionFactor2::expression not provided: cannot deserialize.");
227  }
228 
229  protected:
232 
236  const T& measurement)
237  : ExpressionFactor<T>(noiseModel, measurement) {
238  this->keys_.push_back(key1);
239  this->keys_.push_back(key2);
240  }
241 
242  private:
244  virtual Expression<T> expression() const {
245  return expression(this->keys_[0], this->keys_[1]);
246  }
247 };
248 // ExpressionFactor2
249 
250 }// \ namespace gtsam
251 
Expression class that supports automatic differentiation.
Definition: Expression.h:49
ExpressionFactor2()
Default constructor, for serialization.
Definition: ExpressionFactor.h:231
void insert(Key j, const Value &val)
Add a variable with the given j, throws KeyAlreadyExists<J> if j is already present.
Definition: Values.cpp:133
Nonlinear factor base class.
Definition: NonlinearFactor.h:52
A nonlinear sum-of-squares factor with a zero-mean noise model implementing the density Templated on...
Definition: NonlinearFactor.h:163
virtual gtsam::NonlinearFactor::shared_ptr clone() const
Definition: ExpressionFactor.h:135
T valueAndDerivatives(const Values &values, const KeyVector &keys, const FastVector< int > &dims, std::vector< Matrix > &H) const
private version that takes keys and dimensions, returns derivatives
Definition: Expression-inl.h:157
noiseModel::Base::shared_ptr SharedNoiseModel
Note, deliberately not in noiseModel namespace.
Definition: NoiseModel.h:1072
Definition: VerticalBlockMatrix.h:41
virtual double error(const Values &c) const
Calculate the error of the factor.
Definition: NonlinearFactor.cpp:97
virtual bool equals(const NonlinearFactor &f, double tol=1e-9) const
Check if two factors are equal.
Definition: NonlinearFactor.cpp:71
void print(const std::string &s="", const KeyFormatter &keyFormatter=DefaultKeyFormatter) const
print relies on Testable traits being defined for T
Definition: ExpressionFactor.h:64
T valueAndJacobianMap(const Values &values, internal::JacobianMap &jacobians) const
brief Return value and derivatives, reverse AD version
Definition: Expression-inl.h:188
Expression< T > expression_
the expression that is AD enabled
Definition: ExpressionFactor.h:43
A non-templated config holding any types of Manifold-group elements.
Definition: Values.h:70
virtual void print(const std::string &s="", const KeyFormatter &keyFormatter=DefaultKeyFormatter) const
Print.
Definition: NonlinearFactor.cpp:63
virtual boost::shared_ptr< GaussianFactor > linearize(const Values &x) const
linearize to a GaussianFactor
Definition: ExpressionFactor.h:96
A helper that implements the traits interface for GTSAM types.
Definition: Testable.h:150
size_t size() const
Definition: Factor.h:126
const SharedNoiseModel & noiseModel() const
access to the noise model
Definition: NonlinearFactor.h:212
FastVector< int > dims_
dimensions of the Jacobian matrices
Definition: ExpressionFactor.h:44
virtual Expression< T > expression() const
Recreate expression from keys_ and measured_, used in load below.
Definition: ExpressionFactor.h:166
Binary specialization of ExpressionFactor meant as a base class for binary factors Enforces expressio...
Definition: ExpressionFactor.h:204
const Matrix & matrix() const
Access to full matrix (including any portions excluded by rowStart(), rowEnd(), and firstBlock()) ...
Definition: VerticalBlockMatrix.h:187
ExpressionFactor(const SharedNoiseModel &noiseModel, const T &measurement)
Default constructor, for serialization.
Definition: ExpressionFactor.h:145
ExpressionFactor(const SharedNoiseModel &noiseModel, const T &measurement, const Expression< T > &expression)
Constructor.
Definition: ExpressionFactor.h:51
virtual bool active(const Values &) const
Checks whether a factor should be used based on a set of values.
Definition: NonlinearFactor.h:115
virtual ~ExpressionFactor()
Destructor.
Definition: ExpressionFactor.h:58
FastVector< Key > keys_
The keys involved in this factor.
Definition: Factor.h:69
ExpressionFactor2(Key key1, Key key2, const SharedNoiseModel &noiseModel, const T &measurement)
Constructor takes care of keys, but still need to call initialize.
Definition: ExpressionFactor.h:234
T value(const Values &values, boost::optional< std::vector< Matrix > & > H=boost::none) const
Return value and optional derivatives, reverse AD version Notes: this is not terribly efficient...
Definition: Expression-inl.h:132
A manifold defines a space in which there is a notion of a linear tangent space that can be centered ...
Definition: concepts.h:30
bool equals(const NonlinearFactor &f, double tol) const
equals relies on Testable traits being defined for T
Definition: ExpressionFactor.h:71
const T & measured() const
return the measurement
Definition: ExpressionFactor.h:61
Factor that supports arbitrary expressions via AD.
Definition: Expression.h:38
virtual Vector unwhitenedError(const Values &x, boost::optional< std::vector< Matrix > & > H=boost::none) const
Error function without the NoiseModel, .
Definition: ExpressionFactor.h:83
virtual Expression< T > expression(Key key1, Key key2) const
Recreate expression from given keys_ and measured_, used in load Needed to deserialize a derived fact...
Definition: ExpressionFactor.h:225
void initialize(const Expression< T > &expression)
Initialize with constructor arguments.
Definition: ExpressionFactor.h:151
A Constrained constrained model is a specialization of Diagonal which allows some or all of the sigma...
Definition: NoiseModel.h:372
virtual ~ExpressionFactor2()
Destructor.
Definition: ExpressionFactor.h:207
Non-linear factor base classes.
Vector evaluateError(const A1 &a1, const A2 &a2, boost::optional< Matrix & > H1=boost::none, boost::optional< Matrix & > H2=boost::none) const
Backwards compatible evaluateError, to make existing tests compile.
Definition: ExpressionFactor.h:210
A Gaussian factor in the squared-error form.
Definition: JacobianFactor.h:87
Expressions for Block Automatic Differentiation.
T measured_
the measurement to be compared with the expression
Definition: ExpressionFactor.h:42
std::uint64_t Key
Integer nonlinear key type.
Definition: types.h:57
Global functions in a separate testing namespace.
Definition: chartTesting.h:28
boost::function< std::string(Key)> KeyFormatter
Typedef for a function to format a key, i.e. to convert it to a string.
Definition: Key.h:33
Concept check for values that can be used in unit tests.