gtsam  4.0.0
gtsam
BayesTree-inst.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 
21 #pragma once
22 
26 #include <gtsam/base/timing.h>
27 
28 #include <boost/optional.hpp>
29 #include <boost/assign/list_of.hpp>
30 #include <fstream>
31 
32 using boost::assign::cref_list_of;
33 
34 namespace gtsam {
35 
36  /* ************************************************************************* */
37  template<class CLIQUE>
40  for(const sharedClique& root: roots_)
41  getCliqueData(data, root);
42  return data;
43  }
44 
45  /* ************************************************************************* */
46  template<class CLIQUE>
48  data.conditionalSizes.push_back(clique->conditional()->nrFrontals());
49  data.separatorSizes.push_back(clique->conditional()->nrParents());
50  for(sharedClique c: clique->children) {
51  getCliqueData(data, c);
52  }
53  }
54 
55  /* ************************************************************************* */
56  template<class CLIQUE>
58  size_t count = 0;
59  for(const sharedClique& root: roots_)
60  count += root->numCachedSeparatorMarginals();
61  return count;
62  }
63 
64  /* ************************************************************************* */
65  template<class CLIQUE>
66  void BayesTree<CLIQUE>::saveGraph(const std::string &s, const KeyFormatter& keyFormatter) const {
67  if (roots_.empty()) throw std::invalid_argument("the root of Bayes tree has not been initialized!");
68  std::ofstream of(s.c_str());
69  of<< "digraph G{\n";
70  for(const sharedClique& root: roots_)
71  saveGraph(of, root, keyFormatter);
72  of<<"}";
73  of.close();
74  }
75 
76  /* ************************************************************************* */
77  template<class CLIQUE>
78  void BayesTree<CLIQUE>::saveGraph(std::ostream &s, sharedClique clique, const KeyFormatter& indexFormatter, int parentnum) const {
79  static int num = 0;
80  bool first = true;
81  std::stringstream out;
82  out << num;
83  std::string parent = out.str();
84  parent += "[label=\"";
85 
86  for(Key index: clique->conditional_->frontals()) {
87  if(!first) parent += ","; first = false;
88  parent += indexFormatter(index);
89  }
90 
91  if(clique->parent()){
92  parent += " : ";
93  s << parentnum << "->" << num << "\n";
94  }
95 
96  first = true;
97  for(Key sep: clique->conditional_->parents()) {
98  if(!first) parent += ","; first = false;
99  parent += indexFormatter(sep);
100  }
101  parent += "\"];\n";
102  s << parent;
103  parentnum = num;
104 
105  for(sharedClique c: clique->children) {
106  num++;
107  saveGraph(s, c, indexFormatter, parentnum);
108  }
109  }
110 
111  /* ************************************************************************* */
112  template<class CLIQUE>
113  size_t BayesTree<CLIQUE>::size() const {
114  size_t size = 0;
115  for(const sharedClique& clique: roots_)
116  size += clique->treeSize();
117  return size;
118  }
119 
120  /* ************************************************************************* */
121  template<class CLIQUE>
122  void BayesTree<CLIQUE>::addClique(const sharedClique& clique, const sharedClique& parent_clique) {
123  for(Key j: clique->conditional()->frontals())
124  nodes_[j] = clique;
125  if (parent_clique != NULL) {
126  clique->parent_ = parent_clique;
127  parent_clique->children.push_back(clique);
128  } else {
129  roots_.push_back(clique);
130  }
131  }
132 
133  /* ************************************************************************* */
134  // TODO: Clean up
135  namespace {
136  template<class FACTOR, class CLIQUE>
137  int _pushClique(FactorGraph<FACTOR>& fg, const boost::shared_ptr<CLIQUE>& clique) {
138  fg.push_back(clique->conditional_);
139  return 0;
140  }
141 
142  template<class FACTOR, class CLIQUE>
143  struct _pushCliqueFunctor {
144  _pushCliqueFunctor(FactorGraph<FACTOR>& graph_) : graph(graph_) {}
145  FactorGraph<FACTOR>& graph;
146  int operator()(const boost::shared_ptr<CLIQUE>& clique, int dummy) {
147  graph.push_back(clique->conditional_);
148  return 0;
149  }
150  };
151  }
152 
153  /* ************************************************************************* */
154  template<class CLIQUE>
156  {
157  // Traverse the BayesTree and add all conditionals to this graph
158  int data = 0; // Unused
159  _pushCliqueFunctor<FactorType,CLIQUE> functor(graph);
160  treeTraversal::DepthFirstForest(*this, data, functor); // FIXME: sort of works?
161 // treeTraversal::DepthFirstForest(*this, data, boost::bind(&_pushClique<FactorType,CLIQUE>, boost::ref(graph), _1));
162  }
163 
164  /* ************************************************************************* */
165  template<class CLIQUE>
167  *this = other;
168  }
169 
170  /* ************************************************************************* */
171  namespace {
172  template<typename NODE>
173  boost::shared_ptr<NODE>
174  BayesTreeCloneForestVisitorPre(const boost::shared_ptr<NODE>& node, const boost::shared_ptr<NODE>& parentPointer)
175  {
176  // Clone the current node and add it to its cloned parent
177  boost::shared_ptr<NODE> clone = boost::make_shared<NODE>(*node);
178  clone->children.clear();
179  clone->parent_ = parentPointer;
180  parentPointer->children.push_back(clone);
181  return clone;
182  }
183  }
184 
185  /* ************************************************************************* */
186  template<class CLIQUE>
188  this->clear();
189  boost::shared_ptr<Clique> rootContainer = boost::make_shared<Clique>();
190  treeTraversal::DepthFirstForest(other, rootContainer, BayesTreeCloneForestVisitorPre<Clique>);
191  for(const sharedClique& root: rootContainer->children) {
192  root->parent_ = typename Clique::weak_ptr(); // Reset the parent since it's set to the dummy clique
193  insertRoot(root);
194  }
195  return *this;
196  }
197 
198  /* ************************************************************************* */
199  template<class CLIQUE>
200  void BayesTree<CLIQUE>::print(const std::string& s, const KeyFormatter& keyFormatter) const {
201  std::cout << s << ": cliques: " << size() << ", variables: " << nodes_.size() << std::endl;
202  treeTraversal::PrintForest(*this, s, keyFormatter);
203  }
204 
205  /* ************************************************************************* */
206  // binary predicate to test equality of a pair for use in equals
207  template<class CLIQUE>
208  bool check_sharedCliques(
209  const std::pair<Key, typename BayesTree<CLIQUE>::sharedClique>& v1,
210  const std::pair<Key, typename BayesTree<CLIQUE>::sharedClique>& v2
211  ) {
212  return v1.first == v2.first &&
213  ((!v1.second && !v2.second) || (v1.second && v2.second && v1.second->equals(*v2.second)));
214  }
215 
216  /* ************************************************************************* */
217  template<class CLIQUE>
218  bool BayesTree<CLIQUE>::equals(const BayesTree<CLIQUE>& other, double tol) const {
219  return size()==other.size() &&
220  std::equal(nodes_.begin(), nodes_.end(), other.nodes_.begin(), &check_sharedCliques<CLIQUE>);
221  }
222 
223  /* ************************************************************************* */
224  template<class CLIQUE>
225  template<class CONTAINER>
226  Key BayesTree<CLIQUE>::findParentClique(const CONTAINER& parents) const {
227  typename CONTAINER::const_iterator lowestOrderedParent = min_element(parents.begin(), parents.end());
228  assert(lowestOrderedParent != parents.end());
229  return *lowestOrderedParent;
230  }
231 
232  /* ************************************************************************* */
233  template<class CLIQUE>
235  // Add each frontal variable of this root node
236  for(const Key& j: subtree->conditional()->frontals()) {
237  bool inserted = nodes_.insert(std::make_pair(j, subtree)).second;
238  assert(inserted); (void)inserted;
239  }
240  // Fill index for each child
242  for(const sharedClique& child: subtree->children) {
243  fillNodesIndex(child); }
244  }
245 
246  /* ************************************************************************* */
247  template<class CLIQUE>
249  roots_.push_back(subtree); // Add to roots
250  fillNodesIndex(subtree); // Populate nodes index
251  }
252 
253  /* ************************************************************************* */
254  // First finds clique marginal then marginalizes that
255  /* ************************************************************************* */
256  template<class CLIQUE>
257  typename BayesTree<CLIQUE>::sharedConditional
258  BayesTree<CLIQUE>::marginalFactor(Key j, const Eliminate& function) const
259  {
260  gttic(BayesTree_marginalFactor);
261 
262  // get clique containing Key j
263  sharedClique clique = this->clique(j);
264 
265  // calculate or retrieve its marginal P(C) = P(F,S)
266  FactorGraphType cliqueMarginal = clique->marginal2(function);
267 
268  // Now, marginalize out everything that is not variable j
269  BayesNetType marginalBN = *cliqueMarginal.marginalMultifrontalBayesNet(
270  Ordering(cref_list_of<1,Key>(j)), boost::none, function);
271 
272  // The Bayes net should contain only one conditional for variable j, so return it
273  return marginalBN.front();
274  }
275 
276  /* ************************************************************************* */
277  // Find two cliques, their joint, then marginalizes
278  /* ************************************************************************* */
279  template<class CLIQUE>
280  typename BayesTree<CLIQUE>::sharedFactorGraph
281  BayesTree<CLIQUE>::joint(Key j1, Key j2, const Eliminate& function) const
282  {
283  gttic(BayesTree_joint);
284  return boost::make_shared<FactorGraphType>(*jointBayesNet(j1, j2, function));
285  }
286 
287  /* ************************************************************************* */
288  template<class CLIQUE>
289  typename BayesTree<CLIQUE>::sharedBayesNet
290  BayesTree<CLIQUE>::jointBayesNet(Key j1, Key j2, const Eliminate& function) const
291  {
292  gttic(BayesTree_jointBayesNet);
293  // get clique C1 and C2
294  sharedClique C1 = (*this)[j1], C2 = (*this)[j2];
295 
296  gttic(Lowest_common_ancestor);
297  // Find lowest common ancestor clique
298  sharedClique B; {
299  // Build two paths to the root
300  FastList<sharedClique> path1, path2; {
301  sharedClique p = C1;
302  while(p) {
303  path1.push_front(p);
304  p = p->parent();
305  }
306  } {
307  sharedClique p = C2;
308  while(p) {
309  path2.push_front(p);
310  p = p->parent();
311  }
312  }
313  // Find the path intersection
314  typename FastList<sharedClique>::const_iterator p1 = path1.begin(), p2 = path2.begin();
315  if(*p1 == *p2)
316  B = *p1;
317  while(p1 != path1.end() && p2 != path2.end() && *p1 == *p2) {
318  B = *p1;
319  ++p1;
320  ++p2;
321  }
322  }
323  gttoc(Lowest_common_ancestor);
324 
325  // Build joint on all involved variables
326  FactorGraphType p_BC1C2;
327 
328  if(B)
329  {
330  // Compute marginal on lowest common ancestor clique
331  gttic(LCA_marginal);
332  FactorGraphType p_B = B->marginal2(function);
333  gttoc(LCA_marginal);
334 
335  // Compute shortcuts of the requested cliques given the lowest common ancestor
336  gttic(Clique_shortcuts);
337  BayesNetType p_C1_Bred = C1->shortcut(B, function);
338  BayesNetType p_C2_Bred = C2->shortcut(B, function);
339  gttoc(Clique_shortcuts);
340 
341  // Factor the shortcuts to be conditioned on the full root
342  // Get the set of variables to eliminate, which is C1\B.
343  gttic(Full_root_factoring);
344  boost::shared_ptr<typename EliminationTraitsType::BayesTreeType> p_C1_B; {
345  FastVector<Key> C1_minus_B; {
346  KeySet C1_minus_B_set(C1->conditional()->beginParents(), C1->conditional()->endParents());
347  for(const Key j: *B->conditional()) {
348  C1_minus_B_set.erase(j); }
349  C1_minus_B.assign(C1_minus_B_set.begin(), C1_minus_B_set.end());
350  }
351  // Factor into C1\B | B.
352  sharedFactorGraph temp_remaining;
353  boost::tie(p_C1_B, temp_remaining) =
354  FactorGraphType(p_C1_Bred).eliminatePartialMultifrontal(Ordering(C1_minus_B), function);
355  }
356  boost::shared_ptr<typename EliminationTraitsType::BayesTreeType> p_C2_B; {
357  FastVector<Key> C2_minus_B; {
358  KeySet C2_minus_B_set(C2->conditional()->beginParents(), C2->conditional()->endParents());
359  for(const Key j: *B->conditional()) {
360  C2_minus_B_set.erase(j); }
361  C2_minus_B.assign(C2_minus_B_set.begin(), C2_minus_B_set.end());
362  }
363  // Factor into C2\B | B.
364  sharedFactorGraph temp_remaining;
365  boost::tie(p_C2_B, temp_remaining) =
366  FactorGraphType(p_C2_Bred).eliminatePartialMultifrontal(Ordering(C2_minus_B), function);
367  }
368  gttoc(Full_root_factoring);
369 
370  gttic(Variable_joint);
371  p_BC1C2 += p_B;
372  p_BC1C2 += *p_C1_B;
373  p_BC1C2 += *p_C2_B;
374  if(C1 != B)
375  p_BC1C2 += C1->conditional();
376  if(C2 != B)
377  p_BC1C2 += C2->conditional();
378  gttoc(Variable_joint);
379  }
380  else
381  {
382  // The nodes have no common ancestor, they're in different trees, so they're joint is just the
383  // product of their marginals.
384  gttic(Disjoint_marginals);
385  p_BC1C2 += C1->marginal2(function);
386  p_BC1C2 += C2->marginal2(function);
387  gttoc(Disjoint_marginals);
388  }
389 
390  // now, marginalize out everything that is not variable j1 or j2
391  return p_BC1C2.marginalMultifrontalBayesNet(Ordering(cref_list_of<2,Key>(j1)(j2)), boost::none, function);
392  }
393 
394  /* ************************************************************************* */
395  template<class CLIQUE>
397  // Remove all nodes and clear the root pointer
398  nodes_.clear();
399  roots_.clear();
400  }
401 
402  /* ************************************************************************* */
403  template<class CLIQUE>
405  for(const sharedClique& root: roots_) {
406  root->deleteCachedShortcuts();
407  }
408  }
409 
410  /* ************************************************************************* */
411  template<class CLIQUE>
413  {
414  if (clique->isRoot()) {
415  typename Roots::iterator root = std::find(roots_.begin(), roots_.end(), clique);
416  if(root != roots_.end())
417  roots_.erase(root);
418  } else { // detach clique from parent
419  sharedClique parent = clique->parent_.lock();
420  typename Roots::iterator child = std::find(parent->children.begin(), parent->children.end(), clique);
421  assert(child != parent->children.end());
422  parent->children.erase(child);
423  }
424 
425  // orphan my children
426  for(sharedClique child: clique->children)
427  child->parent_ = typename Clique::weak_ptr();
428 
429  for(Key j: clique->conditional()->frontals()) {
430  nodes_.unsafe_erase(j);
431  }
432  }
433 
434  /* ************************************************************************* */
435  template<class CLIQUE>
436  void BayesTree<CLIQUE>::removePath(sharedClique clique, BayesNetType& bn, Cliques& orphans)
437  {
438  // base case is NULL, if so we do nothing and return empties above
439  if (clique) {
440 
441  // remove the clique from orphans in case it has been added earlier
442  orphans.remove(clique);
443 
444  // remove me
445  this->removeClique(clique);
446 
447  // remove path above me
448  this->removePath(typename Clique::shared_ptr(clique->parent_.lock()), bn, orphans);
449 
450  // add children to list of orphans (splice also removed them from clique->children_)
451  orphans.insert(orphans.begin(), clique->children.begin(), clique->children.end());
452  clique->children.clear();
453 
454  bn.push_back(clique->conditional_);
455 
456  }
457  }
458 
459  /* ************************************************************************* */
460  template<class CLIQUE>
461  void BayesTree<CLIQUE>::removeTop(const FastVector<Key>& keys, BayesNetType& bn, Cliques& orphans)
462  {
463  // process each key of the new factor
464  for(const Key& j: keys)
465  {
466  // get the clique
467  // TODO: Nodes will be searched again in removeClique
468  typename Nodes::const_iterator node = nodes_.find(j);
469  if(node != nodes_.end()) {
470  // remove path from clique to root
471  this->removePath(node->second, bn, orphans);
472  }
473  }
474 
475  // Delete cachedShortcuts for each orphan subtree
476  //TODO: Consider Improving
477  for(sharedClique& orphan: orphans)
478  orphan->deleteCachedShortcuts();
479  }
480 
481  /* ************************************************************************* */
482  template<class CLIQUE>
484  const sharedClique& subtree)
485  {
486  // Result clique list
487  Cliques cliques;
488  cliques.push_back(subtree);
489 
490  // Remove the first clique from its parents
491  if(!subtree->isRoot())
492  subtree->parent()->children.erase(std::find(
493  subtree->parent()->children.begin(), subtree->parent()->children.end(), subtree));
494  else
495  roots_.erase(std::find(roots_.begin(), roots_.end(), subtree));
496 
497  // Add all subtree cliques and erase the children and parent of each
498  for(typename Cliques::iterator clique = cliques.begin(); clique != cliques.end(); ++clique)
499  {
500  // Add children
501  for(const sharedClique& child: (*clique)->children) {
502  cliques.push_back(child); }
503 
504  // Delete cached shortcuts
505  (*clique)->deleteCachedShortcutsNonRecursive();
506 
507  // Remove this node from the nodes index
508  for(Key j: (*clique)->conditional()->frontals()) {
509  nodes_.unsafe_erase(j); }
510 
511  // Erase the parent and children pointers
512  (*clique)->parent_.reset();
513  (*clique)->children.clear();
514  }
515 
516  return cliques;
517  }
518 
519 }
BayesTreeCliqueData getCliqueData() const
Gather data on all cliques.
Definition: BayesTree-inst.h:38
void addFactorsToGraph(FactorGraph< FactorType > &graph) const
Add all cliques in this BayesTree to the specified factor graph.
Definition: BayesTree-inst.h:155
void DepthFirstForest(FOREST &forest, DATA &rootData, VISITOR_PRE &visitorPre, VISITOR_POST &visitorPost)
Traverse a forest depth-first with pre-order and post-order visits.
Definition: treeTraversal-inst.h:77
size_t numCachedSeparatorMarginals() const
Collect number of cliques with cached separator marginals.
Definition: BayesTree-inst.h:57
void saveGraph(const std::string &s, const KeyFormatter &keyFormatter=DefaultKeyFormatter) const
Read only with side effects.
Definition: BayesTree-inst.h:66
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:436
Definition: FastList.h:38
Cliques removeSubtree(const sharedClique &subtree)
Remove the requested subtree.
Definition: BayesTree-inst.h:483
Key findParentClique(const CONTAINER &parents) const
Find parent clique of a conditional.
Definition: BayesTree-inst.h:226
Nodes nodes_
Map from indices to Clique.
Definition: BayesTree.h:95
boost::shared_ptr< Clique > sharedClique
Shared pointer to a clique.
Definition: BayesTree.h:72
Definition: BayesTree.h:64
Bayes Tree is a tree of cliques of a Bayes Chain.
void fillNodesIndex(const sharedClique &subtree)
Fill the nodes index for a subtree.
Definition: BayesTree-inst.h:234
void removeClique(sharedClique clique)
remove a clique: warning, can result in a forest
Definition: BayesTree-inst.h:412
void print(const std::string &s="", const KeyFormatter &keyFormatter=DefaultKeyFormatter) const
print
Definition: BayesTree-inst.h:200
bool equals(const This &other, double tol=1e-9) const
check equality
Definition: BayesTree-inst.h:218
void deleteCachedShortcuts()
Clear all shortcut caches - use before timing on marginal calculation to avoid residual cache data...
Definition: BayesTree-inst.h:404
void clear()
Remove all nodes.
Definition: BayesTree-inst.h:396
store all the sizes
Definition: BayesTree.h:46
void addClique(const sharedClique &clique, const sharedClique &parent_clique=sharedClique())
add a clique (top down)
Definition: BayesTree-inst.h:122
size_t size() const
number of cliques
Definition: BayesTree-inst.h:113
BayesTree()
Create an empty Bayes Tree.
Definition: BayesTree.h:107
This & operator=(const This &other)
Assignment operator.
Definition: BayesTree-inst.h:187
Definition: Ordering.h:33
void insertRoot(const sharedClique &subtree)
Insert a new subtree with known parent clique.
Definition: BayesTree-inst.h:248
bool equal(const T &obj1, const T &obj2, double tol)
Call equal on the object.
Definition: Testable.h:83
void PrintForest(const FOREST &forest, std::string str, const KeyFormatter &keyFormatter)
Print a tree, prefixing each line with str, and formatting keys using keyFormatter.
Definition: treeTraversal-inst.h:220
boost::enable_if< boost::is_base_of< FactorType, DERIVEDFACTOR > >::type push_back(boost::shared_ptr< DERIVEDFACTOR > factor)
Add a factor directly using a shared_ptr.
Definition: FactorGraph.h:155
sharedConditional marginalFactor(Key j, const Eliminate &function=EliminationTraitsType::DefaultEliminate) const
Return marginal on any variable.
Definition: BayesTree-inst.h:258
A factor graph is a bipartite graph with factor nodes connected to variable nodes.
Definition: BayesTree.h:32
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:281
Timing utilities.
void removeTop(const FastVector< Key > &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:461
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
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:290