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  return combine(nrFrontals, Ring::add);
395 }
396 
397 /* ************************************************************************ */
399  return combine(keys, Ring::add);
400 }
401 
402 /* ************************************************************************ */
403 double TableFactor::max() const {
404  double max_value = std::numeric_limits<double>::lowest();
406  max_value = std::max(max_value, it.value());
407  }
408  return max_value;
409 }
410 
411 /* ************************************************************************ */
413  return combine(nrFrontals, Ring::max);
414 }
415 
416 /* ************************************************************************ */
418  return combine(keys, Ring::max);
419 }
420 
421 /* ************************************************************************ */
423  // Initialize new factor.
424  uint64_t cardi = 1;
425  for (auto [key, c] : cardinalities_) cardi *= c;
426  Eigen::SparseVector<double> sparse_table(cardi);
427  sparse_table.reserve(sparse_table_.nonZeros());
428 
429  // Populate
430  for (SparseIt it(sparse_table_); it; ++it) {
431  sparse_table.coeffRef(it.index()) = op(it.value());
432  }
433 
434  // Free unused memory and return.
435  sparse_table.pruned();
436  sparse_table.data().squeeze();
437  return TableFactor(discreteKeys(), sparse_table);
438 }
439 
440 /* ************************************************************************ */
442  // Initialize new factor.
443  uint64_t cardi = 1;
444  for (auto [key, c] : cardinalities_) cardi *= c;
445  Eigen::SparseVector<double> sparse_table(cardi);
446  sparse_table.reserve(sparse_table_.nonZeros());
447 
448  // Populate
449  for (SparseIt it(sparse_table_); it; ++it) {
450  DiscreteValues assignment = findAssignments(it.index());
451  sparse_table.coeffRef(it.index()) = op(assignment, it.value());
452  }
453 
454  // Free unused memory and return.
455  sparse_table.pruned();
456  sparse_table.data().squeeze();
457  return TableFactor(discreteKeys(), sparse_table);
458 }
459 
460 /* ************************************************************************ */
462  if (keys_.empty() && sparse_table_.nonZeros() == 0)
463  return f;
464  else if (f.keys_.empty() && f.sparse_table_.nonZeros() == 0)
465  return *this;
466  // 1. Identify keys for contract and free modes.
467  DiscreteKeys contract_dkeys = contractDkeys(f);
468  DiscreteKeys f_free_dkeys = f.freeDkeys(*this);
469  DiscreteKeys union_dkeys = unionDkeys(f);
470  // 2. Create hash table for input factor f
471  unordered_map<uint64_t, AssignValList> map_f =
472  f.createMap(contract_dkeys, f_free_dkeys);
473  // 3. Initialize multiplied factor.
474  uint64_t card = 1;
475  for (auto u_dkey : union_dkeys) card *= u_dkey.second;
476  Eigen::SparseVector<double> mult_sparse_table(card);
477  mult_sparse_table.reserve(card);
478  // 3. Multiply.
479  for (SparseIt it(sparse_table_); it; ++it) {
480  uint64_t contract_unique = uniqueRep(contract_dkeys, it.index());
481  if (map_f.find(contract_unique) == map_f.end()) continue;
482  for (auto assignVal : map_f[contract_unique]) {
483  uint64_t union_idx = unionRep(union_dkeys, assignVal.first, it.index());
484  mult_sparse_table.insert(union_idx) = op(it.value(), assignVal.second);
485  }
486  }
487  // 4. Free unused memory.
488  mult_sparse_table.pruned();
489  mult_sparse_table.data().squeeze();
490  // 5. Create union keys and return.
491  return TableFactor(union_dkeys, mult_sparse_table);
492 }
493 
494 /* ************************************************************************ */
496  // Find contract modes.
497  DiscreteKeys contract;
498  set_intersection(sorted_dkeys_.begin(), sorted_dkeys_.end(),
499  f.sorted_dkeys_.begin(), f.sorted_dkeys_.end(),
500  back_inserter(contract));
501  return contract;
502 }
503 
504 /* ************************************************************************ */
506  // Find free modes.
507  DiscreteKeys free;
508  set_difference(sorted_dkeys_.begin(), sorted_dkeys_.end(),
509  f.sorted_dkeys_.begin(), f.sorted_dkeys_.end(),
510  back_inserter(free));
511  return free;
512 }
513 
514 /* ************************************************************************ */
516  // Find union modes.
517  DiscreteKeys union_dkeys;
518  set_union(sorted_dkeys_.begin(), sorted_dkeys_.end(), f.sorted_dkeys_.begin(),
519  f.sorted_dkeys_.end(), back_inserter(union_dkeys));
520  return union_dkeys;
521 }
522 
523 /* ************************************************************************ */
525  const DiscreteValues& f_free,
526  const uint64_t idx) const {
527  uint64_t union_idx = 0, card = 1;
528  for (auto it = union_keys.rbegin(); it != union_keys.rend(); it++) {
529  if (f_free.find(it->first) == f_free.end()) {
530  union_idx += keyValueForIndex(it->first, idx) * card;
531  } else {
532  union_idx += f_free.at(it->first) * card;
533  }
534  card *= it->second;
535  }
536  return union_idx;
537 }
538 
539 /* ************************************************************************ */
540 unordered_map<uint64_t, TableFactor::AssignValList> TableFactor::createMap(
541  const DiscreteKeys& contract, const DiscreteKeys& free) const {
542  // 1. Initialize map.
543  unordered_map<uint64_t, AssignValList> map_f;
544  // 2. Iterate over nonzero elements.
545  for (SparseIt it(sparse_table_); it; ++it) {
546  // 3. Create unique representation of contract modes.
547  uint64_t unique_rep = uniqueRep(contract, it.index());
548  // 4. Create assignment for free modes.
549  DiscreteValues free_assignments;
550  for (auto& key : free)
551  free_assignments[key.first] = keyValueForIndex(key.first, it.index());
552  // 5. Populate map.
553  if (map_f.find(unique_rep) == map_f.end()) {
554  map_f[unique_rep] = {make_pair(free_assignments, it.value())};
555  } else {
556  map_f[unique_rep].push_back(make_pair(free_assignments, it.value()));
557  }
558  }
559  return map_f;
560 }
561 
562 /* ************************************************************************ */
564  const uint64_t idx) const {
565  if (dkeys.empty()) return 0;
566  uint64_t unique_rep = 0, card = 1;
567  for (auto it = dkeys.rbegin(); it != dkeys.rend(); it++) {
568  unique_rep += keyValueForIndex(it->first, idx) * card;
569  card *= it->second;
570  }
571  return unique_rep;
572 }
573 
574 /* ************************************************************************ */
575 uint64_t TableFactor::uniqueRep(const DiscreteValues& assignments) const {
576  if (assignments.empty()) return 0;
577  uint64_t unique_rep = 0, card = 1;
578  for (auto it = assignments.rbegin(); it != assignments.rend(); it++) {
579  unique_rep += it->second * card;
580  card *= cardinalities_.at(it->first);
581  }
582  return unique_rep;
583 }
584 
585 /* ************************************************************************ */
587  DiscreteValues assignment;
588  for (Key key : keys_) {
589  assignment[key] = keyValueForIndex(key, idx);
590  }
591  return assignment;
592 }
593 
594 /* ************************************************************************ */
596  Binary op) const {
597  if (nrFrontals > size()) {
598  throw invalid_argument(
599  "TableFactor::combine: invalid number of frontal "
600  "keys " +
601  to_string(nrFrontals) + ", nr.keys=" + std::to_string(size()));
602  }
603  // Find remaining keys.
604  DiscreteKeys remain_dkeys;
605  uint64_t card = 1;
606  for (auto i = nrFrontals; i < keys_.size(); i++) {
607  remain_dkeys.push_back(discreteKey(i));
608  card *= cardinality(keys_[i]);
609  }
610  // Create combined table.
611  Eigen::SparseVector<double> combined_table(card);
612  combined_table.reserve(sparse_table_.nonZeros());
613  // Populate combined table.
614  for (SparseIt it(sparse_table_); it; ++it) {
615  uint64_t idx = uniqueRep(remain_dkeys, it.index());
616  double new_val = op(combined_table.coeff(idx), it.value());
617  combined_table.coeffRef(idx) = new_val;
618  }
619  // Free unused memory.
620  combined_table.pruned();
621  combined_table.data().squeeze();
622  return std::make_shared<TableFactor>(remain_dkeys, combined_table);
623 }
624 
625 /* ************************************************************************ */
627  Binary op) const {
628  if (frontalKeys.size() > size()) {
629  throw invalid_argument(
630  "TableFactor::combine: invalid number of frontal "
631  "keys " +
632  std::to_string(frontalKeys.size()) +
633  ", nr.keys=" + std::to_string(size()));
634  }
635  // Find remaining keys.
636  DiscreteKeys remain_dkeys;
637  uint64_t card = 1;
638  for (Key key : keys_) {
639  if (std::find(frontalKeys.begin(), frontalKeys.end(), key) ==
640  frontalKeys.end()) {
641  remain_dkeys.emplace_back(key, cardinality(key));
642  card *= cardinality(key);
643  }
644  }
645  // Create combined table.
646  Eigen::SparseVector<double> combined_table(card);
647  combined_table.reserve(sparse_table_.nonZeros());
648  // Populate combined table.
649  for (SparseIt it(sparse_table_); it; ++it) {
650  uint64_t idx = uniqueRep(remain_dkeys, it.index());
651  double new_val = op(combined_table.coeff(idx), it.value());
652  combined_table.coeffRef(idx) = new_val;
653  }
654  // Free unused memory.
655  combined_table.pruned();
656  combined_table.data().squeeze();
657  return std::make_shared<TableFactor>(remain_dkeys, combined_table);
658 }
659 
660 /* ************************************************************************ */
661 size_t TableFactor::keyValueForIndex(Key target_key, uint64_t index) const {
662  // http://phrogz.net/lazy-cartesian-product
663  return (index / denominators_.at(target_key)) % cardinality(target_key);
664 }
665 
666 /* ************************************************************************ */
667 std::vector<std::pair<DiscreteValues, double>> TableFactor::enumerate() const {
668  // Get all possible assignments
669  std::vector<std::pair<Key, size_t>> pairs = discreteKeys();
670  // Reverse to make cartesian product output a more natural ordering.
671  std::vector<std::pair<Key, size_t>> rpairs(pairs.rbegin(), pairs.rend());
672  const auto assignments = DiscreteValues::CartesianProduct(rpairs);
673  // Construct unordered_map with values
674  std::vector<std::pair<DiscreteValues, double>> result;
675  for (const auto& assignment : assignments) {
676  result.emplace_back(assignment, operator()(assignment));
677  }
678  return result;
679 }
680 
681 // Print out header.
682 /* ************************************************************************ */
683 string TableFactor::markdown(const KeyFormatter& keyFormatter,
684  const Names& names) const {
685  stringstream ss;
686 
687  // Print out header.
688  ss << "|";
689  for (auto& key : keys()) {
690  ss << keyFormatter(key) << "|";
691  }
692  ss << "value|\n";
693 
694  // Print out separator with alignment hints.
695  ss << "|";
696  for (size_t j = 0; j < size(); j++) ss << ":-:|";
697  ss << ":-:|\n";
698 
699  // Print out all rows.
700  for (SparseIt it(sparse_table_); it; ++it) {
701  DiscreteValues assignment = findAssignments(it.index());
702  ss << "|";
703  for (auto& key : keys()) {
704  size_t index = assignment.at(key);
705  ss << DiscreteValues::Translate(names, key, index) << "|";
706  }
707  ss << it.value() << "|\n";
708  }
709  return ss.str();
710 }
711 
712 /* ************************************************************************ */
713 string TableFactor::html(const KeyFormatter& keyFormatter,
714  const Names& names) const {
715  stringstream ss;
716 
717  // Print out preamble.
718  ss << "<div>\n<table class='TableFactor'>\n <thead>\n";
719 
720  // Print out header row.
721  ss << " <tr>";
722  for (auto& key : keys()) {
723  ss << "<th>" << keyFormatter(key) << "</th>";
724  }
725  ss << "<th>value</th></tr>\n";
726 
727  // Finish header and start body.
728  ss << " </thead>\n <tbody>\n";
729 
730  // Print out all rows.
731  for (SparseIt it(sparse_table_); it; ++it) {
732  DiscreteValues assignment = findAssignments(it.index());
733  ss << " <tr>";
734  for (auto& key : keys()) {
735  size_t index = assignment.at(key);
736  ss << "<th>" << DiscreteValues::Translate(names, key, index) << "</th>";
737  }
738  ss << "<td>" << it.value() << "</td>"; // value
739  ss << "</tr>\n";
740  }
741  ss << " </tbody>\n</table>\n</div>";
742  return ss.str();
743 }
744 
745 /* ************************************************************************ */
746 TableFactor TableFactor::prune(size_t maxNrAssignments) const {
747  const size_t N = maxNrAssignments;
748 
749  // Get the probabilities in the TableFactor so we can threshold.
750  vector<pair<Eigen::Index, double>> probabilities;
751 
752  // Store non-zero probabilities along with their indices in a vector.
753  for (SparseIt it(sparse_table_); it; ++it) {
754  probabilities.emplace_back(it.index(), it.value());
755  }
756 
757  // The number of probabilities can be lower than max_leaves.
758  if (probabilities.size() <= N) return *this;
759 
760  // Sort the vector in descending order based on the element values.
761  sort(probabilities.begin(), probabilities.end(),
762  [](const std::pair<Eigen::Index, double>& a,
763  const std::pair<Eigen::Index, double>& b) {
764  return a.second > b.second;
765  });
766 
767  // Keep the largest N probabilities in the vector.
768  if (probabilities.size() > N) probabilities.resize(N);
769 
770  // Create pruned sparse vector.
771  Eigen::SparseVector<double> pruned_vec(sparse_table_.size());
772  pruned_vec.reserve(probabilities.size());
773 
774  // Populate pruned sparse vector.
775  for (const auto& prob : probabilities) {
776  pruned_vec.insert(prob.first) = prob.second;
777  }
778 
779  // Create pruned decision tree factor and return.
780  return TableFactor(this->discreteKeys(), pruned_vec);
781 }
782 
783 /* ************************************************************************ */
785  const DiscreteValues& assignment) const {
786  throw std::runtime_error("TableFactor::restrict not implemented");
787 }
788 
789 /* ************************************************************************ */
790 } // namespace gtsam
gtsam::TableFactor::markdown
std::string markdown(const KeyFormatter &keyFormatter=DefaultKeyFormatter, const Names &names={}) const override
Render as markdown table.
Definition: TableFactor.cpp:683
gtsam::TableFactor
Definition: TableFactor.h:54
gtsam::DecisionTreeFactor
Definition: DecisionTreeFactor.h:45
gtsam::HybridValues
Definition: HybridValues.h:37
gtsam::TableFactor::sum
DiscreteFactor::shared_ptr sum(size_t nrFrontals) const override
Create new factor by summing all values with the same separator values.
Definition: TableFactor.cpp:393
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:208
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:563
different_sigmas::values
HybridValues values
Definition: testHybridBayesNet.cpp:247
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:495
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:661
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:667
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:524
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:148
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::max
double max() const override
Find the maximum value in the factor.
Definition: TableFactor.cpp:403
gtsam::TableFactor::findAssignments
DiscreteValues findAssignments(const uint64_t idx) const
Find DiscreteValues for corresponding index.
Definition: TableFactor.cpp:586
gtsam::TableFactor::prune
TableFactor prune(size_t maxNrAssignments) const
Prune the decision tree of discrete variables.
Definition: TableFactor.cpp:746
Ring::max
static double max(const double &a, const double &b)
Definition: Ring.h:28
gtsam::TableFactor::html
std::string html(const KeyFormatter &keyFormatter=DefaultKeyFormatter, const Names &names={}) const override
Render as html table.
Definition: TableFactor.cpp:713
gtsam::TableFactor::createMap
std::unordered_map< uint64_t, AssignValList > createMap(const DiscreteKeys &contract, const DiscreteKeys &free) const
Definition: TableFactor.cpp:540
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:595
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
Ring::add
static double add(const double &a, const double &b)
Definition: Ring.h:27
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:190
gtsam::DiscreteValues
Definition: DiscreteValues.h:34
gtsam::TableFactor::operator*
DiscreteFactor::shared_ptr operator*(double s) const override
multiply with a scalar
Definition: TableFactor.h:175
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:505
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:71
gtsam::TableFactor::choose
TableFactor choose(const DiscreteValues parentAssignments, DiscreteKeys parent_keys) const
Create a TableFactor that is a subset of this TableFactor.
Definition: TableFactor.cpp:322
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::restrict
DiscreteFactor::shared_ptr restrict(const DiscreteValues &assignment) const override
Restrict the factor to the given assignment.
Definition: TableFactor.cpp:784
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:422
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:515
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:96
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
max
#define max(a, b)
Definition: datatypes.h:20
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 Wed Mar 19 2025 03:04:38