gtsam
Loading...
Searching...
No Matches
Expression-inl.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
20#pragma once
21
22#include <gtsam/nonlinear/internal/ExpressionNode.h>
23
24#include <map>
25#include <memory>
26#include <set>
27#include <string>
28#include <vector>
29#include <cassert>
30
31
32namespace gtsam {
33
34template<typename T>
36 root_(new internal::ConstantExpression<T>(value)) {
37}
38
39template<typename T>
41 root_(new internal::LeafExpression<T>(key)) {
42}
43
44template<typename T>
46 root_(new internal::LeafExpression<T>(symbol)) {
47}
48
49template<typename T>
50Expression<T>::Expression(unsigned char c, std::uint64_t j) :
51 root_(new internal::LeafExpression<T>(Symbol(c, j))) {
52}
53
55template<typename T>
56template<typename A>
57Expression<T>::Expression(typename UnaryFunction<A>::type function,
58 const Expression<A>& expression) :
59 root_(new internal::UnaryExpression<T, A>(function, expression)) {
60}
61
63template<typename T>
64template<typename A1, typename A2>
65Expression<T>::Expression(typename BinaryFunction<A1, A2>::type function,
66 const Expression<A1>& expression1, const Expression<A2>& expression2) :
67 root_(
68 new internal::BinaryExpression<T, A1, A2>(function, expression1,
69 expression2)) {
70}
71
73template<typename T>
74template<typename A1, typename A2, typename A3>
75Expression<T>::Expression(typename TernaryFunction<A1, A2, A3>::type function,
76 const Expression<A1>& expression1, const Expression<A2>& expression2,
77 const Expression<A3>& expression3) :
78 root_(
79 new internal::TernaryExpression<T, A1, A2, A3>(function, expression1,
80 expression2, expression3)) {
81}
82
84template<typename T>
85template<typename A>
87 T (A::*method)(typename MakeOptionalJacobian<T, A>::type) const) :
88 root_(
89 new internal::UnaryExpression<T, A>(std::bind(method,
90 std::placeholders::_1, std::placeholders::_2),
91 expression)) {
92}
93
95template<typename T>
96template<typename A1, typename A2>
98 T (A1::*method)(const A2&, typename MakeOptionalJacobian<T, A1>::type,
99 typename MakeOptionalJacobian<T, A2>::type) const,
100 const Expression<A2>& expression2) :
101 root_(
102 new internal::BinaryExpression<T, A1, A2>(
103 std::bind(method, std::placeholders::_1,
104 std::placeholders::_2, std::placeholders::_3,
105 std::placeholders::_4),
106 expression1, expression2)) {
107}
108
110template<typename T>
111template<typename A1, typename A2, typename A3>
113 T (A1::*method)(const A2&, const A3&,
114 typename MakeOptionalJacobian<T, A1>::type,
115 typename MakeOptionalJacobian<T, A2>::type,
116 typename MakeOptionalJacobian<T, A3>::type) const,
117 const Expression<A2>& expression2, const Expression<A3>& expression3) :
118 root_(
119 new internal::TernaryExpression<T, A1, A2, A3>(
120 std::bind(method, std::placeholders::_1,
121 std::placeholders::_2, std::placeholders::_3,
122 std::placeholders::_4, std::placeholders::_5,
123 std::placeholders::_6),
124 expression1, expression2, expression3)) {
125}
126
127template<typename T>
128KeySet Expression<T>::keys() const {
129 return root_->keys();
130}
131
132template<typename T>
133void Expression<T>::dims(std::map<Key, int>& map) const {
134 root_->dims(map);
135}
136
137template<typename T>
138void Expression<T>::print(const std::string& s) const {
139 root_->print(s);
140}
141
142template<typename T>
144 std::vector<Matrix>* H) const {
145 if (H) {
146 // Call private version that returns derivatives in H
147 const auto [keys, dims] = keysAndDims();
148 return valueAndDerivatives(values, keys, dims, *H);
149 } else {
150 // no derivatives needed, just return value
151 return root_->value(values);
152 }
153}
154
155template<typename T>
156const std::shared_ptr<internal::ExpressionNode<T> >& Expression<T>::root() const {
157 return root_;
158}
159
160template<typename T>
162 return root_->traceSize();
163}
164
165// Private methods:
166
167template<typename T>
169 const KeyVector& keys, const FastVector<int>& dims,
170 std::vector<Matrix>& H) const {
171
172 // H should be pre-allocated
173 assert(H.size()==keys.size());
174
175 // Pre-allocate and zero VerticalBlockMatrix
176 static const int Dim = traits<T>::dimension;
177 VerticalBlockMatrix Ab(dims, Dim);
178 Ab.matrix().setZero();
179 internal::JacobianMap jacobianMap(keys, Ab);
180
181 // Call unsafe version
182 T result = valueAndJacobianMap(values, jacobianMap);
183
184 // Copy blocks into the vector of jacobians passed in
185 for (DenseIndex i = 0; i < static_cast<DenseIndex>(keys.size()); i++)
186 H[i] = Ab(i);
187
188 return result;
189}
190
191template<typename T>
193 internal::ExecutionTrace<T>& trace, char* traceStorage) const {
194 return root_->traceExecution(values, trace, traceStorage);
195}
196
197// Allocate a single block of aligned memory using a unique_ptr.
198inline std::unique_ptr<internal::ExecutionTraceStorage[]> allocAligned(size_t size) {
199 const size_t alignedSize = (size + internal::TraceAlignment - 1) / internal::TraceAlignment;
200 return std::unique_ptr<internal::ExecutionTraceStorage[]>(
201 new internal::ExecutionTraceStorage[alignedSize]);
202}
203
204template<typename T>
206 internal::JacobianMap& jacobians) const {
207 try {
208 // We allocate a single block of aligned memory using a unique_ptr.
209 const size_t size = traceSize();
210 auto traceStorage = allocAligned(size);
211
212 // The traceExecution call then fills this memory
213 // with an execution trace, made up entirely of "Record" structs, see
214 // the FunctionalNode class in expression-inl.h
216 T value(this->traceExecution(values, trace, reinterpret_cast<char *>(traceStorage.get())));
217
218 // We then calculate the Jacobians using reverse automatic differentiation (AD).
219 trace.startReverseAD1(jacobians);
220 return value;
221 } catch (const std::bad_alloc &e) {
222 std::cerr << "valueAndJacobianMap exception: " << e.what() << '\n';
223 throw e;
224 }
225 // Here traceStorage will be de-allocated properly.
226}
227
228template<typename T>
229typename Expression<T>::KeysAndDims Expression<T>::keysAndDims() const {
230 std::map<Key, int> map;
231 dims(map);
232 size_t n = map.size();
233 KeysAndDims pair = {KeyVector(n), FastVector<int>(n)};
234 // Copy map into pair of vectors
235 auto key_it = pair.first.begin();
236 auto dim_it = pair.second.begin();
237 for (const auto& [key, value] : map) {
238 *key_it++ = key;
239 *dim_it++ = value;
240 }
241 return pair;
242}
243
244namespace internal {
245// http://stackoverflow.com/questions/16260445/boost-bind-to-operator
246template<class T>
248 typedef T result_type;
249 static const int Dim = traits<T>::dimension;
250 T operator()(const T& x, const T& y, OptionalJacobian<Dim, Dim> H1 =
251 {}, OptionalJacobian<Dim, Dim> H2 = {}) const {
252 return x.compose(y, H1, H2);
253 }
254};
255
256template <>
257struct apply_compose<double> {
258 double operator()(const double& x, const double& y,
260 OptionalJacobian<1, 1> H2 = {}) const {
261 if (H1) H1->setConstant(y);
262 if (H2) H2->setConstant(x);
263 return x * y;
264 }
265};
266
267} // namespace internal
268
269// Global methods:
270
272template<typename T>
274 const Expression<T>& expression2) {
275 return Expression<T>(
276 std::bind(internal::apply_compose<T>(), std::placeholders::_1,
277 std::placeholders::_2, std::placeholders::_3,
278 std::placeholders::_4),
279 expression1, expression2);
280}
281
283template<typename T>
284std::vector<Expression<T> > createUnknowns(size_t n, char c, size_t start) {
285 std::vector<Expression<T> > unknowns;
286 unknowns.reserve(n);
287 for (size_t i = start; i < start + n; i++)
288 unknowns.push_back(Expression<T>(c, i));
289 return unknowns;
290}
291
292template <typename T>
293ScalarMultiplyExpression<T>::ScalarMultiplyExpression(double s, const Expression<T>& e)
294 : Expression<T>(std::make_shared<internal::ScalarMultiplyNode<T>>(s, e)) {}
295
296
297template <typename T>
298BinarySumExpression<T>::BinarySumExpression(const Expression<T>& e1, const Expression<T>& e2)
299 : Expression<T>(std::make_shared<internal::BinarySumNode<T>>(e1, e2)) {}
300
301template <typename T>
303 root_ = std::make_shared<internal::BinarySumNode<T>>(*this, e);
304 return *this;
305}
306
307} // namespace gtsam
std::vector< T, typename internal::FastDefaultVectorAllocator< T >::type > FastVector
FastVector is a type alias to a std::vector with a custom memory allocator.
Definition FastVector.h:33
STL namespace.
Global functions in a separate testing namespace.
Definition chartTesting.h:28
ptrdiff_t DenseIndex
The index type for Eigen objects.
Definition types.h:49
FastVector< Key > KeyVector
Define collection type once and for all - also used in wrappers.
Definition Key.h:91
Key symbol(unsigned char c, std::uint64_t j)
Create a symbol key from a character and index, i.e.
Definition Symbol.h:139
std::vector< Expression< T > > createUnknowns(size_t n, char c, size_t start)
Construct an array of leaves.
Definition Expression-inl.h:284
Point2 operator*(double s, const Point2 &p)
multiply with scalar
Definition Point2.h:52
std::uint64_t Key
Integer nonlinear key type.
Definition types.h:43
A manifold defines a space in which there is a notion of a linear tangent space that can be centered ...
Definition Group.h:37
OptionalJacobian is an Eigen::Ref like class that can take be constructed using either a fixed size o...
Definition OptionalJacobian.h:40
This class stores a dense matrix and allows it to be accessed as a collection of vertical blocks.
Definition VerticalBlockMatrix.h:47
const Matrix & matrix() const
Access to full matrix (including any portions excluded by rowStart(), rowEnd(), and firstBlock()).
Definition VerticalBlockMatrix.h:278
Character and index key used to refer to variables.
Definition Symbol.h:37
Definition Expression-inl.h:247
Definition Expression.h:41
Expression class that supports automatic differentiation.
Definition Expression.h:49
Expression(const std::shared_ptr< internal::ExpressionNode< T > > &root)
Construct with a custom root.
Definition Expression.h:62
KeySet keys() const
Return keys that play in this expression.
Definition Expression-inl.h:128
Expression()
Default constructor, for serialization.
Definition Expression.h:190
const std::shared_ptr< internal::ExpressionNode< T > > & root() const
Return root.
Definition Expression-inl.h:156
std::pair< KeyVector, FastVector< int > > KeysAndDims
Keys and dimensions in same order.
Definition Expression.h:193
T traceExecution(const Values &values, internal::ExecutionTrace< T > &trace, char *traceStorage) const
trace execution, very unsafe
Definition Expression-inl.h:192
void dims(std::map< Key, int > &map) const
Return dimensions for each argument, as a map.
Definition Expression-inl.h:133
void print(const std::string &s) const
Print.
Definition Expression-inl.h:138
T valueAndJacobianMap(const Values &values, internal::JacobianMap &jacobians) const
brief Return value and derivatives, reverse AD version
Definition Expression-inl.h:205
T value(const Values &values, std::vector< Matrix > *H=nullptr) const
Return value and optional derivatives, reverse AD version Notes: this is not terribly efficient,...
Definition Expression-inl.h:143
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:168
Expression< T > & operator+=(const Expression< T > &e)
Add another expression to this expression.
Definition Expression-inl.h:302
size_t traceSize() const
Return size needed for memory buffer in traceExecution.
Definition Expression-inl.h:161
A non-templated config holding any types of Manifold-group elements.
Definition Values.h:65
STL class.
STL class.