gtsam
Loading...
Searching...
No Matches
BayesTree.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
17
18// \callgraph
19
20#pragma once
21
22#include <gtsam/inference/Key.h>
23#include <gtsam/base/FastList.h>
24#include <gtsam/base/ConcurrentMap.h>
26
27#if GTSAM_ENABLE_BOOST_SERIALIZATION
28#include <boost/serialization/shared_ptr.hpp>
29#include <boost/serialization/split_member.hpp>
30#include <boost/serialization/vector.hpp>
31#include <boost/serialization/version.hpp>
32
33#include <stdexcept>
34#include <unordered_map>
35#include <vector>
36#endif
37
38#include <memory>
39#include <string>
40
41namespace gtsam {
42
43 // Forward declarations
44 template<class FACTOR> class FactorGraph;
45 template<class BAYESTREE, class GRAPH> class EliminatableClusterTree;
46
47 /* ************************************************************************* */
49 struct GTSAM_EXPORT BayesTreeCliqueStats {
50 double avgConditionalSize;
51 std::size_t maxConditionalSize;
52 double avgSeparatorSize;
53 std::size_t maxSeparatorSize;
54 void print(const std::string& s = "") const ;
55 };
56
58 struct GTSAM_EXPORT BayesTreeCliqueData {
59 FastVector<std::size_t> conditionalSizes;
60 FastVector<std::size_t> separatorSizes;
61 BayesTreeCliqueStats getStats() const;
62 };
63
64 /* ************************************************************************* */
75 template<class CLIQUE>
77 {
78 protected:
79 typedef BayesTree<CLIQUE> This;
80 typedef std::shared_ptr<This> shared_ptr;
81
82 public:
83 typedef CLIQUE Clique;
84 typedef std::shared_ptr<Clique> sharedClique;
85 typedef Clique Node;
87 typedef typename CLIQUE::ConditionalType ConditionalType;
88 typedef std::shared_ptr<ConditionalType> sharedConditional;
89 typedef typename CLIQUE::BayesNetType BayesNetType;
90 typedef std::shared_ptr<BayesNetType> sharedBayesNet;
91 typedef typename CLIQUE::FactorType FactorType;
92 typedef std::shared_ptr<FactorType> sharedFactor;
93 typedef typename CLIQUE::FactorGraphType FactorGraphType;
94 typedef std::shared_ptr<FactorGraphType> sharedFactorGraph;
95 typedef typename FactorGraphType::Eliminate Eliminate;
96 typedef typename CLIQUE::EliminationTraitsType EliminationTraitsType;
97
100
103
106
107 protected:
108
111
114
117
120
122 BayesTree(const This& other);
123
125
128
130 This& operator=(const This& other);
131
132 public:
133
136
138 bool equals(const This& other, double tol = 1e-9) const;
139
141 void print(const std::string& s = "",
142 const KeyFormatter& keyFormatter = DefaultKeyFormatter) const;
144
147
149 size_t size() const;
150
152 inline bool empty() const {
153 return nodes_.empty();
154 }
155
157 const Nodes& nodes() const { return nodes_; }
158
160 sharedClique operator[](Key j) const { return nodes_.at(j); }
161
163 const Roots& roots() const { return roots_; }
164
166 const sharedClique& clique(Key j) const {
167 typename Nodes::const_iterator c = nodes_.find(j);
168 if(c == nodes_.end())
169 throw std::out_of_range("Requested the BayesTree clique for a key that is not in the BayesTree");
170 else
171 return c->second;
172 }
173
176
179
185 sharedConditional marginalFactor(Key j, const Eliminate& function = EliminationTraitsType::DefaultEliminate) const;
186
191 sharedFactorGraph joint(Key j1, Key j2, const Eliminate& function = EliminationTraitsType::DefaultEliminate) const;
192
194 sharedFactorGraph joint(
195 const KeyVector& keys,
196 const Eliminate& function = EliminationTraitsType::DefaultEliminate) const;
197
202 sharedBayesNet jointBayesNet(Key j1, Key j2, const Eliminate& function = EliminationTraitsType::DefaultEliminate) const;
203
208 sharedBayesNet jointBayesNet(
209 const KeyVector& keys,
210 const Eliminate& function = EliminationTraitsType::DefaultEliminate) const;
211
215
217 void dot(std::ostream& os, const KeyFormatter& keyFormatter = DefaultKeyFormatter) const;
218
220 std::string dot(
221 const KeyFormatter& keyFormatter = DefaultKeyFormatter) const;
222
224 void saveGraph(const std::string& filename,
225 const KeyFormatter& keyFormatter = DefaultKeyFormatter) const;
226
230
235 template<class CONTAINER>
236 Key findParentClique(const CONTAINER& parents) const;
237
239 void clear();
240
243
248 void removePath(sharedClique clique, BayesNetType* bn, Cliques* orphans);
249
254 void removeTop(const KeyVector& keys, BayesNetType* bn, Cliques* orphans);
255
259
263 void insertRoot(const sharedClique& subtree);
264
266 void addClique(const sharedClique& clique, const sharedClique& parent_clique = sharedClique());
267
270
279 gtsam::KeySet collectAffectedKeys(const gtsam::KeyVector& keys) const;
280
281 protected:
282
284 void dot(std::ostream &s, sharedClique clique, const KeyFormatter& keyFormatter,
285 size_t parentnum = 0) const;
286
289
292
294 void fillNodesIndex(const sharedClique& subtree);
295
298 void collectAffectedPathKeys(gtsam::KeySet& traversedKeys,
299 const sharedClique& clique) const;
300
301 // Friend JunctionTree because it directly fills roots and nodes index.
302 template<class BAYESTREE, class GRAPH> friend class EliminatableClusterTree;
303
304 private:
305#if GTSAM_ENABLE_BOOST_SERIALIZATION
307 friend class boost::serialization::access;
308 template<class ARCHIVE>
309 void save(ARCHIVE& ar, const unsigned int version) const {
310 if (version == 0) {
311 ar & BOOST_SERIALIZATION_NVP(nodes_);
312 ar & BOOST_SERIALIZATION_NVP(roots_);
313 return;
314 }
315
316 std::vector<sharedClique> cliques, detached;
317 std::unordered_map<const Clique*, size_t> indices;
318 for (const sharedClique& root : roots_) {
319 if (!indices.emplace(root.get(), cliques.size()).second)
320 throw std::invalid_argument("BayesTree contains duplicate cliques");
321 cliques.push_back(root);
322 }
323
324 std::vector<std::vector<size_t>> children;
325 for (size_t i = 0; i < cliques.size(); ++i) {
326 sharedClique copy = std::make_shared<Clique>(*cliques[i]);
327 copy->parent_.reset();
328 copy->children.clear();
329 copy->is_root = true;
330 detached.push_back(copy);
331 children.emplace_back();
332 for (const sharedClique& child : cliques[i]->children) {
333 if (!indices.emplace(child.get(), cliques.size()).second)
334 throw std::invalid_argument("BayesTree contains duplicate cliques");
335 children.back().push_back(cliques.size());
336 cliques.push_back(child);
337 }
338 }
339
340 const size_t rootCount = roots_.size();
341 ar & BOOST_SERIALIZATION_NVP(rootCount);
342 ar & boost::serialization::make_nvp("cliques", detached);
343 ar & BOOST_SERIALIZATION_NVP(children);
344 }
345
347 template<class ARCHIVE>
348 void load(ARCHIVE& ar, const unsigned int version) {
349 if (version == 0) {
350 ar & BOOST_SERIALIZATION_NVP(nodes_);
351 ar & BOOST_SERIALIZATION_NVP(roots_);
352 return;
353 }
354
355 size_t rootCount;
356 std::vector<sharedClique> cliques;
357 std::vector<std::vector<size_t>> children;
358 ar & BOOST_SERIALIZATION_NVP(rootCount);
359 ar & BOOST_SERIALIZATION_NVP(cliques);
360 ar & BOOST_SERIALIZATION_NVP(children);
361 if (rootCount > cliques.size() || children.size() != cliques.size())
362 throw std::invalid_argument("Invalid serialized BayesTree structure");
363
364 nodes_.clear();
365 roots_.assign(cliques.begin(), cliques.begin() + rootCount);
366 for (size_t i = 0; i < cliques.size(); ++i) {
367 sharedClique& clique = cliques[i];
368 clique->parent_.reset();
369 clique->children.clear();
370 clique->is_root = i < rootCount;
371 }
372 for (size_t i = 0; i < cliques.size(); ++i) {
373 sharedClique& clique = cliques[i];
374 for (size_t childIndex : children[i]) {
375 if (childIndex >= cliques.size())
376 throw std::invalid_argument("Invalid serialized BayesTree child");
377 sharedClique& child = cliques[childIndex];
378 if (!child->parent_.expired())
379 throw std::invalid_argument("Serialized BayesTree child has multiple parents");
380 clique->children.push_back(child);
381 child->parent_ = clique;
382 child->is_root = false;
383 }
384 }
385
386 for (size_t i = 0; i < cliques.size(); ++i) {
387 if ((i < rootCount) != cliques[i]->isRoot())
388 throw std::invalid_argument("Invalid serialized BayesTree roots");
389 for (Key key : cliques[i]->conditional()->frontals()) {
390 if (!nodes_.insert({key, cliques[i]}).second)
391 throw std::invalid_argument("Serialized BayesTree contains duplicate keys");
392 }
393 }
394 }
395
396 BOOST_SERIALIZATION_SPLIT_MEMBER()
397#endif
398
400
401 }; // BayesTree
402
403 /* ************************************************************************* */
404 template <class CLIQUE, typename = void>
405 class BayesTreeOrphanWrapper : public CLIQUE::ConditionalType {
406 public:
407 typedef CLIQUE CliqueType;
408 typedef typename CLIQUE::ConditionalType Base;
409
410 std::shared_ptr<CliqueType> clique;
411
422 BayesTreeOrphanWrapper(const std::shared_ptr<CliqueType>& clique)
423 : clique(clique) {
424 this->keys_.assign(clique->conditional()->beginParents(),
425 clique->conditional()->endParents());
426 }
427
428 void print(
429 const std::string& s = "",
430 const KeyFormatter& formatter = DefaultKeyFormatter) const override {
431 clique->print(s + "stored clique", formatter);
432 }
433 };
434
435}
436
437#if GTSAM_ENABLE_BOOST_SERIALIZATION
438namespace boost {
439namespace serialization {
440
442template <class CLIQUE>
443struct version<gtsam::BayesTree<CLIQUE>> {
444 typedef mpl::int_<1> type;
445 typedef mpl::integral_c_tag tag;
446 BOOST_STATIC_CONSTANT(int, value = type::value);
447};
448
449} // namespace serialization
450} // namespace boost
451#endif
A thin wrapper around std::vector that uses a custom allocator.
A thin wrapper around std::list that uses boost's fast_pool_allocator.
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
Global functions in a separate testing namespace.
Definition chartTesting.h:28
KeyFormatter DefaultKeyFormatter
Assign default key formatter.
Definition Key.cpp:30
FastVector< Key > KeyVector
Define collection type once and for all - also used in wrappers.
Definition Key.h:91
void save(const Matrix &A, const string &s, const string &filename)
save a matrix to file, which can be loaded by matlab
Definition Matrix.cpp:154
void print(const Matrix &A, const string &s, ostream &stream)
print without optional string, must specify cout yourself
Definition Matrix.cpp:143
std::function< std::string(Key)> KeyFormatter
Typedef for a function to format a key, i.e. to convert it to a string.
Definition Key.h:35
std::uint64_t Key
Integer nonlinear key type.
Definition types.h:43
FastMap is a thin wrapper around std::map that uses the boost fast_pool_allocator instead of the defa...
Definition ConcurrentMap.h:69
FastList is a thin wrapper around std::list that uses the boost fast_pool_allocator instead of the de...
Definition FastList.h:43
static std::pair< std::shared_ptr< ConditionalType >, std::shared_ptr< FactorType > > DefaultEliminate(const FactorGraphType &factors, const Ordering &keys)
The default dense elimination function.
Definition DiscreteFactorGraph.h:81
A factor graph is a bipartite graph with factor nodes connected to variable nodes.
Definition FactorGraph.h:58
A cluster-tree that eliminates to a Bayes tree.
Definition ClusterTree.h:205
clique statistics
Definition BayesTree.h:49
store all the sizes
Definition BayesTree.h:58
sharedFactorGraph joint(const KeyVector &keys, const Eliminate &function=EliminationTraitsType::DefaultEliminate) const
Return a joint factor graph on an arbitrary set of variables.
Definition BayesTree-inst.h:369
std::shared_ptr< Clique > sharedClique
Definition BayesTree.h:84
Nodes nodes_
Definition BayesTree.h:110
void removeClique(sharedClique clique)
remove a clique: warning, can result in a forest
Definition BayesTree-inst.h:700
sharedFactorGraph joint(Key j1, Key j2, const Eliminate &function=EliminationTraitsType::DefaultEliminate) const
return joint on two variables Limitation: can only calculate joint if cliques are disjoint or one of ...
Definition BayesTree-inst.h:361
sharedBayesNet jointBayesNet(const KeyVector &keys, const Eliminate &function=EliminationTraitsType::DefaultEliminate) const
Return a joint marginal Bayes net whose elimination order follows the first occurrence of each key.
Definition BayesTree-inst.h:632
void fillNodesIndex(const sharedClique &subtree)
Fill the nodes index for a subtree.
Definition BayesTree-inst.h:314
void dot(std::ostream &os, const KeyFormatter &keyFormatter=DefaultKeyFormatter) const
Output to graphviz format, stream version.
Definition BayesTree-inst.h:66
void addFactorsToGraph(FactorGraph< FactorType > *graph) const
Add all cliques in this BayesTree to the specified factor graph.
Definition BayesTree-inst.h:171
void dot(std::ostream &s, sharedClique clique, const KeyFormatter &keyFormatter, size_t parentnum=0) const
private helper method for saving the Tree to a text file in GraphViz format
Definition BayesTree-inst.h:99
bool equals(const This &other, double tol=1e-9) const
check equality
Definition BayesTree-inst.h:271
sharedClique operator[](Key j) const
Access node by variable.
Definition BayesTree.h:160
This & operator=(const This &other)
Assignment operator.
Definition BayesTree-inst.h:240
BayesTree()
Create an empty Bayes Tree.
Definition BayesTree.h:119
Clique Node
Definition BayesTree.h:85
void clear()
Remove all nodes.
Definition BayesTree-inst.h:684
void collectAffectedPathKeys(gtsam::KeySet &traversedKeys, const sharedClique &clique) const
Helper for collectAffectedKeys that recursively aggregates affected keys from a path from 'clique' to...
Definition BayesTree-inst.h:810
Roots roots_
Definition BayesTree.h:113
void addClique(const sharedClique &clique, const sharedClique &parent_clique=sharedClique())
add a clique (top down)
Definition BayesTree-inst.h:145
sharedBayesNet jointBayesNet(Key j1, Key j2, const Eliminate &function=EliminationTraitsType::DefaultEliminate) const
return joint on two variables as a BayesNet Limitation: can only calculate joint if cliques are disjo...
Definition BayesTree-inst.h:594
std::string dot(const KeyFormatter &keyFormatter=DefaultKeyFormatter) const
Output to graphviz format string.
Definition BayesTree-inst.h:82
sharedClique sharedNode
Definition BayesTree.h:86
Key findParentClique(const CONTAINER &parents) const
Find parent clique of a conditional.
Definition BayesTree-inst.h:306
size_t size() const
number of cliques
Definition BayesTree-inst.h:136
void getCliqueData(sharedClique clique, BayesTreeCliqueData *stats) const
Gather data on a single clique.
Definition BayesTree-inst.h:45
void deleteCachedShortcuts()
Clear all shortcut caches - use before timing on marginal calculation to avoid residual cache data.
Definition BayesTree-inst.h:692
BayesTree(const This &other)
Copy constructor.
Definition BayesTree-inst.h:181
void removePath(sharedClique clique, BayesNetType *bn, Cliques *orphans)
Remove path from clique to root and return that path as factors plus a list of orphaned subtree roots...
Definition BayesTree-inst.h:724
const Nodes & nodes() const
Return nodes.
Definition BayesTree.h:157
FastList< sharedClique > Cliques
Definition BayesTree.h:99
DiscreteBayesTreeClique Clique
Definition BayesTree.h:83
sharedConditional marginalFactor(Key j, const Eliminate &function=EliminationTraitsType::DefaultEliminate) const
Return marginal on any variable.
Definition BayesTree-inst.h:338
const Roots & roots() const
return root cliques
Definition BayesTree.h:163
const sharedClique & clique(Key j) const
alternate syntax for matlab: find the clique that contains the variable with Key j
Definition BayesTree.h:166
ConcurrentMap< Key, sharedClique > Nodes
Definition BayesTree.h:102
~BayesTree()
Destructor.
Definition BayesTree-inst.h:193
size_t numCachedSeparatorMarginals() const
Collect number of cliques with cached separator marginals.
Definition BayesTree-inst.h:57
BayesTreeCliqueData getCliqueData() const
Gather data on all cliques.
Definition BayesTree-inst.h:37
Cliques removeSubtree(const sharedClique &subtree)
Remove the requested subtree.
Definition BayesTree-inst.h:772
bool empty() const
Check if there are any cliques in the tree.
Definition BayesTree.h:152
void print(const std::string &s="", const KeyFormatter &keyFormatter=DefaultKeyFormatter) const
print
Definition BayesTree-inst.h:253
void insertRoot(const sharedClique &subtree)
Insert a new subtree with known parent clique.
Definition BayesTree-inst.h:328
void saveGraph(const std::string &filename, const KeyFormatter &keyFormatter=DefaultKeyFormatter) const
output to file with graphviz format.
Definition BayesTree-inst.h:90
void removeTop(const KeyVector &keys, BayesNetType *bn, Cliques *orphans)
Given a list of indices, turn "contaminated" part of the tree back into a factor graph.
Definition BayesTree-inst.h:751
FastVector< sharedClique > Roots
Definition BayesTree.h:105
gtsam::KeySet collectAffectedKeys(const gtsam::KeyVector &keys) const
Returns the set of keys from the tree that are affected by a update to 'keys'.
Definition BayesTree-inst.h:824
BayesTreeOrphanWrapper(const std::shared_ptr< CliqueType > &clique)
Construct a new Bayes Tree Orphan Wrapper object.
Definition BayesTree.h:422
std::function< EliminationResult(const FactorGraphType &, const Ordering &)> Eliminate
Definition EliminateableFactorGraph.h:91