TableFactor.cpp
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 #include <gtsam/base/FastSet.h>
24 
25 #include <utility>
26 
27 using namespace std;
28 
29 namespace gtsam {
30 
31 /* ************************************************************************ */
32 TableFactor::TableFactor() {}
33 
34 /* ************************************************************************ */
35 TableFactor::TableFactor(const DiscreteKeys& dkeys,
36  const TableFactor& potentials)
37  : DiscreteFactor(dkeys.indices(), dkeys.cardinalities()) {
38  sparse_table_ = potentials.sparse_table_;
39  denominators_ = potentials.denominators_;
41  sort(sorted_dkeys_.begin(), sorted_dkeys_.end());
42 }
43 
44 /* ************************************************************************ */
47  : DiscreteFactor(dkeys.indices(), dkeys.cardinalities()),
48  sparse_table_(table.size()) {
50  double denom = table.size();
51  for (const DiscreteKey& dkey : dkeys) {
52  denom /= dkey.second;
53  denominators_.insert(std::pair<Key, double>(dkey.first, denom));
54  }
56  sort(sorted_dkeys_.begin(), sorted_dkeys_.end());
57 }
58 
59 /* ************************************************************************ */
61  const DecisionTree<Key, double>& dtree)
62  : TableFactor(dkeys, DecisionTreeFactor(dkeys, dtree)) {}
63 
76  const DiscreteKeys& dkeys, const DecisionTreeFactor& dt) {
77  // SparseVector needs to know the maximum possible index,
78  // so we compute the product of cardinalities.
79  size_t cardinalityProduct = 1;
80  for (auto&& [_, c] : dt.cardinalities()) {
81  cardinalityProduct *= c;
82  }
83  Eigen::SparseVector<double> sparseTable(cardinalityProduct);
84  size_t nrValues = 0;
85  dt.visit([&nrValues](double x) {
86  if (x > 0) nrValues += 1;
87  });
88  sparseTable.reserve(nrValues);
89 
90  KeySet allKeys(dt.keys().begin(), dt.keys().end());
91 
92  // Compute denominators to be used in computing sparse table indices
93  std::map<Key, size_t> denominators;
94  double denom = sparseTable.size();
95  for (const DiscreteKey& dkey : dkeys) {
96  denom /= dkey.second;
97  denominators.insert(std::pair<Key, double>(dkey.first, denom));
98  }
99 
110  auto op = [&](const Assignment<Key>& assignment, double p) {
111  if (p > 0) {
112  // Get all the keys involved in this assignment
113  KeySet assignmentKeys;
114  for (auto&& [k, _] : assignment) {
115  assignmentKeys.insert(k);
116  }
117 
118  // Find the keys missing in the assignment
119  KeyVector diff;
120  std::set_difference(allKeys.begin(), allKeys.end(),
121  assignmentKeys.begin(), assignmentKeys.end(),
122  std::back_inserter(diff));
123 
124  // Generate all assignments using the missing keys
125  DiscreteKeys extras;
126  for (auto&& key : diff) {
127  extras.push_back({key, dt.cardinality(key)});
128  }
129  auto&& extraAssignments = DiscreteValues::CartesianProduct(extras);
130 
131  for (auto&& extra : extraAssignments) {
132  // Create new assignment using the extra assignment
133  DiscreteValues updatedAssignment(assignment);
134  updatedAssignment.insert(extra);
135 
136  // Generate index and add to the sparse vector.
137  Eigen::Index idx = 0;
138  // We go in reverse since a DecisionTree has the highest label first
139  for (auto&& it = updatedAssignment.rbegin();
140  it != updatedAssignment.rend(); it++) {
141  idx += it->second * denominators.at(it->first);
142  }
143  sparseTable.coeffRef(idx) = p;
144  }
145  }
146  };
147 
148  // Visit each leaf in `dt` to get the Assignment and leaf value
149  // to populate the sparseTable.
150  dt.visitWith(op);
151 
152  return sparseTable;
153 }
154 
155 /* ************************************************************************ */
157  const DecisionTreeFactor& dtf)
158  : TableFactor(dkeys, ComputeSparseTable(dkeys, dtf)) {}
159 
160 /* ************************************************************************ */
162  : TableFactor(dtf.discreteKeys(), dtf) {}
163 
164 /* ************************************************************************ */
166  : TableFactor(c.discreteKeys(), c) {}
167 
168 /* ************************************************************************ */
170  const DiscreteKeys& keys, const std::vector<double>& table) {
171  size_t max_size = 1;
172  for (auto&& [_, cardinality] : keys.cardinalities()) {
173  max_size *= cardinality;
174  }
175  if (table.size() != max_size) {
176  throw std::runtime_error(
177  "The cardinalities of the keys don't match the number of values in the "
178  "input.");
179  }
180 
181  Eigen::SparseVector<double> sparse_table(table.size());
182  // Count number of nonzero elements in table and reserve the space.
183  const uint64_t nnz = std::count_if(table.begin(), table.end(),
184  [](uint64_t i) { return i != 0; });
185  sparse_table.reserve(nnz);
186  for (uint64_t i = 0; i < table.size(); i++) {
187  if (table[i] != 0) sparse_table.insert(i) = table[i];
188  }
189  sparse_table.pruned();
190  sparse_table.data().squeeze();
191  return sparse_table;
192 }
193 
194 /* ************************************************************************ */
196  const std::string& table) {
197  // Convert string to doubles.
198  std::vector<double> ys;
199  std::istringstream iss(table);
200  std::copy(std::istream_iterator<double>(iss), std::istream_iterator<double>(),
201  std::back_inserter(ys));
202  return Convert(keys, ys);
203 }
204 
205 /* ************************************************************************ */
206 bool TableFactor::equals(const DiscreteFactor& other, double tol) const {
207  if (!dynamic_cast<const TableFactor*>(&other)) {
208  return false;
209  } else {
210  const auto& f(static_cast<const TableFactor&>(other));
211  return Base::equals(other, tol) &&
212  sparse_table_.isApprox(f.sparse_table_, tol);
213  }
214 }
215 
216 /* ************************************************************************ */
218  // a b c d => D * (C * (B * (a) + b) + c) + d
219  uint64_t idx = 0, card = 1;
220  for (auto it = sorted_dkeys_.rbegin(); it != sorted_dkeys_.rend(); ++it) {
221  if (values.find(it->first) != values.end()) {
222  idx += card * values.at(it->first);
223  }
224  card *= it->second;
225  }
226  return sparse_table_.coeff(idx);
227 }
228 
229 /* ************************************************************************ */
231  // a b c d => D * (C * (B * (a) + b) + c) + d
232  uint64_t idx = 0, card = 1;
233  for (auto it = keys_.rbegin(); it != keys_.rend(); ++it) {
234  if (values.find(*it) != values.end()) {
235  idx += card * values.at(*it);
236  }
237  card *= cardinality(*it);
238  }
239  return sparse_table_.coeff(idx);
240 }
241 
242 /* ************************************************************************ */
244  return -log(evaluate(values));
245 }
246 
247 /* ************************************************************************ */
248 double TableFactor::error(const HybridValues& values) const {
249  return error(values.discrete());
250 }
251 
252 /* ************************************************************************ */
254  return toDecisionTreeFactor() * f;
255 }
256 
257 /* ************************************************************************ */
259  const DiscreteFactor::shared_ptr& f) const {
261  if (auto tf = std::dynamic_pointer_cast<TableFactor>(f)) {
262  // If `f` is a TableFactor, we can simply call `operator*`.
263  result = std::make_shared<TableFactor>(this->operator*(*tf));
264 
265  } else if (auto dtf = std::dynamic_pointer_cast<DecisionTreeFactor>(f)) {
266  // If `f` is a DecisionTreeFactor, we convert to a TableFactor which is
267  // cheaper than converting `this` to a DecisionTreeFactor.
268  result = std::make_shared<TableFactor>(this->operator*(TableFactor(*dtf)));
269 
270  } else {
271  // Simulate double dispatch in C++
272  // Useful for other classes which inherit from DiscreteFactor and have
273  // only `operator*(DecisionTreeFactor)` defined. Thus, other classes don't
274  // need to be updated to know about TableFactor.
275  // Those classes can be specialized to use TableFactor
276  // if efficiency is a problem.
277  result = std::make_shared<DecisionTreeFactor>(
278  f->operator*(this->toDecisionTreeFactor()));
279  }
280  return result;
281 }
282 
283 /* ************************************************************************ */
285  const DiscreteFactor::shared_ptr& f) const {
286  if (auto tf = std::dynamic_pointer_cast<TableFactor>(f)) {
287  return std::make_shared<TableFactor>(this->operator/(*tf));
288  } else if (auto dtf = std::dynamic_pointer_cast<DecisionTreeFactor>(f)) {
289  return std::make_shared<TableFactor>(
290  this->operator/(TableFactor(f->discreteKeys(), *dtf)));
291  } else {
292  TableFactor divisor(f->toDecisionTreeFactor());
293  return std::make_shared<TableFactor>(this->operator/(divisor));
294  }
295 }
296 
297 /* ************************************************************************ */
299  DiscreteKeys dkeys = discreteKeys();
300 
301  // If no keys, then return empty DecisionTreeFactor
302  if (dkeys.size() == 0) {
304  // We can have an empty sparse_table_ or one with a single value.
305  if (sparse_table_.size() != 0) {
307  }
308  return DecisionTreeFactor(dkeys, tree);
309  }
310 
311  std::vector<double> table(sparse_table_.size(), 0.0);
312  for (SparseIt it(sparse_table_); it; ++it) {
313  table[it.index()] = it.value();
314  }
315 
317  DecisionTreeFactor f(dkeys, tree);
318  return f;
319 }
320 
321 /* ************************************************************************ */
323  DiscreteKeys parent_keys) const {
324  if (parent_keys.empty()) return *this;
325 
326  // Unique representation of parent values.
327  uint64_t unique = 0;
328  uint64_t card = 1;
329  for (auto it = keys_.rbegin(); it != keys_.rend(); ++it) {
330  if (parent_assign.find(*it) != parent_assign.end()) {
331  unique += parent_assign.at(*it) * card;
332  card *= cardinality(*it);
333  }
334  }
335 
336  // Find child DiscreteKeys
337  DiscreteKeys child_dkeys;
338  std::sort(parent_keys.begin(), parent_keys.end());
339  std::set_difference(sorted_dkeys_.begin(), sorted_dkeys_.end(),
340  parent_keys.begin(), parent_keys.end(),
341  std::back_inserter(child_dkeys));
342 
343  // Create child sparse table to populate.
344  uint64_t child_card = 1;
345  for (const DiscreteKey& child_dkey : child_dkeys)
346  child_card *= child_dkey.second;
347  Eigen::SparseVector<double> child_sparse_table_(child_card);
348  child_sparse_table_.reserve(child_card);
349 
350  // Populate child sparse table.
351  for (SparseIt it(sparse_table_); it; ++it) {
352  // Create unique representation of parent keys
353  uint64_t parent_unique = uniqueRep(parent_keys, it.index());
354  // Populate the table
355  if (parent_unique == unique) {
356  uint64_t idx = uniqueRep(child_dkeys, it.index());
357  child_sparse_table_.insert(idx) = it.value();
358  }
359  }
360 
361  child_sparse_table_.pruned();
362  child_sparse_table_.data().squeeze();
363  return TableFactor(child_dkeys, child_sparse_table_);
364 }
365 
366 /* ************************************************************************ */
367 double TableFactor::safe_div(const double& a, const double& b) {
368  // The use for safe_div is when we divide the product factor by the sum
369  // factor. If the product or sum is zero, we accord zero probability to the
370  // event.
371  return (a == 0 || b == 0) ? 0 : (a / b);
372 }
373 
374 /* ************************************************************************ */
375 void TableFactor::print(const string& s, const KeyFormatter& formatter) const {
376  cout << s;
377  cout << " f[";
378  for (auto&& key : keys())
379  cout << " (" << formatter(key) << "," << cardinality(key) << "),";
380  cout << " ]" << endl;
381  for (SparseIt it(sparse_table_); it; ++it) {
382  DiscreteValues assignment = findAssignments(it.index());
383  for (auto&& kv : assignment) {
384  cout << "(" << formatter(kv.first) << ", " << kv.second << ")";
385  }
386  cout << " | " << std::setw(10) << std::left << it.value() << " | "
387  << it.index() << endl;
388  }
389  cout << "number of nnzs: " << sparse_table_.nonZeros() << endl;
390 }
391 
392 /* ************************************************************************ */
394  // Initialize new factor.
395  uint64_t cardi = 1;
396  for (auto [key, c] : cardinalities_) cardi *= c;
397  Eigen::SparseVector<double> sparse_table(cardi);
398  sparse_table.reserve(sparse_table_.nonZeros());
399 
400  // Populate
401  for (SparseIt it(sparse_table_); it; ++it) {
402  sparse_table.coeffRef(it.index()) = op(it.value());
403  }
404 
405  // Free unused memory and return.
406  sparse_table.pruned();
407  sparse_table.data().squeeze();
408  return TableFactor(discreteKeys(), sparse_table);
409 }
410 
411 /* ************************************************************************ */
413  // Initialize new factor.
414  uint64_t cardi = 1;
415  for (auto [key, c] : cardinalities_) cardi *= c;
416  Eigen::SparseVector<double> sparse_table(cardi);
417  sparse_table.reserve(sparse_table_.nonZeros());
418 
419  // Populate
420  for (SparseIt it(sparse_table_); it; ++it) {
421  DiscreteValues assignment = findAssignments(it.index());
422  sparse_table.coeffRef(it.index()) = op(assignment, it.value());
423  }
424 
425  // Free unused memory and return.
426  sparse_table.pruned();
427  sparse_table.data().squeeze();
428  return TableFactor(discreteKeys(), sparse_table);
429 }
430 
431 /* ************************************************************************ */
433  if (keys_.empty() && sparse_table_.nonZeros() == 0)
434  return f;
435  else if (f.keys_.empty() && f.sparse_table_.nonZeros() == 0)
436  return *this;
437  // 1. Identify keys for contract and free modes.
438  DiscreteKeys contract_dkeys = contractDkeys(f);
439  DiscreteKeys f_free_dkeys = f.freeDkeys(*this);
440  DiscreteKeys union_dkeys = unionDkeys(f);
441  // 2. Create hash table for input factor f
442  unordered_map<uint64_t, AssignValList> map_f =
443  f.createMap(contract_dkeys, f_free_dkeys);
444  // 3. Initialize multiplied factor.
445  uint64_t card = 1;
446  for (auto u_dkey : union_dkeys) card *= u_dkey.second;
447  Eigen::SparseVector<double> mult_sparse_table(card);
448  mult_sparse_table.reserve(card);
449  // 3. Multiply.
450  for (SparseIt it(sparse_table_); it; ++it) {
451  uint64_t contract_unique = uniqueRep(contract_dkeys, it.index());
452  if (map_f.find(contract_unique) == map_f.end()) continue;
453  for (auto assignVal : map_f[contract_unique]) {
454  uint64_t union_idx = unionRep(union_dkeys, assignVal.first, it.index());
455  mult_sparse_table.insert(union_idx) = op(it.value(), assignVal.second);
456  }
457  }
458  // 4. Free unused memory.
459  mult_sparse_table.pruned();
460  mult_sparse_table.data().squeeze();
461  // 5. Create union keys and return.
462  return TableFactor(union_dkeys, mult_sparse_table);
463 }
464 
465 /* ************************************************************************ */
467  // Find contract modes.
468  DiscreteKeys contract;
469  set_intersection(sorted_dkeys_.begin(), sorted_dkeys_.end(),
470  f.sorted_dkeys_.begin(), f.sorted_dkeys_.end(),
471  back_inserter(contract));
472  return contract;
473 }
474 
475 /* ************************************************************************ */
477  // Find free modes.
478  DiscreteKeys free;
479  set_difference(sorted_dkeys_.begin(), sorted_dkeys_.end(),
480  f.sorted_dkeys_.begin(), f.sorted_dkeys_.end(),
481  back_inserter(free));
482  return free;
483 }
484 
485 /* ************************************************************************ */
487  // Find union modes.
488  DiscreteKeys union_dkeys;
489  set_union(sorted_dkeys_.begin(), sorted_dkeys_.end(), f.sorted_dkeys_.begin(),
490  f.sorted_dkeys_.end(), back_inserter(union_dkeys));
491  return union_dkeys;
492 }
493 
494 /* ************************************************************************ */
496  const DiscreteValues& f_free,
497  const uint64_t idx) const {
498  uint64_t union_idx = 0, card = 1;
499  for (auto it = union_keys.rbegin(); it != union_keys.rend(); it++) {
500  if (f_free.find(it->first) == f_free.end()) {
501  union_idx += keyValueForIndex(it->first, idx) * card;
502  } else {
503  union_idx += f_free.at(it->first) * card;
504  }
505  card *= it->second;
506  }
507  return union_idx;
508 }
509 
510 /* ************************************************************************ */
511 unordered_map<uint64_t, TableFactor::AssignValList> TableFactor::createMap(
512  const DiscreteKeys& contract, const DiscreteKeys& free) const {
513  // 1. Initialize map.
514  unordered_map<uint64_t, AssignValList> map_f;
515  // 2. Iterate over nonzero elements.
516  for (SparseIt it(sparse_table_); it; ++it) {
517  // 3. Create unique representation of contract modes.
518  uint64_t unique_rep = uniqueRep(contract, it.index());
519  // 4. Create assignment for free modes.
520  DiscreteValues free_assignments;
521  for (auto& key : free)
522  free_assignments[key.first] = keyValueForIndex(key.first, it.index());
523  // 5. Populate map.
524  if (map_f.find(unique_rep) == map_f.end()) {
525  map_f[unique_rep] = {make_pair(free_assignments, it.value())};
526  } else {
527  map_f[unique_rep].push_back(make_pair(free_assignments, it.value()));
528  }
529  }
530  return map_f;
531 }
532 
533 /* ************************************************************************ */
535  const uint64_t idx) const {
536  if (dkeys.empty()) return 0;
537  uint64_t unique_rep = 0, card = 1;
538  for (auto it = dkeys.rbegin(); it != dkeys.rend(); it++) {
539  unique_rep += keyValueForIndex(it->first, idx) * card;
540  card *= it->second;
541  }
542  return unique_rep;
543 }
544 
545 /* ************************************************************************ */
546 uint64_t TableFactor::uniqueRep(const DiscreteValues& assignments) const {
547  if (assignments.empty()) return 0;
548  uint64_t unique_rep = 0, card = 1;
549  for (auto it = assignments.rbegin(); it != assignments.rend(); it++) {
550  unique_rep += it->second * card;
551  card *= cardinalities_.at(it->first);
552  }
553  return unique_rep;
554 }
555 
556 /* ************************************************************************ */
558  DiscreteValues assignment;
559  for (Key key : keys_) {
560  assignment[key] = keyValueForIndex(key, idx);
561  }
562  return assignment;
563 }
564 
565 /* ************************************************************************ */
567  Binary op) const {
568  if (nrFrontals > size()) {
569  throw invalid_argument(
570  "TableFactor::combine: invalid number of frontal "
571  "keys " +
572  to_string(nrFrontals) + ", nr.keys=" + std::to_string(size()));
573  }
574  // Find remaining keys.
575  DiscreteKeys remain_dkeys;
576  uint64_t card = 1;
577  for (auto i = nrFrontals; i < keys_.size(); i++) {
578  remain_dkeys.push_back(discreteKey(i));
579  card *= cardinality(keys_[i]);
580  }
581  // Create combined table.
582  Eigen::SparseVector<double> combined_table(card);
583  combined_table.reserve(sparse_table_.nonZeros());
584  // Populate combined table.
585  for (SparseIt it(sparse_table_); it; ++it) {
586  uint64_t idx = uniqueRep(remain_dkeys, it.index());
587  double new_val = op(combined_table.coeff(idx), it.value());
588  combined_table.coeffRef(idx) = new_val;
589  }
590  // Free unused memory.
591  combined_table.pruned();
592  combined_table.data().squeeze();
593  return std::make_shared<TableFactor>(remain_dkeys, combined_table);
594 }
595 
596 /* ************************************************************************ */
598  Binary op) const {
599  if (frontalKeys.size() > size()) {
600  throw invalid_argument(
601  "TableFactor::combine: invalid number of frontal "
602  "keys " +
603  std::to_string(frontalKeys.size()) +
604  ", nr.keys=" + std::to_string(size()));
605  }
606  // Find remaining keys.
607  DiscreteKeys remain_dkeys;
608  uint64_t card = 1;
609  for (Key key : keys_) {
610  if (std::find(frontalKeys.begin(), frontalKeys.end(), key) ==
611  frontalKeys.end()) {
612  remain_dkeys.emplace_back(key, cardinality(key));
613  card *= cardinality(key);
614  }
615  }
616  // Create combined table.
617  Eigen::SparseVector<double> combined_table(card);
618  combined_table.reserve(sparse_table_.nonZeros());
619  // Populate combined table.
620  for (SparseIt it(sparse_table_); it; ++it) {
621  uint64_t idx = uniqueRep(remain_dkeys, it.index());
622  double new_val = op(combined_table.coeff(idx), it.value());
623  combined_table.coeffRef(idx) = new_val;
624  }
625  // Free unused memory.
626  combined_table.pruned();
627  combined_table.data().squeeze();
628  return std::make_shared<TableFactor>(remain_dkeys, combined_table);
629 }
630 
631 /* ************************************************************************ */
632 size_t TableFactor::keyValueForIndex(Key target_key, uint64_t index) const {
633  // http://phrogz.net/lazy-cartesian-product
634  return (index / denominators_.at(target_key)) % cardinality(target_key);
635 }
636 
637 /* ************************************************************************ */
638 std::vector<std::pair<DiscreteValues, double>> TableFactor::enumerate() const {
639  // Get all possible assignments
640  std::vector<std::pair<Key, size_t>> pairs = discreteKeys();
641  // Reverse to make cartesian product output a more natural ordering.
642  std::vector<std::pair<Key, size_t>> rpairs(pairs.rbegin(), pairs.rend());
643  const auto assignments = DiscreteValues::CartesianProduct(rpairs);
644  // Construct unordered_map with values
645  std::vector<std::pair<DiscreteValues, double>> result;
646  for (const auto& assignment : assignments) {
647  result.emplace_back(assignment, operator()(assignment));
648  }
649  return result;
650 }
651 
652 // Print out header.
653 /* ************************************************************************ */
654 string TableFactor::markdown(const KeyFormatter& keyFormatter,
655  const Names& names) const {
656  stringstream ss;
657 
658  // Print out header.
659  ss << "|";
660  for (auto& key : keys()) {
661  ss << keyFormatter(key) << "|";
662  }
663  ss << "value|\n";
664 
665  // Print out separator with alignment hints.
666  ss << "|";
667  for (size_t j = 0; j < size(); j++) ss << ":-:|";
668  ss << ":-:|\n";
669 
670  // Print out all rows.
671  for (SparseIt it(sparse_table_); it; ++it) {
672  DiscreteValues assignment = findAssignments(it.index());
673  ss << "|";
674  for (auto& key : keys()) {
675  size_t index = assignment.at(key);
676  ss << DiscreteValues::Translate(names, key, index) << "|";
677  }
678  ss << it.value() << "|\n";
679  }
680  return ss.str();
681 }
682 
683 /* ************************************************************************ */
684 string TableFactor::html(const KeyFormatter& keyFormatter,
685  const Names& names) const {
686  stringstream ss;
687 
688  // Print out preamble.
689  ss << "<div>\n<table class='TableFactor'>\n <thead>\n";
690 
691  // Print out header row.
692  ss << " <tr>";
693  for (auto& key : keys()) {
694  ss << "<th>" << keyFormatter(key) << "</th>";
695  }
696  ss << "<th>value</th></tr>\n";
697 
698  // Finish header and start body.
699  ss << " </thead>\n <tbody>\n";
700 
701  // Print out all rows.
702  for (SparseIt it(sparse_table_); it; ++it) {
703  DiscreteValues assignment = findAssignments(it.index());
704  ss << " <tr>";
705  for (auto& key : keys()) {
706  size_t index = assignment.at(key);
707  ss << "<th>" << DiscreteValues::Translate(names, key, index) << "</th>";
708  }
709  ss << "<td>" << it.value() << "</td>"; // value
710  ss << "</tr>\n";
711  }
712  ss << " </tbody>\n</table>\n</div>";
713  return ss.str();
714 }
715 
716 /* ************************************************************************ */
717 TableFactor TableFactor::prune(size_t maxNrAssignments) const {
718  const size_t N = maxNrAssignments;
719 
720  // Get the probabilities in the TableFactor so we can threshold.
721  vector<pair<Eigen::Index, double>> probabilities;
722 
723  // Store non-zero probabilities along with their indices in a vector.
724  for (SparseIt it(sparse_table_); it; ++it) {
725  probabilities.emplace_back(it.index(), it.value());
726  }
727 
728  // The number of probabilities can be lower than max_leaves.
729  if (probabilities.size() <= N) return *this;
730 
731  // Sort the vector in descending order based on the element values.
732  sort(probabilities.begin(), probabilities.end(),
733  [](const std::pair<Eigen::Index, double>& a,
734  const std::pair<Eigen::Index, double>& b) {
735  return a.second > b.second;
736  });
737 
738  // Keep the largest N probabilities in the vector.
739  if (probabilities.size() > N) probabilities.resize(N);
740 
741  // Create pruned sparse vector.
742  Eigen::SparseVector<double> pruned_vec(sparse_table_.size());
743  pruned_vec.reserve(probabilities.size());
744 
745  // Populate pruned sparse vector.
746  for (const auto& prob : probabilities) {
747  pruned_vec.insert(prob.first) = prob.second;
748  }
749 
750  // Create pruned decision tree factor and return.
751  return TableFactor(this->discreteKeys(), pruned_vec);
752 }
753 
754 /* ************************************************************************ */
755 } // namespace gtsam
gtsam::TableFactor::markdown
std::string markdown(const KeyFormatter &keyFormatter=DefaultKeyFormatter, const Names &names={}) const override
Render as markdown table.
Definition: TableFactor.cpp:654
gtsam::TableFactor
Definition: TableFactor.h:54
gtsam::DecisionTreeFactor
Definition: DecisionTreeFactor.h:45
gtsam::HybridValues
Definition: HybridValues.h:37
gtsam::TableFactor::choose
TableFactor choose(const DiscreteValues assignments, DiscreteKeys parent_keys) const
Create a TableFactor that is a subset of this TableFactor.
Definition: TableFactor.cpp:322
s
RealScalar s
Definition: level1_cplx_impl.h:126
gtsam::TableFactor::operator/
TableFactor operator/(const TableFactor &f) const
divide by factor f (safely)
Definition: TableFactor.h:202
keys
const KeyVector keys
Definition: testRegularImplicitSchurFactor.cpp:40
Eigen::SparseVector::reserve
void reserve(Index reserveSize)
Definition: SparseVector.h:204
gtsam::TableFactor::sparse_table_
Eigen::SparseVector< double > sparse_table_
SparseVector of nonzero probabilities.
Definition: TableFactor.h:57
c
Scalar Scalar * c
Definition: benchVecAdd.cpp:17
tree
Definition: testExpression.cpp:212
gtsam::DiscreteFactor::cardinalities_
std::map< Key, size_t > cardinalities_
Map of Keys and their cardinalities.
Definition: DiscreteFactor.h:57
pybind_wrapper_test_script.this
this
Definition: pybind_wrapper_test_script.py:38
x
set noclip points set clip one set noclip two set bar set border lt lw set xdata set ydata set zdata set x2data set y2data set boxwidth set dummy x
Definition: gnuplot_common_settings.hh:12
dt
const double dt
Definition: testVelocityConstraint.cpp:15
formatter
const KeyFormatter & formatter
Definition: treeTraversal-inst.h:204
gtsam::TableFactor::uniqueRep
uint64_t uniqueRep(const DiscreteKeys &keys, const uint64_t idx) const
Create unique representation.
Definition: TableFactor.cpp:534
different_sigmas::values
HybridValues values
Definition: testHybridBayesNet.cpp:245
log
const EIGEN_DEVICE_FUNC LogReturnType log() const
Definition: ArrayCwiseUnaryOps.h:128
gtsam::DiscreteKeys
DiscreteKeys is a set of keys that can be assembled using the & operator.
Definition: DiscreteKey.h:41
gtsam::FastSet< Key >
DiscreteConditional.h
gtsam::TableFactor::contractDkeys
DiscreteKeys contractDkeys(const TableFactor &f) const
Definition: TableFactor.cpp:466
gtsam::TableFactor::keyValueForIndex
size_t keyValueForIndex(Key target_key, uint64_t index) const
Uses lazy cartesian product to find nth entry in the cartesian product of arrays in O(1) Example) v0 ...
Definition: TableFactor.cpp:632
gtsam::KeyVector
FastVector< Key > KeyVector
Define collection type once and for all - also used in wrappers.
Definition: Key.h:92
result
Values result
Definition: OdometryOptimize.cpp:8
Eigen::SparseCompressedBase::InnerIterator
Definition: SparseCompressedBase.h:158
gtsam::TableFactor::enumerate
std::vector< std::pair< DiscreteValues, double > > enumerate() const
Enumerate all values into a map from values to double.
Definition: TableFactor.cpp:638
gtsam::AlgebraicDecisionTree< Key >
test_eigen_tensor.indices
indices
Definition: test_eigen_tensor.py:33
size
Scalar Scalar int size
Definition: benchVecAdd.cpp:17
ss
static std::stringstream ss
Definition: testBTree.cpp:31
gtsam::TableFactor::unionRep
uint64_t unionRep(const DiscreteKeys &keys, const DiscreteValues &assign, const uint64_t idx) const
Create unique representation of union modes.
Definition: TableFactor.cpp:495
gtsam::TableFactor::findValue
double findValue(const DiscreteValues &values) const
Find value for corresponding DiscreteValues.
Definition: TableFactor.cpp:230
FastSet.h
A thin wrapper around std::set that uses boost's fast_pool_allocator.
Eigen::SparseVector::nonZeros
Index nonZeros() const
Definition: SparseVector.h:140
gtsam::TableFactor::multiply
virtual DiscreteFactor::shared_ptr multiply(const DiscreteFactor::shared_ptr &f) const override
Multiply factors, DiscreteFactor::shared_ptr edition.
Definition: TableFactor.cpp:258
gtsam::TableFactor::sorted_dkeys_
DiscreteKeys sorted_dkeys_
Sorted DiscreteKeys to use internally.
Definition: TableFactor.h:63
table
ArrayXXf table(10, 4)
j
std::ptrdiff_t j
Definition: tut_arithmetic_redux_minmax.cpp:2
gtsam::DiscreteValues::CartesianProduct
static std::vector< DiscreteValues > CartesianProduct(const DiscreteKeys &keys)
Return a vector of DiscreteValues, one for each possible combination of values.
Definition: DiscreteValues.h:85
left
static char left
Definition: blas_interface.hh:62
gtsam::KeyFormatter
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
gtsam::TableFactor::findAssignments
DiscreteValues findAssignments(const uint64_t idx) const
Find DiscreteValues for corresponding index.
Definition: TableFactor.cpp:557
gtsam::TableFactor::prune
TableFactor prune(size_t maxNrAssignments) const
Prune the decision tree of discrete variables.
Definition: TableFactor.cpp:717
gtsam::TableFactor::html
std::string html(const KeyFormatter &keyFormatter=DefaultKeyFormatter, const Names &names={}) const override
Render as html table.
Definition: TableFactor.cpp:684
gtsam::TableFactor::createMap
std::unordered_map< uint64_t, AssignValList > createMap(const DiscreteKeys &contract, const DiscreteKeys &free) const
Definition: TableFactor.cpp:511
gtsam::Assignment< Key >
TableFactor.h
gtsam::DiscreteFactor::Binary
std::function< double(const double, const double)> Binary
Definition: DiscreteFactor.h:53
gtsam::TableFactor::Convert
static Eigen::SparseVector< double > Convert(const DiscreteKeys &keys, const std::vector< double > &table)
Definition: TableFactor.cpp:169
gtsam::TableFactor::combine
shared_ptr combine(size_t nrFrontals, Binary op) const
Definition: TableFactor.cpp:566
key
const gtsam::Symbol key('X', 0)
tree::f
Point2(* f)(const Point3 &, OptionalJacobian< 2, 3 >)
Definition: testExpression.cpp:218
gtsam::DecisionTree< Key, double >
gtsam::DiscreteFactor::cardinality
size_t cardinality(Key j) const
Definition: DiscreteFactor.h:99
process_shonan_timing_results.names
dictionary names
Definition: process_shonan_timing_results.py:175
gtsam::b
const G & b
Definition: Group.h:79
gtsam::DiscreteConditional
Definition: DiscreteConditional.h:37
gtsam::TableFactor::error
double error(const DiscreteValues &values) const override
Calculate error for DiscreteValues x, is -log(probability).
Definition: TableFactor.cpp:243
a
ArrayXXi a
Definition: Array_initializer_list_23_cxx11.cpp:1
gtsam::Symbol::index
std::uint64_t index() const
Definition: inference/Symbol.h:80
gtsam::TableFactor::operator*
TableFactor operator*(const TableFactor &f) const
multiply two TableFactors
Definition: TableFactor.h:175
gtsam
traits
Definition: SFMdata.h:40
gtsam::Factor::keys_
KeyVector keys_
The keys involved in this factor.
Definition: Factor.h:88
gtsam::DiscreteFactor::shared_ptr
std::shared_ptr< DiscreteFactor > shared_ptr
shared_ptr to this class
Definition: DiscreteFactor.h:45
gtsam::DiscreteFactor::Names
DiscreteValues::Names Names
Translation table from values to strings.
Definition: DiscreteFactor.h:172
gtsam::DiscreteValues
Definition: DiscreteValues.h:34
gtsam::Factor::keys
const KeyVector & keys() const
Access the factor's involved variable keys.
Definition: Factor.h:143
gtsam::DiscreteKey
std::pair< Key, size_t > DiscreteKey
Definition: DiscreteKey.h:38
Eigen::SparseVector< double >
std
Definition: BFloat16.h:88
gtsam::TableFactor::safe_div
static double safe_div(const double &a, const double &b)
Definition: TableFactor.cpp:367
gtsam::TableFactor::freeDkeys
DiscreteKeys freeDkeys(const TableFactor &f) const
Return keys in free mode which are the dimensions not involved in the contraction operation.
Definition: TableFactor.cpp:476
gtsam::TableFactor::denominators_
std::map< Key, size_t > denominators_
Map of Keys and their denominators used in keyValueForIndex.
Definition: TableFactor.h:61
gtsam::DiscreteValues::insert
std::pair< iterator, bool > insert(const value_type &value)
Definition: DiscreteValues.h:68
p
float * p
Definition: Tutorial_Map_using.cpp:9
gtsam::tol
const G double tol
Definition: Group.h:79
gtsam::TableFactor::equals
bool equals(const DiscreteFactor &other, double tol=1e-9) const override
equality
Definition: TableFactor.cpp:206
gtsam::TableFactor::discreteKey
DiscreteKey discreteKey(size_t i) const
Return ith key in keys_ as a DiscreteKey.
Definition: TableFactor.h:86
gtsam::TableFactor::apply
TableFactor apply(Unary op) const
Definition: TableFactor.cpp:393
gtsam::TableFactor::print
void print(const std::string &s="TableFactor:\n", const KeyFormatter &formatter=DefaultKeyFormatter) const override
print
Definition: TableFactor.cpp:375
gtsam::DiscreteFactor::discreteKeys
DiscreteKeys discreteKeys() const
Return all the discrete keys associated with this factor.
Definition: DiscreteFactor.cpp:37
gtsam::TableFactor::evaluate
double evaluate(const Assignment< Key > &values) const override
Evaluate probability distribution, is just look up in TableFactor.
Definition: TableFactor.cpp:217
uint64_t
unsigned __int64 uint64_t
Definition: ms_stdint.h:95
N
#define N
Definition: igam.h:9
gtsam::DiscreteFactor
Definition: DiscreteFactor.h:40
gtsam::DiscreteFactor::UnaryAssignment
std::function< double(const Assignment< Key > &, const double &)> UnaryAssignment
Definition: DiscreteFactor.h:52
gtsam::TableFactor::unionDkeys
DiscreteKeys unionDkeys(const TableFactor &f) const
Return union of DiscreteKeys in two factors.
Definition: TableFactor.cpp:486
gtsam::DiscreteValues::Translate
static std::string Translate(const Names &names, Key key, size_t index)
Translate an integer index value for given key to a string.
Definition: DiscreteValues.cpp:78
gtsam::TableFactor::TableFactor
TableFactor()
Definition: TableFactor.cpp:32
gtsam::Factor::size
size_t size() const
Definition: Factor.h:160
gtsam::Key
std::uint64_t Key
Integer nonlinear key type.
Definition: types.h:97
gtsam::DiscreteFactor::Unary
std::function< double(const double &)> Unary
Definition: DiscreteFactor.h:50
_
constexpr descr< N - 1 > _(char const (&text)[N])
Definition: descr.h:109
HybridValues.h
gtsam::Ordering
Definition: inference/Ordering.h:33
Eigen::SparseVector::coeffRef
Scalar & coeffRef(Index row, Index col)
Definition: SparseVector.h:113
DecisionTreeFactor.h
Eigen::SparseVector::data
Storage & data()
Definition: SparseVector.h:98
i
int i
Definition: BiCGSTAB_step_by_step.cpp:9
pybind_wrapper_test_script.other
other
Definition: pybind_wrapper_test_script.py:42
Eigen::internal::CompressedStorage::squeeze
void squeeze()
Definition: CompressedStorage.h:83
gtsam::TableFactor::shared_ptr
std::shared_ptr< TableFactor > shared_ptr
Definition: TableFactor.h:105
gtsam::TableFactor::toDecisionTreeFactor
DecisionTreeFactor toDecisionTreeFactor() const override
Convert into a decisiontree.
Definition: TableFactor.cpp:298
Eigen::SparseVector::insert
Scalar & insert(Index row, Index col)
Definition: SparseVector.h:172
Eigen::Index
EIGEN_DEFAULT_DENSE_INDEX_TYPE Index
The Index type as used for the API.
Definition: Meta.h:74
gtsam::ComputeSparseTable
static Eigen::SparseVector< double > ComputeSparseTable(const DiscreteKeys &dkeys, const DecisionTreeFactor &dt)
Compute the indexing of the leaves in the decision tree based on the assignment and add the (index,...
Definition: TableFactor.cpp:75
Eigen::SparseVector::coeff
Scalar coeff(Index row, Index col) const
Definition: SparseVector.h:102
gtsam::DiscreteFactor::equals
virtual bool equals(const DiscreteFactor &lf, double tol=1e-9) const
equals
Definition: DiscreteFactor.cpp:32


gtsam
Author(s):
autogenerated on Tue Jan 7 2025 04:05:13